summaryrefslogtreecommitdiff
path: root/internal/rpn/persistence_test.go
blob: 2b8b50510ec9809f4fb013f5dcb267a42419c927 (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
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Paul Buetow

package rpn

import (
	"math"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"
)

func TestVariablesSaveLoadCorruptFile(t *testing.T) {
	tmpFile := filepath.Join(t.TempDir(), "corrupt.json")

	// Write invalid JSON
	if err := os.WriteFile(tmpFile, []byte("{invalid json"), 0644); err != nil {
		t.Fatalf("failed to create corrupt file: %v", err)
	}

	vars := NewVariables()
	err := vars.Load(tmpFile)
	if err == nil {
		t.Error("Load from corrupt JSON file should return an error")
	}
	if !strings.Contains(err.Error(), "unmarshal") {
		t.Errorf("error should mention unmarshal, got: %v", err)
	}
}

func TestVariablesLoadFiltersInvalidVariableNames(t *testing.T) {
	tmpFile := filepath.Join(t.TempDir(), "vars.json")

	// Write JSON with valid and invalid variable names
	jsonData := `[
		{"Name": "valid_name", "Value": 42},
		{"Name": "alsoValid123", "Value": 99.5},
		{"Name": "", "Value": 10},
		{"Name": "has space", "Value": 20},
		{"Name": "has@symbol", "Value": 30},
		{"Name": "valid_too", "Value": -5}
	]`
	if err := os.WriteFile(tmpFile, []byte(jsonData), 0644); err != nil {
		t.Fatalf("failed to write test file: %v", err)
	}

	vars := NewVariables()
	if err := vars.Load(tmpFile); err != nil {
		t.Fatalf("Load failed: %v", err)
	}

	// Valid variables should be loaded
	if vars.Count() != 3 {
		t.Errorf("should have 3 valid variables, got %d", vars.Count())
	}

	if val, exists := vars.GetVariable("valid_name"); !exists || val != 42 {
		t.Errorf("valid_name = %v (exists=%v), want 42", val, exists)
	}
	if val, exists := vars.GetVariable("alsoValid123"); !exists || val != 99.5 {
		t.Errorf("alsoValid123 = %v (exists=%v), want 99.5", val, exists)
	}
	if val, exists := vars.GetVariable("valid_too"); !exists || val != -5 {
		t.Errorf("valid_too = %v (exists=%v), want -5", val, exists)
	}

	// Invalid names should not be loaded
	if vars.HasVariable("") {
		t.Error("empty variable name should not be loaded")
	}
	if vars.HasVariable("has space") {
		t.Error("variable with space should not be loaded")
	}
	if vars.HasVariable("has@symbol") {
		t.Error("variable with symbol should not be loaded")
	}
}

func TestVariablesSaveLoadRoundTripDiverseValues(t *testing.T) {
	tests := []struct {
		name  string
		value float64
	}{
		{"zero", 0},
		{"negative", -42.5},
		{"positive", 42.5},
		{"veryLarge", 1.7976931348623157e+308}, // near max float64
		{"verySmall", 5e-324},                  // near min float64
		{"scientific", 1.23e-10},
		{"pi", 3.141592653589793},
		{"integer", 100},
		{"decimal", 0.1},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tmpFile := filepath.Join(t.TempDir(), "vars.json")

			// Create and save
			vars := NewVariables()
			err := vars.SetVariable("v", tt.value)
			if err != nil {
				t.Fatalf("SetVariable failed: %v", err)
			}
			if err := vars.Save(tmpFile); err != nil {
				t.Fatalf("Save failed: %v", err)
			}

			// Load and verify
			newVars := NewVariables()
			if err := newVars.Load(tmpFile); err != nil {
				t.Fatalf("Load failed: %v", err)
			}

			loadedVal, exists := newVars.GetVariable("v")
			if !exists {
				t.Fatal("variable 'v' not found after load")
			}
			if loadedVal != tt.value {
				t.Errorf("value = %v, want %v", loadedVal, tt.value)
			}
		})
	}
}

func TestVariablesSaveFileFormat(t *testing.T) {
	tmpFile := filepath.Join(t.TempDir(), "vars.json")

	vars := NewVariables()
	_ = vars.SetVariable("z", 3.0)
	_ = vars.SetVariable("a", 1.0)

	if err := vars.Save(tmpFile); err != nil {
		t.Fatalf("Save failed: %v", err)
	}

	// Verify JSON structure
	data, err := os.ReadFile(tmpFile)
	if err != nil {
		t.Fatalf("failed to read saved file: %v", err)
	}

	content := string(data)
	// Variables should be sorted by name, so "a" appears before "z"
	aIdx := strings.Index(content, `"a"`)
	zIdx := strings.Index(content, `"z"`)
	if aIdx >= zIdx {
		t.Errorf("variables should be sorted by name in JSON, got: %s", content)
	}
	// Should use indented JSON (MarshalIndent)
	if !strings.Contains(content, "\n  ") {
		t.Errorf("expected indented JSON, got: %s", content)
	}
}

func TestVariablesSaveLoadMultipleVariables(t *testing.T) {
	tmpFile := filepath.Join(t.TempDir(), "vars.json")

	// Create and save many variables
	vars := NewVariables()
	for i := 0; i < 50; i++ {
		name := string(rune('a'+i%26)) + string(rune('a'+(i/26)%26))
		_ = vars.SetVariable(name, float64(i)*1.5)
	}

	if err := vars.Save(tmpFile); err != nil {
		t.Fatalf("Save failed: %v", err)
	}

	// Load and verify all
	newVars := NewVariables()
	if err := newVars.Load(tmpFile); err != nil {
		t.Fatalf("Load failed: %v", err)
	}

	if newVars.Count() != 50 {
		t.Errorf("Count = %d, want 50", newVars.Count())
	}

	for i := 0; i < 50; i++ {
		name := string(rune('a'+i%26)) + string(rune('a'+(i/26)%26))
		want := float64(i) * 1.5
		got, exists := newVars.GetVariable(name)
		if !exists {
			t.Errorf("variable %q not found", name)
			continue
		}
		if got != want {
			t.Errorf("%s = %v, want %v", name, got, want)
		}
	}
}

