1//go:build unit
2
3package service
4
5import (
6 "context"
7 "testing"
8
9 "git.sr.ht/~gabrielgio/img/pkg/database/repository"
10 "git.sr.ht/~gabrielgio/img/pkg/ext"
11 "git.sr.ht/~gabrielgio/img/pkg/testkit"
12)
13
14type (
15 scene struct {
16 ctx context.Context
17 authRepository repository.AuthRepository
18 userRepository repository.UserRepository
19 controller *AuthController
20 }
21)
22
23var (
24 key = []byte("6368616e676520746869732070617373")
25)
26
27func setUp() *scene {
28 userRepository := NewUserRepository()
29 return &scene{
30 ctx: context.Background(),
31 authRepository: userRepository,
32 userRepository: userRepository,
33 controller: NewAuthController(userRepository, userRepository, key),
34 }
35}
36
37func TestInitialRegisterAndLogin(t *testing.T) {
38 testCases := []struct {
39 name string
40 username string
41 password []byte
42 }{
43 {
44 name: "Normal register",
45 username: "username",
46 password: []byte("this is an password"),
47 },
48 }
49
50 for _, tc := range testCases {
51 t.Run(tc.name, func(t *testing.T) {
52 scene := setUp()
53
54 err := scene.controller.InitialRegister(scene.ctx, []byte(tc.username), tc.password, []byte("/"))
55 testkit.TestFatalError(t, "Register", err)
56
57 users, err := scene.userRepository.List(scene.ctx)
58 userID := users[0].ID
59
60 user, err := scene.userRepository.Get(scene.ctx, userID)
61 testkit.TestFatalError(t, "Get", err)
62 testkit.TestValue(t, "Register", tc.username, user.Username)
63
64 auth, err := scene.controller.Login(scene.ctx, []byte(tc.username), tc.password)
65 testkit.TestFatalError(t, "Login", err)
66
67 token, err := ext.ReadToken(auth, key)
68 testkit.TestFatalError(t, "Login", err)
69
70 testkit.TestValue(t, "Login", tc.username, token.Username)
71 testkit.TestValue(t, "Login", userID, token.UserID)
72 })
73 }
74}
75
76func remove[T any](slice []T, s int) []T {
77 return append(slice[:s], slice[s+1:]...)
78}