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
This commit is contained in:
Tiago Yamamoto 2025-12-28 01:48:12 -03:00
parent 1e30f57705
commit 6c87078200
5 changed files with 393 additions and 0 deletions

View file

@ -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"))
}
}

View file

@ -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)
}
}

View file

@ -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)
}
}

View file

@ -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)
}
}

View file

@ -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", "<b>Bold</b> text", "&lt;b&gt;Bold&lt;/b&gt; 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)
}
}