This repository was archived by the owner on May 29, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhelpers_test.go
More file actions
309 lines (268 loc) · 7.52 KB
/
Copy pathhelpers_test.go
File metadata and controls
309 lines (268 loc) · 7.52 KB
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package main
import (
"encoding/json"
"os"
"path/filepath"
"testing"
)
// --- LoadUserJSON / SaveUserJSON ---
func TestSaveAndLoadUserJSON(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "userdata_test_*")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
origPath := USERDATA_PATH
USERDATA_PATH = tmpDir
defer func() { USERDATA_PATH = origPath }()
// Setup a minimal idToUser mapping so Username.Id() works
idToUserMutex.Lock()
if usernameToId == nil {
usernameToId = make(map[Username]UserId)
}
if idToUser == nil {
idToUser = make(map[UserId]User)
}
usernameToId["jsontestuser"] = UserId("id_jsontestuser")
idToUser[UserId("id_jsontestuser")] = User{"username": "jsontestuser", "sys.id": "id_jsontestuser"}
idToUserMutex.Unlock()
defer func() {
idToUserMutex.Lock()
delete(usernameToId, "jsontestuser")
delete(idToUser, "id_jsontestuser")
idToUserMutex.Unlock()
}()
type TestStruct struct {
Name string `json:"name"`
Value int `json:"value"`
}
username := Username("jsontestuser")
userId := username.Id()
orig := TestStruct{Name: "test", Value: 42}
err = SaveUserJSON(userId, "test_data.json", orig)
if err != nil {
t.Fatalf("SaveUserJSON failed: %v", err)
}
loaded, err := LoadUserJSON[TestStruct](userId, "test_data.json")
if err != nil {
t.Fatalf("LoadUserJSON failed: %v", err)
}
if loaded.Name != "test" || loaded.Value != 42 {
t.Errorf("Loaded data mismatch: got %+v, want {Name:test Value:42}", loaded)
}
}
func TestLoadUserJSON_NotExists(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "userdata_test_*")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
origPath := USERDATA_PATH
USERDATA_PATH = tmpDir
defer func() { USERDATA_PATH = origPath }()
idToUserMutex.Lock()
if usernameToId == nil {
usernameToId = make(map[Username]UserId)
}
if idToUser == nil {
idToUser = make(map[UserId]User)
}
usernameToId["nonexistuser"] = UserId("id_nonexistuser")
idToUser[UserId("id_nonexistuser")] = User{"username": "nonexistuser", "sys.id": "id_nonexistuser"}
idToUserMutex.Unlock()
defer func() {
idToUserMutex.Lock()
delete(usernameToId, "nonexistuser")
delete(idToUser, "id_nonexistuser")
idToUserMutex.Unlock()
}()
_, err = LoadUserJSON[struct{}](UserId("id_nonexistuser"), "nonexistent.json")
if err == nil {
t.Error("LoadUserJSON should return error for nonexistent file")
}
}
func TestSaveUserJSON_CreatesDirectory(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "userdata_test_*")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
origPath := USERDATA_PATH
USERDATA_PATH = filepath.Join(tmpDir, "deep", "nested")
defer func() { USERDATA_PATH = origPath }()
idToUserMutex.Lock()
if usernameToId == nil {
usernameToId = make(map[Username]UserId)
}
if idToUser == nil {
idToUser = make(map[UserId]User)
}
usernameToId["dirtestuser"] = UserId("id_dirtestuser")
idToUser[UserId("id_dirtestuser")] = User{"username": "dirtestuser", "sys.id": "id_dirtestuser"}
idToUserMutex.Unlock()
defer func() {
idToUserMutex.Lock()
delete(usernameToId, "dirtestuser")
delete(idToUser, "id_dirtestuser")
idToUserMutex.Unlock()
}()
err = SaveUserJSON(UserId("id_dirtestuser"), "data.json", map[string]string{"k": "v"})
if err != nil {
t.Fatalf("SaveUserJSON should create nested dirs, got: %v", err)
}
dirPath := filepath.Join(USERDATA_PATH, "id_dirtestuser")
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
t.Errorf("Directory %s should exist", dirPath)
}
}
// --- isValidJSON (more comprehensive tests) ---
func TestIsValidJSON_VariousTypes(t *testing.T) {
tests := []struct {
input string
expected bool
}{
{`{"key": "value"}`, true},
{`[1, 2, 3]`, true},
{`42`, true},
{`"hello"`, true},
{`true`, true},
{`false`, true},
{`null`, true},
{`{}`, true},
{`[]`, true},
{``, false},
{`{broken`, false},
{`[1, 2,`, false},
{`undefined`, false},
}
for _, tt := range tests {
got := isValidJSON(tt.input)
if got != tt.expected {
t.Errorf("isValidJSON(%q) = %v, want %v", tt.input, got, tt.expected)
}
}
}
// --- JSONStringify ---
func TestJSONStringify_NilMap(t *testing.T) {
// json.Marshal(nil map) should produce "null" or "{}"
result := JSONStringify(map[string]string(nil))
if result != "null" {
t.Logf("JSONStringify(nil map) = %q (depends on json.Marshal behavior)", result)
}
}
func TestJSONStringify_Struct(t *testing.T) {
type testStruct struct {
Name string `json:"name"`
}
result := JSONStringify(testStruct{Name: "test"})
expected := `{"name":"test"}`
if result != expected {
t.Errorf("JSONStringify(struct) = %q, want %q", result, expected)
}
}
// --- JSON round-trip for Gift ---
func TestGift_JSON_RoundTrip(t *testing.T) {
now := int64(1700000000000)
claimedAt := now + 1000
claimedBy := UserId("user1")
g := Gift{
Id: "gift1",
Code: "abc123def456",
Amount: 50.0,
Note: "test gift",
CreatorId: UserId("creator1"),
CreatedAt: now,
ExpiresAt: now + 86400000,
ClaimedAt: &claimedAt,
ClaimedBy: &claimedBy,
}
data, err := json.Marshal(g)
if err != nil {
t.Fatalf("Failed to marshal Gift: %v", err)
}
var decoded Gift
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatalf("Failed to unmarshal Gift: %v", err)
}
if decoded.Id != g.Id {
t.Errorf("Id mismatch: got %q, want %q", decoded.Id, g.Id)
}
if decoded.Code != g.Code {
t.Errorf("Code mismatch: got %q, want %q", decoded.Code, g.Code)
}
if decoded.Amount != g.Amount {
t.Errorf("Amount mismatch: got %v, want %v", decoded.Amount, g.Amount)
}
if decoded.ClaimedAt == nil || *decoded.ClaimedAt != claimedAt {
t.Errorf("ClaimedAt mismatch: got %v, want %d", decoded.ClaimedAt, claimedAt)
}
}
// --- JSON round-trip for Key ---
func TestKey_JSON_RoundTrip(t *testing.T) {
webhook := "https://example.com/hook"
data := "some data"
k := Key{
Key: "key123",
Creator: UserId("creator1"),
Users: map[UserId]KeyUserData{},
Name: "Test Key",
Price: 10,
Type: "subscription",
Webhook: &webhook,
Data: &data,
TotalIncome: 100,
}
k.Users[UserId("user1")] = KeyUserData{
Time: 1700000000000,
Price: 10,
}
encoded, err := json.Marshal(k)
if err != nil {
t.Fatalf("Failed to marshal Key: %v", err)
}
var decoded Key
if err := json.Unmarshal(encoded, &decoded); err != nil {
t.Fatalf("Failed to unmarshal Key: %v", err)
}
if decoded.Key != "key123" {
t.Errorf("Key mismatch: got %q, want %q", decoded.Key, "key123")
}
if decoded.Name != "Test Key" {
t.Errorf("Name mismatch: got %q, want %q", decoded.Name, "Test Key")
}
if decoded.Price != 10 {
t.Errorf("Price mismatch: got %d, want %d", decoded.Price, 10)
}
}
// --- JSON round-trip for Transaction ---
func TestTransaction_JSON_RoundTrip(t *testing.T) {
tx := Transaction{
Type: "transfer",
User: UserId("user1"),
To: "user2",
Amount: 50.0,
Note: "payment",
Timestamp: 1700000000000,
NewTotal: 150.0,
PetitionId: "pet1",
KeyName: "mykey",
KeyId: "key1",
}
data, err := json.Marshal(tx)
if err != nil {
t.Fatalf("Failed to marshal Transaction: %v", err)
}
var decoded Transaction
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatalf("Failed to unmarshal Transaction: %v", err)
}
if decoded.Type != "transfer" {
t.Errorf("Type mismatch: got %q, want %q", decoded.Type, "transfer")
}
if decoded.Amount != 50.0 {
t.Errorf("Amount mismatch: got %v, want %v", decoded.Amount, 50.0)
}
if decoded.KeyName != "mykey" {
t.Errorf("KeyName mismatch: got %q, want %q", decoded.KeyName, "mykey")
}
}