mirror of
https://github.com/volatiletech/authboss.git
synced 2025-03-25 22:00:57 +02:00
Move duplicate testing mocks to internal/mocks
- Add force err ability to internal/mocks
This commit is contained in:
parent
db6738cb23
commit
1aa0da808c
@ -20,7 +20,7 @@ var (
|
||||
// Init authboss and it's loaded modules with a configuration.
|
||||
func Init(config *Config) error {
|
||||
if config.Storer == nil {
|
||||
return errors.New("Configuration must provide a storer.")
|
||||
return errors.New("configuration must provide a storer.")
|
||||
}
|
||||
|
||||
cfg = config
|
||||
|
@ -24,7 +24,7 @@ func TestExpire(t *testing.T) {
|
||||
func TestExpire_Touch(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
session := mocks.MockClientStorer{}
|
||||
session := mocks.NewMockClientStorer()
|
||||
|
||||
if _, ok := session.Get(UserLastAction); ok {
|
||||
t.Error("It should not have been set")
|
||||
@ -43,7 +43,7 @@ func TestExpire_BeforeAuth(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
expire := &Expire{window: time.Hour}
|
||||
session := mocks.MockClientStorer{}
|
||||
session := mocks.NewMockClientStorer()
|
||||
|
||||
ctx := mocks.MockRequestContext()
|
||||
ctx.SessionStorer = session
|
||||
@ -52,8 +52,8 @@ func TestExpire_BeforeAuth(t *testing.T) {
|
||||
t.Error("There's no user in session, should be no-op.")
|
||||
}
|
||||
|
||||
session[authboss.SessionKey] = "moo"
|
||||
session[UserLastAction] = "cow"
|
||||
session.Values[authboss.SessionKey] = "moo"
|
||||
session.Values[UserLastAction] = "cow"
|
||||
if err := expire.BeforeAuth(ctx); err != nil {
|
||||
t.Error("There's a malformed date, this should not error, just fix it:", err)
|
||||
}
|
||||
@ -65,12 +65,12 @@ func TestExpire_BeforeAuth(t *testing.T) {
|
||||
t.Error("The time is set in the future.")
|
||||
}
|
||||
|
||||
session[UserLastAction] = time.Now().UTC().Add(-2 * time.Hour).Format(time.RFC3339)
|
||||
session.Values[UserLastAction] = time.Now().UTC().Add(-2 * time.Hour).Format(time.RFC3339)
|
||||
if err := expire.BeforeAuth(ctx); err != ErrExpired {
|
||||
t.Error("The user should have been expired, got:", err)
|
||||
}
|
||||
|
||||
if _, ok := session[authboss.SessionKey]; ok {
|
||||
if _, ok := session.Values[authboss.SessionKey]; ok {
|
||||
t.Error("The user session should have been expired.")
|
||||
}
|
||||
}
|
||||
@ -82,7 +82,8 @@ func (t *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func TestExpire_Middleware(t *testing.T) {
|
||||
session := mocks.MockClientStorer{
|
||||
session := mocks.NewMockClientStorer()
|
||||
session.Values = map[string]string{
|
||||
authboss.SessionKey: "username",
|
||||
}
|
||||
maker := func(w http.ResponseWriter, r *http.Request) authboss.ClientStorer { return session }
|
||||
|
@ -9,7 +9,10 @@ import (
|
||||
func TestPull(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
storer := mocks.MockClientStorer{"a": "1"}
|
||||
storer := mocks.NewMockClientStorer()
|
||||
storer.Values = map[string]string{
|
||||
"a": "1",
|
||||
}
|
||||
|
||||
v := Pull(storer, "a")
|
||||
|
||||
@ -17,7 +20,7 @@ func TestPull(t *testing.T) {
|
||||
t.Error(`Expected value "1", got:`, v)
|
||||
}
|
||||
|
||||
if len(storer) != 0 {
|
||||
if len(storer.Values) != 0 {
|
||||
t.Error("Expected length of zero")
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,9 @@
|
||||
// mocks defines implemented interfaces for testing modules
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
@ -9,17 +11,21 @@ import (
|
||||
"gopkg.in/authboss.v0"
|
||||
)
|
||||
|
||||
// MockUser represents all possible fields a authboss User may have
|
||||
type MockUser struct {
|
||||
Username string
|
||||
Email string
|
||||
Password string
|
||||
RecoverToken string
|
||||
RecoverTokenExpiry time.Time
|
||||
Locked bool
|
||||
}
|
||||
|
||||
// MockStorer should be valid for any module storer defined in authboss.
|
||||
type MockStorer struct {
|
||||
Users map[string]authboss.Attributes
|
||||
Tokens map[string][]string
|
||||
Users map[string]authboss.Attributes
|
||||
Tokens map[string][]string
|
||||
CreateErr, PutErr, GetErr, AddTokenErr, DelTokensErr, UseTokenErr, RecoverUserErr string
|
||||
}
|
||||
|
||||
func NewMockStorer() *MockStorer {
|
||||
@ -30,11 +36,19 @@ func NewMockStorer() *MockStorer {
|
||||
}
|
||||
|
||||
func (m *MockStorer) Create(key string, attr authboss.Attributes) error {
|
||||
if len(m.CreateErr) > 0 {
|
||||
return errors.New(m.CreateErr)
|
||||
}
|
||||
|
||||
m.Users[key] = attr
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MockStorer) Put(key string, attr authboss.Attributes) error {
|
||||
if len(m.PutErr) > 0 {
|
||||
return errors.New(m.PutErr)
|
||||
}
|
||||
|
||||
if _, ok := m.Users[key]; !ok {
|
||||
m.Users[key] = attr
|
||||
return nil
|
||||
@ -46,39 +60,47 @@ func (m *MockStorer) Put(key string, attr authboss.Attributes) error {
|
||||
}
|
||||
|
||||
func (m *MockStorer) Get(key string, attrMeta authboss.AttributeMeta) (result interface{}, err error) {
|
||||
if _, ok := m.Users[key]; !ok {
|
||||
if len(m.GetErr) > 0 {
|
||||
return nil, errors.New(m.GetErr)
|
||||
}
|
||||
|
||||
userAttrs, ok := m.Users[key]
|
||||
if !ok {
|
||||
return nil, authboss.ErrUserNotFound
|
||||
}
|
||||
|
||||
u := &MockUser{}
|
||||
|
||||
if val, ok := m.Users[key]["username"]; ok {
|
||||
u.Username = val.(string)
|
||||
}
|
||||
|
||||
if val, ok := m.Users[key]["email"]; ok {
|
||||
u.Email = val.(string)
|
||||
}
|
||||
|
||||
if val, ok := m.Users[key]["password"]; ok {
|
||||
u.Password = val.(string)
|
||||
if err := userAttrs.Bind(u); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (m *MockStorer) AddToken(key, token string) error {
|
||||
if len(m.AddTokenErr) > 0 {
|
||||
return errors.New(m.AddTokenErr)
|
||||
}
|
||||
|
||||
arr := m.Tokens[key]
|
||||
m.Tokens[key] = append(arr, token)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MockStorer) DelTokens(key string) error {
|
||||
if len(m.DelTokensErr) > 0 {
|
||||
return errors.New(m.DelTokensErr)
|
||||
}
|
||||
|
||||
delete(m.Tokens, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MockStorer) UseToken(givenKey, token string) (key string, err error) {
|
||||
if len(m.UseTokenErr) > 0 {
|
||||
return "", errors.New(m.UseTokenErr)
|
||||
}
|
||||
|
||||
if arr, ok := m.Tokens[givenKey]; ok {
|
||||
for _, tok := range arr {
|
||||
if tok == token {
|
||||
@ -91,29 +113,18 @@ func (m *MockStorer) UseToken(givenKey, token string) (key string, err error) {
|
||||
}
|
||||
|
||||
func (m *MockStorer) RecoverUser(token string) (result interface{}, err error) {
|
||||
if len(m.RecoverUserErr) > 0 {
|
||||
return nil, errors.New(m.RecoverUserErr)
|
||||
}
|
||||
|
||||
for _, user := range m.Users {
|
||||
if user["recover_token"] == token {
|
||||
|
||||
u := &MockUser{}
|
||||
|
||||
if val, ok := user["username"]; ok {
|
||||
u.Username = val.(string)
|
||||
if err = user.Bind(u); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if val, ok := user["email"]; ok {
|
||||
u.Email = val.(string)
|
||||
}
|
||||
|
||||
if val, ok := user["password"]; ok {
|
||||
u.Password = val.(string)
|
||||
}
|
||||
|
||||
if val, ok := user["recover_token"]; ok {
|
||||
u.RecoverToken = val.(string)
|
||||
}
|
||||
|
||||
if val, ok := user["recover_token_expiry"]; ok {
|
||||
u.RecoverTokenExpiry = val.(time.Time)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
}
|
||||
@ -121,15 +132,43 @@ func (m *MockStorer) RecoverUser(token string) (result interface{}, err error) {
|
||||
return nil, authboss.ErrUserNotFound
|
||||
}
|
||||
|
||||
type MockClientStorer map[string]string
|
||||
// MockFailStorer is used for testing module initialize functions that recover more than the base storer
|
||||
type MockFailStorer struct{}
|
||||
|
||||
func (m MockClientStorer) Get(key string) (string, bool) {
|
||||
v, ok := m[key]
|
||||
func (_ MockFailStorer) Create(_ string, _ authboss.Attributes) error {
|
||||
return errors.New("fail storer: create")
|
||||
}
|
||||
func (_ MockFailStorer) Put(_ string, _ authboss.Attributes) error {
|
||||
return errors.New("fail storer: put")
|
||||
}
|
||||
func (_ MockFailStorer) Get(_ string, _ authboss.AttributeMeta) (interface{}, error) {
|
||||
return nil, errors.New("fail storer: get")
|
||||
}
|
||||
|
||||
// MockClientStorer is used for testing the client stores on context
|
||||
type MockClientStorer struct {
|
||||
Values map[string]string
|
||||
GetShouldFail bool
|
||||
}
|
||||
|
||||
func NewMockClientStorer() *MockClientStorer {
|
||||
return &MockClientStorer{
|
||||
Values: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MockClientStorer) Get(key string) (string, bool) {
|
||||
if m.GetShouldFail {
|
||||
return "", false
|
||||
}
|
||||
|
||||
v, ok := m.Values[key]
|
||||
return v, ok
|
||||
}
|
||||
func (m MockClientStorer) Put(key, val string) { m[key] = val }
|
||||
func (m MockClientStorer) Del(key string) { delete(m, key) }
|
||||
func (m *MockClientStorer) Put(key, val string) { m.Values[key] = val }
|
||||
func (m *MockClientStorer) Del(key string) { delete(m.Values, key) }
|
||||
|
||||
// MockRequestContext returns a new context as if it came from POST request.
|
||||
func MockRequestContext(postKeyValues ...string) *authboss.Context {
|
||||
keyValues := &bytes.Buffer{}
|
||||
for i := 0; i < len(postKeyValues); i += 2 {
|
||||
@ -153,11 +192,21 @@ func MockRequestContext(postKeyValues ...string) *authboss.Context {
|
||||
return ctx
|
||||
}
|
||||
|
||||
// MockMailer helps simplify mailer testing by storing the last sent email
|
||||
type MockMailer struct {
|
||||
Last authboss.Email
|
||||
Last authboss.Email
|
||||
SendErr string
|
||||
}
|
||||
|
||||
func NewMockMailer() *MockMailer {
|
||||
return &MockMailer{}
|
||||
}
|
||||
|
||||
func (m *MockMailer) Send(email authboss.Email) error {
|
||||
if len(m.SendErr) > 0 {
|
||||
return errors.New(m.SendErr)
|
||||
}
|
||||
|
||||
m.Last = email
|
||||
return nil
|
||||
}
|
||||
|
@ -19,13 +19,6 @@ func TestStorage(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func setup(keyValuePairs interface{}) {
|
||||
storer := mocks.NewMockStorer()
|
||||
L.storer = storer
|
||||
_ = make(mocks.MockClientStorer)
|
||||
_ = make(mocks.MockClientStorer)
|
||||
}
|
||||
|
||||
func TestBeforeAuth(t *testing.T) {
|
||||
ctx := authboss.NewContext()
|
||||
L.logger = ioutil.Discard
|
||||
|
@ -37,7 +37,7 @@ func Test_recoverCompleteHandlerFunc_GET_TokenExpired(t *testing.T) {
|
||||
}
|
||||
|
||||
w, r, ctx := testHttpRequest("GET", fmt.Sprintf("/recover/complete?token=%s", testUrlBase64Token), nil)
|
||||
clientStorer := mocks.MockClientStorer{}
|
||||
clientStorer := mocks.NewMockClientStorer()
|
||||
ctx.SessionStorer = clientStorer
|
||||
|
||||
m.recoverCompleteHandlerFunc(ctx, w, r)
|
||||
@ -50,7 +50,7 @@ func Test_recoverCompleteHandlerFunc_GET_TokenExpired(t *testing.T) {
|
||||
t.Error("Expected logs to start with:", "recover [token expired]:")
|
||||
}
|
||||
|
||||
if flash := clientStorer[authboss.FlashErrorKey]; flash != m.config.RecoverTokenExpiredFlash {
|
||||
if flash := clientStorer.Values[authboss.FlashErrorKey]; flash != m.config.RecoverTokenExpiredFlash {
|
||||
t.Error("Unexpected error flash:", flash)
|
||||
}
|
||||
|
||||
@ -96,7 +96,9 @@ func Test_recoverCompleteHandlerFunc_GET(t *testing.T) {
|
||||
}
|
||||
|
||||
w, r, ctx := testHttpRequest("GET", fmt.Sprintf("/recover/complete?token=%s", testUrlBase64Token), nil)
|
||||
ctx.SessionStorer = mocks.MockClientStorer{authboss.FlashErrorKey: "asdf"}
|
||||
sessionStorer := mocks.NewMockClientStorer()
|
||||
sessionStorer.Values = map[string]string{authboss.FlashErrorKey: "asdf"}
|
||||
ctx.SessionStorer = sessionStorer
|
||||
|
||||
m.recoverCompleteHandlerFunc(ctx, w, r)
|
||||
|
||||
@ -329,7 +331,7 @@ func Test_recoverComplete(t *testing.T) {
|
||||
m, _ := testValidRecoverModule()
|
||||
ctx := mocks.MockRequestContext("token", testUrlBase64Token, "password", "a", "confirmPassword", "a")
|
||||
|
||||
clientStorer := mocks.MockClientStorer{}
|
||||
clientStorer := mocks.NewMockClientStorer()
|
||||
ctx.SessionStorer = clientStorer
|
||||
|
||||
storer, ok := m.config.Storer.(*mocks.MockStorer)
|
||||
|
@ -3,7 +3,6 @@ package recover
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/ioutil"
|
||||
@ -87,7 +86,7 @@ func Test_recoverHandlerFunc_POST(t *testing.T) {
|
||||
t.Error("Unexpected redirect:", location)
|
||||
}
|
||||
|
||||
successFlash := ctx.SessionStorer.(mocks.MockClientStorer)[authboss.FlashSuccessKey]
|
||||
successFlash := ctx.SessionStorer.(*mocks.MockClientStorer).Values[authboss.FlashSuccessKey]
|
||||
if successFlash != m.config.RecoverInitiateSuccessFlash {
|
||||
t.Error("Unexpected success flash message:", successFlash)
|
||||
}
|
||||
@ -316,17 +315,13 @@ func Test_sendRecoverEmail_InvalidTemplates(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
type failMailer struct{}
|
||||
|
||||
func (_ failMailer) Send(_ authboss.Email) error {
|
||||
return errors.New("")
|
||||
}
|
||||
|
||||
func Test_sendRecoverEmail_FailToSend(t *testing.T) {
|
||||
t.Parallel()
|
||||
m, logger := testValidRecoverModule()
|
||||
|
||||
m.config.Mailer = failMailer{}
|
||||
mailer := mocks.NewMockMailer()
|
||||
mailer.SendErr = "explode"
|
||||
m.config.Mailer = mailer
|
||||
<-m.sendRecoverEmail("a@b.c", []byte("abc123"))
|
||||
|
||||
actualLog, err := ioutil.ReadAll(logger)
|
||||
|
@ -19,12 +19,6 @@ import (
|
||||
"gopkg.in/authboss.v0/internal/views"
|
||||
)
|
||||
|
||||
type failStorer int
|
||||
|
||||
func (_ failStorer) Create(_ string, _ authboss.Attributes) error { return nil }
|
||||
func (_ failStorer) Put(_ string, _ authboss.Attributes) error { return nil }
|
||||
func (_ failStorer) Get(_ string, _ authboss.AttributeMeta) (interface{}, error) { return nil, nil }
|
||||
|
||||
func Test_Initialize(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@ -36,7 +30,7 @@ func Test_Initialize(t *testing.T) {
|
||||
} else if err.Error() != "recover: Need a RecoverStorer." {
|
||||
t.Error("Got error but wrong reason:", err)
|
||||
}
|
||||
config.Storer = new(failStorer)
|
||||
config.Storer = mocks.MockFailStorer{}
|
||||
|
||||
if err := m.Initialize(config); err == nil {
|
||||
t.Error("Expected error")
|
||||
@ -185,7 +179,8 @@ func testHttpRequest(method, url string, data url.Values) (*httptest.ResponseRec
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
ctx.SessionStorer = mocks.MockClientStorer{}
|
||||
sessionStorer := mocks.NewMockClientStorer()
|
||||
ctx.SessionStorer = sessionStorer
|
||||
|
||||
return w, r, ctx
|
||||
}
|
||||
|
@ -9,12 +9,6 @@ import (
|
||||
"gopkg.in/authboss.v0/internal/mocks"
|
||||
)
|
||||
|
||||
type failStorer int
|
||||
|
||||
func (_ failStorer) Create(_ string, _ authboss.Attributes) error { return nil }
|
||||
func (_ failStorer) Put(_ string, _ authboss.Attributes) error { return nil }
|
||||
func (_ failStorer) Get(_ string, _ authboss.AttributeMeta) (interface{}, error) { return nil, nil }
|
||||
|
||||
func TestInitialize(t *testing.T) {
|
||||
testConfig := authboss.NewConfig()
|
||||
|
||||
@ -24,7 +18,7 @@ func TestInitialize(t *testing.T) {
|
||||
t.Error("Expected error about token storers.")
|
||||
}
|
||||
|
||||
testConfig.Storer = new(failStorer)
|
||||
testConfig.Storer = mocks.MockFailStorer{}
|
||||
err = r.Initialize(testConfig)
|
||||
if err == nil {
|
||||
t.Error("Expected error about token storers.")
|
||||
@ -40,8 +34,8 @@ func TestInitialize(t *testing.T) {
|
||||
func TestAfterAuth(t *testing.T) {
|
||||
storer := mocks.NewMockStorer()
|
||||
R.storer = storer
|
||||
cookies := make(mocks.MockClientStorer)
|
||||
session := make(mocks.MockClientStorer)
|
||||
cookies := mocks.NewMockClientStorer()
|
||||
session := mocks.NewMockClientStorer()
|
||||
|
||||
req, err := http.NewRequest("POST", "http://localhost", bytes.NewBufferString("rm=true"))
|
||||
if err != nil {
|
||||
@ -60,7 +54,7 @@ func TestAfterAuth(t *testing.T) {
|
||||
|
||||
R.AfterAuth(ctx)
|
||||
|
||||
if _, ok := cookies[ValueKey]; !ok {
|
||||
if _, ok := cookies.Values[ValueKey]; !ok {
|
||||
t.Error("Expected a cookie to have been set.")
|
||||
}
|
||||
}
|
||||
@ -68,7 +62,7 @@ func TestAfterAuth(t *testing.T) {
|
||||
func TestNew(t *testing.T) {
|
||||
storer := mocks.NewMockStorer()
|
||||
R.storer = storer
|
||||
cookies := make(mocks.MockClientStorer)
|
||||
cookies := mocks.NewMockClientStorer()
|
||||
|
||||
key := "tester"
|
||||
token, err := R.New(cookies, key)
|
||||
@ -87,7 +81,7 @@ func TestNew(t *testing.T) {
|
||||
t.Error("Expected a token to be saved.")
|
||||
}
|
||||
|
||||
if token != cookies[ValueKey] {
|
||||
if token != cookies.Values[ValueKey] {
|
||||
t.Error("Expected a cookie set with the token.")
|
||||
}
|
||||
}
|
||||
@ -95,8 +89,8 @@ func TestNew(t *testing.T) {
|
||||
func TestAuth(t *testing.T) {
|
||||
storer := mocks.NewMockStorer()
|
||||
R.storer = storer
|
||||
cookies := make(mocks.MockClientStorer)
|
||||
session := make(mocks.MockClientStorer)
|
||||
cookies := mocks.NewMockClientStorer()
|
||||
session := mocks.NewMockClientStorer()
|
||||
|
||||
key := "tester"
|
||||
token, err := R.New(cookies, key)
|
||||
@ -109,11 +103,11 @@ func TestAuth(t *testing.T) {
|
||||
t.Error("Unexpected error:", err)
|
||||
}
|
||||
|
||||
if session[authboss.HalfAuthKey] != "true" {
|
||||
if session.Values[authboss.HalfAuthKey] != "true" {
|
||||
t.Error("The user should have been half-authed.")
|
||||
}
|
||||
|
||||
if session[authboss.SessionKey] != key {
|
||||
if session.Values[authboss.SessionKey] != key {
|
||||
t.Error("The user should have been logged in.")
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user