From 6c870782001a978fe04561d2bf7bc7ddbb8c1495 Mon Sep 17 00:00:00 2001 From: Tiago Yamamoto Date: Sun, 28 Dec 2025 01:48:12 -0300 Subject: [PATCH] test: increase backend test coverage - sanitizer, middleware, handlers, services - Add tests for SanitizeEmail, SanitizeDescription, DefaultSanitizer - Add AuthMiddleware and RequireRole tests - Add admin_handlers_test.go and location_handlers_test.go - Expand application_service_test.go with more methods --- .../api/handlers/admin_handlers_test.go | 33 +++++ .../api/handlers/location_handlers_test.go | 85 ++++++++++++ .../internal/middleware/middleware_test.go | 70 ++++++++++ .../services/application_service_test.go | 123 ++++++++++++++++++ backend/internal/utils/sanitizer_test.go | 82 ++++++++++++ 5 files changed, 393 insertions(+) create mode 100644 backend/internal/api/handlers/admin_handlers_test.go create mode 100644 backend/internal/api/handlers/location_handlers_test.go diff --git a/backend/internal/api/handlers/admin_handlers_test.go b/backend/internal/api/handlers/admin_handlers_test.go new file mode 100644 index 0000000..d7f19cc --- /dev/null +++ b/backend/internal/api/handlers/admin_handlers_test.go @@ -0,0 +1,33 @@ +package handlers_test + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/rede5/gohorsejobs/backend/internal/api/handlers" +) + +func TestNewAdminHandlers(t *testing.T) { + h := handlers.NewAdminHandlers(nil, nil, nil, nil) + if h == nil { + t.Error("NewAdminHandlers should not return nil") + } +} + +func TestListAccessRoles(t *testing.T) { + h := handlers.NewAdminHandlers(nil, nil, nil, nil) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/roles", nil) + rr := httptest.NewRecorder() + + h.ListAccessRoles(rr, req) + + if rr.Code != http.StatusOK { + t.Errorf("Expected status 200, got %d", rr.Code) + } + + if rr.Header().Get("Content-Type") != "application/json" { + t.Errorf("Expected Content-Type application/json, got %s", rr.Header().Get("Content-Type")) + } +} diff --git a/backend/internal/api/handlers/location_handlers_test.go b/backend/internal/api/handlers/location_handlers_test.go new file mode 100644 index 0000000..b3b3635 --- /dev/null +++ b/backend/internal/api/handlers/location_handlers_test.go @@ -0,0 +1,85 @@ +package handlers_test + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/rede5/gohorsejobs/backend/internal/api/handlers" +) + +func TestNewLocationHandlers(t *testing.T) { + h := handlers.NewLocationHandlers(nil) + if h == nil { + t.Error("NewLocationHandlers should not return nil") + } +} + +func TestListStatesByCountry_MissingID(t *testing.T) { + h := handlers.NewLocationHandlers(nil) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/locations/countries/states", nil) + rr := httptest.NewRecorder() + + h.ListStatesByCountry(rr, req) + + if rr.Code != http.StatusBadRequest { + t.Errorf("Expected status 400, got %d", rr.Code) + } +} + +func TestListCitiesByState_MissingID(t *testing.T) { + h := handlers.NewLocationHandlers(nil) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/locations/states/cities", nil) + rr := httptest.NewRecorder() + + h.ListCitiesByState(rr, req) + + if rr.Code != http.StatusBadRequest { + t.Errorf("Expected status 400, got %d", rr.Code) + } +} + +func TestSearchLocations_ShortQuery(t *testing.T) { + h := handlers.NewLocationHandlers(nil) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/locations/search?q=a&country_id=1", nil) + rr := httptest.NewRecorder() + + h.SearchLocations(rr, req) + + // Short query returns empty array + if rr.Code != http.StatusOK { + t.Errorf("Expected status 200, got %d", rr.Code) + } + if rr.Body.String() != "[]" { + t.Errorf("Expected [], got %s", rr.Body.String()) + } +} + +func TestSearchLocations_MissingCountryID(t *testing.T) { + h := handlers.NewLocationHandlers(nil) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/locations/search?q=tokyo", nil) + rr := httptest.NewRecorder() + + h.SearchLocations(rr, req) + + if rr.Code != http.StatusBadRequest { + t.Errorf("Expected status 400, got %d", rr.Code) + } +} + +func TestSearchLocations_InvalidCountryID(t *testing.T) { + h := handlers.NewLocationHandlers(nil) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/locations/search?q=tokyo&country_id=abc", nil) + rr := httptest.NewRecorder() + + h.SearchLocations(rr, req) + + if rr.Code != http.StatusBadRequest { + t.Errorf("Expected status 400, got %d", rr.Code) + } +} diff --git a/backend/internal/middleware/middleware_test.go b/backend/internal/middleware/middleware_test.go index 2982309..f9636a4 100644 --- a/backend/internal/middleware/middleware_test.go +++ b/backend/internal/middleware/middleware_test.go @@ -80,3 +80,73 @@ func TestSecurityHeadersMiddleware(t *testing.T) { } } } + +func TestAuthMiddleware_NoAuthHeader(t *testing.T) { + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + middleware := AuthMiddleware(handler) + + req := httptest.NewRequest("GET", "/test", nil) + rr := httptest.NewRecorder() + + middleware.ServeHTTP(rr, req) + + if rr.Code != http.StatusUnauthorized { + t.Errorf("Expected status 401, got %d", rr.Code) + } +} + +func TestAuthMiddleware_InvalidFormat(t *testing.T) { + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + middleware := AuthMiddleware(handler) + + req := httptest.NewRequest("GET", "/test", nil) + req.Header.Set("Authorization", "InvalidFormat") + rr := httptest.NewRecorder() + + middleware.ServeHTTP(rr, req) + + if rr.Code != http.StatusUnauthorized { + t.Errorf("Expected status 401, got %d", rr.Code) + } +} + +func TestAuthMiddleware_InvalidToken(t *testing.T) { + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + middleware := AuthMiddleware(handler) + + req := httptest.NewRequest("GET", "/test", nil) + req.Header.Set("Authorization", "Bearer invalid.token.here") + rr := httptest.NewRecorder() + + middleware.ServeHTTP(rr, req) + + if rr.Code != http.StatusUnauthorized { + t.Errorf("Expected status 401, got %d", rr.Code) + } +} + +func TestRequireRole_NoClaims(t *testing.T) { + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + middleware := RequireRole("admin")(handler) + + req := httptest.NewRequest("GET", "/test", nil) + rr := httptest.NewRecorder() + + middleware.ServeHTTP(rr, req) + + if rr.Code != http.StatusUnauthorized { + t.Errorf("Expected status 401, got %d", rr.Code) + } +} diff --git a/backend/internal/services/application_service_test.go b/backend/internal/services/application_service_test.go index 2c01f4d..3abe712 100644 --- a/backend/internal/services/application_service_test.go +++ b/backend/internal/services/application_service_test.go @@ -2,10 +2,19 @@ package services import ( "testing" + "time" "github.com/DATA-DOG/go-sqlmock" + "github.com/rede5/gohorsejobs/backend/internal/dto" ) +func TestNewApplicationService(t *testing.T) { + s := NewApplicationService(nil) + if s == nil { + t.Error("NewApplicationService should not return nil") + } +} + func TestApplicationService_DeleteApplication(t *testing.T) { db, mock, err := sqlmock.New() if err != nil { @@ -29,3 +38,117 @@ func TestApplicationService_DeleteApplication(t *testing.T) { t.Errorf("there were unfulfilled expectations: %s", err) } } + +func TestApplicationService_CreateApplication(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("Failed to create mock db: %v", err) + } + defer db.Close() + + s := NewApplicationService(db) + + userID := "user-456" + name := "Test Candidate" + phone := "123456789" + email := "test@example.com" + message := "I want this job" + resumeURL := "https://example.com/resume.pdf" + + req := dto.CreateApplicationRequest{ + JobID: "job-123", + UserID: &userID, + Name: &name, + Phone: &phone, + Email: &email, + Message: &message, + ResumeURL: &resumeURL, + } + + mock.ExpectQuery("INSERT INTO applications"). + WithArgs( + req.JobID, req.UserID, req.Name, req.Phone, req.LineID, req.WhatsApp, req.Email, + req.Message, req.ResumeURL, req.Documents, "pending", sqlmock.AnyArg(), sqlmock.AnyArg(), + ). + WillReturnRows(sqlmock.NewRows([]string{"id", "created_at", "updated_at"}). + AddRow("app-789", time.Now(), time.Now())) + + app, err := s.CreateApplication(req) + if err != nil { + t.Fatalf("CreateApplication failed: %v", err) + } + if app.ID != "app-789" { + t.Errorf("Expected app ID 'app-789', got '%s'", app.ID) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("Unmet expectations: %v", err) + } +} + +func TestApplicationService_GetApplications(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("Failed to create mock db: %v", err) + } + defer db.Close() + + s := NewApplicationService(db) + jobID := "job-123" + + rows := sqlmock.NewRows([]string{ + "id", "job_id", "user_id", "name", "phone", "line_id", "whatsapp", "email", + "message", "resume_url", "status", "created_at", "updated_at", + }).AddRow( + "app-1", jobID, "user-1", "John Doe", "123", nil, nil, "john@test.com", + "Hello", "http://resume.pdf", "pending", time.Now(), time.Now(), + ) + + mock.ExpectQuery("SELECT id, job_id, user_id, name, phone, line_id, whatsapp, email"). + WithArgs(jobID). + WillReturnRows(rows) + + apps, err := s.GetApplications(jobID) + if err != nil { + t.Fatalf("GetApplications failed: %v", err) + } + if len(apps) != 1 { + t.Errorf("Expected 1 application, got %d", len(apps)) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("Unmet expectations: %v", err) + } +} + +func TestApplicationService_GetApplicationByID(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("Failed to create mock db: %v", err) + } + defer db.Close() + + s := NewApplicationService(db) + appID := "app-123" + + rows := sqlmock.NewRows([]string{ + "id", "job_id", "user_id", "name", "phone", "line_id", "whatsapp", "email", + "message", "resume_url", "documents", "status", "created_at", "updated_at", + }).AddRow( + appID, "job-1", "user-1", "Jane Doe", "456", nil, nil, "jane@test.com", + "Hi", "http://cv.pdf", nil, "pending", time.Now(), time.Now(), + ) + + mock.ExpectQuery("SELECT id, job_id, user_id, name, phone, line_id, whatsapp, email"). + WithArgs(appID). + WillReturnRows(rows) + + app, err := s.GetApplicationByID(appID) + if err != nil { + t.Fatalf("GetApplicationByID failed: %v", err) + } + if app.ID != appID { + t.Errorf("Expected app ID '%s', got '%s'", appID, app.ID) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("Unmet expectations: %v", err) + } +} diff --git a/backend/internal/utils/sanitizer_test.go b/backend/internal/utils/sanitizer_test.go index 7063773..3b1bdac 100644 --- a/backend/internal/utils/sanitizer_test.go +++ b/backend/internal/utils/sanitizer_test.go @@ -99,3 +99,85 @@ func TestStripHTML(t *testing.T) { }) } } + +func TestSanitizeEmail(t *testing.T) { + s := DefaultSanitizer() + + tests := []struct { + name string + input string + expected string + }{ + {"simple email", "Test@Example.COM", "test@example.com"}, + {"with whitespace", " test@example.com ", "test@example.com"}, + {"empty string", "", ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := s.SanitizeEmail(tt.input) + if result != tt.expected { + t.Errorf("SanitizeEmail(%q) = %q, want %q", tt.input, result, tt.expected) + } + }) + } + + // Test max length + t.Run("over max length", func(t *testing.T) { + s.MaxEmailLength = 10 + longEmail := "abcdefghijklmnop@example.com" + result := s.SanitizeEmail(longEmail) + if result != "" { + t.Errorf("SanitizeEmail with over max length should return empty, got %q", result) + } + }) +} + +func TestSanitizeDescription(t *testing.T) { + s := DefaultSanitizer() + s.MaxDescriptionLength = 50 // Larger limit for testing + + tests := []struct { + name string + input string + expected string + }{ + {"short description", "Hello world", "Hello world"}, + {"with html", "Bold text", "<b>Bold</b> text"}, + {"empty string", "", ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := s.SanitizeDescription(tt.input) + if result != tt.expected { + t.Errorf("SanitizeDescription(%q) = %q, want %q", tt.input, result, tt.expected) + } + }) + } + + // Test truncation separately + t.Run("over limit", func(t *testing.T) { + s.MaxDescriptionLength = 10 + result := s.SanitizeDescription("This is a very long text") + if len([]rune(result)) > 10 { + t.Errorf("SanitizeDescription should truncate to MaxDescriptionLength") + } + }) +} + +func TestDefaultSanitizer(t *testing.T) { + s := DefaultSanitizer() + if s == nil { + t.Error("DefaultSanitizer should not return nil") + } + if s.MaxNameLength != 255 { + t.Errorf("MaxNameLength = %d, want 255", s.MaxNameLength) + } + if s.MaxDescriptionLength != 10000 { + t.Errorf("MaxDescriptionLength = %d, want 10000", s.MaxDescriptionLength) + } + if s.MaxEmailLength != 320 { + t.Errorf("MaxEmailLength = %d, want 320", s.MaxEmailLength) + } +}