package main import ( "encoding/json" "log" "net/http" "net/http/httptest" "testing" "github.com/spf13/viper" "github.com/stretchr/testify/assert" ) func getTestUserCredentials() (string, string) { viper.SetConfigFile("../.env") viper.AddConfigPath(".") viper.AutomaticEnv() err := viper.ReadInConfig() if err != nil { log.Fatalf("Error while reading config file %s", err) } testUser := viper.GetString("TEST_USER") testPass := viper.GetString("TEST_PASS") return testUser, testPass } func TestAuthRoute(t *testing.T) { router := setupRouter() username, password := getTestUserCredentials() log.Println("username", username) log.Println("password", password) w := httptest.NewRecorder() req, err := http.NewRequest("POST", "/api/v1/auth", nil) if err != nil { t.Fatalf("Failed to create request: %v", err) } req.SetBasicAuth(username, password) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code, "response should return a 200 code") var response map[string]interface{} err = json.Unmarshal(w.Body.Bytes(), &response) if err != nil { t.Fatalf("Failed to unmarshal response: %v", err) } _, exists := response["token"] assert.True(t, exists, "response should return a token") if !exists { t.Fatalf("response did not contain token") } } func TestAuthRouteFailure(t *testing.T) { router := setupRouter() w := httptest.NewRecorder() req, _ := http.NewRequest("POST", "/api/v1/auth", nil) req.SetBasicAuth("asdf", "asdf") router.ServeHTTP(w, req) assert.Equal(t, http.StatusUnauthorized, w.Code, "should return a 401 code") }