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