对 Bcrypt 进行单元测试
golang学习网今天将给大家带来《对 Bcrypt 进行单元测试》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!
我正在对一项服务执行单元测试,其中使用 go 的 bcrypt 包验证请求 dto 并对用户密码进行哈希处理,然后将其传递到存储库以插入数据库。
我不知道我的模拟函数应该如何返回一个与服务的哈希值匹配的虚拟响应。
func test_should_create_new_account(t *testing.t) {
// arrange
teardown := setup(t)
defer teardown()
// ** focus here **
hashedpassword, err := appcrypto.hashandsalt([]byte("securepassword"))
request := dto.registerrequest{
email: "[email protected]",
password: "securepassword",
roleid: 1,
}
account := realdomain.account{
email: request.email,
password: hashedpassword,
roleid: request.roleid,
}
accountwithid := account
accountwithid.accountid = 1
mockrepo.expect().create(account).return(&accountwithid, nil)
// act
res, err := service.registeraccount(request)
// assert
if err != nil {
t.error("failed while creating account")
}
if !res.created {
t.error("failed while creating account")
}
}
hashandsalt 只是对给定字符串进行哈希处理。
// hashandsalt hashes a given string
func hashandsalt(pwd []byte) (string, *errs.apperror) {
// use generatefrompassword to hash & salt pwd.
// mincost is just an integer constant provided by the bcrypt
// package along with defaultcost & maxcost.
// the cost can be any value you want provided it isn't lower
// than the mincost (4)
hash, err := bcrypt.generatefrompassword(pwd, bcrypt.mincost)
if err != nil {
return "", errs.newunexpectederror("an unexpected error ocurred while hashing the password" + err.error())
} // generatefrompassword returns a byte slice so we need to
// convert the bytes to a string and return it
return string(hash), nil
}
这是服务的 registeraccount
func (d defaultaccountservice) registeraccount(request dto.registerrequest) (*dto.registerresponse, *errs.apperror) {
err := request.validate()
if err != nil {
return nil, err
}
// hash the request's password
hashedpassword, err := appcrypto.hashandsalt([]byte(request.password))
if err != nil {
return nil, err
}
// assign the hashed password to the request obj
request.password = hashedpassword
a := request.todomainobject()
_, err = d.repo.create(a)
if err != nil {
return nil, err
}
response := dto.registerresponse{
created: true,
}
return &response, nil
}
这是抛出的错误,请注意 got 块,其中模拟请求与给定请求不匹配。
accountService.go:34: Unexpected call to *domain.MockAccountRepository.Create([{0 [email protected] 1 $2a$04$.ORGMDZNk3.ySMpKwJYYcONdpAbgMJh79UDApzwRnzkCe.qeiECUG false}]) at /home/dio/Documents/Code/go-beex-backend/auth-server/mocks/domain/accountRepositoryDB.go:40 because:
expected call at /home/dio/Documents/Code/go-beex-backend/auth-server/service/accountService_test.go:52 doesn't match the argument at index 0.
Got: {0 [email protected] 1 $2a$04$.ORGMDZNk3.ySMpKwJYYcONdpAbgMJh79UDApzwRnzkCe.qeiECUG false}
Want: is equal to {0 [email protected] 1 $2a$04$Bah8tCOzf7Z9Suw55DfyHOvnsBbXLyJEWV8QZ.owCBUOxxomAuEM2 false}
希望我的解释有意义,我的代码所依据的文章中没有讨论单元测试。
解决方案
我设法模拟了我的加密包,然后在我的测试中进行了模拟,该解决方案相当冗长,但我希望它将来对其他人有帮助。我还在学习 go,所以有些术语可能不正确(呵呵)
首先创建一个包,其中将创建您的哈希逻辑,more info here,我使用mockgen来创建我的模拟,所以我在界面中添加了注释
//go:generate mockgen -destination=../mocks/crypto/mockcrypto.go -package=crypto auth-server/crypto appcrypto
type appcrypto interface {
hashandsalt(pwd []byte) (string, *errs.apperror)
comparepasswords(hashedpwd string, plainpwd []byte) bool
}
type defaultappcrypto struct {
}
// hashandsalt hashes a given string
func (d defaultappcrypto) hashandsalt(pwd []byte) (string, *errs.apperror) {
hash, err := bcrypt.generatefrompassword(pwd, bcrypt.mincost)
if err != nil {
return "", errs.newunexpectederror("an unexpected error ocurred while hashing the password" + err.error())
}
return string(hash), nil
}
func (d defaultappcrypto) comparepasswords(hashedpwd string, plainpwd []byte) bool {
bytehash := []byte(hashedpwd)
err := bcrypt.comparehashandpassword(bytehash, plainpwd)
if err != nil {
return false
}
return true
}
我正在关注您在 udemy 课程 here 中学到的 hexagonal architecture(强烈推荐),因此我正在创建一个用于注册新用户的帐户服务,该服务需要一个用于访问其结构中的数据层的存储库,所以如果我们要注入加密包,然后我们就可以在测试中模拟它的实现。
这里省略一些代码,主要是实现:
type accountservice interface {
registeraccount(dto.registerrequest) (*dto.registerresponse, *errs.apperror)
}
type defaultaccountservice struct {
repo domain.accountrepository
crypto crypto.appcrypto
}
// more code here
func newaccountservice(repo domain.accountrepository, crypto crypto.appcrypto) defaultaccountservice {
return defaultaccountservice{repo, crypto}
}
现在我们应该能够模拟这个包,这样类似的东西就可以工作了。
var mockRepo *domain.MockAccountRepository
var mockCrypto *crypto.MockAppCrypto
var ctrl gomock.Controller
var service AccountService
func setup(t *testing.T) func() {
ctrl := gomock.NewController(t)
mockRepo = domain.NewMockAccountRepository(ctrl)
mockCrypto = crypto.NewMockAppCrypto(ctrl)
service = NewAccountService(mockRepo, mockCrypto)
return func() {
service = nil
defer ctrl.Finish()
}
}
func Test_should_create_new_account(t *testing.T) {
// Arrange
teardown := setup(t)
defer teardown()
cryptoService := realCrypto.DefaultAppCrypto{}
password := "securepassword"
hashedpassword, err := cryptoService.HashAndSalt([]byte(password))
request := dto.RegisterRequest{
Email: "[email protected]",
Password: password,
RoleID: 1,
}
account := realDomain.Account{
Email: request.Email,
Password: hashedpassword,
RoleID: request.RoleID,
}
accountWithID := account
accountWithID.AccountID = 1
// ** MOCK THE DATA LAYER IMPLEMENTATION
mockRepo.EXPECT().Create(account).Return(&accountWithID, nil)
// ** MOCK THE CRYPTO PACKAGE's HashAndSalt
mockCrypto.EXPECT().HashAndSalt([]byte(password)).Return(hashedpassword, nil)
// Act
res, err := service.RegisterAccount(request)
// Assert
if err != nil {
t.Error("Failed while creating account")
}
if !res.Created {
t.Error("Failed while creating account")
}
}
最初我的加密包只有哈希所需的函数,但我被迫将它们包含在 struct 中,因此如果有更多经验的人知道一种模拟哈希函数的方法,帐户服务将使用模拟实现会很棒,因为代码会简单得多。
到这里,我们也就讲完了《对 Bcrypt 进行单元测试》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
docker-compose中的服务无法解析Postgres主机名
- 上一篇
- docker-compose中的服务无法解析Postgres主机名
- 下一篇
- 在 JetBrains Goland 中如何设置和使用 IPFS (kubo)?
-
- Golang · Go问答 | 27分钟前 | go · Go image.Gray PixOffset 灰度像素
- Go image.Gray.PixOffset 怎样根据坐标定位灰度像素
- 444浏览 收藏
-
- Golang · Go问答 | 41分钟前 |
- Go image/color.NRGBA.RGBA 怎样理解颜色分量的 alpha 预乘
- 317浏览 收藏
-
- Golang · Go问答 | 49分钟前 | Go问答 · Go 颜色转换 RGB image/color CMYK RGBToCMYK
- Go image/color.RGBToCMYK 怎样把 RGB 分量转换成印刷色
- 390浏览 收藏
-
- Golang · Go问答 | 58分钟前 |
- Go encoding/gob.Decoder.DecodeValue 怎样通过反射目标接收解码值
- 394浏览 收藏
-
- Golang · Go问答 | 1小时前 | 标准库 · go · Go encoding/base32 Encoding.EncodeToString Base32编码
- Go encoding/base32.Encoding.EncodeToString 怎样直接生成 Base32 字符串
- 485浏览 收藏
-
- Golang · Go问答 | 1小时前 | go · Go net/textproto 文本协议 Pipeline.StartRequest 请求编号
- Go net/textproto.Pipeline.StartRequest 怎样按编号协调请求写入
- 376浏览 收藏
-
- Golang · Go问答 | 1小时前 | go · Go net/textproto Reader.ReadDotLines dot-encoding
- Go net/textproto.Reader.ReadDotLines 怎样把点终止正文读成多行字符串
- 463浏览 收藏
-
- Golang · Go问答 | 1小时前 | 网络编程 · go · Go net/textproto Reader.ReadResponse 多行响应
- Go net/textproto.Reader.ReadResponse 怎样读取带续行的协议响应
- 260浏览 收藏
-
- Golang · Go问答 | 1小时前 | go · Go text/scanner 词法扫描 Scanner.TokenText 记号文本
- Go text/scanner.Scanner.TokenText 怎样保留当前记号的原始文本
- 360浏览 收藏
-
- Golang · Go问答 | 1小时前 | go · regexp · Go 正则匹配 index/suffixarray FindAllIndex 字节区间
- Go index/suffixarray.Index.FindAllIndex 怎样返回正则匹配的字节区间
- 238浏览 收藏
-
- Golang · Go问答 | 1小时前 | 标准库 · 数据一致性 · Go问答 · Go 原始数据 index/suffixarray Index.Bytes 后缀数组 索引持久化
- Go index/suffixarray.Index.Bytes 怎样取得索引引用的原始数据
- 501浏览 收藏
-
- Golang · Go问答 | 1小时前 | 数据结构 · 标准库 · go · Go container/ring Ring.Move 环形指针
- Go container/ring.Ring.Move 怎样按正负偏移移动环形指针
- 377浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 1095次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 1092次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 1258次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 1198次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 1047次使用
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go index/suffixarray.Index.Bytes 怎样取得索引引用的原始数据
- 2026-11-18 501浏览
-
- Go gosym.Sym.BaseName 怎样去掉符号的包名与接收者
- 2026-11-17 501浏览
-
- 正则命名捕获组取不到值怎么办
- 2026-11-15 501浏览

