Skip to content

Commit

Permalink
Add test for client's POST fallback
Browse files Browse the repository at this point in the history
Signed-off-by: Thomas Jackson <jacksontj.89@gmail.com>
  • Loading branch information
jacksontj committed Apr 24, 2019
1 parent 22f9e9b commit 2d0ac02
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions api/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@
package api

import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
Expand Down Expand Up @@ -113,3 +116,70 @@ func TestClientURL(t *testing.T) {
}
}
}

func TestDoGetFallback(t *testing.T) {
v := url.Values{"a": []string{"1", "2"}}

type testResponse struct {
Values string
Method string
}

acceptPost := true
// Start a local HTTP server
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
r := &testResponse{
Values: req.Form.Encode(),
Method: req.Method,
}

body, _ := json.Marshal(r)

if req.Method == http.MethodPost {
if !acceptPost {
http.Error(w, string(body), http.StatusMethodNotAllowed)
return
}
}

w.Write(body)
}))
// Close the server when test finishes
defer server.Close()

u, _ := url.Parse(server.URL)
client := &httpClient{client: *(server.Client())}

// Do a post, and ensure that the post succeeds
_, b, err := DoGetFallback(client, context.TODO(), u, v)
if err != nil {
t.Fatalf("Error doing local request: %v", err)
}
resp := &testResponse{}
if err := json.Unmarshal(b, resp); err != nil {
t.Fatal(err)
}
if resp.Method != http.MethodPost {
t.Fatalf("Mismatch method")
}
if resp.Values != v.Encode() {
t.Fatalf("Mismatch in values")
}

// Do a fallbcak to a get
acceptPost = false
_, b, err = DoGetFallback(client, context.TODO(), u, v)
if err != nil {
t.Fatalf("Error doing local request: %v", err)
}
if err := json.Unmarshal(b, resp); err != nil {
t.Fatal(err)
}
if resp.Method != http.MethodGet {
t.Fatalf("Mismatch method")
}
if resp.Values != v.Encode() {
t.Fatalf("Mismatch in values")
}
}

0 comments on commit 2d0ac02

Please sign in to comment.