如何解决测试来自GitHub.com/Shopify/sarama
我正在尝试为配置了github.com/Shopify/sarama
的Logger
的功能选项编写单元测试。像这样用Kafka运行Docker容器后,
docker run -p 2181:2181 -p 9092:9092 -e ADVERTISED_HOST=127.0.0.1 -e NUM_PARTITIONS=10 johnnypark/kafka-zookeeper
我正在尝试运行此程序:
package main
import (
"bufio"
"bytes"
"io/IoUtil"
"log"
"github.com/Shopify/Sarama"
)
func main() {
var b bytes.Buffer
out := bufio.NewWriter(&b)
Sarama.Logger = log.New(out,"[Sarama] ",log.LstdFlags)
if _,err := Sarama.NewClient([]string{"localhost:9092"},Sarama.NewConfig()); err != nil {
log.Fatalln("NewClient:",err)
}
output,err := IoUtil.ReadAll(&b)
if err != nil {
log.Fatalln("ReadAll:",err)
}
log.Printf("output: %s",output)
}
> go run main.go
2020/09/25 16:44:58 output:
通过对比,如果我将输出设置为os.Stderr
,
package main
import (
"log"
"os"
"github.com/Shopify/Sarama"
)
func main() {
Sarama.Logger = log.New(os.Stderr,err)
}
}
> go run main.go
[Sarama] 2020/09/25 16:46:04 Initializing new client
[Sarama] 2020/09/25 16:46:04 ClientID is the default of 'Sarama',you should consider setting it to something application-specific.
[Sarama] 2020/09/25 16:46:04 ClientID is the default of 'Sarama',you should consider setting it to something application-specific.
[Sarama] 2020/09/25 16:46:04 client/Metadata fetching Metadata for all topics from broker localhost:9092
[Sarama] 2020/09/25 16:46:04 Connected to broker at localhost:9092 (unregistered)
[Sarama] 2020/09/25 16:46:04 client/brokers registered new broker #0 at 127.0.0.1:9092
[Sarama] 2020/09/25 16:46:04 Successfully initialized new client
似乎*bytes.Buffer
并没有被IoUtil.ReadAll()
冲昏头脑?如何解决前面的示例,以使output
是非空的?
解决方法
原来我只需要打电话
out.Flush()
在ioutil.ReadAll()
之前。现在输出如预期:
> go run main.go
2020/09/25 16:58:26 output: [Sarama] 2020/09/25 16:58:26 Initializing new client
[Sarama] 2020/09/25 16:58:26 ClientID is the default of 'sarama',you should consider setting it to something application-specific.
[Sarama] 2020/09/25 16:58:26 ClientID is the default of 'sarama',you should consider setting it to something application-specific.
[Sarama] 2020/09/25 16:58:26 client/metadata fetching metadata for all topics from broker localhost:9092
[Sarama] 2020/09/25 16:58:26 Connected to broker at localhost:9092 (unregistered)
[Sarama] 2020/09/25 16:58:26 client/brokers registered new broker #0 at 127.0.0.1:9092
[Sarama] 2020/09/25 16:58:26 Successfully initialized new client
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。