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 25, 2019
1 parent ab83660 commit 222b53e
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 1 deletion.
2 changes: 1 addition & 1 deletion api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ type Client interface {
Do(context.Context, *http.Request) (*http.Response, []byte, error)
}

// DoGetFallback will attempt to do the request as-is, and on a 405 it will fallback to a GET request
// DoGetFallback will attempt to do the request as-is, and on a 405 it will fallback to a GET request.
func DoGetFallback(c Client, ctx context.Context, u *url.URL, args url.Values) (*http.Response, []byte, error) {
req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(args.Encode()))
if err != nil {
Expand Down
72 changes: 72 additions & 0 deletions api/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,14 @@
package api

import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"testing"

"github.com/prometheus/tsdb/testutil"
)

func TestConfig(t *testing.T) {
Expand Down Expand Up @@ -113,3 +118,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
}

// 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 req.URL.Path == "/blockPost" {
http.Error(w, string(body), http.StatusMethodNotAllowed)
return
}
}

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

u, err := url.Parse(server.URL)
testutil.Ok(t, err)
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
u.Path = "/blockPost"
_, 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 222b53e

Please sign in to comment.