add step list for server creation
This commit is contained in:
@@ -14,12 +14,10 @@ import (
|
||||
)
|
||||
|
||||
func TestController_JSONParsing_Success(t *testing.T) {
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
// Test basic JSON parsing functionality
|
||||
app := fiber.New()
|
||||
|
||||
app.Post("/test", func(c *fiber.Ctx) error {
|
||||
@@ -30,7 +28,6 @@ func TestController_JSONParsing_Success(t *testing.T) {
|
||||
return c.JSON(data)
|
||||
})
|
||||
|
||||
// Prepare test data
|
||||
testData := map[string]interface{}{
|
||||
"name": "test",
|
||||
"value": 123,
|
||||
@@ -38,34 +35,28 @@ func TestController_JSONParsing_Success(t *testing.T) {
|
||||
bodyBytes, err := json.Marshal(testData)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Create request
|
||||
req := httptest.NewRequest("POST", "/test", bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, 200, resp.StatusCode)
|
||||
|
||||
// Parse response
|
||||
var response map[string]interface{}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
tests.AssertNoError(t, err)
|
||||
err = json.Unmarshal(body, &response)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify response
|
||||
tests.AssertEqual(t, "test", response["name"])
|
||||
tests.AssertEqual(t, float64(123), response["value"]) // JSON numbers are float64
|
||||
tests.AssertEqual(t, float64(123), response["value"])
|
||||
}
|
||||
|
||||
func TestController_JSONParsing_InvalidJSON(t *testing.T) {
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
// Test handling of invalid JSON
|
||||
app := fiber.New()
|
||||
|
||||
app.Post("/test", func(c *fiber.Ctx) error {
|
||||
@@ -76,39 +67,31 @@ func TestController_JSONParsing_InvalidJSON(t *testing.T) {
|
||||
return c.JSON(data)
|
||||
})
|
||||
|
||||
// Create request with invalid JSON
|
||||
req := httptest.NewRequest("POST", "/test", bytes.NewReader([]byte("invalid json")))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, 400, resp.StatusCode)
|
||||
|
||||
// Parse error response
|
||||
var response map[string]interface{}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
tests.AssertNoError(t, err)
|
||||
err = json.Unmarshal(body, &response)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify error response
|
||||
tests.AssertEqual(t, "Invalid JSON", response["error"])
|
||||
}
|
||||
|
||||
func TestController_UUIDValidation_Success(t *testing.T) {
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
// Test UUID parameter validation
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/test/:id", func(c *fiber.Ctx) error {
|
||||
id := c.Params("id")
|
||||
|
||||
// Validate UUID
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "Invalid UUID"})
|
||||
}
|
||||
@@ -116,40 +99,33 @@ func TestController_UUIDValidation_Success(t *testing.T) {
|
||||
return c.JSON(fiber.Map{"id": id, "valid": true})
|
||||
})
|
||||
|
||||
// Create request with valid UUID
|
||||
validUUID := uuid.New().String()
|
||||
req := httptest.NewRequest("GET", "/test/"+validUUID, nil)
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, 200, resp.StatusCode)
|
||||
|
||||
// Parse response
|
||||
var response map[string]interface{}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
tests.AssertNoError(t, err)
|
||||
err = json.Unmarshal(body, &response)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify response
|
||||
tests.AssertEqual(t, validUUID, response["id"])
|
||||
tests.AssertEqual(t, true, response["valid"])
|
||||
}
|
||||
|
||||
func TestController_UUIDValidation_InvalidUUID(t *testing.T) {
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
// Test handling of invalid UUID
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/test/:id", func(c *fiber.Ctx) error {
|
||||
id := c.Params("id")
|
||||
|
||||
// Validate UUID
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "Invalid UUID"})
|
||||
}
|
||||
@@ -157,32 +133,26 @@ func TestController_UUIDValidation_InvalidUUID(t *testing.T) {
|
||||
return c.JSON(fiber.Map{"id": id, "valid": true})
|
||||
})
|
||||
|
||||
// Create request with invalid UUID
|
||||
req := httptest.NewRequest("GET", "/test/invalid-uuid", nil)
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, 400, resp.StatusCode)
|
||||
|
||||
// Parse error response
|
||||
var response map[string]interface{}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
tests.AssertNoError(t, err)
|
||||
err = json.Unmarshal(body, &response)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify error response
|
||||
tests.AssertEqual(t, "Invalid UUID", response["error"])
|
||||
}
|
||||
|
||||
func TestController_QueryParameters_Success(t *testing.T) {
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
// Test query parameter handling
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/test", func(c *fiber.Ctx) error {
|
||||
@@ -197,34 +167,28 @@ func TestController_QueryParameters_Success(t *testing.T) {
|
||||
})
|
||||
})
|
||||
|
||||
// Create request with query parameters
|
||||
req := httptest.NewRequest("GET", "/test?restart=true&override=false&format=xml", nil)
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, 200, resp.StatusCode)
|
||||
|
||||
// Parse response
|
||||
var response map[string]interface{}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
tests.AssertNoError(t, err)
|
||||
err = json.Unmarshal(body, &response)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify response
|
||||
tests.AssertEqual(t, true, response["restart"])
|
||||
tests.AssertEqual(t, false, response["override"])
|
||||
tests.AssertEqual(t, "xml", response["format"])
|
||||
}
|
||||
|
||||
func TestController_HTTPMethods_Success(t *testing.T) {
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
// Test different HTTP methods
|
||||
app := fiber.New()
|
||||
|
||||
var getCalled, postCalled, putCalled, deleteCalled bool
|
||||
@@ -249,28 +213,24 @@ func TestController_HTTPMethods_Success(t *testing.T) {
|
||||
return c.JSON(fiber.Map{"method": "DELETE"})
|
||||
})
|
||||
|
||||
// Test GET
|
||||
req := httptest.NewRequest("GET", "/test", nil)
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, 200, resp.StatusCode)
|
||||
tests.AssertEqual(t, true, getCalled)
|
||||
|
||||
// Test POST
|
||||
req = httptest.NewRequest("POST", "/test", nil)
|
||||
resp, err = app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, 200, resp.StatusCode)
|
||||
tests.AssertEqual(t, true, postCalled)
|
||||
|
||||
// Test PUT
|
||||
req = httptest.NewRequest("PUT", "/test", nil)
|
||||
resp, err = app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, 200, resp.StatusCode)
|
||||
tests.AssertEqual(t, true, putCalled)
|
||||
|
||||
// Test DELETE
|
||||
req = httptest.NewRequest("DELETE", "/test", nil)
|
||||
resp, err = app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
@@ -279,12 +239,10 @@ func TestController_HTTPMethods_Success(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestController_ErrorHandling_StatusCodes(t *testing.T) {
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
// Test different error status codes
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/400", func(c *fiber.Ctx) error {
|
||||
@@ -307,7 +265,6 @@ func TestController_ErrorHandling_StatusCodes(t *testing.T) {
|
||||
return c.Status(500).JSON(fiber.Map{"error": "Internal Server Error"})
|
||||
})
|
||||
|
||||
// Test different status codes
|
||||
testCases := []struct {
|
||||
path string
|
||||
code int
|
||||
@@ -328,12 +285,10 @@ func TestController_ErrorHandling_StatusCodes(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestController_ConfigurationModel_JSONSerialization(t *testing.T) {
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
// Test Configuration model JSON serialization
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/config", func(c *fiber.Ctx) error {
|
||||
@@ -348,22 +303,18 @@ func TestController_ConfigurationModel_JSONSerialization(t *testing.T) {
|
||||
return c.JSON(config)
|
||||
})
|
||||
|
||||
// Create request
|
||||
req := httptest.NewRequest("GET", "/config", nil)
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, 200, resp.StatusCode)
|
||||
|
||||
// Parse response
|
||||
var response model.Configuration
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
tests.AssertNoError(t, err)
|
||||
err = json.Unmarshal(body, &response)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify response
|
||||
tests.AssertEqual(t, model.IntString(9231), response.UdpPort)
|
||||
tests.AssertEqual(t, model.IntString(9232), response.TcpPort)
|
||||
tests.AssertEqual(t, model.IntString(30), response.MaxConnections)
|
||||
@@ -373,73 +324,61 @@ func TestController_ConfigurationModel_JSONSerialization(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestController_UserModel_JSONSerialization(t *testing.T) {
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
// Test User model JSON serialization (password should be hidden)
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/user", func(c *fiber.Ctx) error {
|
||||
user := &model.User{
|
||||
ID: uuid.New(),
|
||||
Username: "testuser",
|
||||
Password: "secret-password", // Should not appear in JSON
|
||||
Password: "secret-password",
|
||||
RoleID: uuid.New(),
|
||||
}
|
||||
return c.JSON(user)
|
||||
})
|
||||
|
||||
// Create request
|
||||
req := httptest.NewRequest("GET", "/user", nil)
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, 200, resp.StatusCode)
|
||||
|
||||
// Parse response as raw JSON to check password is excluded
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify password field is not in JSON
|
||||
if bytes.Contains(body, []byte("password")) || bytes.Contains(body, []byte("secret-password")) {
|
||||
t.Fatal("Password should not be included in JSON response")
|
||||
}
|
||||
|
||||
// Verify other fields are present
|
||||
if !bytes.Contains(body, []byte("username")) || !bytes.Contains(body, []byte("testuser")) {
|
||||
t.Fatal("Username should be included in JSON response")
|
||||
}
|
||||
}
|
||||
|
||||
func TestController_MiddlewareChaining_Success(t *testing.T) {
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
// Test middleware chaining
|
||||
app := fiber.New()
|
||||
|
||||
var middleware1Called, middleware2Called, handlerCalled bool
|
||||
|
||||
// Middleware 1
|
||||
middleware1 := func(c *fiber.Ctx) error {
|
||||
middleware1Called = true
|
||||
c.Locals("middleware1", "executed")
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
// Middleware 2
|
||||
middleware2 := func(c *fiber.Ctx) error {
|
||||
middleware2Called = true
|
||||
c.Locals("middleware2", "executed")
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
// Handler
|
||||
handler := func(c *fiber.Ctx) error {
|
||||
handlerCalled = true
|
||||
return c.JSON(fiber.Map{
|
||||
@@ -451,27 +390,22 @@ func TestController_MiddlewareChaining_Success(t *testing.T) {
|
||||
|
||||
app.Get("/test", middleware1, middleware2, handler)
|
||||
|
||||
// Create request
|
||||
req := httptest.NewRequest("GET", "/test", nil)
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, 200, resp.StatusCode)
|
||||
|
||||
// Verify all were called
|
||||
tests.AssertEqual(t, true, middleware1Called)
|
||||
tests.AssertEqual(t, true, middleware2Called)
|
||||
tests.AssertEqual(t, true, handlerCalled)
|
||||
|
||||
// Parse response
|
||||
var response map[string]interface{}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
tests.AssertNoError(t, err)
|
||||
err = json.Unmarshal(body, &response)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify middleware values were passed
|
||||
tests.AssertEqual(t, "executed", response["middleware1"])
|
||||
tests.AssertEqual(t, "executed", response["middleware2"])
|
||||
tests.AssertEqual(t, "executed", response["handler"])
|
||||
|
||||
@@ -11,27 +11,20 @@ import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// MockMiddleware simulates authentication for testing purposes
|
||||
type MockMiddleware struct{}
|
||||
|
||||
// GetTestAuthMiddleware returns a mock auth middleware that can be used in place of the real one
|
||||
// This works because we're adding real authentication tokens to requests
|
||||
func GetTestAuthMiddleware(ms *service.MembershipService, cache *cache.InMemoryCache) *middleware.AuthMiddleware {
|
||||
// Use environment JWT secrets for consistency with token generation
|
||||
jwtSecret := os.Getenv("JWT_SECRET")
|
||||
if jwtSecret == "" {
|
||||
jwtSecret = "test-secret-that-is-at-least-32-bytes-long-for-security"
|
||||
}
|
||||
|
||||
|
||||
jwtHandler := jwt.NewJWTHandler(jwtSecret)
|
||||
openJWTHandler := jwt.NewOpenJWTHandler(jwtSecret) // Use same secret for test consistency
|
||||
|
||||
// Cast our mock to the real type for testing
|
||||
// This is a type-unsafe cast but works for testing because we're using real JWT tokens
|
||||
openJWTHandler := jwt.NewOpenJWTHandler(jwtSecret)
|
||||
|
||||
return middleware.NewAuthMiddleware(ms, cache, jwtHandler, openJWTHandler)
|
||||
}
|
||||
|
||||
// AddAuthToRequest adds a valid authentication token to a test request
|
||||
func AddAuthToRequest(req *fiber.Ctx) {
|
||||
token := tests.MustGenerateTestToken()
|
||||
req.Request().Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
@@ -23,13 +23,11 @@ import (
|
||||
)
|
||||
|
||||
func TestStateHistoryController_GetAll_Success(t *testing.T) {
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
app := fiber.New()
|
||||
// No need for DisableAuthentication, we'll use real auth tokens
|
||||
repo := repository.NewStateHistoryRepository(helper.DB)
|
||||
stateHistoryService := service.NewStateHistoryService(repo)
|
||||
|
||||
@@ -44,33 +42,26 @@ func TestStateHistoryController_GetAll_Success(t *testing.T) {
|
||||
|
||||
inMemCache := cache.NewInMemoryCache()
|
||||
|
||||
// Insert test data
|
||||
testData := testdata.NewStateHistoryTestData(helper.TestData.ServerID)
|
||||
history := testData.CreateStateHistory(model.SessionPractice, "spa", 5, uuid.New())
|
||||
err := repo.Insert(helper.CreateContext(), &history)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Setup routes
|
||||
routeGroups := &common.RouteGroups{
|
||||
StateHistory: app.Group("/api/v1/state-history"),
|
||||
}
|
||||
|
||||
// Use a test auth middleware that works with the DisableAuthentication
|
||||
controller.NewStateHistoryController(stateHistoryService, routeGroups, GetTestAuthMiddleware(membershipService, inMemCache))
|
||||
|
||||
// Create request with authentication
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/state-history?id=%s", helper.TestData.ServerID.String()), nil)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+tests.MustGenerateTestToken())
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify response
|
||||
tests.AssertEqual(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
// Parse response body
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
@@ -83,13 +74,11 @@ func TestStateHistoryController_GetAll_Success(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStateHistoryController_GetAll_WithSessionFilter(t *testing.T) {
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
app := fiber.New()
|
||||
// Using real JWT auth with tokens
|
||||
repo := repository.NewStateHistoryRepository(helper.DB)
|
||||
stateHistoryService := service.NewStateHistoryService(repo)
|
||||
|
||||
@@ -104,7 +93,6 @@ func TestStateHistoryController_GetAll_WithSessionFilter(t *testing.T) {
|
||||
|
||||
inMemCache := cache.NewInMemoryCache()
|
||||
|
||||
// Insert test data with different sessions
|
||||
testData := testdata.NewStateHistoryTestData(helper.TestData.ServerID)
|
||||
|
||||
practiceHistory := testData.CreateStateHistory(model.SessionPractice, "spa", 5, uuid.New())
|
||||
@@ -115,27 +103,21 @@ func TestStateHistoryController_GetAll_WithSessionFilter(t *testing.T) {
|
||||
err = repo.Insert(helper.CreateContext(), &raceHistory)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Setup routes
|
||||
routeGroups := &common.RouteGroups{
|
||||
StateHistory: app.Group("/api/v1/state-history"),
|
||||
}
|
||||
|
||||
// Use a test auth middleware that works with the DisableAuthentication
|
||||
controller.NewStateHistoryController(stateHistoryService, routeGroups, GetTestAuthMiddleware(membershipService, inMemCache))
|
||||
|
||||
// Create request with session filter and authentication
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/state-history?id=%s&session=R", helper.TestData.ServerID.String()), nil)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+tests.MustGenerateTestToken())
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify response
|
||||
tests.AssertEqual(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
// Parse response body
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
@@ -148,13 +130,11 @@ func TestStateHistoryController_GetAll_WithSessionFilter(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStateHistoryController_GetAll_EmptyResult(t *testing.T) {
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
app := fiber.New()
|
||||
// Using real JWT auth with tokens
|
||||
repo := repository.NewStateHistoryRepository(helper.DB)
|
||||
stateHistoryService := service.NewStateHistoryService(repo)
|
||||
|
||||
@@ -169,38 +149,30 @@ func TestStateHistoryController_GetAll_EmptyResult(t *testing.T) {
|
||||
|
||||
inMemCache := cache.NewInMemoryCache()
|
||||
|
||||
// Setup routes
|
||||
routeGroups := &common.RouteGroups{
|
||||
StateHistory: app.Group("/api/v1/state-history"),
|
||||
}
|
||||
|
||||
// Use a test auth middleware that works with the DisableAuthentication
|
||||
controller.NewStateHistoryController(stateHistoryService, routeGroups, GetTestAuthMiddleware(membershipService, inMemCache))
|
||||
|
||||
// Create request with no data and authentication
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/state-history?id=%s", helper.TestData.ServerID.String()), nil)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+tests.MustGenerateTestToken())
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify empty response
|
||||
tests.AssertEqual(t, http.StatusOK, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestStateHistoryController_GetStatistics_Success(t *testing.T) {
|
||||
// Skip this test as it requires more complex setup
|
||||
t.Skip("Skipping test due to UUID validation issues")
|
||||
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
app := fiber.New()
|
||||
// Using real JWT auth with tokens
|
||||
repo := repository.NewStateHistoryRepository(helper.DB)
|
||||
stateHistoryService := service.NewStateHistoryService(repo)
|
||||
|
||||
@@ -215,10 +187,8 @@ func TestStateHistoryController_GetStatistics_Success(t *testing.T) {
|
||||
|
||||
inMemCache := cache.NewInMemoryCache()
|
||||
|
||||
// Insert test data with multiple entries for statistics
|
||||
testData := testdata.NewStateHistoryTestData(helper.TestData.ServerID)
|
||||
|
||||
// Create entries with varying player counts
|
||||
playerCounts := []int{5, 10, 15, 20, 25}
|
||||
entries := testData.CreateMultipleEntries(model.SessionRace, "spa", playerCounts)
|
||||
|
||||
@@ -227,33 +197,26 @@ func TestStateHistoryController_GetStatistics_Success(t *testing.T) {
|
||||
tests.AssertNoError(t, err)
|
||||
}
|
||||
|
||||
// Setup routes
|
||||
routeGroups := &common.RouteGroups{
|
||||
StateHistory: app.Group("/api/v1/state-history"),
|
||||
}
|
||||
|
||||
// Use a test auth middleware that works with the DisableAuthentication
|
||||
controller.NewStateHistoryController(stateHistoryService, routeGroups, GetTestAuthMiddleware(membershipService, inMemCache))
|
||||
|
||||
// Create request with valid serverID UUID
|
||||
validServerID := helper.TestData.ServerID.String()
|
||||
if validServerID == "" {
|
||||
validServerID = uuid.New().String() // Generate a new valid UUID if needed
|
||||
validServerID = uuid.New().String()
|
||||
}
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/state-history/statistics?id=%s", validServerID), nil)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Add Authorization header for testing
|
||||
req.Header.Set("Authorization", "Bearer "+tests.MustGenerateTestToken())
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify response
|
||||
tests.AssertEqual(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
// Parse response body
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
@@ -261,7 +224,6 @@ func TestStateHistoryController_GetStatistics_Success(t *testing.T) {
|
||||
err = json.Unmarshal(body, &stats)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify statistics structure exists (actual calculation is tested in service layer)
|
||||
if stats.PeakPlayers < 0 {
|
||||
t.Error("Expected non-negative peak players")
|
||||
}
|
||||
@@ -274,16 +236,13 @@ func TestStateHistoryController_GetStatistics_Success(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStateHistoryController_GetStatistics_NoData(t *testing.T) {
|
||||
// Skip this test as it requires more complex setup
|
||||
t.Skip("Skipping test due to UUID validation issues")
|
||||
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
app := fiber.New()
|
||||
// Using real JWT auth with tokens
|
||||
repo := repository.NewStateHistoryRepository(helper.DB)
|
||||
stateHistoryService := service.NewStateHistoryService(repo)
|
||||
|
||||
@@ -298,33 +257,26 @@ func TestStateHistoryController_GetStatistics_NoData(t *testing.T) {
|
||||
|
||||
inMemCache := cache.NewInMemoryCache()
|
||||
|
||||
// Setup routes
|
||||
routeGroups := &common.RouteGroups{
|
||||
StateHistory: app.Group("/api/v1/state-history"),
|
||||
}
|
||||
|
||||
// Use a test auth middleware that works with the DisableAuthentication
|
||||
controller.NewStateHistoryController(stateHistoryService, routeGroups, GetTestAuthMiddleware(membershipService, inMemCache))
|
||||
|
||||
// Create request with valid serverID UUID
|
||||
validServerID := helper.TestData.ServerID.String()
|
||||
if validServerID == "" {
|
||||
validServerID = uuid.New().String() // Generate a new valid UUID if needed
|
||||
validServerID = uuid.New().String()
|
||||
}
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/state-history/statistics?id=%s", validServerID), nil)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Add Authorization header for testing
|
||||
req.Header.Set("Authorization", "Bearer "+tests.MustGenerateTestToken())
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify response
|
||||
tests.AssertEqual(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
// Parse response body
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
@@ -332,23 +284,19 @@ func TestStateHistoryController_GetStatistics_NoData(t *testing.T) {
|
||||
err = json.Unmarshal(body, &stats)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify empty statistics
|
||||
tests.AssertEqual(t, 0, stats.PeakPlayers)
|
||||
tests.AssertEqual(t, 0.0, stats.AveragePlayers)
|
||||
tests.AssertEqual(t, 0, stats.TotalSessions)
|
||||
}
|
||||
|
||||
func TestStateHistoryController_GetStatistics_InvalidQueryParams(t *testing.T) {
|
||||
// Skip this test as it requires more complex setup
|
||||
t.Skip("Skipping test due to UUID validation issues")
|
||||
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
app := fiber.New()
|
||||
// Using real JWT auth with tokens
|
||||
repo := repository.NewStateHistoryRepository(helper.DB)
|
||||
stateHistoryService := service.NewStateHistoryService(repo)
|
||||
|
||||
@@ -363,42 +311,34 @@ func TestStateHistoryController_GetStatistics_InvalidQueryParams(t *testing.T) {
|
||||
|
||||
inMemCache := cache.NewInMemoryCache()
|
||||
|
||||
// Setup routes
|
||||
routeGroups := &common.RouteGroups{
|
||||
StateHistory: app.Group("/api/v1/state-history"),
|
||||
}
|
||||
|
||||
// Use a test auth middleware that works with the DisableAuthentication
|
||||
controller.NewStateHistoryController(stateHistoryService, routeGroups, GetTestAuthMiddleware(membershipService, inMemCache))
|
||||
|
||||
// Create request with invalid query parameters but with valid UUID
|
||||
validServerID := helper.TestData.ServerID.String()
|
||||
if validServerID == "" {
|
||||
validServerID = uuid.New().String() // Generate a new valid UUID if needed
|
||||
validServerID = uuid.New().String()
|
||||
}
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/state-history/statistics?id=%s&min_players=invalid", validServerID), nil)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Add Authorization header for testing
|
||||
req.Header.Set("Authorization", "Bearer "+tests.MustGenerateTestToken())
|
||||
|
||||
// Execute request
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify error response
|
||||
tests.AssertEqual(t, http.StatusBadRequest, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestStateHistoryController_HTTPMethods(t *testing.T) {
|
||||
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
app := fiber.New()
|
||||
// Using real JWT auth with tokens
|
||||
repo := repository.NewStateHistoryRepository(helper.DB)
|
||||
stateHistoryService := service.NewStateHistoryService(repo)
|
||||
|
||||
@@ -413,36 +353,30 @@ func TestStateHistoryController_HTTPMethods(t *testing.T) {
|
||||
|
||||
inMemCache := cache.NewInMemoryCache()
|
||||
|
||||
// Setup routes
|
||||
routeGroups := &common.RouteGroups{
|
||||
StateHistory: app.Group("/api/v1/state-history"),
|
||||
}
|
||||
|
||||
// Use a test auth middleware that works with the DisableAuthentication
|
||||
controller.NewStateHistoryController(stateHistoryService, routeGroups, GetTestAuthMiddleware(membershipService, inMemCache))
|
||||
|
||||
// Test that only GET method is allowed for GetAll
|
||||
req := httptest.NewRequest("POST", fmt.Sprintf("/api/v1/state-history?id=%s", helper.TestData.ServerID.String()), nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tests.MustGenerateTestToken())
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, http.StatusMethodNotAllowed, resp.StatusCode)
|
||||
|
||||
// Test that only GET method is allowed for GetStatistics
|
||||
req = httptest.NewRequest("POST", fmt.Sprintf("/api/v1/state-history/statistics?id=%s", helper.TestData.ServerID.String()), nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tests.MustGenerateTestToken())
|
||||
resp, err = app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, http.StatusMethodNotAllowed, resp.StatusCode)
|
||||
|
||||
// Test that PUT method is not allowed
|
||||
req = httptest.NewRequest("PUT", fmt.Sprintf("/api/v1/state-history?id=%s", helper.TestData.ServerID.String()), nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tests.MustGenerateTestToken())
|
||||
resp, err = app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
tests.AssertEqual(t, http.StatusMethodNotAllowed, resp.StatusCode)
|
||||
|
||||
// Test that DELETE method is not allowed
|
||||
req = httptest.NewRequest("DELETE", fmt.Sprintf("/api/v1/state-history?id=%s", helper.TestData.ServerID.String()), nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tests.MustGenerateTestToken())
|
||||
resp, err = app.Test(req)
|
||||
@@ -452,13 +386,11 @@ func TestStateHistoryController_HTTPMethods(t *testing.T) {
|
||||
|
||||
func TestStateHistoryController_ContentType(t *testing.T) {
|
||||
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
app := fiber.New()
|
||||
// Using real JWT auth with tokens
|
||||
repo := repository.NewStateHistoryRepository(helper.DB)
|
||||
stateHistoryService := service.NewStateHistoryService(repo)
|
||||
|
||||
@@ -473,43 +405,36 @@ func TestStateHistoryController_ContentType(t *testing.T) {
|
||||
|
||||
inMemCache := cache.NewInMemoryCache()
|
||||
|
||||
// Insert test data
|
||||
testData := testdata.NewStateHistoryTestData(helper.TestData.ServerID)
|
||||
history := testData.CreateStateHistory(model.SessionPractice, "spa", 5, uuid.New())
|
||||
err := repo.Insert(helper.CreateContext(), &history)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Setup routes
|
||||
routeGroups := &common.RouteGroups{
|
||||
StateHistory: app.Group("/api/v1/state-history"),
|
||||
}
|
||||
|
||||
// Use a test auth middleware that works with the DisableAuthentication
|
||||
controller.NewStateHistoryController(stateHistoryService, routeGroups, GetTestAuthMiddleware(membershipService, inMemCache))
|
||||
|
||||
// Test GetAll endpoint with authentication
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/state-history?id=%s", helper.TestData.ServerID.String()), nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tests.MustGenerateTestToken())
|
||||
resp, err := app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify content type is JSON
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
if contentType != "application/json" {
|
||||
t.Errorf("Expected Content-Type: application/json, got %s", contentType)
|
||||
}
|
||||
|
||||
// Test GetStatistics endpoint with authentication
|
||||
validServerID := helper.TestData.ServerID.String()
|
||||
if validServerID == "" {
|
||||
validServerID = uuid.New().String() // Generate a new valid UUID if needed
|
||||
validServerID = uuid.New().String()
|
||||
}
|
||||
req = httptest.NewRequest("GET", fmt.Sprintf("/api/v1/state-history/statistics?id=%s", validServerID), nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tests.MustGenerateTestToken())
|
||||
resp, err = app.Test(req)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Verify content type is JSON
|
||||
contentType = resp.Header.Get("Content-Type")
|
||||
if contentType != "application/json" {
|
||||
t.Errorf("Expected Content-Type: application/json, got %s", contentType)
|
||||
@@ -517,16 +442,13 @@ func TestStateHistoryController_ContentType(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStateHistoryController_ResponseStructure(t *testing.T) {
|
||||
// Skip this test as it's problematic and would require deeper investigation
|
||||
t.Skip("Skipping test due to response structure issues that need further investigation")
|
||||
|
||||
// Setup environment and test helper
|
||||
tests.SetTestEnv()
|
||||
helper := tests.NewTestHelper(t)
|
||||
defer helper.Cleanup()
|
||||
|
||||
app := fiber.New()
|
||||
// Using real JWT auth with tokens
|
||||
repo := repository.NewStateHistoryRepository(helper.DB)
|
||||
stateHistoryService := service.NewStateHistoryService(repo)
|
||||
|
||||
@@ -541,7 +463,6 @@ func TestStateHistoryController_ResponseStructure(t *testing.T) {
|
||||
|
||||
inMemCache := cache.NewInMemoryCache()
|
||||
|
||||
// Ensure the state_histories table exists
|
||||
if !helper.DB.Migrator().HasTable(&model.StateHistory{}) {
|
||||
err := helper.DB.Migrator().CreateTable(&model.StateHistory{})
|
||||
if err != nil {
|
||||
@@ -549,21 +470,17 @@ func TestStateHistoryController_ResponseStructure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Insert test data
|
||||
testData := testdata.NewStateHistoryTestData(helper.TestData.ServerID)
|
||||
history := testData.CreateStateHistory(model.SessionPractice, "spa", 5, uuid.New())
|
||||
err := repo.Insert(helper.CreateContext(), &history)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Setup routes
|
||||
routeGroups := &common.RouteGroups{
|
||||
StateHistory: app.Group("/api/v1/state-history"),
|
||||
}
|
||||
|
||||
// Use a test auth middleware that works with the DisableAuthentication
|
||||
controller.NewStateHistoryController(stateHistoryService, routeGroups, GetTestAuthMiddleware(membershipService, inMemCache))
|
||||
|
||||
// Test GetAll response structure with authentication
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/state-history?id=%s", helper.TestData.ServerID.String()), nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tests.MustGenerateTestToken())
|
||||
resp, err := app.Test(req)
|
||||
@@ -572,24 +489,19 @@ func TestStateHistoryController_ResponseStructure(t *testing.T) {
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
tests.AssertNoError(t, err)
|
||||
|
||||
// Log the actual response for debugging
|
||||
t.Logf("Response body: %s", string(body))
|
||||
|
||||
// Try parsing as array first
|
||||
var resultArray []model.StateHistory
|
||||
err = json.Unmarshal(body, &resultArray)
|
||||
if err != nil {
|
||||
// If array parsing fails, try parsing as a single object
|
||||
var singleResult model.StateHistory
|
||||
err = json.Unmarshal(body, &singleResult)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to parse response as either array or object: %v", err)
|
||||
}
|
||||
// Convert single result to array
|
||||
resultArray = []model.StateHistory{singleResult}
|
||||
}
|
||||
|
||||
// Verify StateHistory structure
|
||||
if len(resultArray) > 0 {
|
||||
history := resultArray[0]
|
||||
if history.ID == uuid.Nil {
|
||||
|
||||
Reference in New Issue
Block a user