func TestVariablesSaveLoadConcurrency(t *testing.T) {
	vars := NewVariables()
	for i := 0; i < 10; i++ {
		_ = vars.SetVariable(string(rune('a'+i)), float64(i))
	}

	// Save to a stable file first
	tmpFile := filepath.Join(t.TempDir(), "vars.json")
	if err := vars.Save(tmpFile); err != nil {
		t.Fatalf("initial Save failed: %v", err)
	}

	errChan := make(chan error, 10)

	// Concurrent loads from the same file (reads are safe)
	for i := 0; i < 10; i++ {
		go func() {
			v := NewVariables()
			errChan <- v.Load(tmpFile)
		}()
	}

	for i := 0; i < 10; i++ {
		if err := <-errChan; err != nil {
			t.Errorf("concurrent load failed: %v", err)
		}
	}

	// Test concurrent SetVariable/GetVariable on same instance
	vars2 := NewVariables()
	var wg sync.WaitGroup

	// Concurrent writes
	for i := 0; i < 50; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			_ = vars2.SetVariable(string(rune('x'+id%26)), float64(id))
		}(i)
	}

	// Concurrent reads
	for i := 0; i < 50; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			vars2.GetVariable(string(rune('x' + id%26)))
		}(i)
	}

	// Concurrent count/list
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			_ = vars2.Count()
			_ = vars2.ListVariables()
		}()
	}

	wg.Wait()

	// Verify final state is consistent
	if vars2.Count() > 26 {
		t.Errorf("Count = %d, expected at most 26 (x0-x25)", vars2.Count())
	}
}

func TestVariablesLoadEmptyJSON(t *testing.T) {
	tmpFile := filepath.Join(t.TempDir(), "empty.json")

	// Write empty JSON array
	if err := os.WriteFile(tmpFile, []byte("[]"), 0644); err != nil {
		t.Fatalf("failed to create file: %v", err)
	}

	vars := NewVariables()
	if err := vars.Load(tmpFile); err != nil {
		t.Fatalf("Load of empty JSON array failed: %v", err)
	}

	if vars.Count() != 0 {
		t.Errorf("Count = %d, want 0", vars.Count())
	}
}

func TestVariablesLoadPreservesExistingAfterError(t *testing.T) {
	vars := NewVariables()
	if err := vars.SetVariable("existing", 42.0); err != nil {
		t.Fatalf("SetVariable failed: %v", err)
	}

	// Load from corrupt file
	tmpFile := filepath.Join(t.TempDir(), "corrupt.json")
	if err := os.WriteFile(tmpFile, []byte("not json"), 0644); err != nil {
		t.Fatalf("failed to create corrupt file: %v", err)
	}

	err := vars.Load(tmpFile)
	if err == nil {
		t.Fatal("expected error loading corrupt file")
	}

	// Load() calls loadVariables() before acquiring the write lock.
	// When loadVariables() errors, Load() returns the error without
	// modifying the map, so existing state is preserved.
	val, exists := vars.GetVariable("existing")
	if !exists || val != 42.0 {
		t.Errorf("existing variable should be preserved after failed Load: got %v (exists=%v)", val, exists)
	}
}

func TestVariablesSaveInfReturnsError(t *testing.T) {
	tmpFile := filepath.Join(t.TempDir(), "inf.json")

	vars := NewVariables()
	// Inf values cannot be marshaled to JSON, so Save should fail
	if err := vars.SetVariable("inf", math.Inf(1)); err != nil {
		t.Fatalf("SetVariable failed: %v", err)
	}
	err := vars.Save(tmpFile)
	if err == nil {
		t.Error("Save with Inf value should return an error (JSON cannot represent Inf)")
	}
	if !strings.Contains(err.Error(), "unsupported value") {
		t.Errorf("error should mention unsupported value, got: %v", err)
	}
}

func TestVariablesLoadDuplicateNames(t *testing.T) {
	tmpFile := filepath.Join(t.TempDir(), "dupes.json")

	// JSON with duplicate names — last one wins in Go maps
	jsonData := `[{"Name":"x","Value":1},{"Name":"x","Value":2}]`
	if err := os.WriteFile(tmpFile, []byte(jsonData), 0644); err != nil {
		t.Fatalf("failed to write file: %v", err)
	}

	vars := NewVariables()
	if err := vars.Load(tmpFile); err != nil {
		t.Fatalf("Load failed: %v", err)
	}

	// Should have exactly 1 variable (x), with value 2 (last wins)
	if vars.Count() != 1 {
		t.Errorf("Count = %d, want 1", vars.Count())
	}
	val, exists := vars.GetVariable("x")
	if !exists || val != 2 {
		t.Errorf("x = %v (exists=%v), want 2 (last wins)", val, exists)
	}
}

func TestVariablesLoadEmptyFile(t *testing.T) {
	tmpFile := filepath.Join(t.TempDir(), "empty.json")

	// Write empty file (not even valid JSON)
	if err := os.WriteFile(tmpFile, []byte{}, 0644); err != nil {
		t.Fatalf("failed to create empty file: %v", err)
	}

	vars := NewVariables()
	err := vars.Load(tmpFile)
	if err == nil {
		t.Error("Load from empty file should return an error (invalid JSON)")
	}
}