通道关闭时收到的布尔标志与Golang中的预期不符
我有一个用于重复身份验证的类型:通道关闭时收到的布尔标志与Golang中的预期不符,go,channel,Go,Channel,我有一个用于重复身份验证的类型: type Authorizer struct { requester *Requester closeChannel chan error } func (requester *Requester) Authorize(autoClose bool) { // Create a new authorizer from the requester and the close-channel authorizer := Au
type Authorizer struct {
requester *Requester
closeChannel chan error
}
func (requester *Requester) Authorize(autoClose bool) {
// Create a new authorizer from the requester and the close-channel
authorizer := Authorizer{
requester: requester,
closeChannel: requester.closer,
}
// Ensure that the requester has a reference to the authorizer so we can access the
// updated token
requester.authorizer = &authorizer
// Begin the authentication loop concurrently
go authorizer.manageAuthorization()
}
func (authorizer *Authorizer) manageAuthorization() {
for {
select {
case _, ok := <-authorizer.closeChannel:
if ok {
fmt.Printf("Closed\n")
return // NEVER RUNS
}
default:
break
}
fmt.Printf("Not closed\n")
// Do inner authorization logic
}
}
到目前为止,我的测试都通过了这段代码。然而,我在做报道时遇到了一个有趣的问题。考虑下面的片段:
// Create the test client
client := Requester{}
client.closer = make(chan error)
// Begin authentication
client.Authorize(false)
// Now, close the channel
close(client.closer)
如果我将其嵌入到测试中并尝试使用它运行代码覆盖率,我会注意到指示的行从未运行过。此外,我在此处添加的调试消息显示以下内容:
Not closed
Not closed
Not closed
Closing...
Not closed
Not closed
Not closed
在非点处,
关闭
消息不打印。那么,我做错了什么呢?ok
频道关闭时将false
。试一试
case _, ok := <-authorizer.closeChannel:
if !ok {
return // RUNS
}
case u,ok:=ok
在频道关闭时将为false
。试一试
case _, ok := <-authorizer.closeChannel:
if !ok {
return // RUNS
}
case,ok:=“我有一个我正在使用的类…”注意:Go没有任何类。如果不看到它,调试测试用例将非常困难。你能为你的问题添加一个吗?client:=Requestor{}
应该是client:=Requester{}
“我有一个我正在使用的类…”注意:Go没有任何类。在没有看到它的情况下调试测试用例是非常困难的。你能给你的问题加一个吗?client:=请求者{}
应该是client:=请求者{}
。