Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test(middleware): Improves test coverage #700

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions middleware/basic_auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package middleware

import (
"net/http"
"net/http/httptest"
"testing"

chi "github.com/go-chi/chi/v5"
)

var testAuthCreds = map[string]string{
"testUser": "testPassword",
}

func TestBasicAuth(t *testing.T) {
r := chi.NewRouter()
r.Use(BasicAuth("localhost", testAuthCreds))
r.Get("/secure", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("authentication accepted"))
}))

cases := []struct {
name string
digest string
expected int
errorMessage string
wantErr bool
}{
{
name: "No auth header provided",
expected: http.StatusUnauthorized,
errorMessage: "basic auth: accepted request without a valid header",
wantErr: true,
},
{
name: "Invalid auth header provided",
digest: "Basic dGVzdFVzZXI6d3JvbmdwYXNzd29yZA==",
expected: http.StatusUnauthorized,
errorMessage: "basic auth: accepted invalid bearer token",
wantErr: true,
},
{
name: "Valid auth header provided",
digest: "Basic dGVzdFVzZXI6dGVzdFBhc3N3b3Jk",
expected: http.StatusOK,
errorMessage: "basic auth: did not accept a valid bearer token",
wantErr: false,
},
}

for _, c := range cases {
// Record response
w := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/secure", nil)
if err != nil {
t.Fatalf("basic auth: failed to create test request")
}

if c.digest != "" {
req.Header.Set("Authorization", c.digest)
}

// Serve request
r.ServeHTTP(w, req)

// Test response code
if w.Result().StatusCode != c.expected {
t.Errorf(c.errorMessage)
}
}
}
23 changes: 23 additions & 0 deletions middleware/clean_path_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package middleware

import (
"net/http"
"net/http/httptest"
"testing"

chi "github.com/go-chi/chi/v5"
)

func TestCleanPath(t *testing.T) {
r := chi.NewRouter()
r.Use(CleanPath)
r.Get("/users/1", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }))

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/users////1", nil)
r.ServeHTTP(w, req)

if w.Result().StatusCode != http.StatusOK {
t.Errorf("clean path: unexpected response code: %v", w.Result().StatusCode)
}
}
23 changes: 23 additions & 0 deletions middleware/heartbeat_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package middleware

import (
"net/http"
"net/http/httptest"
"testing"

chi "github.com/go-chi/chi/v5"
)

func TestHeartbeat(t *testing.T) {
r := chi.NewRouter()
r.Use(Heartbeat("/ping"))
r.Get("/ping", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/ping", nil)
r.ServeHTTP(w, req)

if w.Result().StatusCode != http.StatusOK {
t.Errorf("heartbeat: unexpected response code: %v", w.Result().StatusCode)
}
}
44 changes: 44 additions & 0 deletions middleware/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ import (
"path"
"reflect"
"runtime"
"strings"
"testing"
"time"

chi "github.com/go-chi/chi/v5"
)

var testdataDir string
Expand All @@ -20,6 +23,47 @@ func init() {
testdataDir = path.Join(path.Dir(filename), "/../testdata")
}

type customMiddleware struct{}

func (c *customMiddleware) ServeHTTP(w http.ResponseWriter, req *http.Request) {
for name, headers := range req.Header {
if strings.ToLower(name) == "x-custom-header" {
if len(headers) == 1 {
w.WriteHeader(http.StatusOK)
return
}
}
}

w.WriteHeader(http.StatusUnauthorized)
}

func TestNew(t *testing.T) {
r := chi.NewRouter()
r.Use(New(&customMiddleware{}))
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
})

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
req.Header.Set("X-Custom-Header", "abc123")
r.ServeHTTP(w, req)

if w.Result().StatusCode != http.StatusOK {
t.Errorf("new: middleware was not register in the stack")
}
}

func Test_contextKey_String(t *testing.T) {
k := &contextKey{
name: "test",
}
if got := k.String(); got != "chi/middleware context value test" {
t.Errorf("got: %q, expected: %q", got, "chi/middleware context value test")
}
}

func TestWrapWriterHTTP2(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Proto != "HTTP/2.0" {
Expand Down
26 changes: 26 additions & 0 deletions middleware/path_rewrite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package middleware

import (
"net/http"
"net/http/httptest"
"testing"

chi "github.com/go-chi/chi/v5"
)

func TestPathRewrite(t *testing.T) {
r := chi.NewRouter()
r.Use(PathRewrite("/endpoint", "/v1/endpoint"))

r.Get("/v1/endpoint", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
})

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/endpoint", nil)
r.ServeHTTP(w, req)

if w.Result().StatusCode != http.StatusOK {
t.Errorf("path rewrite: unexpected response code: %v", w.Result().StatusCode)
}
}
34 changes: 34 additions & 0 deletions middleware/terminal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package middleware

import (
"bytes"
"testing"
)

func Test_cW(t *testing.T) {
cases := []struct {
name string
useColor bool
color []byte
s string
args []interface{}
expected string
}{
{
name: "No color",
useColor: false,
color: nGreen,
s: "no color test",
expected: "no color test",
},
}

for name, c := range cases {
actual := &bytes.Buffer{}
cW(actual, c.useColor, c.color, c.s, c.args...)

if actual.String() != c.expected {
t.Errorf("(case %q) unexpected output: got %q, expected: %q", name, actual.String(), c.expected)
}
}
}
33 changes: 33 additions & 0 deletions middleware/value_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package middleware

import (
"net/http"
"net/http/httptest"
"testing"

chi "github.com/go-chi/chi/v5"
)

func TestWithValue(t *testing.T) {
ctxKey := "customKey"
ctxValue := "customValue"
request := func() *http.Request {
req, _ := http.NewRequest("GET", "/", nil)
return req
}
testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
val := r.Context().Value(ctxKey).(string)
w.Write([]byte(val))
})

w := httptest.NewRecorder()
r := chi.NewRouter()
r.Use(WithValue(ctxKey, ctxValue))
r.Get("/", testHandler)

r.ServeHTTP(w, request())

if w.Body.String() != ctxValue {
t.Errorf("value: context did not contain expected value")
}
}