hashicorp / hashicorp/consul

[refactor] Test endpoints through ServeHTTP, not by raw handler

Open
#11,396 2 comments 1 reaction 0 assignees View on GitHub
theme/api theme/internal-cleanup
Dominant language
Go
Stars
30.1k
Forks
4.6k
Avg merge
1d 18h
Merged PRs (30d)
39

Description

### Background
In many places in our tests, when we want to make API calls to handlers, we tend to use the raw handler (e.g. `a.srv.AgentToken(resp, req)`).

This is problematic because it skips the middleware that real HTTP requests go through, which includes (but is not limited to) multiplexing based on URL patterns, blocking not-allowed HTTP methods, and translating application-level errors to HTTP error codes and messages.

This means that developer errors like this may not get caught by the test suite:
```go
// http_register.go
// registerEndpoint("/v1/agent/join/", []string{"PUT"}, (*HTTPHandlers).AgentJoin)

req, _ := http.NewRequest("GET", "/v1/agent/node", nil) // wrong method and endpoint

resp := httptest.NewRecorder()
_, err := a.srv.AgentJoin(resp, req) // does not immediately reject the request
```

`AgentJoin` is not responsible for validating the request's URL or method and may fail in unpredictable ways, wasting developer time or misleading devs to make incorrect test assertions.

### Solution

The proposed solution is to start using `Agent.srv.h.ServeHTTP(resp, req)` to handle requests generically instead of specifying a typed handler.

See examples [here](https://github.com/hashicorp/consul/blob/main/agent/acl_endpoint_legacy_test.go#L26-L32).

### Related PRs

https://github.com/hashicorp/consul/pull/11445 (thanks @Mathew-Estafanous)

Contributor guide

Open the contributing guide

Research direction

Start with the examples in agent/acl_endpoint_legacy_test.go and the endpoint registration described in http_register.go. Locate tests that call typed handlers directly and evaluate converting them to ServeHTTP requests. Done means the tests exercise routing, method validation, and HTTP error translation through the normal middleware path.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
api, testing
Issue type
Refactor
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.