cabinet/internal/router/router_test.go

95 lines
2.7 KiB
Go

package router
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"go.jolheiser.com/cabinet"
"go.jolheiser.com/cabinet/internal/workspace"
"go.jolheiser.com/cabinet/internal/workspace/mock"
"github.com/matryer/is"
"github.com/rs/zerolog"
)
func TestRouter(t *testing.T) {
zerolog.SetGlobalLevel(zerolog.Disabled)
m := mock.New()
server := httptest.NewUnstartedServer(nil)
server.Start()
defer server.Close()
r := New(server.URL, m, NewLimit(12, 5*1024*1024, 100*1024*1024, 1024*1024))
server.Config.Handler = r
c := cabinet.New(server.URL, cabinet.WithHTTPClient(server.Client()))
testRouter(t, "No Token", true, true, c)
// All token
aToken := workspace.Token{Key: "all", Permission: workspace.TokenFile | workspace.TokenRedirect}
_ = m.AddToken(aToken)
testRouter(t, "Incorrect Token", false, false, c)
c.Token = aToken.Key
testRouter(t, "All Token", true, true, c)
// Redirect token
rToken := workspace.Token{Key: "redirect", Permission: workspace.TokenRedirect}
_ = m.AddToken(rToken)
c.Token = rToken.Key
testRouter(t, "Redirect Token", true, false, c)
// File token
fToken := workspace.Token{Key: "file", Permission: workspace.TokenFile}
_ = m.AddToken(fToken)
c.Token = fToken.Key
testRouter(t, "File Token", false, true, c)
}
func testRouter(t *testing.T, name string, rSucceed, fSucceed bool, c *cabinet.Client) {
// Redirect
t.Run(name+" Redirect", func(t *testing.T) {
assert := is.New(t)
redir := "https://duckduckgo.com"
u, res, err := c.Redirect(redir)
switch {
case rSucceed:
assert.NoErr(err) // Creating a redirect should succeed
resp, err := http.Get(u)
assert.NoErr(err)
assert.Equal(redir, resp.Request.URL.String()) // The redirect should match what was given
case c.Token == "":
assert.Equal(res.StatusCode, http.StatusUnauthorized) // Creating a redirect should be unauthorized
case c.Token != "":
assert.Equal(res.StatusCode, http.StatusForbidden) // Creating a redirect should be forbidden
default:
assert.Fail() // Unknown case in test
}
})
// File
t.Run(name+" File", func(t *testing.T) {
assert := is.New(t)
file := "foobar"
f, res, err := c.File("test.txt", strings.NewReader(file))
switch {
case fSucceed:
assert.NoErr(err) // Creating a file should succeed
resp, err := http.Get(f)
assert.NoErr(err)
b, err := io.ReadAll(resp.Body)
assert.NoErr(err)
assert.Equal(file, string(b)) // The file should match what was given
case c.Token == "":
assert.Equal(res.StatusCode, http.StatusUnauthorized) // Creating a redirect should be unauthorized
case c.Token != "":
assert.Equal(res.StatusCode, http.StatusForbidden) // Creating a redirect should be forbidden
default:
assert.Fail() // Unknown case in test
}
})
}