trepa/internal/accounts/service/account_test.go
qpismont 7c810ded85
Some checks failed
ci/woodpecker/push/lint Pipeline was successful
ci/woodpecker/push/tests Pipeline failed
ci/woodpecker/push/build unknown status
Update dependencies and improve account tests: add objx library, replace assert library with testify, enhance password assertions, and modify SQL fixtures for password hashing.
2025-03-24 21:18:01 +00:00

92 lines
2.1 KiB
Go

package service
import (
"testing"
"gitea.qpismont.fr/qpismont/trepa/internal/accounts/domain"
"gitea.qpismont.fr/qpismont/trepa/internal/accounts/repository"
"gitea.qpismont.fr/qpismont/trepa/internal/core"
"gitea.qpismont.fr/qpismont/trepa/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type MockRepository struct {
mock.Mock
}
func (m *MockRepository) FetchOneById(id int) (*domain.Account, error) {
args := m.Called(id)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*domain.Account), args.Error(1)
}
func (m *MockRepository) FetchOneByUsername(username string) (*domain.Account, error) {
args := m.Called(username)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*domain.Account), args.Error(1)
}
func (m *MockRepository) Insert(account domain.Account) (int, error) {
args := m.Called(account)
return args.Int(0), args.Error(1)
}
func TestService_GetAccount(t *testing.T) {
db := test.SetupTestDB(t, "../../..")
defer db.Close()
repo := repository.NewRepository(db)
service := NewService(repo)
account, err := service.GetAccount(1)
if err != nil {
t.Fatalf("Failed to get account: %v", err)
}
if account == nil {
t.Fatalf("Account not found")
}
assert.Equal(t, "admin", account.Username)
assert.Equal(t, 1, account.RoleId)
assert.NotEmpty(t, account.Password)
}
func TestService_Login(t *testing.T) {
mockRepo := new(MockRepository)
testPassword := "testpassword"
hashedPassword, _ := core.HashPassword(testPassword)
mockRepo.On("FetchOneByUsername", "admin").Return(&domain.Account{
Id: 1,
Username: "admin",
Password: hashedPassword,
RoleId: 1,
}, nil)
service := NewService(mockRepo)
result, err := service.Login(domain.AccountLogin{
Username: "admin",
Password: testPassword,
})
if err != nil {
t.Fatalf("Failed to login: %v", err)
}
assert.NotNil(t, result)
assert.NotNil(t, result.Token)
assert.NotNil(t, result.Account)
assert.Equal(t, "admin", result.Account.Username)
assert.Equal(t, 1, result.Account.RoleId)
mockRepo.AssertExpectations(t)
}