{{.Title}}
+ {{if .Username}}Logged in to Lichess as {{.Username}}
{{end}} +{{.Message}}
+ {{if .OK}}diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e9daed5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,37 @@ +name: ci + +on: + push: + pull_request: + +jobs: + test: + strategy: + fail-fast: false # a failure on one system doesn't cancel the others + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + # Stockfish, so the analysis test runs against the real engine (it's + # skipped where Stockfish is missing, so a failed install isn't fatal) + - name: Install Stockfish (Linux) + if: runner.os == 'Linux' + continue-on-error: true + run: sudo apt-get update && sudo apt-get install -y stockfish + - name: Install Stockfish (macOS) + if: runner.os == 'macOS' + continue-on-error: true + run: brew install stockfish + - name: Install Stockfish (Windows) + if: runner.os == 'Windows' + continue-on-error: true + run: choco install stockfish -y --no-progress + - run: go vet ./... + - run: go test -race ./... + if: runner.os != 'Windows' + - run: go test ./... + if: runner.os == 'Windows' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..d5a0628 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,25 @@ +name: release + +on: + push: + tags: ["v*"] + +permissions: + contents: write + +jobs: + goreleaser: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - uses: goreleaser/goreleaser-action@v6 + with: + version: "~> v2" + args: release --clean + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..6335353 --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,30 @@ +# Builds release binaries when a version tag (e.g. v0.2.0) is pushed. +# Test locally with: goreleaser release --snapshot --clean +version: 2 +project_name: chess-cli + +builds: + - env: + - CGO_ENABLED=0 + goos: [linux, darwin, windows] + goarch: [amd64, arm64] + ldflags: + - -s -w -X main.version={{.Version}} + +archives: + - formats: [tar.gz] + format_overrides: + - goos: windows + formats: [zip] + files: + - README.md + - LICENSE.md + +checksum: + name_template: checksums.txt + +changelog: + sort: asc + filters: + exclude: + - "^Merge " diff --git a/README.md b/README.md index 004efba..376f191 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@
A chess tui app written in Go.
- Play locally with a friend or online with Lichess!
+ Play locally with a friend or online with Lichess!
♞♞♞♞♞♞♞♞♞♞♞
-# Features +# Install - -- Mouse input support -- Displays move history -- UCI chess notation input -- Saving and restoring local games -- Lichess features: - - Lichess login w/ oauth - - Lichess challenge request for real time, unlimited, or correspondence games, with all variants and options supported - - Challenge a friend or a random player - - Play against the stockfish AI - - Join ongoing games - - Join from your incoming challenges +**Download a binary** for Linux, macOS or Windows from the +[releases page](https://github.com/nate-xyz/chess-cli/releases), unpack it and +run `chess-cli`. +**Or install with Go** (1.24+): +```sh +go install github.com/nate-xyz/chess-cli@latest +``` +**Or build from source:** +```sh +git clone https://github.com/nate-xyz/chess-cli +cd chess-cli +go run . # or: go build -o chess-cli . && ./chess-cli +``` -♞♞♞♞♞♞♞♞♞♞♞
+A terminal with true colour and a font with the Unicode chess symbols gives the +best result. The board scales with your terminal, so make it big. + +### How the board looks + +Choose under **Options** on the home screen: + +| Rendering | What you get | Where | +|---|---|---| +| **Image** | Lichess boards and piece sets as real images, scaled to the board. 12 piece sets and 6 boards, previewed as you pick | terminals with the [kitty graphics protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol/): kitty, Ghostty, WezTerm | +| **Advanced** | Unicode chess symbols, drawn big with kitty's [text sizing protocol](https://sw.kovidgoyal.net/kitty/text-sizing-protocol/) where available | everywhere; big in kitty 0.40+ | +| **Basic** | Plain symbols in the terminal's 8 standard colours, like the original chess-cli | any terminal, including old ones | + +Support is detected at startup (image rendering falls back to advanced where +images aren't supported, e.g. inside tmux). `CHESS_CLI_IMAGES=0/1` and +`CHESS_CLI_BIG_PIECES=0/1` override the detection. + +Options also has: + +- **Move box**: typed-move box always shown, or only on `Ctrl-K` +- **Clock bar**: clocks as a bar beside the board, or plain text in the sidebar +- **Zen mode**: hides names, ratings, chat and game info during games, like + Lichess's zen mode +- **Sound**: Retro (chiptune) or Wood, or off. chess-cli's own sounds, + played with your system's player (`pw-play`, `paplay` or `aplay` on Linux, + `afplay` on macOS, built in on Windows) + +# Playing + +| | | +|---|---| +| **Mouse** | Click a piece, then click where it should go. Legal moves are dotted, captures marked. | +| **Typing** | `Ctrl-K` opens the move box: UCI (`e2e4`) or standard notation (`Nf3`, `exd5`, `O-O`). Promotions need the piece: `e7e8=Q`, `e8=Q` or `e7e8q`. | +| **Keyboard on the board** | Arrows or `hjkl` move the cursor, `Enter`/`Space` selects, `Esc` cancels, `Tab` goes to the menu. | +| **Going back** | Click a move in the move list, scroll the mouse wheel on the board, or `[` `]` (`Home`/`End` for the start/now). Click the board to return. Works on the game-over screen too. | +| **Drawing** | Right-click a square for a circle, right-drag for an arrow; `Shift` red, `Alt` blue, both yellow. Left-click clears. | +| **Promotion** | A picker opens over the promotion square: click a piece, or press `q` `r` `b` `n`. | +| **Online chat** | `Tab` cycles board → chat → menu. | + +Local games are two players on one keyboard; the board flips each move. Games +can be saved and resumed. + +# Puzzles +*Puzzles* on the home screen: the **daily puzzle**, or **puzzle training** +(new puzzles one after another, five difficulty levels relative to your +rating). **Rated** puzzles update your Lichess puzzle rating and need a login; +**casual** ones work without. Hints, solutions and themes as on Lichess. +# Watching, studies and news -### dependency documentation: +Once you've logged in to Lichess, the home screen also has: -https://lichess.org/api for lichess +- **Watch**: Lichess TV channels (top rated, bullet, blitz, rapid, classical, + Chess960, bots, computer), a player's current game, or any game by link or + ID. Live clocks and moves; scroll back through the game as usual. +- **Studies**: your Lichess studies (private ones too) or any study by link. + Chapters, variations, comments and the study's arrows and circles. `←` `→` + step through the moves, `↑` `↓` jump to the start/end, click any move + (in a variation too) to go there. +- **Chess news**: elite events Lichess is broadcasting (live, coming up, just + finished, with leaders and winners) and the latest Lichess blog posts. -https://pkg.go.dev/github.com/notnil/chess chess lib +Without a login chess-cli doesn't contact Lichess at all (casual puzzles +aside, which you choose explicitly). -https://docs.rocketnine.space/code.rocketnine.space/tslocum/cview/ cview +# Lichess -https://code.rocketnine.space/tslocum/cview/src/branch/master/demos cview demos +Choose *Lichess* on the home screen and log in through your browser (if it +doesn't open, the link is shown in the app). chess-cli uses the +[Lichess Board API](https://lichess.org/api#tag/board): -https://pkg.go.dev/net/http +- Challenge a friend, seek a random opponent, or play Lichess's Stockfish (levels 1–8) +- All variants, rated or casual, real-time, correspondence or unlimited +- Resume ongoing games; accept, decline (`d`) and cancel challenges +- Chat, draw offers, takebacks, resign/abort +- Claim victory or a draw when your opponent leaves +- Rematch from the game-over screen +- `Esc` on the waiting screen withdraws your challenge or seek -https://mholt.github.io/json-to-go/ +**Time controls:** Lichess only allows Rapid, Classical and Correspondence +through the Board API, plus Blitz for direct challenges and games against the AI. +Bullet isn't available to third-party clients. + +Only one chess-cli runs at a time; a second copy tells you one is already +running. + +Your Lichess token and saved games are kept in `~/.config/chess-cli` +(`chess-cli --help` prints the exact folder on your system).♞♞♞♞♞♞♞♞♞♞♞
-### todo: +# Development + +```sh +go test -race ./... +``` + +The tests include an end-to-end online game: the real UI running on tcell's +mock terminal against a fake Lichess server. -#### general +**Releasing:** push a version tag and GitHub Actions builds and publishes the +binaries with [GoReleaser](https://goreleaser.com): -- Handle all notation types or choose notation to start - -#### local client +```sh +git tag v0.2.0 && git push origin v0.2.0 +``` -- add time options - -#### oauth +### Credits - - handle if oauth rejected mid process +Piece sets come from [Lichess](https://github.com/lichess-org/lila); each +keeps its own licence (GPL, MIT, Apache, CC0, CC BY, CC BY-SA). See +[pkg/assets/pieces](pkg/assets/pieces/README.md). -#### online +### Dependency documentation + +- [Lichess API](https://lichess.org/api) +- [notnil/chess](https://pkg.go.dev/github.com/notnil/chess): rules and move generation +- [cview](https://pkg.go.dev/codeberg.org/tslocum/cview): TUI widgets +- [tcell](https://pkg.go.dev/github.com/gdamore/tcell/v3): terminal handling -- exit option on loader -- challenge construction - - set default interval position for sliders - - custom starting position option for challenges -- client - - chat - - rematch option post game -♞♞♞♞♞♞♞♞♞♞♞
+### Todo + +#### general + +- Sixel support for image rendering (foot, Konsole, xterm, Windows Terminal) + +#### local client + +- Save clock times with saved games +- Stockfish analysis of a finished game + +#### online + +- Challenge construction + - Set default positions for sliders + - Custom starting position +- Puzzle themes, opening explorer, game history/PGN export +- Variants: the board follows standard chess rules only. Games in variants + like crazyhouse or atomic can be created but the app can't follow them yet; + Chess960 is untested. + +♞♞♞♞♞♞♞♞♞♞♞
diff --git a/api/api_test.go b/api/api_test.go new file mode 100644 index 0000000..911838a --- /dev/null +++ b/api/api_test.go @@ -0,0 +1,410 @@ +package api + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" + "sync/atomic" + "testing" + "time" +) + +// fakeLichess points the API at a test server for the duration of a test. +func fakeLichess(t *testing.T, h http.Handler) *httptest.Server { + t.Helper() + srv := httptest.NewServer(h) + old, oldUser := HostUrl, UserInfo + HostUrl = srv.URL + UserInfo = UserConfig{ApiToken: "test-token"} + t.Cleanup(func() { + srv.Close() + HostUrl, UserInfo = old, oldUser + }) + return srv +} + +func TestResponseErrorMessages(t *testing.T) { + for _, tc := range []struct { + status int + body string + want string + }{ + {400, `{"error":"Not your turn, or game already over"}`, "lichess: Not your turn, or game already over"}, + {400, `{"error":{"clock.limit":["Invalid value"],"days":["Required"]}}`, "lichess: clock.limit: Invalid value; days: Required"}, + {429, ``, "lichess: rate limited by Lichess, wait a minute and try again"}, + {404, `not json`, "lichess: 404 Not Found"}, + } { + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tc.status) + fmt.Fprint(w, tc.body) + })) + err := MakeMove("abcd1234", "e2e4") + var apiErr *APIError + if !errors.As(err, &apiErr) || apiErr.Status != tc.status || err.Error() != tc.want { + t.Errorf("status %d: got %v, want %q", tc.status, err, tc.want) + } + } +} + +func TestRequestsSendAuthAndForm(t *testing.T) { + var got *http.Request + var form url.Values + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got = r + r.ParseForm() + form = r.PostForm + fmt.Fprint(w, `{"ok":true}`) + })) + if err := WriteChat("game1234", "player", "good game"); err != nil { + t.Fatal(err) + } + if got.URL.Path != "/api/board/game/game1234/chat" || got.Header.Get("Authorization") != "Bearer test-token" { + t.Errorf("bad request: %s %v", got.URL.Path, got.Header) + } + if form.Get("room") != "player" || form.Get("text") != "good game" { + t.Errorf("bad form: %v", form) + } +} + +func TestCreateChallengeKeepsAliveUntilDeclined(t *testing.T) { + release := make(chan struct{}) + var form url.Values + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + form = r.PostForm + fmt.Fprintln(w, `{"challenge":{"id":"chal1234","status":"created"}}`) + w.(http.Flusher).Flush() + <-release + fmt.Fprintln(w, `{"done":"declined"}`) + })) + p, err := CreateChallenge(CreateChallengeType{ + DestUser: "friend", Variant: "standard", Rated: "false", Color: "white", + TimeOption: TimeRealTime, ClockLimit: "600", ClockIncrement: "5", + }) + if err != nil { + t.Fatal(err) + } + if p.ID != "chal1234" { + t.Fatalf("id %q", p.ID) + } + if form.Get("keepAliveStream") != "true" || form.Get("clock.limit") != "600" || form.Get("clock.increment") != "5" { + t.Errorf("form %v", form) + } + select { + case r := <-p.Done(): + t.Fatalf("finished early: %q", r) + case <-time.After(100 * time.Millisecond): + } + close(release) + if r := <-p.Done(); r != "declined" { + t.Fatalf("done = %q", r) + } +} + +func TestCancelChallengeClosesConnection(t *testing.T) { + closed := make(chan struct{}) + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprintln(w, `{"challenge":{"id":"chal1234"}}`) + w.(http.Flusher).Flush() + <-r.Context().Done() // Lichess cancels the challenge when we hang up + close(closed) + })) + p, err := CreateChallenge(CreateChallengeType{DestUser: "friend", TimeOption: TimeUnlimited}) + if err != nil { + t.Fatal(err) + } + p.Cancel() + select { + case <-closed: + case <-time.After(2 * time.Second): + t.Fatal("connection not closed by Cancel") + } +} + +func TestSeekUsesMinutes(t *testing.T) { + var form url.Values + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + form = r.PostForm + // real-time seeks stream keep-alive newlines until paired, then close + fmt.Fprint(w, "\n") + })) + p, err := CreateSeek(CreateChallengeType{Variant: "standard", Rated: "true", Color: "random", + TimeOption: TimeRealTime, ClockLimit: "900", MinTurn: 15, ClockIncrement: "10"}) + if err != nil { + t.Fatal(err) + } + <-p.Done() + if form.Get("time") != "15" || form.Get("increment") != "10" || form.Has("clock.limit") || form.Has("color") { + t.Errorf("seek form %v", form) + } +} + +func TestStreamBoardStateEvents(t *testing.T) { + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + for _, line := range []string{ + `{"type":"gameFull","id":"g1","white":{"id":"harry","name":"Harry"},"black":{"aiLevel":3},"initialFen":"startpos","state":{"type":"gameState","moves":"e2e4","wtime":60000,"btime":60000,"status":"started"}}`, + ``, + `{"type":"chatLine","username":"lichess","text":"Good luck","room":"player"}`, + `{"type":"somethingNew"}`, + `{"type":"opponentGone","gone":true,"claimWinInSeconds":10}`, + `{"type":"gameState","moves":"e2e4 e7e5","status":"started","bdraw":true}`, + } { + fmt.Fprintln(w, line) + } + })) + events := make(chan BoardEvent, 10) + errs := make(chan error, 1) + StreamBoardState(context.Background(), events, errs, "g1") + close(events) + var got []BoardEvent + for ev := range events { + got = append(got, ev) + } + if len(errs) != 0 { + t.Fatal(<-errs) + } + if len(got) != 5 { + t.Fatalf("got %d events: %+v", len(got), got) + } + if got[0].Type != GameFull || got[0].Full.Black.AiLevel != 3 || got[0].Full.State.Moves != "e2e4" { + t.Errorf("gameFull: %+v", got[0].Full) + } + if got[1].Type != ChatLine || got[1].Chat.Text != "Good luck" { + t.Errorf("chat: %+v", got[1]) + } + if got[2].Type != OpponentGone || !got[2].Gone.Gone || got[2].Gone.ClaimWinInSeconds != 10 { + t.Errorf("gone: %+v", got[2]) + } + if got[3].Type != GameState || !got[3].State.Bdraw { + t.Errorf("state: %+v", got[3]) + } + if got[4].Type != EOF { + t.Errorf("last event should be EOF: %+v", got[4]) + } +} + +func TestStreamBoardStateStopsOnCancel(t *testing.T) { + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.(http.Flusher).Flush() + <-r.Context().Done() + })) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + StreamBoardState(ctx, make(chan BoardEvent), make(chan error), "g1") + close(done) + }() + time.Sleep(50 * time.Millisecond) + cancel() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("stream did not stop on cancel") + } +} + +// browserLogin plays the browser's part of the OAuth flow: it follows the +// login URL's redirect_uri with the given query (code/state/error). +func browserLogin(t *testing.T, authURL string, query func(state string) url.Values) { + u, err := url.Parse(authURL) + if err != nil { + t.Error(err) + return + } + q := u.Query() + if q.Get("code_challenge_method") != "S256" || q.Get("code_challenge") == "" || q.Get("client_id") != ClientID { + t.Errorf("bad auth url: %s", authURL) + } + go func() { + res, err := http.Get(q.Get("redirect_uri") + "?" + query(q.Get("state")).Encode()) + if err == nil { + res.Body.Close() + } + }() +} + +func useTempConfig(t *testing.T) string { + dir := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", dir) + t.Setenv("HOME", dir) // os.UserConfigDir on macOS + t.Setenv("AppData", dir) + return dir +} + +func TestOAuthLoginSavesTokenPrivately(t *testing.T) { + dir := useTempConfig(t) + var tokenForm url.Values + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/token" { + r.ParseForm() + tokenForm = r.PostForm + fmt.Fprint(w, `{"token_type":"Bearer","access_token":"lio_secret","expires_in":31536000}`) + } + })) + UserInfo = UserConfig{} + token, err := AuthUser(context.Background(), func(authURL string) { + browserLogin(t, authURL, func(state string) url.Values { + return url.Values{"code": {"the-code"}, "state": {state}} + }) + }) + if err != nil { + t.Fatal(err) + } + if token != "lio_secret" || tokenForm.Get("code") != "the-code" || tokenForm.Get("code_verifier") == "" { + t.Fatalf("token %q form %v", token, tokenForm) + } + path := filepath.Join(dir, "chess-cli", "config.json") + if runtimeConfig, err := ConfigDir(); err == nil { + path = filepath.Join(runtimeConfig, "config.json") + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 { // Windows has no Unix permissions + t.Errorf("config perms %v, want 0600", info.Mode().Perm()) + } + if time.Until(UserInfo.TokenExpirationDate) < 364*24*time.Hour { + t.Errorf("expiry not taken from expires_in: %v", UserInfo.TokenExpirationDate) + } +} + +// Logging in (e.g. again, for rated puzzles) must keep the other settings. +func TestOAuthLoginKeepsSettings(t *testing.T) { + useTempConfig(t) + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"access_token":"new-token","expires_in":3600}`) + })) + if err := UpdateConfig(func(c *UserConfig) { c.Pieces, c.PieceSet, c.Zen = "image", "merida", true }); err != nil { + t.Fatal(err) + } + if _, err := AuthUser(context.Background(), func(authURL string) { + browserLogin(t, authURL, func(state string) url.Values { + return url.Values{"code": {"c"}, "state": {state}} + }) + }); err != nil { + t.Fatal(err) + } + UserInfo = UserConfig{} + if err := LoadConfig(); err != nil { + t.Fatal(err) + } + if UserInfo.ApiToken != "new-token" || UserInfo.Pieces != "image" || UserInfo.PieceSet != "merida" || !UserInfo.Zen { + t.Errorf("settings after login: %+v", UserInfo) + } +} + +func TestOAuthLoginCancelled(t *testing.T) { + useTempConfig(t) + fakeLichess(t, http.NotFoundHandler()) + _, err := AuthUser(context.Background(), func(authURL string) { + browserLogin(t, authURL, func(state string) url.Values { + return url.Values{"error": {"access_denied"}, "state": {state}} + }) + }) + if !errors.Is(err, ErrLoginCancelled) { + t.Fatalf("got %v, want ErrLoginCancelled", err) + } +} + +func TestOAuthIgnoresWrongState(t *testing.T) { + useTempConfig(t) + fakeLichess(t, http.NotFoundHandler()) + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + _, err := AuthUser(ctx, func(authURL string) { + browserLogin(t, authURL, func(string) url.Values { + return url.Values{"code": {"x"}, "state": {"forged"}} + }) + }) + if err == nil || !strings.Contains(err.Error(), "timed out") && !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("forged callback should be ignored until timeout, got %v", err) + } +} + +func TestLegacyConfigMigrated(t *testing.T) { + useTempConfig(t) + work := t.TempDir() + t.Chdir(work) + os.WriteFile(legacyConfigFile, []byte(`{"ApiToken":"old-token"}`), 0o644) + UserInfo = UserConfig{} + if err := LoadConfig(); err != nil { + t.Fatal(err) + } + if UserInfo.ApiToken != "old-token" { + t.Fatalf("token %q", UserInfo.ApiToken) + } + if _, err := os.Stat(legacyConfigFile); !os.IsNotExist(err) { + t.Errorf("world-readable legacy token file should be removed") + } +} + +// After Lichess rejects the token the event stream stops; logging in again +// must be able to start it again. +func TestEventStreamRestartsAfterRejection(t *testing.T) { + useTempConfig(t) + var calls atomic.Int32 + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/stream/event" { + if calls.Add(1) == 1 { + http.Error(w, `{"error":"No such token"}`, http.StatusUnauthorized) + return + } + fmt.Fprintln(w, `{"type":"gameStart","game":{"id":"abcd1234"}}`) + w.(http.Flusher).Flush() + <-r.Context().Done() + } + })) + events := make(chan StreamEventType, 4) + StartEventStream(events) + deadline := time.Now().Add(3 * time.Second) + for streamRunning.Load() && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if streamRunning.Load() { + t.Fatal("stream kept running after a 401") + } + StartEventStream(events) // e.g. after logging in again + defer StopEventStream() + select { + case e := <-events: + if e.GameID != "abcd1234" { + t.Errorf("event %+v", e) + } + case <-time.After(3 * time.Second): + t.Fatal("stream didn't restart") + } +} + +// The login landing page: success names the account, failures say what +// went wrong (escaped), and nothing is loaded from elsewhere. +func TestLoginPage(t *testing.T) { + var ok, failed, cancelled strings.Builder + if err := writeLoginPage(&ok, "hfwitte", nil); err != nil { + t.Fatal(err) + } + _ = writeLoginPage(&failed, "", errors.New("lichess:Logged in to Lichess as {{.Username}}
{{end}} +{{.Message}}
+ {{if .OK}}