init: technical take home for gitlab operate

This commit is contained in:
uhryniuk
2026-01-15 20:18:23 -06:00
commit a9a7e13bbe
149 changed files with 1812 additions and 0 deletions

98
main_test.go Normal file
View File

@@ -0,0 +1,98 @@
package main
import (
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
)
// TestValidateToken ensures the token validation logic works as expected.
func TestValidateToken(t *testing.T) {
tests := []struct {
authHeader string
secret string
want bool
}{
{"Bearer mysecret", "mysecret", true},
{"Bearer wrong", "mysecret", false},
{"mysecret", "mysecret", false},
{"", "mysecret", false},
}
for _, tt := range tests {
if got := validateToken(tt.authHeader, tt.secret); got != tt.want {
t.Errorf("validateToken(%q, %q) = %v, want %v", tt.authHeader, tt.secret, got, tt.want)
}
}
}
// TestConfigLoader_Load tests loading configuration from file and environment variables.
func TestConfigLoader_Load(t *testing.T) {
tests := []struct {
name string
file string
fileData string
envVars map[string]string
wantPort int
wantErr bool
}{
{"defaults", "", "", map[string]string{}, 8080, false},
{"from file", "cfg.json", `{"port":3000}`, map[string]string{}, 3000, false},
{"env override", "cfg.json", `{"port":3000}`, map[string]string{"SERVER_PORT": "9000"}, 9000, false},
{"invalid port", "", "", map[string]string{"SERVER_PORT": "bad"}, 0, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
loader := &ConfigLoader{
readFile: func(string) ([]byte, error) { return []byte(tt.fileData), nil },
getEnv: func(key string) string { return tt.envVars[key] },
}
cfg, err := loader.Load(tt.file)
if (err != nil) != tt.wantErr {
t.Fatalf("Load() error = %v, wantErr %v", err, tt.wantErr)
}
if !tt.wantErr && cfg.Port != tt.wantPort {
t.Errorf("Port = %v, want %v", cfg.Port, tt.wantPort)
}
})
}
}
// TestServer_authMiddleware ensures authentication middleware enforces token validation correctly.
func TestServer_authMiddleware(t *testing.T) {
tests := []struct {
name string
secret string
authHeader string
wantStatus int
}{
{"valid token", "secret", "Bearer secret", http.StatusOK},
{"invalid token", "secret", "Bearer wrong", http.StatusUnauthorized},
{"no secret", "", "", http.StatusOK},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := NewServer(&Config{AuthSecret: tt.secret}, slog.New(slog.NewTextHandler(io.Discard, nil)))
handler := server.authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
req := httptest.NewRequest(http.MethodGet, "/api/test", nil)
if tt.authHeader != "" {
req.Header.Set("Authorization", tt.authHeader)
}
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != tt.wantStatus {
t.Errorf("status = %v, want %v", rr.Code, tt.wantStatus)
}
})
}
}