# Write Handler Tests for a Fiber Auth API

Yes. An agent writes Go tests for a Fiber v3 auth API's register, login, refresh and protected routes with app.Test and an in-process database, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/write-handler-tests/fiber/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the routes and how they are wired before it writes a test. In an API like the `auth-jwt` example in the official Fiber cookbook repository, `router/router.go` builds everything inside `SetupRoutes(app)`: it reads `SECRET` from the environment and panics without it, builds an `AuthService` with a fifteen-minute access token TTL that `ACCESS_TOKEN_TTL_MINUTES` can override, and registers `POST /api/auth/register`, `/login`, `/refresh-token`, `/logout` behind `middleware.Protected()`, `/api/users/:id` with `GET`, `PATCH` and `DELETE` all protected, and `/api/products` with public reads and protected writes. `middleware/auth.go` wraps `github.com/gofiber/contrib/v3/jwt` with an `ErrorHandler` that answers `400` with `Missing or malformed JWT` when the header is absent and `401` with `Invalid or expired JWT` otherwise. `go.mod` pins `github.com/gofiber/fiber/v3` v3.6.1, the contrib JWT middleware v1.2.7, `golang-jwt/jwt/v5` v5.3.1, `gorm.io/gorm` v1.31.2 and the Postgres driver, on `go 1.26.0`. There is no `_test.go` file.

The behaviour worth pinning is in `handlers/auth.go` and `services/auth.go`. `Register` rejects a blank field or an address `net/mail` cannot parse with `400`, a duplicate email with `409 Email already in use`, and answers the new user's id as a string. `Login` answers `401 Invalid credentials` for a wrong password, otherwise an `access_token` and `refresh_token` plus an `HttpOnly` cookie named `jwt` whose expiry is read back from the token's `exp` claim. `RefreshAccessToken` rotates: it revokes the presented token and issues a new one with the remaining TTL, so the old string must fail with `401` on a second use. `Logout` calls `RevokeAllUserRefreshTokens`, and `GetUser` compares the `sub` claim with the `:id` parameter and answers `401 Invalid token id` for someone else's id.

The database is the only obstacle. `database/database.go` opens Postgres from `DB_*` variables into a package-level `database.DB` and runs `AutoMigrate` on `Product`, `User` and `RefreshToken`. The sandbox has no Docker, so instead of a container the tests open an in-memory SQLite database through a pure-Go driver, assign it to `database.DB`, run the same `AutoMigrate`, set `SECRET` with `t.Setenv`, and call `router.SetupRoutes(app)` on a fresh `fiber.New()`; `uniqueIndex` on `email` and `username` behaves the same there, which is what the duplicate-email case depends on. Requests go through `app.Test(req, fiber.TestConfig{Timeout: 0, FailOnTimeout: false})`, the form the repository's own `unit-test` example uses, with `testify` assertions.

The tests live in `handlers/auth_test.go`, `handlers/user_test.go` and `middleware/auth_test.go`, one table per route: register happy path, blank field, bad email, duplicate; login wrong password and success with the cookie attributes asserted; refresh once then reuse the old token; logout then refresh; users with no header, a garbage header, another user's id and the owner's id. A `testhelpers` package holds the database and app setup so each file stays short. The agent runs `go vet ./...`, `gofumpt -l .` and `go test ./... -count=1` and includes the output; the repository's `Makefile` lint target runs golangci-lint with the `modernize` linter enabled, so the agent runs that too and fixes what it reports in the new files.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Write handler tests for the Fiber v3 authentication API in this repository. Read the router, handlers, middleware, services, models and database package first. Cover register (success, blank field, invalid email, duplicate email), login (wrong password, success with the jwt cookie's HttpOnly and expiry), refresh-token rotation (the old token must fail on reuse), logout revoking refresh tokens, and the protected /api/users/:id routes with no header, a malformed header, another user's id and the owner's id, asserting the exact status codes and messages the handlers return. Use app.Test as the unit-test example in this repository does, with testify. Replace the Postgres connection in tests with an in-memory SQLite database through a pure-Go driver assigned to the package-level DB, run the same AutoMigrate, and set SECRET with t.Setenv. Do not change handler behaviour; if a test exposes a bug, keep the test red and describe it. Run go vet, gofumpt, the Makefile lint target and go test, and include the output. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that adds `handlers/auth_test.go`, `handlers/user_test.go`, `middleware/auth_test.go` and a small `testhelpers` package, and extends `go.mod` and `go.sum` with `testify` and the pure-Go SQLite driver as test-only dependencies. No handler, service or model file changes.

