lens @ 049b9acbd9635c206f5eeb01074b5d63803c4cd5

  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 := 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}
 79
 80func TestReadWriteToken(t *testing.T) {
 81	t.Parallel()
 82
 83	testCases := []struct {
 84		name  string
 85		key   []byte
 86		token *Token
 87	}{
 88		{
 89			name: "Normal write",
 90			key:  []byte("AES256Key-32Characters1234567890"),
 91			token: &Token{
 92				UserID:   3,
 93				Username: "username",
 94			},
 95		},
 96	}
 97
 98	for _, tc := range testCases {
 99		t.Run(tc.name, func(t *testing.T) {
100			data, err := WriteToken(tc.token, tc.key)
101			testkit.TestFatalError(t, "WriteToken", err)
102
103			token, err := ReadToken(data, tc.key)
104			testkit.TestFatalError(t, "ReadToken", err)
105
106			testkit.TestValue(t, "ReadWriteToken", token, tc.token)
107		})
108	}
109}