Created
November 2, 2019 19:34
-
-
Save efueyo/b4bf63e4ee946039f944bbfa4e46c07d to your computer and use it in GitHub Desktop.
MockedServer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const books string = ` | |
[ | |
{ "id": 1, "title": "Pedro Páramo", author: "Juan Rulfo" }, | |
{ "id": 2, "title": "Meditations", author: "Marcus Aurelius" }, | |
{ "id": 3, "title": "Walden", author: "Henry David Thoreau" } | |
] | |
` | |
const book1 string = ` | |
{ "id": 1, "title": "Pedro Páramo", author: "Juan Rulfo" } | |
` | |
const ok string = ` | |
{ "ok": true } | |
` | |
// NewBooksServer returns a new mocked Books Server. You will need to call Close when finished | |
func NewBooksServer(token string) *Server { | |
authorization := fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(token))) | |
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
resp := []byte("Not found") | |
status := http.StatusNotFound | |
if r.Header.Get("Authorization") != authorization { | |
http.Error(w, "Unauthorized", http.StatusUnauthorized) | |
return | |
} | |
switch r.Method { | |
case http.MethodGet: | |
switch r.URL.Path { | |
case "/api/books.json": | |
resp = []byte(books) | |
status = http.StatusOK | |
case "/api/books/1.json": | |
resp = []byte(book1) | |
status = http.StatusOK | |
} | |
case http.MethodPost: | |
switch r.URL.Path { | |
case "/api/books.json": | |
resp = []byte(ok) | |
status = http.StatusAccepted | |
} | |
case http.MethodPut: | |
switch r.URL.Path { | |
case "/api/books/1.json": | |
resp = []byte(ok) | |
status = http.StatusAccepted | |
} | |
case http.MethodDelete: | |
switch r.URL.Path { | |
case "/api/books/1.json": | |
resp = []byte(ok) | |
status = http.StatusAccepted | |
} | |
w.WriteHeader(status) | |
w.Write(resp) | |
})) | |
} | |
// then, in the tests: | |
func TestSomething(t *testing.T){ | |
token := "a-token-for-tests" | |
ts := NewBooksServer(token) | |
defer ts.Close() | |
client := NewBooksClient(ts.URL, token) // NewBooksClient(apiURL, token string)... | |
books, _ := client.GetBooks() // omit error for this gist | |
MustCheckGolden(t, books) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment