Tests: Add unit tests

This commit is contained in:
graciousgrey
2024-04-29 18:36:39 +02:00
parent 020e9e7e19
commit 43011da182
3 changed files with 78 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
package api
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewResponse(t *testing.T) {
t.Run("404", func(t *testing.T) {
r := NewResponse(404, errors.New("not found"), "details")
assert.Equal(t, 404, r.Code)
assert.Equal(t, "details", r.Details)
})
}

View File

@@ -202,4 +202,63 @@ func TestCreateOAuthToken(t *testing.T) {
t.Logf("BODY: %s", w.Body.String())
assert.Equal(t, http.StatusUnauthorized, w.Code)
})
t.Run("GrantPasswordNoSession", func(t *testing.T) {
app, router, conf := NewApiTest()
conf.SetAuthMode(config.AuthModePasswd)
defer conf.SetAuthMode(config.AuthModePublic)
CreateOAuthToken(router)
var method = "POST"
var path = "/api/v1/oauth/token"
data := url.Values{
"grant_type": {authn.GrantPassword.String()},
"client_name": {"AppPasswordAlice"},
"username": {"alice"},
"password": {"Alice123!"},
"scope": {"*"},
}
req, _ := http.NewRequest(method, path, strings.NewReader(data.Encode()))
req.Header.Add(header.ContentType, header.ContentTypeForm)
w := httptest.NewRecorder()
app.ServeHTTP(w, req)
t.Logf("Header: %s", w.Header())
t.Logf("BODY: %s", w.Body.String())
assert.Equal(t, http.StatusUnauthorized, w.Code)
})
t.Run("GrantPasswordSuccess", func(t *testing.T) {
app, router, conf := NewApiTest()
conf.SetAuthMode(config.AuthModePasswd)
defer conf.SetAuthMode(config.AuthModePublic)
sessId := AuthenticateUser(app, router, "alice", "Alice123!")
CreateOAuthToken(router)
var method = "POST"
var path = "/api/v1/oauth/token"
data := url.Values{
"grant_type": {authn.GrantPassword.String()},
"client_name": {"AppPasswordAlice"},
"username": {"alice"},
"password": {"Alice123!"},
"scope": {"*"},
}
req, _ := http.NewRequest(method, path, strings.NewReader(data.Encode()))
req.Header.Add(header.ContentType, header.ContentTypeForm)
req.Header.Add(header.XAuthToken, sessId)
w := httptest.NewRecorder()
app.ServeHTTP(w, req)
t.Logf("Header: %s", w.Header())
t.Logf("BODY: %s", w.Body.String())
assert.Equal(t, http.StatusOK, w.Code)
})
}

View File

@@ -23,4 +23,7 @@ func TestLogError(t *testing.T) {
t.Run("Invalid", func(t *testing.T) {
assert.Equal(t, "??https://?host?:?port?/?path??", Error(errors.New("${https://<host>:<port>/<path>}")))
})
t.Run("Quotes", func(t *testing.T) {
assert.Equal(t, "the quick 'brown fox", Error(errors.New("the quick `brown fox")))
})
}