Skip to content

Commit

Permalink
Add WithBasicAuth
Browse files Browse the repository at this point in the history
  • Loading branch information
gavv committed Jun 29, 2016
1 parent 3e8b004 commit 251b663
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
17 changes: 15 additions & 2 deletions expect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,14 +183,22 @@ func createBasicHandler() http.Handler {
}
})

mux.HandleFunc("/wee", func(w http.ResponseWriter, r *http.Request) {
if u, p, ok := r.BasicAuth(); ok {
w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
w.Write([]byte(`username=` + u))
w.Write([]byte(`&password=` + p))
} else {
w.WriteHeader(http.StatusBadRequest)
}
})

return mux
}

func testBasicHandler(e *Expect) {
e.GET("/foo")

e.GET("/foo").Expect()

e.GET("/foo").Expect().Status(http.StatusOK)

e.GET("/foo").Expect().
Expand All @@ -211,6 +219,11 @@ func testBasicHandler(e *Expect) {
WithJSON(map[string]string{"test": "ok"}).
Expect().
Status(http.StatusNoContent).Body().Empty()

e.PUT("/wee").WithBasicAuth("john", "secret").
Expect().
Status(http.StatusOK).
Form().ValueEqual("username", "john").ValueEqual("password", "secret")
}

func TestExpectBasicHandlerLiveDefault(t *testing.T) {
Expand Down
14 changes: 14 additions & 0 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,20 @@ func (r *Request) WithCookie(k, v string) *Request {
return r
}

// WithBasicAuth sets the request's Authorization header to use HTTP
// Basic Authentication with the provided username and password.
//
// With HTTP Basic Authentication the provided username and password
// are not encrypted.
//
// Example:
// req := NewRequest(config, "PUT", "http://example.org/path")
// req.WithBasicAuth("john", "secret")
func (r *Request) WithBasicAuth(username, password string) *Request {
r.http.SetBasicAuth(username, password)
return r
}

// WithChunked enables chunked encoding and sets request body reader.
//
// Expect() will read all available data from given reader. Content-Length
Expand Down
19 changes: 19 additions & 0 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,25 @@ func TestRequestCookies(t *testing.T) {
assert.Equal(t, &client.resp, resp.Raw())
}

func TestRequestBasicAuth(t *testing.T) {
client := &mockClient{}

reporter := newMockReporter(t)

config := Config{
Client: client,
Reporter: reporter,
}

req := NewRequest(config, "METHOD", "url")

req.WithBasicAuth("Aladdin", "open sesame")
req.chain.assertOK(t)

assert.Equal(t, "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
req.http.Header.Get("Authorization"))
}

func TestRequestBodyChunked(t *testing.T) {
client := &mockClient{}

Expand Down

0 comments on commit 251b663

Please sign in to comment.