【发布时间】:2018-09-12 19:35:31
【问题描述】:
我正在尝试测试以下方法:
//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)
}
在这种情况下,如果 r 包含需要授权的 URL,并且授权成功,则会调用 SessionRelease。
知道这一点可能很重要:
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初始化为,它只为CheckTokenAndSetSession返回nil(当然,会话设置被抽象为存根对象本身的创建,它具有@987654335 @),还有一个MiddlewareSt满是假的nonAuthURLs为GetInfo() - 创建一个模拟
session.Store,对于除健全性测试之外的所有测试,预计对SessionRelease的调用为零。
可能值得注意(但假设)我正在使用 testify,mockery 库来进行模拟和断言。
测试
是这样实现的:
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()
注意 session.Store.SessionRelease 不返回任何内容,因此我什至懒得使用 Return()。
我是在断言它会被准确地调用零次吗?
【问题讨论】:
-
不是您问题的确切答案,所以我将其作为评论发布。但看起来很容易回避问题并使用自定义测试替身,这只会引发
SessionRelease方法出错。
标签: unit-testing go testify