HTTP integration tests with MySQL fixtures
Test a running API with database-backed fixtures so your integration suite can verify pagination and filtering through the actual restaurant-list contract.
Learning outcomes
- Explain what testing the running API against real MySQL catches that a fake cannot.
- Configure integration tests using
TEST_API_URLandTEST_MYSQL_DSN. - Isolate fixtures in a shared database using generated IDs and
t.Cleanup. - Test complete pagination walks using opaque cursors and set-based ID comparisons.
- Detect filtering and cursor regressions while handling HTTP rate limits.
The restaurant list already supports geographic filtering and keyset pagination. You need to verify that GET /v1/restaurants actually returns every matching restaurant, without duplicates, inactive rows or restaurants outside the requested geographic bounds.
Build a Go integration test suite in backend/integration. Your tests will write fixture restaurants into MySQL and call a running API over HTTP. The database already contains 50 seeded restaurants and may contain rows from other tests, so your tests must account for shared data.
The HTTP and database boundary
A unit test can provide a fake Queries implementation and verify how the restaurant service handles returned records. It cannot establish that the real SQL works against MySQL or that the HTTP handler and database query are wired together correctly.
Consider what happens when the listing query contains a missing geographic predicate. A fake can return exactly the rows your test asks it to return, even when the actual SQL would include distant restaurants.
The same applies to pagination. A fake can provide the expected rows while the real SQL uses the wrong comparison or fails to fetch the extra row needed to detect another page.
An Integration test exercises multiple parts of the application together through a real dependency. Here, your test sends HTTP requests to a running Go API while that API reads from a real MySQL database.
This exercises the actual path:
- Your Go integration test sends an HTTP request.
- The running API queries MySQL.
- The API returns an HTTP response.
- Your test asserts on the response.
This catches problems that unit tests with fake dependencies cannot establish:
- SQL predicates that do not filter the intended rows.
- Pagination queries that use incorrect boundaries or limits.
- Database and application wiring problems.
- Mismatches between database values and the values returned by the API.
You do not need to replace your unit tests. Keep them for isolated business rules and use integration tests to verify that the actual database and HTTP boundary work together.
Test configuration
Your integration suite uses two environment variables.
TEST_API_URL identifies the base URL of the running API. TEST_MYSQL_DSN identifies the MySQL database that the API reads.
Read both at test startup:
apiURL := os.Getenv("TEST_API_URL")
dsn := os.Getenv("TEST_MYSQL_DSN")
if apiURL == "" || dsn == "" {
t.Fatal("TEST_API_URL and TEST_MYSQL_DSN are required")
}The API and test database connections must point to the same database. Otherwise, your test might insert fixtures into one database while the API queries another.
Use TEST_MYSQL_DSN to open a database connection:
db, err := sql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
if err := db.PingContext(t.Context()); err != nil {
t.Fatal(err)
}sql.Open creates a database handle but does not necessarily establish a connection immediately. PingContext verifies that the database is reachable.
Validate TEST_API_URL as an absolute URL before constructing requests. Build listing URLs with net/url and url.Values so query parameters are encoded correctly.
The tests run with a supplied API URL. They do not start the application themselves. The grader changes this URL to point at different implementations while keeping the database available.
Use -count=1 when running the tests. This disables Go's successful test-result cache, ensuring that the integration suite executes against the current API and database state.
Fixture isolation in a shared database
Test isolation means each test controls the database state it creates and does not depend on rows left behind by another test.
This is Test isolation. You can achieve it with a private database per test or by carefully isolating your fixtures inside a shared database.
The W2B8 suite uses the second approach. MySQL already contains 50 seeded restaurants, and other tests may have inserted additional rows.
Never assume that the restaurants table starts empty.
Inserting identifiable fixtures
Give your test restaurants recognizable names and record every generated database ID. These IDs let you identify exactly which rows belong to your test.
For example:
type fixture struct {
db *sql.DB
ids []int64
}
func (f *fixture) insert(t *testing.T, lat, lng float64, active bool) int64 {
t.Helper()
result, err := f.db.ExecContext(t.Context(),
"INSERT INTO restaurants (name, lat, lng, is_active) VALUES (?, ?, ?, ?)",
fmt.Sprintf("W2B8 integration %d", time.Now().UnixNano()),
lat, lng, active)
if err != nil {
t.Fatal(err)
}
id, err := result.LastInsertId()
if err != nil {
t.Fatal(err)
}
f.ids = append(f.ids, id)
return id
}LastInsertId gives you the database-generated ID. Do not assume that the first fixture receives ID 1 or that subsequent tests start from the same auto-increment value.
Use the returned IDs to build expected results. When unrelated rows could also match the request, either isolate the fixture location from existing data or query MySQL to determine the complete expected set.
Your assertions must reflect the actual data in the database, not an imagined empty database.
Cleanup with t.Cleanup
Register cleanup as soon as you acquire the database resources. t.Cleanup runs when the test finishes, including when an assertion calls t.Fatal.
Delete only the restaurant IDs your fixture inserted:
t.Cleanup(func() {
for _, id := range f.ids {
_, err := f.db.ExecContext(context.Background(),
"DELETE FROM restaurants WHERE id = ?", id)
if err != nil {
t.Errorf("delete fixture %d: %v", id, err)
}
}
if err := f.db.Close(); err != nil {
t.Errorf("close fixture database: %v", err)
}
})The cleanup uses context.Background() because t.Context() is cancelled when the test finishes, before cleanup functions execute.
The database connection is closed after deleting the fixtures. This keeps the cleanup order explicit.
Database isolation strategies
There are three common approaches to database-backed test isolation.
A private database per test
Each test creates its own database, applies the schema and drops the database during cleanup. This provides strong isolation, but it does not fit this exercise because the API is already running and connects to its configured database. Creating another database does not redirect the running API to it.
A transaction rolled back after the test
A transaction can isolate fixture writes when all operations use the same transaction. However, the running API uses a separate database connection. It cannot see uncommitted fixture rows from your test transaction. Committing those rows would also mean cleanup must remove them separately.
Truncating tables between tests
Truncation can clear a database, but this suite shares its database with seeded restaurants and other tests. Removing those rows would damage data that your test does not own.
For this exercise, use identifiable fixtures and delete their exact IDs. This gives the running API access to committed fixture rows without disturbing unrelated data.
Pagination as a public contract
The restaurant list uses Keyset pagination. A client follows next_cursor to retrieve the next page until the cursor is empty.
Testing only the first page cannot prove that pagination works. The first page might look correct while subsequent pages repeat or omit restaurants.
Your test should walk the complete result set. It should use a small limit so that the fixture dataset spans several pages.
Treat next_cursor as an Opaque cursor. You do not need to understand its encoding. Pass the exact string returned by one response into the next request.
A decoded response can use these fields:
type restaurantItem struct {
ID int64 `json:"id"`
}
type restaurantPage struct {
Items []restaurantItem `json:"items"`
NextCursor *string `json:"next_cursor"`
}Checking that Items is not nil and NextCursor is not nil lets you distinguish a missing JSON field from a valid empty array or empty cursor.
Collecting every page
Maintain a set of restaurant IDs encountered across all pages. A duplicate means the pagination walk has repeated a restaurant.
For each page, also check that its item count does not exceed the requested limit.
The structure is:
cursor := ""
seen := empty set
repeat:
page := request(cursor)
verify page size
add every ID, failing on duplicates
if next_cursor is empty:
compare seen with expected IDs
finish
cursor := next_cursorPut a maximum page count on the loop. Choose a cap comfortably above the number of pages your fixtures should require. This prevents a broken cursor that never reaches the empty value from running forever without making a valid fixture walk fail prematurely.
An empty page with a non-empty next_cursor is also a failure. No restaurants were returned, so the client has made no useful progress.
Comparing the complete result
At the end of the walk, compare the IDs you collected with the expected IDs.
Use set comparison when the contract does not guarantee a particular ordering. Check that every expected ID appeared exactly once and that no unexpected ID appeared.
Do not compare only the number of returned restaurants. A result with one missing restaurant and one duplicate can have the correct total length.
For example, suppose your fixtures produce:
Expected: {101, 102, 103, 104, 105}
Actual: {101, 102, 103, 103, 105}Both collections have five entries, but restaurant 103 appears twice and restaurant 104 is missing.
Checking membership and occurrence counts exposes both problems.
The grader also runs your suite against a different correct implementation. That implementation can use another cursor format and need not use the exact same ordering. Tests that decode the cursor or compare a specific ordering may reject a correct implementation.
Focus on the observable contract: every expected restaurant must appear exactly once, and the walk must finish.
Fixture design for filtering
A good filtering test inserts rows that should and should not appear in the same request.
For example, create:
- An active restaurant inside the requested geographic bounds.
- An inactive restaurant inside those bounds.
- An active restaurant outside the requested radius.
The first must appear. The other two must not.
The default restaurant listing uses a geographic square based on the latitude and longitude bounds. Place excluded fixtures far enough outside the relevant bounds to make their exclusion unambiguous.
You can also place one fixture outside only the latitude range and another outside only the longitude range. This exposes a query that accidentally omits one of the geographic predicates.
Avoid testing filters only with rows that violate several conditions simultaneously. Such a fixture might still be excluded when one of the filters is broken, hiding the regression.
Testing cursor errors
An invalid cursor is an observable HTTP error. You do not need to inspect the application's cursor implementation to test it.
Send a forged cursor that your test did not receive from the API:
GET /v1/restaurants?lat=28.46&lng=77.03&radius_km=5&limit=5&cursor=not-a-valid-cursorThe expected response is HTTP 400 with:
{
"error": "invalid_cursor",
"message": "..."
}The message can vary. Assert the status code and the stable error value, not an exact human-readable message.
This checks that the API rejects cursors it did not issue instead of silently restarting pagination from the beginning.
Rate limits and HTTP retries
Every API route is rate limited. When a client exceeds the limit, the API responds with HTTP 429 and error: "rate_limited".
The response includes Retry-After in seconds. Your integration client must respect this header and retry rather than treating rate limiting as a permanent test failure.
A request helper can use this structure:
for attempt := range 6 {
resp, body := sendRequest()
if resp.StatusCode != http.StatusTooManyRequests {
return resp, body
}
seconds, err := strconv.Atoi(resp.Header.Get("Retry-After"))
if err != nil || seconds < 1 {
seconds = 1
}
time.Sleep(time.Duration(seconds) * time.Second)
}Read and close each response body before retrying. After the retry limit is exhausted, fail with the response details so you can distinguish persistent rate limiting from an endpoint error.
Set an X-User-ID header in your requests. Rate limiting is keyed by that header when present, rather than by the shared client IP.
Keep the retry policy in one helper. Otherwise, each test may handle HTTP 429 differently, and a successful test could depend on request timing.
Thinking in regressions
An integration suite is useful when it catches plausible mistakes in the implementation.
Think about each test in terms of the bug it should expose:
| Test scenario | Regression it should catch |
|---|---|
| Multiple full pages | A restaurant is dropped from every full page |
| Duplicate detection | The last restaurant is repeated on the next page |
| Complete cursor walk | Pagination stops before all matching restaurants are returned |
| Inactive fixture | Inactive restaurants appear in the list |
| Distant fixture | The geographic filter is ignored |
| Small requested limit | The API returns more items than the requested limit |
| Forged cursor | An invalid cursor is accepted instead of returning an error |
These cases should be independent enough that a failure tells you which observable behavior is broken.
The grader checks this property by running your tests against seven deliberately broken implementations, one bug at a time. Your suite must fail against each broken implementation while passing against your own API and a different correct implementation.
That last requirement is important. A test that catches a bug by assuming an undocumented cursor encoding is not a good contract test. It may reject an implementation that is completely correct.
The restaurant list integration suite
The Restaurant list integration suite exercise puts these ideas together in backend/integration.
You will write tests that insert their own fixtures through TEST_MYSQL_DSN, call GET /v1/restaurants through TEST_API_URL and verify the complete pagination and filtering behavior.
Keep the tests focused on externally observable results. Let the database provide the fixture IDs and expected data, let the API provide the cursor, and let cleanup remove only the rows your tests created.
Check your understanding
A unit test passes using a fake Queries implementation. The real restaurant list query accidentally omits the longitude filter. Why can the unit test still pass?
References
Everything above is explained on this page; these are where it comes from (Go 1.25 testing, MySQL 8, go-sql-driver/mysql).