Documentation
¶
Overview ¶
Package reqtest contains helpers for writing tests of HTTP clients and servers.
Index ¶
- func Caching(rt http.RoundTripper, basepath string) requests.Transport
- func Record(rt http.RoundTripper, basepath string) requests.Transport
- func Replay(basepath string) requests.Transport
- func ReplayFS(fsys fs.FS) requests.Transport
- func ReplayJSON(code int, obj any) requests.Transport
- func ReplayString(rawResponse string) requests.Transport
- func Server(s *httptest.Server) requests.Config
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Caching ¶
func Caching(rt http.RoundTripper, basepath string) requests.Transport
Caching returns an http.RoundTripper that attempts to read its responses from text files in basepath. If the response is absent, it caches the result of issuing the request with rt in basepath. Requests are named according to a hash of their contents. Responses are named according to the request that made them.
func Record ¶
func Record(rt http.RoundTripper, basepath string) requests.Transport
Record returns an http.RoundTripper that writes out its requests and their responses to text files in basepath. Requests are named according to a hash of their contents. Responses are named according to the request that made them.
func Replay ¶
Replay returns an http.RoundTripper that reads its responses from text files in basepath. Responses are looked up according to a hash of the request. Response file names may optionally be prefixed with comments for better human organization.
func ReplayFS ¶
ReplayFS returns an http.RoundTripper that reads its responses from text files in the fs.FS. Responses are looked up according to a hash of the request. Response file names may optionally be prefixed with comments for better human organization.
Example ¶
package main
import (
"context"
"fmt"
"testing/fstest"
"github.com/carlmjohnson/requests"
"github.com/carlmjohnson/requests/reqtest"
)
func main() {
fsys := fstest.MapFS{
"fsys.example - MKIYDwjs.res.txt": &fstest.MapFile{
Data: []byte(`HTTP/1.1 200 OK
Content-Type: text/plain; charset=UTF-8
Date: Mon, 24 May 2021 18:48:50 GMT
An example response.`),
},
}
var s string
const expected = `An example response.`
if err := requests.
URL("http://fsys.example").
Transport(reqtest.ReplayFS(fsys)).
ToString(&s).
Fetch(context.Background()); err != nil {
panic(err)
}
fmt.Println(s == expected)
}
Output: true
func ReplayJSON ¶ added in v0.25.1
ReplayJSON returns a requests.Transport that always responds with the given object marshaled as JSON and the provided HTTP status code. The object is marshaled on each request, so modifications to mutable objects will be reflected in subsequent responses.
If the object cannot be marshaled to JSON, the transport returns the wrapped marshaling error.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"github.com/carlmjohnson/requests"
"github.com/carlmjohnson/requests/reqtest"
)
func main() {
// Create a ReplayJSON transport for testing
data := map[string]any{
"message": "Hello, World!",
"ok": true,
"count": 42,
}
transport := reqtest.ReplayJSON(http.StatusOK, data)
{
type Result struct {
Message string `json:"message"`
OK bool `json:"ok"`
Count int `json:"count"`
}
var result Result
err := requests.
URL("http://example.com/api").
Transport(transport).
ToJSON(&result).
Fetch(context.Background())
if err != nil {
panic(err)
}
fmt.Printf("Message: %s\n", result.Message)
fmt.Printf("Okay: %v\n", result.OK)
fmt.Printf("Count: %d\n", result.Count)
}
// Modify backing map and result will change
data["message"] = "Error!"
data["ok"] = false
data["count"] = 0
{
type Result struct {
Message string `json:"message"`
OK bool `json:"ok"`
Count int `json:"count"`
}
var result Result
err := requests.
URL("http://example.com/api").
Transport(transport).
ToJSON(&result).
Fetch(context.Background())
if err != nil {
panic(err)
}
fmt.Printf("Message: %s\n", result.Message)
fmt.Printf("Okay: %v\n", result.OK)
fmt.Printf("Count: %d\n", result.Count)
}
}
Output: Message: Hello, World! Okay: true Count: 42 Message: Error! Okay: false Count: 0
func ReplayString ¶
ReplayString returns an http.RoundTripper that always responds with a request built from rawResponse. It is intended for use in one-off tests.
Example ¶
package main
import (
"context"
"fmt"
"github.com/carlmjohnson/requests"
"github.com/carlmjohnson/requests/reqtest"
)
func main() {
const res = `HTTP/1.1 200 OK
An example response.`
var s string
const expected = `An example response.`
if err := requests.
URL("http://response.example").
Transport(reqtest.ReplayString(res)).
ToString(&s).
Fetch(context.Background()); err != nil {
panic(err)
}
fmt.Println(s == expected)
}
Output: true
func Server ¶
Server takes an httptest.Server and returns a requests.Config which sets the requests.Builder's BaseURL to s.URL and the requests.Builder's Client to s.Client().
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"github.com/carlmjohnson/requests"
"github.com/carlmjohnson/requests/reqtest"
)
func main() {
// Create an httptest.Server for your project's router
mux := http.NewServeMux()
mux.HandleFunc("/greeting", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world!")
})
mux.HandleFunc("/salutation", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Howdy, planet!")
})
srv := httptest.NewServer(mux)
defer srv.Close()
// Now test that the handler has the expected return values
{
var s string
err := requests.
New(reqtest.Server(srv)).
Path("/greeting").
ToString(&s).
Fetch(context.Background())
if err != nil {
fmt.Println("Error!", err)
}
fmt.Println(s) // Hello, world!
}
{
var s string
err := requests.
New(reqtest.Server(srv)).
Path("/salutation").
ToString(&s).
Fetch(context.Background())
if err != nil {
fmt.Println("Error!", err)
}
fmt.Println(s) // Howdy, planet!
}
}
Output: Hello, world! Howdy, planet!
Types ¶
This section is empty.