All jobs

Write Handler Tests for a Go chi API

Yes. An agent reads your chi routers and handlers, writes httptest table tests with mock stores for the packages that have none, and opens a pull request.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent learns the house style from the one test file that exists. In an API laid out like dhax/go-base, auth/pwdless/api_test.go has a TestMain that sets Viper defaults for the login token and a JWT secret, builds the auth resource with MockAuthStore and email.NewMockMailer(), mounts its router on a fresh chi.NewRouter() and serves it with httptest.NewServer. Four table tests cover login, token, refresh and logout, each row naming an input and an expected status, and a testRequest helper sends JSON with an optional bearer token. MockAuthStore is a struct with one function field and one Invoked flag per method. That is the pattern the rest of the code is missing: go test ./..., which .github/workflows/test.yml runs with -v, finds no test files in api, api/app, api/admin, auth/jwt, auth/authorize or models.

The handlers are ready to be tested the same way, because each resource depends on a small interface. api/app/account.go declares AccountStore with five methods and api/app/profile.go declares ProfileStore with two, and api/admin/accounts.go has its own AccountStore for list, create, get, update and delete. The agent writes a mock for each in the style of MockAuthStore, in a _test.go file so it stays out of the binary, and places the tests inside packages app and admin, since the router() methods are unexported. Both routers read the caller from the request context through jwt.ClaimsFromCtx, so each test server mounts the real Verifier and jwt.Authenticator in front of the resource and signs tokens with a TokenAuth built from a test secret of at least 32 characters, which is the minimum NewTokenAuth accepts.

The table rows come from reading each handler's branches. For the account resource: no token and an expired token are refused, GET / returns the caller's account, a store error in accountCtx answers unauthorized, a PUT whose body sets id, active or roles leaves all three unchanged because accountRequest shadows them, a validation error from the store maps to the validation response, PUT /token/abc answers bad request, and a token id that belongs to another account never reaches UpdateToken or DeleteToken, which the Invoked flags prove. The profile resource gets the same treatment, plus a direct test of models.Profile.Validate, which allows only default and dark for the theme. In admin, a caller without the admin role gets the forbidden response from authorize.RequiresRole on every route, and list, create, update and delete are covered with and without store errors. SPAHandler in api/api.go is tested against a t.TempDir(): a real file is served, an unknown path returns index.html, and a path containing service-worker.js resolves to the one at the root.

It runs go vet ./... and go test -race -cover ./... after each package and reports coverage per package before and after. The race detector matters here: login sends its email from a goroutine while the tests read the mock mailer's flag, so the agent reports any race it flags in existing code and leaves the fix to you. The store implementations under database/ talk to Postgres through Bun and are left out unless you ask; api.New opens a database connection, so the tests never call it and mount each resource directly, as the existing test does.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Write the missing handler tests for this Go API built on chi. Read go.mod, .github/workflows/test.yml, auth/pwdless/api_test.go, auth/pwdless/mockAuthStore.go and email/mockMailer.go first and follow their style: TestMain with Viper defaults, a chi router served by httptest, table tests, mock stores with a function field and an Invoked flag per method. Then read api/api.go, every file under api/app, api/admin, auth/jwt, auth/authorize and models. Add mocks in _test.go files and table tests inside packages app and admin, mounting the real jwt Verifier and Authenticator and signing tokens with a TokenAuth built from a test secret. Cover for account and profile: missing and expired tokens, the happy paths, store errors, validation errors, protected fields in a PUT body (id, active, roles) staying unchanged, a non-numeric tokenID, and a token id from another account never reaching the store. Cover RequiresRole for a caller without the admin role, the admin accounts routes, models.Profile.Validate, and SPAHandler against a temporary directory. Do not call api.New or touch database/. Change no non-test file: if a test exposes a bug or the race detector flags existing code, keep the evidence and describe it in the pull request. Run go vet ./... and go test -race -cover ./... and paste the per-package coverage before and after.",
  "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

The pull request adds _test.go files only: mocks and table tests in api/app and api/admin, and tests for auth/authorize, models and the SPA handler in api. Its description has the coverage of each package before and after from go test -cover, the full -race output, and a list of the branches each table covers, written so a reader can match a row to a line in the handler.

Because no source file changes, the existing test job in the workflow picks the new tests up as it stands; it runs go test -v ./... after setting Go up from go.mod. The job does not pass -race, so the description says which results came from the race detector in the sandbox and would not appear in CI.

A reviewer looks at two things. First the rows about protected fields and foreign token ids, which are the tests that would catch a real authorisation mistake, to confirm each asserts on the store's Invoked flag and not only on the status code. Second the findings list: a race in the login email path, or a small one such as accountCtx building a log entry with WithField and discarding it, are reported there for a follow-up on the same session.

Run it on every pull request adding a handler

Once the mocks exist, keep new routes covered with an automation on the Project: a github trigger on pull_request.opened and pull_request.synchronize, and a prompt that says to add table tests in the existing style for every handler the pull request adds or changes under api/, then run go test -race ./.... The trigger puts the pull request after the prompt, so the prompt needs no placeholder, and only work by an owner, member or collaborator fires it. Set the automation's max runs per hour to fit how often your team pushes.

For a group of chi services, send this page's body from your own server to POST /o/{org}/sessions, one call per repository, each with a request_id that is a UUID v5 of the repository's full name so a retry returns the run already started.

The use case this job follows, with its automation and trigger: Write the missing tests.

Why run it on Rush?

Handler tests are judged by whether they fail when the handler is wrong, and that cannot be seen without running them. In its own sandbox the agent downloads the modules, runs the suite with the race detector after each file, and can break a branch on purpose to watch the matching row go red before restoring it. The commands and their output stay with the run, so the coverage figures in the pull request are measurements a reviewer can trace, taken on the Go version go.mod names.

It is also work that parallelises cleanly. Each package is independent, each repository gets its own sandbox, and nothing needs a database, so a team can have every service's handlers covered at once and spend its own time reviewing the rows instead of typing them.

Frequently asked questions

Does it need a Postgres database to run the tests?

No. The handlers depend on store interfaces, and the tests supply mocks in the style of the existing MockAuthStore. The Bun-backed stores under database/ are out of scope for this request; ask for them and the agent installs Postgres in its sandbox, runs the migrations and tests the stores against it.

Why are the tests inside the package instead of a _test package?

The resources' router() methods and request types are unexported, so only a test in the same package can mount them. The existing auth test is in package pwdless for the same reason. Mocks live in _test.go files, so they are not compiled into the server.

Will it use testify or another assertion library?

Only if your repository already does. The example's test uses the standard library alone, so the new tests do too, and go.mod gains no dependency. Say so in the prompt if you want a library adopted across the suite.

How does it test routes that need a signed-in user?

With real tokens. The test server mounts the same Verifier and Authenticator middleware the API uses and signs a token for a test account, with or without the admin role, using a secret set in TestMain. That exercises the claims parsing as well as the handler.

More chi jobs

The same job on other stacks

More jobs like this: Write the missing tests

Keep reading