[英]Go unit testing Bcrypt
我正在对一项服务执行单元测试,其中验证请求 dto 并使用 Go 的Bcrypt package对用户密码进行哈希处理,然后将其传递到存储库以插入数据库。
我不知道我的模拟函数应该如何返回一个应该与服务的散列匹配的虚拟响应。
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: "test@test.com",
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
}
这是抛出的错误,请注意模拟请求与给定请求不匹配的want
和got
块。
accountService.go:34: Unexpected call to *domain.MockAccountRepository.Create([{0 test@test.com 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 test@test.com 1 $2a$04$.ORGMDZNk3.ySMpKwJYYcONdpAbgMJh79UDApzwRnzkCe.qeiECUG false}
Want: is equal to {0 test@test.com 1 $2a$04$Bah8tCOzf7Z9Suw55DfyHOvnsBbXLyJEWV8QZ.owCBUOxxomAuEM2 false}
希望我的解释是有道理的,在我的代码所依据的文章中没有讨论单元测试。
我设法模拟了我的加密 package,然后在我的测试中模拟,解决方案相当冗长,但我希望它在未来对其他人有所帮助。 我还在学习 Go 所以有些术语可能不正确(呵呵)
首先创建一个 package 将在其中创建您的哈希逻辑, 更多信息在这里,我正在使用 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 课程中学到的六边形架构(强烈推荐),因此我正在创建一个用于注册新用户的帐户服务,该服务需要一个用于访问其结构中数据层的存储库,所以如果我们要注入crypto package 然后我们就可以在测试中模拟它的实现了。
这里会省略一些代码,主要是实现:
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}
}
现在我们应该能够模拟这个 package,所以这样的事情会起作用。
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: "test@test.com",
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")
}
}
最初我的加密 package 仅具有散列所需的 function ,但我被迫将它们包含在struct
中,因此,如果有更多经验的人知道一种模拟散列函数的方法,而帐户服务将使用模拟实现将很棒,因为代码会简单得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.