我正在尝试测试以下方法:
//AuthenticationMiddleware Middleware which handles all of the authentication.
func AuthenticationMiddleware(context context.ContextIntf, w web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
//Check if url is one that doesn't need authorization. If not than send them to the login page.
for _, url := range AuthMWInstance.GetInfo().nonAuthURLs {
if url.Method == r.Method && strings.Contains(r.URL.Path, url.DomainName) {
next(w, r)
return
}
}
if errSt := CheckForAuthorization(context, r, w); errSt != nil {
responses.Write(w, responses.Unauthorized(*errSt))
return
}
defer context.GetInfo().Session.SessionRelease(w)
next(w, r)
}
在这种情况下,如果包含需要授权的 URL 并且授权成功,SessionRelease
则会调用一个。r
了解以下内容可能很重要:
type MiddlewareSt struct {
//NonAuthUrls URLs that can be accessed without a token.
nonAuthURLs []url.URLSt
}
type MiddlewareIntf interface {
GetInfo() *MiddlewareSt
CheckTokenAndSetSession(context context.ContextIntf, r *web.Request, w web.ResponseWriter,
token string, scope string, remoteAddr string) *errors.ErrorSt
}
var AuthMWInstance MiddlewareIntf
而那CheckForAuthorization
的返回值最终取决于AuthMWInstance
我的测试策略
- 创建一个存根中间件实例来初始化
AuthMWInstance
,它只是简单地返回nil
forCheckTokenAndSetSession
(会话设置抽象出来,当然,存根对象本身的创建,它有Session
),以及一个MiddlewareSt
完整的假nonAuthURLs
forGetInfo()
- 创建一个模拟
session.Store
,对于除健全性测试之外的所有测试,预期对SessionRelease
.
可能值得注意(但假设)我正在使用testify,嘲笑库来模拟和断言的东西。
考试
是这样实现的:
func TestAuthenticationMiddleware(t *testing.T) {
// bring in the errors
sdkTesting.InitErrors()
// create/set up the test doubles
// mock session
sessionMock := new(testing_mock.MockStore)
// temporarily set AuthMWInstance to a stub
instance := AuthMWInstance
AuthMWInstance = &StubMiddlewareInstance{
Session: sessionMock,
}
// AuthMWInstance.Session
defer func() { AuthMWInstance = instance }()
// fake ResponseWriter
w := new(StubResponseWriter)
// fake web requests
requestWithoutAuth := new(web.Request)
requestWithoutAuth.Request = httptest.NewRequest("GET",
"http://example.com/logout",
nil,
)
// do tests here
t.Run("AuthorizationNotRequired", func(t *testing.T) {
// place expectations on sessionMock, namely that it does
// **not** invoke `SessionRelease`
sessionMock.On("SessionRelease", w).
Times(0)
AuthenticationMiddleware(new(context.Context),
w,
requestWithoutAuth,
web.NextMiddlewareFunc(func(web.ResponseWriter, *web.Request) {}))
sessionMock.AssertExpectations(t)
})
}
运行时行为
sessionMock.On("SessionRelease", w).
Times(0)
, 我像:
sessionMock.On("SessionRelease", w).
Once()
NOTE session.Store.SessionRelease
不返回任何东西,因此我什至不费心使用Return()
.
我是在断言它应该被准确地调用零次吗?