The description lists each test by name with the route and status it pins, quotes the `go test ./... -count=1` summary, the `go vet` and `gofumpt` results and the lint output, and names any case the agent left red because the handler disagrees with its own error messages. The commands and full output are in the transcript at `GET /o/{org}/sessions/{id}/messages`.

Before merging, a reviewer checks the asserted messages match what clients already depend on, decides whether a Postgres-backed job should also run these tests in CI so dialect differences are caught, and reads any red case before deciding whether the handler or the expectation is wrong.

## Run it on every Fiber service with no handler tests

A team with several Fiber services starts one run per repository with one `POST /o/{org}/sessions` each, the repository in `resources` and this prompt as `input`. Each run reads its own router and middleware, so a service that uses sessions instead of JWT gets tests for its own error paths, and the in-process database setup follows whatever `AutoMigrate` call that service makes.

Send a `request_id`, a UUID v5 of the repository's full name, so a retried call returns the run it already started. The key's `webhook_url` reports when each run the key starts finishes, with the run's final answer in `result`.

## Why run it on Rush?

Auth tests are tedious to write by hand because every case needs a user, a token and the exact message the handler returns, and the first obstacle is a database the service expects to find running. The agent reads the handlers for the real strings, builds the in-process database once, and runs the suite in a sandbox of its own with every command's output kept.

The pull request carries the test list, the passing summary and the lint result, so a reviewer checks expectations against the API contract rather than running the suite to see what it covers. Several services can be done at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Why SQLite in tests when the service runs on Postgres?

The sandbox has no Docker, and the handlers depend on GORM behaviour that SQLite reproduces: unique indexes, `First` returning `ErrRecordNotFound`, `Update` on a `Where`. The pull request says which cases are dialect-sensitive, and a Postgres service job in CI can run the same files unchanged by setting `DB_*` and skipping the SQLite swap.

### Does SetupRoutes need the environment?

Yes. Both `router.SetupRoutes` and `middleware.Protected` panic when `SECRET` is empty, so every test sets it with `t.Setenv` before building the app. `ACCESS_TOKEN_TTL_MINUTES` is left unset so the fifteen-minute default is what the cookie expiry test reads back.

### How is refresh rotation tested?

Log in, call `/api/auth/refresh-token` with the returned refresh token and assert a new pair comes back, then call it again with the original token and assert `401 Invalid or expired refresh token`. That matches `RefreshAccessToken`, which revokes the presented token before creating the replacement.

### What if a test finds a bug?

The agent leaves the test red and explains the mismatch in the pull request rather than editing the handler, because the prompt asks for tests, not behaviour changes. A follow-up message to the same session can fix the handler once you agree it is a bug.

## More Fiber jobs

- [Write Unit Tests for a Fiber v3 App](https://getrush.ai/run/write-unit-tests/fiber/)
- [Add API Key Authentication to a Fiber App](https://getrush.ai/run/add-api-key-auth/fiber/)
- [Add Response Compression to a Fiber App](https://getrush.ai/run/add-compression/fiber/)

## The same job on other stacks

- [Write Handler Tests for a Go chi API](https://getrush.ai/run/write-handler-tests/chi/)

## More jobs like this: Write the missing tests

- [Write Unit Tests for a Helm Chart](https://getrush.ai/run/write-helm-unittest/helm/)
- [Write Integration Tests for an ASP.NET Core API](https://getrush.ai/run/write-integration-tests/aspnet-core/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
