进行单元测试 Bcrypt
Go unit testing Bcrypt
我正在为一项服务执行单元测试,其中验证请求 dto 并使用 Go Bcrypt package 对用户密码进行哈希处理,然后再传递到存储库以插入数据库。
我不知道我的模拟函数应该如何return一个应该与服务的散列相匹配的虚拟响应。
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 a$.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 a$.ORGMDZNk3.ySMpKwJYYcONdpAbgMJh79UDApzwRnzkCe.qeiECUG false}
Want: is equal to {0 test@test.com 1 a$Bah8tCOzf7Z9Suw55DfyHOvnsBbXLyJEWV8QZ.owCBUOxxomAuEM2 false}
希望我的解释有道理,the article 中没有讨论单元测试,我的代码基于。
我设法模拟了我的加密包,然后在我的测试中进行了模拟,解决方案相当冗长,但我希望它能帮助将来的其他人。我还在学习 Go 所以有些术语可能不正确 (heh)
首先创建一个包,其中将创建您的哈希逻辑,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
}
我正在关注 hexagonal architecture which y learned in this Udemy course here(强烈推荐),因此我正在创建一个用于注册新用户的帐户服务,该服务需要一个用于访问其结构中的数据层的回购协议,因此如果我们要注入加密包然后我们就可以在测试中模拟它的实现。
这里会省略一些代码,主要是实现:
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: "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")
}
}
最初我的加密包只有散列所需的函数,但我被迫将它们包含在 struct
中,所以如果有更多经验的人知道一种模拟散列函数的方法帐户服务将使用模拟实现会很棒,因为代码会简单得多。
我正在为一项服务执行单元测试,其中验证请求 dto 并使用 Go Bcrypt package 对用户密码进行哈希处理,然后再传递到存储库以插入数据库。
我不知道我的模拟函数应该如何return一个应该与服务的散列相匹配的虚拟响应。
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 a$.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 a$.ORGMDZNk3.ySMpKwJYYcONdpAbgMJh79UDApzwRnzkCe.qeiECUG false}
Want: is equal to {0 test@test.com 1 a$Bah8tCOzf7Z9Suw55DfyHOvnsBbXLyJEWV8QZ.owCBUOxxomAuEM2 false}
希望我的解释有道理,the article 中没有讨论单元测试,我的代码基于。
我设法模拟了我的加密包,然后在我的测试中进行了模拟,解决方案相当冗长,但我希望它能帮助将来的其他人。我还在学习 Go 所以有些术语可能不正确 (heh)
首先创建一个包,其中将创建您的哈希逻辑,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
}
我正在关注 hexagonal architecture which y learned in this Udemy course here(强烈推荐),因此我正在创建一个用于注册新用户的帐户服务,该服务需要一个用于访问其结构中的数据层的回购协议,因此如果我们要注入加密包然后我们就可以在测试中模拟它的实现。
这里会省略一些代码,主要是实现:
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: "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")
}
}
最初我的加密包只有散列所需的函数,但我被迫将它们包含在 struct
中,所以如果有更多经验的人知道一种模拟散列函数的方法帐户服务将使用模拟实现会很棒,因为代码会简单得多。