generated from UCLALibrary/service-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
92 lines (74 loc) · 2.51 KB
/
main_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//go:build unit
package main
import (
"flag"
"fmt"
"github.com/UCLALibrary/validation-service/api"
"github.com/UCLALibrary/validation-service/testflags"
"github.com/UCLALibrary/validation-service/validation"
"github.com/UCLALibrary/validation-service/validation/config"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/require"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
// TestMain configures our log level flag for the main package.
func TestMain(m *testing.M) {
flag.Parse()
fmt.Println("TestMain's log level:", *testflags.LogLevel)
os.Exit(m.Run())
}
// TestServerHealth checks if the Echo server initializes properly
func TestServerHealth(t *testing.T) {
// Configure the location of the test profiles file
if err := os.Setenv(config.ProfilesFile, "testdata/test_profiles.json"); err != nil {
t.Fatalf("error setting env PROFILES_FILE: %v", err)
}
defer func() {
err := os.Unsetenv(config.ProfilesFile)
require.NoError(t, err)
}()
engine, err := validation.NewEngine()
assert.NoError(t, err)
service := &Service{Engine: engine}
server := echo.New()
server.Use(config.ZapLoggerMiddleware(engine.GetLogger()))
// Register handlers
api.RegisterHandlers(server, service)
// Perform a simple request to check if the server is functional
req := httptest.NewRequest(http.MethodGet, "/status", nil)
rec := httptest.NewRecorder()
// Serve the request
server.ServeHTTP(rec, req)
// Server should respond with a 200 status
assert.Equal(t, http.StatusOK, rec.Code)
}
// TestStatusEndpoint checks if the /status endpoint returns the expected JSON response
func TestStatusEndpoint(t *testing.T) {
// Configure the location of the test profiles file
if err := os.Setenv(config.ProfilesFile, "testdata/test_profiles.json"); err != nil {
t.Fatalf("error setting env PROFILES_FILE: %v", err)
}
defer func() {
err := os.Unsetenv(config.ProfilesFile)
require.NoError(t, err)
}()
engine, err := validation.NewEngine()
assert.NoError(t, err)
service := &Service{Engine: engine}
server := echo.New()
server.Use(config.ZapLoggerMiddleware(engine.GetLogger()))
// Register handlers
api.RegisterHandlers(server, service)
// Create a test request
request := httptest.NewRequest(http.MethodGet, "/status", nil)
recorder := httptest.NewRecorder()
// Execute request
server.ServeHTTP(recorder, request)
// Assertions
assert.Equal(t, http.StatusOK, recorder.Code)
assert.JSONEq(t, `{"fester":"ok", "filesystem":"ok", "service":"ok"}`, recorder.Body.String())
}