Files
acc-server-manager/tests/unit/controller/config_controller_test.go.disabled
Fran Jurmanović 44acb170a7 add tests
2025-07-07 01:40:19 +02:00

548 lines
15 KiB
Plaintext

package controller
import (
"acc-server-manager/local/controller"
"acc-server-manager/local/model"
"acc-server-manager/local/service"
"acc-server-manager/local/utl/common"
"acc-server-manager/tests"
"bytes"
"encoding/json"
"io"
"net/http/httptest"
"testing"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
)
func TestConfigController_GetConfig_Success(t *testing.T) {
// Setup
helper := tests.NewTestHelper(t)
defer helper.Cleanup()
// Create mock services
mockConfigService := &MockConfigService{}
mockApiService := &MockApiService{}
// Setup expected response
expectedConfig := &model.Configuration{
UdpPort: model.IntString(9231),
TcpPort: model.IntString(9232),
MaxConnections: model.IntString(30),
LanDiscovery: model.IntString(1),
RegisterToLobby: model.IntString(1),
ConfigVersion: model.IntString(1),
}
mockConfigService.getConfigResponse = expectedConfig
// Create Fiber app with controller
app := fiber.New()
routeGroups := &common.RouteGroups{
Config: app.Group("/config"),
}
mockAuth := &MockAuthMiddleware{}
controller.NewConfigController(mockConfigService, routeGroups, mockApiService, mockAuth)
// Create test request
serverID := uuid.New().String()
req := httptest.NewRequest("GET", "/config/configuration.json", nil)
req.Header.Set("Content-Type", "application/json")
// Mock authentication
mockAuth.authenticated = true
// 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, expectedConfig.UdpPort, response.UdpPort)
tests.AssertEqual(t, expectedConfig.TcpPort, response.TcpPort)
tests.AssertEqual(t, expectedConfig.MaxConnections, response.MaxConnections)
}
func TestConfigController_GetConfig_Unauthorized(t *testing.T) {
// Setup
helper := tests.NewTestHelper(t)
defer helper.Cleanup()
// Create mock services
mockConfigService := &MockConfigService{}
mockApiService := &MockApiService{}
// Create Fiber app with controller
app := fiber.New()
routeGroups := &common.RouteGroups{
Config: app.Group("/config"),
}
mockAuth := &MockAuthMiddleware{}
controller.NewConfigController(mockConfigService, routeGroups, mockApiService, mockAuth)
// Create test request
req := httptest.NewRequest("GET", "/config/configuration.json", nil)
req.Header.Set("Content-Type", "application/json")
// Mock authentication failure
mockAuth.authenticated = false
// Execute request
resp, err := app.Test(req)
tests.AssertNoError(t, err)
tests.AssertEqual(t, 401, resp.StatusCode)
}
func TestConfigController_GetConfig_ServiceError(t *testing.T) {
// Setup
helper := tests.NewTestHelper(t)
defer helper.Cleanup()
// Create mock services
mockConfigService := &MockConfigService{}
mockApiService := &MockApiService{}
// Setup service error
mockConfigService.shouldFailGet = true
// Create Fiber app with controller
app := fiber.New()
routeGroups := &common.RouteGroups{
Config: app.Group("/config"),
}
mockAuth := &MockAuthMiddleware{}
controller.NewConfigController(mockConfigService, routeGroups, mockApiService, mockAuth)
// Create test request
req := httptest.NewRequest("GET", "/config/configuration.json", nil)
req.Header.Set("Content-Type", "application/json")
// Mock authentication
mockAuth.authenticated = true
// Execute request
resp, err := app.Test(req)
tests.AssertNoError(t, err)
tests.AssertEqual(t, 500, resp.StatusCode)
}
func TestConfigController_UpdateConfig_Success(t *testing.T) {
// Setup
helper := tests.NewTestHelper(t)
defer helper.Cleanup()
// Create mock services
mockConfigService := &MockConfigService{}
mockApiService := &MockApiService{}
// Setup expected response
expectedConfig := &model.Config{
ID: uuid.New(),
ServerID: uuid.New(),
ConfigFile: "configuration.json",
OldConfig: `{"udpPort": "9231"}`,
NewConfig: `{"udpPort": "9999"}`,
}
mockConfigService.updateConfigResponse = expectedConfig
// Create Fiber app with controller
app := fiber.New()
routeGroups := &common.RouteGroups{
Config: app.Group("/config/:id"),
}
mockAuth := &MockAuthMiddleware{}
controller.NewConfigController(mockConfigService, routeGroups, mockApiService, mockAuth)
// Prepare request body
updateData := map[string]interface{}{
"udpPort": "9999",
"tcpPort": "10000",
}
bodyBytes, err := json.Marshal(updateData)
tests.AssertNoError(t, err)
// Create test request
serverID := uuid.New().String()
req := httptest.NewRequest("PUT", "/config/"+serverID+"/configuration.json", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
// Mock authentication
mockAuth.authenticated = true
// Execute request
resp, err := app.Test(req)
tests.AssertNoError(t, err)
tests.AssertEqual(t, 200, resp.StatusCode)
// Parse response
var response model.Config
body, err := io.ReadAll(resp.Body)
tests.AssertNoError(t, err)
err = json.Unmarshal(body, &response)
tests.AssertNoError(t, err)
// Verify response
tests.AssertEqual(t, expectedConfig.ConfigFile, response.ConfigFile)
tests.AssertEqual(t, expectedConfig.OldConfig, response.OldConfig)
tests.AssertEqual(t, expectedConfig.NewConfig, response.NewConfig)
// Verify service was called with correct data
tests.AssertEqual(t, true, mockConfigService.updateConfigCalled)
}
func TestConfigController_UpdateConfig_WithRestart(t *testing.T) {
// Setup
helper := tests.NewTestHelper(t)
defer helper.Cleanup()
// Create mock services
mockConfigService := &MockConfigService{}
mockApiService := &MockApiService{}
// Setup expected response
expectedConfig := &model.Config{
ID: uuid.New(),
ServerID: uuid.New(),
ConfigFile: "configuration.json",
OldConfig: `{"udpPort": "9231"}`,
NewConfig: `{"udpPort": "9999"}`,
}
mockConfigService.updateConfigResponse = expectedConfig
// Create Fiber app with controller
app := fiber.New()
routeGroups := &common.RouteGroups{
Config: app.Group("/config/:id"),
}
mockAuth := &MockAuthMiddleware{}
controller.NewConfigController(mockConfigService, routeGroups, mockApiService, mockAuth)
// Prepare request body
updateData := map[string]interface{}{
"udpPort": "9999",
}
bodyBytes, err := json.Marshal(updateData)
tests.AssertNoError(t, err)
// Create test request with restart parameter
serverID := uuid.New().String()
req := httptest.NewRequest("PUT", "/config/"+serverID+"/configuration.json?restart=true", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
// Mock authentication
mockAuth.authenticated = true
// Execute request
resp, err := app.Test(req)
tests.AssertNoError(t, err)
tests.AssertEqual(t, 200, resp.StatusCode)
// Verify both services were called
tests.AssertEqual(t, true, mockConfigService.updateConfigCalled)
tests.AssertEqual(t, true, mockApiService.restartServerCalled)
}
func TestConfigController_UpdateConfig_InvalidUUID(t *testing.T) {
// Setup
helper := tests.NewTestHelper(t)
defer helper.Cleanup()
// Create mock services
mockConfigService := &MockConfigService{}
mockApiService := &MockApiService{}
// Create Fiber app with controller
app := fiber.New()
routeGroups := &common.RouteGroups{
Config: app.Group("/config/:id"),
}
mockAuth := &MockAuthMiddleware{}
controller.NewConfigController(mockConfigService, routeGroups, mockApiService, mockAuth)
// Prepare request body
updateData := map[string]interface{}{
"udpPort": "9999",
}
bodyBytes, err := json.Marshal(updateData)
tests.AssertNoError(t, err)
// Create test request with invalid UUID
req := httptest.NewRequest("PUT", "/config/invalid-uuid/configuration.json", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
// Mock authentication
mockAuth.authenticated = true
// Execute request
resp, err := app.Test(req)
tests.AssertNoError(t, err)
tests.AssertEqual(t, 400, resp.StatusCode)
// Verify service was not called
tests.AssertEqual(t, false, mockConfigService.updateConfigCalled)
}
func TestConfigController_UpdateConfig_InvalidJSON(t *testing.T) {
// Setup
helper := tests.NewTestHelper(t)
defer helper.Cleanup()
// Create mock services
mockConfigService := &MockConfigService{}
mockApiService := &MockApiService{}
// Create Fiber app with controller
app := fiber.New()
routeGroups := &common.RouteGroups{
Config: app.Group("/config/:id"),
}
mockAuth := &MockAuthMiddleware{}
controller.NewConfigController(mockConfigService, routeGroups, mockApiService, mockAuth)
// Create test request with invalid JSON
serverID := uuid.New().String()
req := httptest.NewRequest("PUT", "/config/"+serverID+"/configuration.json", bytes.NewReader([]byte("invalid json")))
req.Header.Set("Content-Type", "application/json")
// Mock authentication
mockAuth.authenticated = true
// Execute request
resp, err := app.Test(req)
tests.AssertNoError(t, err)
tests.AssertEqual(t, 400, resp.StatusCode)
// Verify service was not called
tests.AssertEqual(t, false, mockConfigService.updateConfigCalled)
}
func TestConfigController_UpdateConfig_ServiceError(t *testing.T) {
// Setup
helper := tests.NewTestHelper(t)
defer helper.Cleanup()
// Create mock services
mockConfigService := &MockConfigService{}
mockApiService := &MockApiService{}
// Setup service error
mockConfigService.shouldFailUpdate = true
// Create Fiber app with controller
app := fiber.New()
routeGroups := &common.RouteGroups{
Config: app.Group("/config/:id"),
}
mockAuth := &MockAuthMiddleware{}
controller.NewConfigController(mockConfigService, routeGroups, mockApiService, mockAuth)
// Prepare request body
updateData := map[string]interface{}{
"udpPort": "9999",
}
bodyBytes, err := json.Marshal(updateData)
tests.AssertNoError(t, err)
// Create test request
serverID := uuid.New().String()
req := httptest.NewRequest("PUT", "/config/"+serverID+"/configuration.json", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
// Mock authentication
mockAuth.authenticated = true
// Execute request
resp, err := app.Test(req)
tests.AssertNoError(t, err)
tests.AssertEqual(t, 500, resp.StatusCode)
// Verify service was called
tests.AssertEqual(t, true, mockConfigService.updateConfigCalled)
}
func TestConfigController_GetConfigs_Success(t *testing.T) {
// Setup
helper := tests.NewTestHelper(t)
defer helper.Cleanup()
// Create mock services
mockConfigService := &MockConfigService{}
mockApiService := &MockApiService{}
// Setup expected response
expectedConfigs := &model.Configurations{
Configuration: model.Configuration{
UdpPort: model.IntString(9231),
TcpPort: model.IntString(9232),
},
Settings: model.ServerSettings{
ServerName: "Test Server",
},
Event: model.EventConfig{
Track: "spa",
},
}
mockConfigService.getConfigsResponse = expectedConfigs
// Create Fiber app with controller
app := fiber.New()
routeGroups := &common.RouteGroups{
Config: app.Group("/config"),
}
mockAuth := &MockAuthMiddleware{}
controller.NewConfigController(mockConfigService, routeGroups, mockApiService, mockAuth)
// Create test request
req := httptest.NewRequest("GET", "/config/", nil)
req.Header.Set("Content-Type", "application/json")
// Mock authentication
mockAuth.authenticated = true
// Execute request
resp, err := app.Test(req)
tests.AssertNoError(t, err)
tests.AssertEqual(t, 200, resp.StatusCode)
// Parse response
var response model.Configurations
body, err := io.ReadAll(resp.Body)
tests.AssertNoError(t, err)
err = json.Unmarshal(body, &response)
tests.AssertNoError(t, err)
// Verify response
tests.AssertEqual(t, expectedConfigs.Configuration.UdpPort, response.Configuration.UdpPort)
tests.AssertEqual(t, expectedConfigs.Settings.ServerName, response.Settings.ServerName)
tests.AssertEqual(t, expectedConfigs.Event.Track, response.Event.Track)
}
// MockConfigService implements the ConfigService interface for testing
type MockConfigService struct {
getConfigResponse interface{}
getConfigsResponse *model.Configurations
updateConfigResponse *model.Config
shouldFailGet bool
shouldFailUpdate bool
getConfigCalled bool
getConfigsCalled bool
updateConfigCalled bool
}
func (m *MockConfigService) GetConfig(c *fiber.Ctx) (interface{}, error) {
m.getConfigCalled = true
if m.shouldFailGet {
return nil, tests.ErrorForTesting("service error")
}
return m.getConfigResponse, nil
}
func (m *MockConfigService) GetConfigs(c *fiber.Ctx) (*model.Configurations, error) {
m.getConfigsCalled = true
if m.shouldFailGet {
return nil, tests.ErrorForTesting("service error")
}
return m.getConfigsResponse, nil
}
func (m *MockConfigService) UpdateConfig(c *fiber.Ctx, body *map[string]interface{}) (*model.Config, error) {
m.updateConfigCalled = true
if m.shouldFailUpdate {
return nil, tests.ErrorForTesting("service error")
}
return m.updateConfigResponse, nil
}
// Additional methods that might be needed by the service interface
func (m *MockConfigService) LoadConfigs(server *model.Server) (*model.Configurations, error) {
return m.getConfigsResponse, nil
}
func (m *MockConfigService) GetConfiguration(server *model.Server) (*model.Configuration, error) {
if config, ok := m.getConfigResponse.(*model.Configuration); ok {
return config, nil
}
return nil, tests.ErrorForTesting("type assertion failed")
}
func (m *MockConfigService) GetEventConfig(server *model.Server) (*model.EventConfig, error) {
if config, ok := m.getConfigResponse.(*model.EventConfig); ok {
return config, nil
}
return nil, tests.ErrorForTesting("type assertion failed")
}
func (m *MockConfigService) SaveConfiguration(server *model.Server, config *model.Configuration) error {
return nil
}
func (m *MockConfigService) SetServerService(serverService *service.ServerService) {
// Mock implementation
}
// MockApiService implements the ApiService interface for testing
type MockApiService struct {
restartServerCalled bool
shouldFailRestart bool
}
func (m *MockApiService) ApiRestartServer(c *fiber.Ctx) (interface{}, error) {
m.restartServerCalled = true
if m.shouldFailRestart {
return nil, tests.ErrorForTesting("restart failed")
}
return fiber.Map{"message": "server restarted"}, nil
}
// MockAuthMiddleware implements the AuthMiddleware interface for testing
type MockAuthMiddleware struct {
authenticated bool
hasPermission bool
}
func (m *MockAuthMiddleware) Authenticate(c *fiber.Ctx) error {
if !m.authenticated {
return c.Status(401).JSON(fiber.Map{"error": "Unauthorized"})
}
return c.Next()
}
func (m *MockAuthMiddleware) HasPermission(permission string) fiber.Handler {
return func(c *fiber.Ctx) error {
if !m.authenticated {
return c.Status(401).JSON(fiber.Map{"error": "Unauthorized"})
}
if !m.hasPermission {
return c.Status(403).JSON(fiber.Map{"error": "Forbidden"})
}
return c.Next()
}
}
func (m *MockAuthMiddleware) AuthRateLimit() fiber.Handler {
return func(c *fiber.Ctx) error {
return c.Next()
}
}
func (m *MockAuthMiddleware) RequireHTTPS() fiber.Handler {
return func(c *fiber.Ctx) error {
return c.Next()
}
}
func (m *MockAuthMiddleware) InvalidateUserPermissions(userID string) {
// Mock implementation
}
func (m *MockAuthMiddleware) InvalidateAllUserPermissions() {
// Mock implementation
}