lens @ 13fd911873a7df311544b1ec916c98ee05c91bbc

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