goshort/internal/util/handler/chain_test.go
Gustavo Maronato be39b22ace
Some checks failed
Check / checks (push) Failing after 3m48s
lint
2024-03-09 05:53:28 -05:00

49 lines
1.0 KiB
Go

package handlerutils_test
import (
"net/http"
"testing"
handler "git.maronato.dev/maronato/goshort/internal/util/handler"
"github.com/stretchr/testify/assert"
)
func TestChainHandler(t *testing.T) {
var stopAt int
// Makes a chain handler factory that writes the status code whrn
// it's n value matches the value of `stopAt`
makeHandler := func(n int) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
if stopAt == n {
w.WriteHeader(200 + n)
return
}
})
}
// Create 3 handlers and chain them together
h1 := makeHandler(1)
h2 := makeHandler(2)
h3 := makeHandler(3)
ch := handler.NewChainedHandler(h1, h2, h3)
stopAt = 2
assert.HTTPStatusCode(t, ch.ServeHTTP, "GET", "/", nil, 202)
stopAt = 1
assert.HTTPStatusCode(t, ch.ServeHTTP, "GET", "/", nil, 201)
stopAt = 3
assert.HTTPStatusCode(t, ch.ServeHTTP, "GET", "/", nil, 203)
stopAt = 4
// Since it isn't handled by anything, it returns 200 by default
assert.HTTPStatusCode(t, ch.ServeHTTP, "GET", "/", nil, 200)
}