summaryrefslogtreecommitdiff
path: root/player-server/internal/service/user_test.go
blob: b4701191dde09a0b27ba893030d82976d74887b1 (plain)
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
package service

import (
	"context"
	"errors"
	"testing"

	"codeberg.org/snonux/player/internal/clock"
	"codeberg.org/snonux/player/internal/model"
	"codeberg.org/snonux/player/internal/repository"
)

type fakeUserHasher struct {
	fixed string
	err   error
}

func (f *fakeUserHasher) Hash(password string) (string, error) {
	if f.err != nil {
		return "", f.err
	}
	return f.fixed, nil
}
func (f *fakeUserHasher) Compare(hash, password string) error {
	return nil
}

func TestUserAdminService_CreateUser(t *testing.T) {
	ctx := context.Background()

	tests := []struct {
		name      string
		password  string
		hashErr   error
		createErr error
		wantErr   bool
	}{
		{
			name:     "ok",
			password: "strongpass", // 10 chars, meets 8-char minimum
		},
		{
			name:     "hash error",
			password: "strongpass",
			hashErr:  errors.New("boom"),
			wantErr:  true,
		},
		{
			name:      "create error",
			password:  "strongpass",
			createErr: errors.New("boom"),
			wantErr:   true,
		},
		{
			name:    "empty password rejected",
			password: "",
			wantErr: true,
		},
		{
			name:    "short password rejected",
			password: "short",
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			store := &repository.MockStore{
				UserRepo: repository.MockUserRepo{
					CreateUserFunc: func(ctx context.Context, user *model.User) (int64, error) {
						return 1, tt.createErr
					},
				},
			}
			hasher := &fakeUserHasher{fixed: "hashed", err: tt.hashErr}
			svc := NewUserAdminService(store, clock.RealClock{}, hasher)
			user, err := svc.CreateUser(ctx, "alice", tt.password, false)
			if tt.wantErr {
				if err == nil {
					t.Fatal("expected error")
				}
				return
			}
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if user.Username != "alice" {
				t.Fatalf("unexpected username %q", user.Username)
			}
		})
	}
}