Skip to content

Instantly share code, notes, and snippets.

@cyx
Created November 21, 2020 01:40
Show Gist options
  • Save cyx/abe013cfb3b016718f34c19bc23af38f to your computer and use it in GitHub Desktop.
Save cyx/abe013cfb3b016718f34c19bc23af38f to your computer and use it in GitHub Desktop.
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestAdmin(t *testing.T) {
srv := httptest.NewServer(authenticate(adminHandler))
defer srv.Close()
tests := []struct {
name string
user string
pass string
wantStatus int
}{
{
name: "unauthenticated",
user: "",
pass: "",
wantStatus: http.StatusUnauthorized,
},
{
name: "authenticated",
user: "john",
pass: "secret",
wantStatus: http.StatusOK,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, srv.URL, nil)
if err != nil {
t.Fatal(err)
}
req.SetBasicAuth(test.user, test.pass)
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
if want, got := test.wantStatus, res.StatusCode; want != got {
t.Fatalf("wanted status: %d, got %d", want, got)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment