add an all-in-one script for running tests; format and fix some code; add ci.yml
This commit is contained in:
@@ -22,7 +22,146 @@ The repository's directory structure is simple: there are 3 directories for each
|
||||
- [ ] Additional in-game features: chat, reactions, live connection status
|
||||
- [ ] Profile customization
|
||||
|
||||
## Testing
|
||||
|
||||
Every part of the project is tested differently. There is a single entry point for all of it — `scripts/test.sh` — and the same script is what `.github/workflows/ci.yml` runs, so local and CI results cannot drift apart.
|
||||
|
||||
| Part | Suite | Single part | Script (from the repo root) | External requirements |
|
||||
|---------------|--------------------------------|-------------------------------------|-----------------------------|-----------------------|
|
||||
| `main-server` | RSpec (17 spec files) + audits | `cd main-server && bundle exec rspec` | `scripts/test.sh main` | Redis on `localhost:6379` |
|
||||
| `game-server` | Go `testing` + httptest | `cd game-server && go test -race ./...` | `scripts/test.sh game` | none |
|
||||
| `frontend` | no automated tests | `cd frontend && npm run build` | `scripts/test.sh frontend` | none |
|
||||
|
||||
Quick run of everything (`all` is the default):
|
||||
|
||||
```bash
|
||||
scripts/test.sh # all three parts
|
||||
scripts/test.sh main # only one part
|
||||
scripts/test.sh frontend --install # force `npm ci` first
|
||||
scripts/test.sh --help
|
||||
```
|
||||
|
||||
The script fails fast (`set -euo pipefail`), checks Redis before touching `main-server`, and prints one `==>` line per step. CI (`.github/workflows/ci.yml`) runs it in three parallel jobs: `scripts/test.sh main` (with a Redis service installed by the job), `scripts/test.sh game`, and `scripts/test.sh frontend --install`. The workflow is written for Gitea Actions as well as GitHub Actions; Gitea picks it up from `.github/workflows` and needs an `act_runner` built for node24 actions (`>= v2.327.1`), because `actions/checkout@v5` and `actions/setup-node@v5` require it.
|
||||
|
||||
> If `.gitea/workflows` is ever created, Gitea ignores `.github/workflows` completely — keep one copy, not two.
|
||||
|
||||
### main-server (Ruby on Rails / RSpec)
|
||||
|
||||
Setup (idempotent):
|
||||
|
||||
```bash
|
||||
cd main-server
|
||||
bundle install
|
||||
bin/rails db:prepare # creates/updates storage/development.sqlite3 and storage/test.sqlite3
|
||||
```
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
bundle exec rspec # full suite
|
||||
bundle exec rspec spec/models # a directory
|
||||
bundle exec rspec spec/models/match_spec.rb:12 # a single example
|
||||
COVERAGE=true bundle exec rspec # SimpleCov report -> main-server/coverage/index.html (git-ignored)
|
||||
```
|
||||
|
||||
Notes:
|
||||
- **Redis is mandatory** for the suite: `MatchmakingService`, the channel and the sweep job specs talk to a real Redis. `config/initializers/redis.rb` forces `Rails.env.test?` onto logical database **15** and the specs run `FLUSHDB` there, so never point `REDIS_URL` in tests at a DB that holds data you care about. A local `redis-server` (or `docker run -d -p 6379:6379 redis`) is enough.
|
||||
- The test database is SQLite (`storage/test.sqlite3`) plus a separate Solid Queue DB; both are recreated from `db/schema.rb` by `maintain_test_schema!`. Pending migrations abort the suite with an explicit message.
|
||||
- Coverage by area: `spec/models`, `spec/services` (`JwtService`, `MatchmakingService`, `InternalSignatureService`), `spec/controllers`, `spec/requests` (including `api/internal/match_results_spec.rb`), `spec/channels`, `spec/jobs`.
|
||||
|
||||
Static checks / audits (all run from `main-server`, and all are steps of `scripts/test.sh main`):
|
||||
|
||||
```bash
|
||||
bundle exec rubocop # style (rubocop-rails-omakase)
|
||||
bundle exec bundler-audit check --update # known CVEs in gems
|
||||
bundle exec brakeman --quiet --no-pager --exit-on-warn --exit-on-error --ensure-ignore-notes
|
||||
```
|
||||
|
||||
Use the `bundle exec` forms: the bare `bin/rubocop`, `bin/brakeman` and `bin/bundler-audit` wrappers put the active Ruby's gem path ahead of Bundler's (`bundle exec ruby -e 'puts Gem.path'` fails on a multi-Ruby-machine), so the wrappers can fail with `Bundler::GemNotFound` even when `bundle exec` works.
|
||||
|
||||
Baseline (verified 2026-11-29): 155 examples green, `rubocop` clean, `bundler-audit` clean, `brakeman` clean. The single security finding — **Ruby2Shell (CVE-2026-132825) on Ruby 4.0.0** — is recorded with an explanation in `main-server/config/brakeman.ignore` (brakeman auto-loads it); Ruby 4.0.10 fixes it but is not installable on this machine yet (no ruby-build definition, and the Docker tag `ruby:4.0.10-slim` exists but the pin in `Dockerfile` must be bumped together with `.ruby-version`). When you bump Ruby, delete that ignore entry — `--ensure-ignore-notes` will keep you honest about it.
|
||||
|
||||
Do **not** use `bin/ci`: it requires `config/ci.rb`, which does not exist in this repo (only the Rails template for it is generated). `scripts/test.sh main` is the replacement.
|
||||
|
||||
### game-server (Go)
|
||||
|
||||
The Go suite is self-contained: the websocket integration tests use `httptest` and sign their own tokens, and the match-result reporter is tested against an in-process HTTP server, so no Redis, main-server or network access is needed.
|
||||
|
||||
```bash
|
||||
cd game-server
|
||||
go test ./... # all packages
|
||||
go test -race ./... # recommended; the CI-equivalent command
|
||||
go test ./internal/game -run TestFireWinCondition -count=1
|
||||
go test ./internal/ws -count=1 # end-to-end websocket scenarios (real sockets, ~2s)
|
||||
|
||||
gofmt -l . # must print nothing (checked by scripts/test.sh)
|
||||
go vet ./... # static check (also in scripts/test.sh)
|
||||
go build -o /tmp/game-server ./cmd/server # compile check (cmd/server has no tests)
|
||||
```
|
||||
|
||||
The `gofmt` check is part of `scripts/test.sh game` (and therefore of CI), so format before pushing. Note that parts of the tree were not gofmt-clean when this check was introduced; they have been reformatted once and the check keeps them that way.
|
||||
|
||||
Covered: JWT claims validation (`internal/auth`), message encoding/parsing incl. ship placement (`internal/protocol`), match manager scenarios (join/timeout/reconnect/ACK/placement/fire/win/reporting — `internal/game`), HMAC signing and the HTTP reporter with retries (`internal/mainserver`), and full end-to-end games over a real websocket (`internal/ws`).
|
||||
|
||||
### frontend (React + Vite)
|
||||
|
||||
There is **no test runner installed** (no vitest/jest/playwright/testing-library in `package.json` or `node_modules`), and no lint/format config. `shipLogic.js` exposes pure helpers (`canPlaceShip`, `randomFleet`, …) which are the natural candidates if a suite is ever added; until then verification is a build plus the manual end-to-end scenario below.
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm ci # deterministic install from package-lock.json
|
||||
npm run dev # Vite dev server on http://localhost:5173
|
||||
npm run build # build check -> dist/ (git-ignored)
|
||||
npm run preview # serve the built bundle
|
||||
```
|
||||
|
||||
`scripts/test.sh frontend` runs `npm ci` (only when `node_modules` is missing or `--install` is passed) and then `npm run build`. It also runs `npm test` **if** a `test` script exists in `package.json` — the hook is already in place for when a runner is added.
|
||||
|
||||
The API base URL defaults to `http://localhost:3000` and can be overridden with `VITE_API_URL` (see `src/api.js`); Action Cable and the game server URLs are derived from it / from the `matched` payload. `http://localhost:5173/uikit.html` renders the UI-kit reference page (a second Vite entry point).
|
||||
|
||||
### Shared cross-part contract
|
||||
|
||||
`contracts/test_signature_vectors.json` is the single source of truth for the HMAC wire format of the internal `game-server -> main-server` report. **Both** suites read it — `main-server/spec/services/internal_signature_service_spec.rb` and `game-server/internal/mainserver/reporter_test.go` (which also reuses its secret for JWT signing in `internal/ws/handler_game_test.go`). If the signature formula changes, update the implementation on both sides and regenerate the vectors; never edit a vector just to make a test pass (the other part will then fail).
|
||||
|
||||
### End-to-end manual test (all three parts together)
|
||||
|
||||
The three processes must agree on two values, otherwise matchmaking succeeds but the game never starts:
|
||||
|
||||
- `main-server` `SECRET_KEY_BASE` **=** `game-server` `JWT_SECRET` (JWT signing and report HMAC share one secret);
|
||||
- `main-server` `GAME_SERVER_URL` **=** `game-server` `PUBLIC_ADDR`, compared byte-for-byte (default `ws://localhost:8081/ws`).
|
||||
|
||||
1. Start Redis: `redis-server` (or `docker run -d -p 6379:6379 redis`).
|
||||
2. Start the main server: `cd main-server && bin/rails server` (Puma on `:3000`); check `curl localhost:3000/up`.
|
||||
3. Start the game server:
|
||||
```bash
|
||||
cd game-server
|
||||
go build -o /tmp/game-server ./cmd/server
|
||||
LISTEN_ADDR=:8081 PUBLIC_ADDR=ws://localhost:8081/ws JWT_SECRET=4 \
|
||||
MAIN_SERVER_URL=http://localhost:3000 /tmp/game-server
|
||||
```
|
||||
(`game-server/.env` already carries `PUBLIC_ADDR`/`JWT_SECRET=4` and is auto-loaded by `godotenv/autoload`; `main-server/.env` sets `SECRET_KEY_BASE=4` and `GAME_SERVER_URL`. Check `curl localhost:8081/healthz`.)
|
||||
4. Start the frontend: `cd frontend && npm run dev`, open `http://localhost:5173`.
|
||||
5. Register two players (two browsers or a normal + private window), then either press "random battle" in both windows, or use the invite flow: `create_invite` → the code comes back as `invite_created` → the second player enters it and gets `matched`.
|
||||
6. Play through the whole loop: ship placement → turns (`STATE` 4/5, `FIRE_RESULT` 1–4) → `END` (code 1 victory / 2 defeat / -1 join timeout). Note `MATCHMAKING_TOKEN_TTL` is 120 s, so a match must be joined soon after `matched`.
|
||||
7. Verify the result travelled back: `GET http://localhost:3000/api/matches/:uuid` (bearer token of a participant) should show the finished status, `finished_at` and `duration_seconds`. This is the same data the game server posts to the internal endpoint, which can also be exercised directly from the shell:
|
||||
```bash
|
||||
UUID=<match uuid>; BODY='{"status":"player1_won","duration_seconds":125}'; TS=$(date +%s)
|
||||
SIG=$(printf '%s.%s.%s' "$TS" "/api/internal/matches/$UUID/result" "$BODY" \
|
||||
| openssl dgst -sha256 -hmac "$SECRET_KEY_BASE" -hex | sed 's/^.* //')
|
||||
curl -X POST "http://localhost:3000/api/internal/matches/$UUID/result" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-H "X-Request-Timestamp: $TS" -H "X-Request-Signature: sha256=$SIG" -d "$BODY"
|
||||
```
|
||||
(idempotent for an already finished match; a `409` means it was closed with a different outcome).
|
||||
|
||||
Match history is visible in the UI (`GET /api/matches`) once the report has been processed; `rating_change` values stay zero until rating recalculation is implemented on `main-server`.
|
||||
|
||||
Quick protocol poke without the UI (the game server speaks raw JSON opcode arrays from `game-server/README.md`): take the `game_token` from the `matched` message and connect with `websocat`/"wscat", send `[1, "<game_token>", "<user_token>"]`, ACK each `seq` with `[4, <seq>]`, then `[5, ...30 ship args]` and `[6, x, y]`. Without `websocat` installed, `go test -race ./internal/ws` covers exactly these flows.
|
||||
|
||||
## Guidelines
|
||||
- The mentioned documentation files should be kept up-to-date and updated in the same language. The formatting can be changed, though, if it could improve readability.
|
||||
- Whenever you change business logic, update (and run) the corresponding suites listed in **Testing** — RSpec for `main-server`, `go test -race ./...` for `game-server`, and keep `contracts/test_signature_vectors.json` in sync if the HMAC format is touched.
|
||||
- Before pushing, run `scripts/test.sh` (or at least the parts you touched). It is the same script CI runs, so a green local run means a green pipeline; do not rely on the bare `bin/*` wrappers of `main-server`, which break on a machine with several Ruby installs.
|
||||
- When adding a check to CI, add the corresponding step to `scripts/test.sh` instead of inlining it in the workflow, otherwise local and CI runs drift apart.
|
||||
- The Ruby backend should be written with Rails principles in mind. The tasks performed by this backend are going to be relatively simple (especially at earlier stages of this project), so the focus should be on clean code and best practices, not unnecessary complexity.
|
||||
- The methods in the Ruby backend comprising the business-logic should be covered with unit-tests after being implemented.
|
||||
|
||||
Reference in New Issue
Block a user