# Write Unit Tests for an Echo API

Yes. An agent writes httptest unit tests for your Echo v5 handlers: JWT login, file upload, the timeout middleware and SSE framing, run with -race, in a PR.

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

## What the agent does

The agent reads the module and the tests it already has before writing any. In a repository laid out like labstack/echox's `cookbook/`, `go.mod` is on Go 1.26 with `echo/v5` 5.4.4, `echo-jwt/v5` 5.0.2, `golang-jwt/jwt/v5`, `gorilla/websocket`, `lestrrat-go/jwx/v3` and `r3labs/sse/v2`; the `Makefile`'s `test` target is `go test -race ./...` and `.github/workflows/ci.yml` runs `go vet ./...` and that same command on every pull request. `cookbook/crud/server_test.go` and the two `cookbook/websocket/*/server_test.go` files set the house style: a `newServer()` that returns the `*echo.Echo`, requests built with `httptest.NewRequest` and `httptest.NewRecorder` and served through `e.ServeHTTP`, `e.Logger = slog.New(slog.DiscardHandler)` to keep the request logger quiet, table-driven error cases, and a `TestConcurrentRequests` whose only point is `-race`. The agent lists the packages with no `_test.go` and picks the ones with behaviour to pin: `jwt/custom-claims`, `jwt/user-defined-keyfunc`, `file-upload/single` and `multiple`, `timeout`, and `sse/simple`.

Where a `main` builds everything inline, it extracts the same `newServer()` the crud example has, so a test can mount the routes without starting a listener. For `jwt/custom-claims` the tests post `username=jon&password=shhh!` as a form to `/login` and decode the `token` from the JSON, send a wrong password and expect 401, call `/restricted` with no token and with a tampered one and expect the two errors echo-jwt answers with, which the agent reads from the middleware's exported errors rather than assuming, and call it with the real token as `Authorization: Bearer` and expect `Welcome Jon Snow!`. A token signed with the same `secret` but an `ExpiresAt` in the past is the last case. `jwt/user-defined-keyfunc` fetches Google's JWKS from `https://www.googleapis.com/oauth2/v3/certs` inside `getKey` on every request, which no unit test can do; the agent moves the URL into a variable the test can point at an `httptest.NewServer` serving a JWKS it generates from a fresh RSA key, signs a token with that key and a `kid`, and asserts the welcome line, the error for a token with no `kid`, and the error for an unknown `kid`.

The upload handlers call `os.Create(file.Filename)` in the working directory, so the tests run from a `t.TempDir()` with `t.Chdir`, build a multipart body with `mime/multipart`, post it to `/upload` and check both the HTML the handler returns and the bytes on disk; the multiple-file variant checks that three files land and that the `name` and `email` fields are echoed. The same test makes the path problem visible: a part named `../escape.txt` is written above the directory, which a cookbook sample never meant to teach. The agent does not fix the handler, because the task is tests; it keeps that case in the file under `t.Skip` with the reason and calls it out in the pull request. For `timeout`, the handler waits ten seconds behind `middleware.ContextTimeout(5 * time.Second)`, so the test would take five seconds per case; `newServer` takes the timeout as a parameter and the test uses 50 milliseconds, asserting the 408 with `Request timed out` and that a fast route is unaffected. For `sse/simple`, `Event.MarshalTo` is pure and gets a table: id, single-line data, data with a newline, event name, retry, a comment alone, and the empty event that writes nothing; the `/sse` route is tested through a real `httptest.NewServer` because it flushes, reading the first two frames with a cancelable context and asserting `Content-Type: text/event-stream` and that the handler returns when the client goes away, the same shape the websocket tests use.

