(t *testing.T)
| 11 | ) |
| 12 | |
| 13 | func TestHttpFileServer(t *testing.T) { |
| 14 | t.Run("starts server successfully", func(t *testing.T) { |
| 15 | mockLogger := &MockLogger{} |
| 16 | testPath := t.TempDir() // Creates a temporary directory for testing |
| 17 | |
| 18 | // Create a real HTTP test server to simulate server readiness |
| 19 | ts := httptest.NewServer(http.FileServer(http.Dir(testPath))) |
| 20 | defer ts.Close() |
| 21 | |
| 22 | // Extract the port from the test server URL |
| 23 | port := ts.Listener.Addr().(*net.TCPAddr).Port |
| 24 | httpPort = fmt.Sprintf("%d", port) // Override the port globally for the test |
| 25 | |
| 26 | // Mock the listenAndServe function |
| 27 | listenAndServe := func(server *http.Server) error { |
| 28 | return nil // Simulate successful server start |
| 29 | } |
| 30 | |
| 31 | server, err := httpFileServer(testPath, mockLogger, listenAndServe, 2*time.Second) |
| 32 | if err != nil { |
| 33 | t.Fatalf("expected no error, got: %v", err) |
| 34 | } |
| 35 | |
| 36 | if server == nil { |
| 37 | t.Fatalf("expected server to be returned, got nil") |
| 38 | } |
| 39 | |
| 40 | // Validate logs |
| 41 | if len(mockLogger.infoMessages) == 0 { |
| 42 | t.Errorf("expected info logs, got none") |
| 43 | } |
| 44 | }) |
| 45 | |
| 46 | t.Run("returns error when path does not exist", func(t *testing.T) { |
| 47 | mockLogger := &MockLogger{} |
| 48 | invalidPath := "/nonexistentpath" |
| 49 | |
| 50 | listenAndServe := func(server *http.Server) error { |
| 51 | return nil |
| 52 | } |
| 53 | |
| 54 | _, err := httpFileServer(invalidPath, mockLogger, listenAndServe, 2*time.Second) |
| 55 | if err == nil { |
| 56 | t.Fatalf("expected error for nonexistent path, got nil") |
| 57 | } |
| 58 | |
| 59 | // Validate error logs |
| 60 | if len(mockLogger.errorMessages) == 0 { |
| 61 | t.Errorf("expected error logs, got none") |
| 62 | } |
| 63 | }) |
| 64 | |
| 65 | t.Run("returns error when server fails to start", func(t *testing.T) { |
| 66 | mockLogger := &MockLogger{} |
| 67 | testPath := t.TempDir() |
| 68 | |
| 69 | // Mock the listenAndServe function to return an error |
| 70 | listenAndServe := func(server *http.Server) error { |
nothing calls this directly
no test coverage detected