diff --git a/daytrader-go/internal/features/auth/auth_test.go b/daytrader-go/internal/features/auth/auth_test.go new file mode 100644 index 0000000..8611c71 --- /dev/null +++ b/daytrader-go/internal/features/auth/auth_test.go @@ -0,0 +1,283 @@ +package auth + +import ( + "context" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/cookiejar" + "net/http/httptest" + "net/url" + "os" + "strings" + "testing" + "time" + + "github.com/Cognition-Partner-Workshops/uc-java-ee-6-modernization/daytrader-go/internal/config" + "github.com/Cognition-Partner-Workshops/uc-java-ee-6-modernization/daytrader-go/internal/store" + "github.com/Cognition-Partner-Workshops/uc-java-ee-6-modernization/daytrader-go/internal/web" +) + +func newApp(t *testing.T, db *store.Store) *web.App { + t.Helper() + cfg, err := config.FromEnv(func(string) (string, bool) { return "", false }) + if err != nil { + t.Fatal(err) + } + app, err := web.New(cfg, db, slog.New(slog.NewTextHandler(io.Discard, nil))) + if err != nil { + t.Fatal(err) + } + return app +} + +// testStore connects to the PostgreSQL from `make go-db`; tests that need it are skipped without it. +func testStore(t *testing.T) *store.Store { + t.Helper() + databaseURL := os.Getenv("DATABASE_URL") + if databaseURL == "" { + databaseURL = "postgres://daytrader:daytrader@localhost:55432/daytrader?sslmode=disable" + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + db, err := store.Open(ctx, databaseURL, 4, 1000) + if err != nil { + t.Skipf("PostgreSQL not available (%v); run make go-seed", err) + } + var table *string + if err := db.Pool.QueryRow(ctx, "SELECT to_regclass('accountejb')::text").Scan(&table); err != nil || table == nil { + db.Close() + t.Skip("schema not created; run make go-seed") + } + t.Cleanup(db.Close) + return db +} + +// addUser inserts a throwaway profile + account and removes them when the test ends. +func addUser(t *testing.T, db *store.Store, password string) (string, int) { + t.Helper() + ctx := context.Background() + accountID := -int(time.Now().UnixNano() % 1_000_000_000) + userID := fmt.Sprintf("authtest:%d", accountID) + if _, err := db.Pool.Exec(ctx, "INSERT INTO accountprofileejb (userid, passwd, fullname) VALUES ($1, $2, 'Auth Test')", userID, password); err != nil { + t.Fatal(err) + } + if _, err := db.Pool.Exec(ctx, "INSERT INTO accountejb (accountid, logincount, logoutcount, creationdate, balance, openbalance, profile_userid) "+ + "VALUES ($1, 0, 0, now(), 100, 100, $2)", accountID, userID); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _, _ = db.Pool.Exec(ctx, "DELETE FROM accountejb WHERE accountid = $1", accountID) + _, _ = db.Pool.Exec(ctx, "DELETE FROM accountprofileejb WHERE userid = $1", userID) + }) + return userID, accountID +} + +func counts(t *testing.T, db *store.Store, accountID int) (logins, logouts int, lastLogin *time.Time) { + t.Helper() + err := db.Pool.QueryRow(context.Background(), "SELECT logincount, logoutcount, lastlogin FROM accountejb WHERE accountid = $1", accountID). + Scan(&logins, &logouts, &lastLogin) + if err != nil { + t.Fatal(err) + } + return +} + +func get(t *testing.T, client *http.Client, target string) (int, string, string) { + t.Helper() + response, err := client.Get(target) + if err != nil { + t.Fatal(err) + } + return read(t, response) +} + +func read(t *testing.T, response *http.Response) (int, string, string) { + t.Helper() + defer response.Body.Close() + body, err := io.ReadAll(response.Body) + if err != nil { + t.Fatal(err) + } + return response.StatusCode, response.Header.Get("Content-Type"), string(body) +} + +func TestPasswordMatches(t *testing.T) { + stored := "xxx" + cases := []struct { + stored *string + given string + want bool + }{ + {&stored, "xxx", true}, + {&stored, "XXX", false}, + {&stored, "xxx ", false}, + {&stored, "", false}, + {nil, "", false}, + {nil, "xxx", false}, + } + for _, c := range cases { + if got := passwordMatches(c.stored, c.given); got != c.want { + t.Errorf("passwordMatches(%v, %q) = %v, want %v", c.stored, c.given, got, c.want) + } + } +} + +func TestRootCause(t *testing.T) { + wrapped := fmt.Errorf("outer: %w", fmt.Errorf("middle: %w", errLoginFailure)) + if got := rootCause(wrapped); got != errLoginFailure { + t.Errorf("rootCause = %v", got) + } +} + +func TestWelcomePages(t *testing.T) { + server := httptest.NewServer(newApp(t, nil).Handler()) + defer server.Close() + base := server.URL + "/daytrader" + + for _, path := range []string{"/app", "/welcome.jsp"} { + status, contentType, body := get(t, server.Client(), base+path) + if status != http.StatusOK || contentType != "text/html" { + t.Errorf("%s: status %d, content type %q", path, status, contentType) + } + for _, want := range []string{ + "