It then runs what CI runs, `go vet ./...` and `go test -race ./...`, plus `gofmt -l`, and pastes the per-package `ok` lines into the pull request. It adds no assertion library, since the module has none and every existing test uses the standard library, and it leaves the packages that already have tests alone. Each extracted `newServer()` is a pure move of the wiring out of `main`, so the sample programs behave exactly as before.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Write unit tests for the Echo v5 handlers in this repository that have none. Read go.mod, Makefile, .github/workflows/ci.yml and the existing cookbook/crud/server_test.go and cookbook/websocket/*/server_test.go first and follow their style: a newServer() that returns the *echo.Echo, httptest.NewRequest and NewRecorder through e.ServeHTTP, e.Logger set to a discarding slog handler, table-driven error cases, standard library only. Cover cookbook/jwt/custom-claims (login success and failure, restricted without a token, with a tampered token, with a valid token, with an expired token, reading echo-jwt's exported errors for the exact responses), cookbook/jwt/user-defined-keyfunc (make the JWKS URL configurable and serve one from httptest with a generated RSA key; test a valid token, no kid, unknown kid), cookbook/file-upload/single and multiple (run from t.TempDir with t.Chdir, build multipart bodies, check the HTML and the files written; keep a path traversal case under t.Skip with the reason and report it), cookbook/timeout (make the timeout a parameter so the test runs in milliseconds; assert the 408 and a fast route), and cookbook/sse/simple (a table for Event.MarshalTo and a streaming test of /sse through httptest.NewServer with a cancelable context). Where a main builds the server inline, extract newServer() without changing behaviour. Run go vet ./..., gofmt -l and go test -race ./... and paste the per-package results into the pull request. Do not touch packages that already have tests and do not add dependencies.",
  "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 six `server_test.go` files and, in four packages, a `newServer()` extracted from `main` with no behaviour change. Its description shows `go test -race ./...` with an `ok` line per package, the `go vet` and `gofmt` runs, and a short table of what each test file pins: the two echo-jwt error responses by their exported names, the welcome line, the 408, the SSE frames byte for byte.

One finding is reported rather than fixed: the upload handlers write `file.Filename` as given, so a crafted part name escapes the working directory. The test for the safe behaviour is in the file under `t.Skip` with that explanation, and the pull request suggests `filepath.Base` as the one-line fix for a maintainer to take separately.

Before merging, a reviewer checks the two refactors that touched the examples themselves, the configurable JWKS URL and the timeout parameter, and decides whether a cookbook page should show them; the pull request keeps each to a single variable so the published snippets still read as before.

## Run it on every night

An automation with a `schedule` trigger, `cron` `0 2 * * *` and your `timezone`, runs this prompt in the Project's repository each night. The sandbox needs nothing beyond the Go toolchain `go.mod` names, which it installs from the `toolchain` line, and the race detector is part of that toolchain, so the run is the same command CI runs.

Each night opens one pull request on its own branch with the tests it added and the per-package results; a night when every package already has tests, or when the only untested code is wiring, ends with a short note and no pull request. `max_runs_per_hour` on the automation keeps a mis-set schedule from starting more than one.

## Why run it on Rush?

Handler tests in Echo are cheap to write and easy to write wrong: a test that starts a real listener on `:1323` collides with the next, a JWKS fetch makes a unit test depend on Google, and a five-second timeout multiplied by a table is a suite nobody runs. The agent reads the tests the repository already trusts and copies their shape, moves the two network and time dependencies behind a variable, and proves the result with `-race` in its own sandbox before opening anything.

The transcript keeps every command and its output, so a reviewer reads the `ok` lines and the skipped case without checking out the branch. Several repositories can get their missing tests at once, each in its own sandbox, and nothing merges until a person reads the diff.

## Frequently asked questions

### Why extract newServer() instead of testing the handler functions directly?

The middleware is part of the behaviour: echo-jwt decides the 401, `ContextTimeout` decides the 408, and `Recover` decides what a panic looks like. Serving a request through the `*echo.Echo` with `e.ServeHTTP` tests the route as a client sees it, and `cookbook/crud` already does it that way, so the new tests match the old ones.

### How does it test the Google-backed key function without the network?

`getKey` fetches a JWKS from a URL; the agent makes that URL a package variable, and the test serves its own JWKS from `httptest.NewServer` built from an RSA key it generated. A token signed with that key and the matching `kid` passes, a token without `kid` fails with the handler's own error, and an unknown `kid` fails with the lookup error, all offline.

### What happens with the path traversal in the upload handler?

The test for the safe behaviour is written and skipped with `t.Skip` and the reason, so the suite stays green and the finding stays visible. The pull request names `filepath.Base(file.Filename)` as the fix and leaves it to the maintainers, because the run was asked for tests and not for a behaviour change.

### Will the suite be slow?

No. The timeout example takes its duration from a parameter so the test uses 50 milliseconds, the SSE test reads two frames and cancels, and nothing opens a real port except the two tests that need streaming, which use `httptest.NewServer` on an ephemeral port. The whole `go test -race ./...` run finishes in seconds.

### Does it add testify or another assertion library?

No. The existing tests use `testing` and `net/http/httptest` only, and the agent follows the repository rather than its own preference. Helpers such as `expectStatus` are written per test file the way `cookbook/crud/server_test.go` does.

## More Echo jobs

- [Add Response Compression to an Echo App](https://getrush.ai/run/add-compression/echo/)
- [Add Test Coverage to CI for an Echo API](https://getrush.ai/run/add-coverage-to-ci/echo/)
- [Add Cursor Pagination to an Echo API](https://getrush.ai/run/add-cursor-pagination/echo/)

## The same job on other stacks

- [Write Unit Tests for an Elixir Project](https://getrush.ai/run/write-unit-tests/elixir/)
- [Write Unit Tests for a Fiber v3 App](https://getrush.ai/run/write-unit-tests/fiber/)
- [Write Unit Tests for a Gatsby Blog](https://getrush.ai/run/write-unit-tests/gatsby/)

## 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/)
