oauth2_proxy/api/api_test.go

130 lines
3.6 KiB
Go
Raw Normal View History

package api
import (
2015-05-13 01:48:13 +00:00
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
2018-11-29 14:26:41 +00:00
"github.com/bitly/go-simplejson"
"github.com/stretchr/testify/assert"
)
2018-11-29 14:26:41 +00:00
func testBackend(responseCode int, payload string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
2018-11-29 14:26:41 +00:00
w.WriteHeader(responseCode)
w.Write([]byte(payload))
}))
}
func TestRequest(t *testing.T) {
backend := testBackend(200, "{\"foo\": \"bar\"}")
defer backend.Close()
req, _ := http.NewRequest("GET", backend.URL, nil)
response, err := Request(req)
assert.Equal(t, nil, err)
result, err := response.Get("foo").String()
assert.Equal(t, nil, err)
assert.Equal(t, "bar", result)
}
func TestRequestFailure(t *testing.T) {
// Create a backend to generate a test URL, then close it to cause a
// connection error.
backend := testBackend(200, "{\"foo\": \"bar\"}")
backend.Close()
req, err := http.NewRequest("GET", backend.URL, nil)
assert.Equal(t, nil, err)
resp, err := Request(req)
assert.Equal(t, (*simplejson.Json)(nil), resp)
assert.NotEqual(t, nil, err)
Reload authenticated-emails-file upon update This change extracts the UserMap class from NewValidator() so that its LoadAuthenticatedEmailsFile() method can be called concurrently. This method is called by a goroutine containing a fsnotify.Watcher watching the authenticated emails file. Watching isn't forever aborted when the authenticated emails file disappears. The goroutine will call os.Stat() up to twenty times a second if the file is persistently missing, but that's the pathological case, not the common one. The common case is that some editors (including Vim) will perform a rename-and-replace when updating a file, triggering fsnotify.Rename events, and the file will temporarily disappear. This watcher goroutine handles that case. Also, on some platforms (notably Arch Linux), a remove will be preceded by a fsnotify.Chmod, causing a race between the upcoming fsnotify.Remove and the call to UserMap.LoadAuthenticatedEmailsFile(). Hence, we treat fsnotify.Chmod the same as fsnotify.Remove and fsnotify.Rename. There's no significant penalty to re-adding a file to the watcher. Also contains the following small changes from the summary of commits below: - Minor optimization of email domain search - Fixed api_test.go on Windows - Add deferred File.Close() calls where needed - Log error and return if emails file doesn't parse These are the original commits from #89 squashed into this one: 0c6f2b6 Refactor validator_test to prepare for more tests e0c792b Add more test cases to validator_test a9a9d93 Minor optimization of email domain search b763ea5 Extract LoadAuthenticatedEmailsFile() 8cdaf7f Introduce synchronized UserMap type 1b84eef Add UserMap methods, locking af15dcf Reload authenticated-emails-file upon update 6d95548 Make UserMap operations lock-free Per: - http://stackoverflow.com/questions/21447463/is-assigning-a-pointer-atomic-in-golang - https://groups.google.com/forum/#!msg/golang-nuts/ueSvaEKgyLY/ZW_74IC4PekJ 75755d5 Fix tests on Windows d0eab2e Ignore email file watcher Chmod events 0b9798b Fix watcher on Ubuntu 12.04 3a8251a WaitForReplacement() to retry emails file watch a57fd29 Add deferred File.Close() calls where needed Because correctness: Don't leak file handles anywhere, and prepare for future panics and early returns. 52ed3fd Log error and return if emails file doesn't parse 40100d4 Add gopkg.in/fsnotify.v1 dependency to Godeps file 17dfbbc Avoid a race when Remove is preceded by Chmod
2015-05-09 23:31:38 +00:00
if !strings.Contains(err.Error(), "refused") {
t.Error("expected error when a connection fails: ", err)
}
}
func TestHttpErrorCode(t *testing.T) {
backend := testBackend(404, "{\"foo\": \"bar\"}")
defer backend.Close()
req, err := http.NewRequest("GET", backend.URL, nil)
assert.Equal(t, nil, err)
resp, err := Request(req)
assert.Equal(t, (*simplejson.Json)(nil), resp)
assert.NotEqual(t, nil, err)
}
func TestJsonParsingError(t *testing.T) {
backend := testBackend(200, "not well-formed JSON")
defer backend.Close()
req, err := http.NewRequest("GET", backend.URL, nil)
assert.Equal(t, nil, err)
resp, err := Request(req)
assert.Equal(t, (*simplejson.Json)(nil), resp)
assert.NotEqual(t, nil, err)
}
2015-05-13 01:48:13 +00:00
// Parsing a URL practically never fails, so we won't cover that test case.
func TestRequestUnparsedResponseUsingAccessTokenParameter(t *testing.T) {
backend := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
token := r.FormValue("access_token")
if r.URL.Path == "/" && token == "my_token" {
w.WriteHeader(200)
w.Write([]byte("some payload"))
} else {
w.WriteHeader(403)
}
}))
defer backend.Close()
response, err := RequestUnparsedResponse(
backend.URL+"?access_token=my_token", nil)
assert.Equal(t, nil, err)
assert.Equal(t, 200, response.StatusCode)
body, err := ioutil.ReadAll(response.Body)
assert.Equal(t, nil, err)
response.Body.Close()
assert.Equal(t, "some payload", string(body))
}
func TestRequestUnparsedResponseUsingAccessTokenParameterFailedResponse(t *testing.T) {
backend := testBackend(200, "some payload")
// Close the backend now to force a request failure.
backend.Close()
response, err := RequestUnparsedResponse(
backend.URL+"?access_token=my_token", nil)
assert.NotEqual(t, nil, err)
assert.Equal(t, (*http.Response)(nil), response)
}
func TestRequestUnparsedResponseUsingHeaders(t *testing.T) {
backend := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" && r.Header["Auth"][0] == "my_token" {
w.WriteHeader(200)
w.Write([]byte("some payload"))
} else {
w.WriteHeader(403)
}
}))
defer backend.Close()
headers := make(http.Header)
headers.Set("Auth", "my_token")
response, err := RequestUnparsedResponse(backend.URL, headers)
assert.Equal(t, nil, err)
assert.Equal(t, 200, response.StatusCode)
body, err := ioutil.ReadAll(response.Body)
assert.Equal(t, nil, err)
response.Body.Close()
assert.Equal(t, "some payload", string(body))
}