Debian Codegraph @

config_concurrent_test.go

raw
1 package gitconfig
2
3 import (
4 "os"
5 "path/filepath"
6 "sync"
7 "testing"
8 "time"
9
10 "github.com/stretchr/testify/assert"
11 "github.com/stretchr/testify/require"
12 )
13
14 // TestConcurrentReads tests that multiple goroutines can safely read from the same config.
15 func TestConcurrentReads(t *testing.T) {
16 t.Parallel()
17
18 td := t.TempDir()
19 configPath := filepath.Join(td, "config")
20
21 // Create a config with multiple keys
22 content := `[user]
23 name = John Doe
24 email = [email protected]
25 [core]
26 editor = vim
27 autocrlf = true
28 filemode = false
29 [remote "origin"]
30 url = https://github.com/test/repo.git
31 fetch = +refs/heads/*:refs/remotes/origin/*
32 `
33 err := os.WriteFile(configPath, []byte(content), 0o644)
34 require.NoError(t, err)
35
36 cfg, err := LoadConfig(configPath)
37 require.NoError(t, err)
38 require.NotNil(t, cfg)
39
40 // Launch multiple goroutines reading different keys
41 var wg sync.WaitGroup
42 iterations := 100
43 goroutines := 10
44
45 for g := range goroutines {
46 wg.Add(1)
47 go func(id int) {
48 defer wg.Done()
49
50 for range iterations {
51 // Each goroutine reads different keys based on its ID
52 switch id % 3 {
53 case 0:
54 name, ok := cfg.Get("user.name")
55 assert.True(t, ok)
56 assert.Equal(t, "John Doe", name)
57 case 1:
58 editor, ok := cfg.Get("core.editor")
59 assert.True(t, ok)
60 assert.Equal(t, "vim", editor)
61 case 2:
62 url, ok := cfg.Get("remote.origin.url")
63 assert.True(t, ok)
64 assert.Equal(t, "https://github.com/test/repo.git", url)
65 }
66 }
67 }(g)
68 }
69
70 wg.Wait()
71 }
72
73 // TestConcurrentLoad tests that loading multiple configs concurrently is safe.
74 func TestConcurrentLoad(t *testing.T) {
75 t.Parallel()
76
77 td := t.TempDir()
78
79 // Create multiple config files
80 configs := make([]string, 5)
81 for i := range configs {
82 configPath := filepath.Join(td, "config"+string(rune('0'+i)))
83 content := "[user]\n\tname = User" + string(rune('0'+i))
84 err := os.WriteFile(configPath, []byte(content), 0o644)
85 require.NoError(t, err)
86 configs[i] = configPath
87 }
88
89 // Load all configs concurrently
90 var wg sync.WaitGroup
91 results := make([]*Config, len(configs))
92 errors := make([]error, len(configs))
93
94 for i := range configs {
95 wg.Add(1)
96 go func(index int) {
97 defer wg.Done()
98 cfg, err := LoadConfig(configs[index])
99 results[index] = cfg
100 errors[index] = err
101 }(i)
102 }
103
104 wg.Wait()
105
106 // Verify all loads succeeded
107 for i := range configs {
108 require.NoError(t, errors[i], "config %d should load without error", i)
109 require.NotNil(t, results[i], "config %d should not be nil", i)
110
111 name, ok := results[i].Get("user.name")
112 assert.True(t, ok)
113 assert.Equal(t, "User"+string(rune('0'+i)), name)
114 }
115 }
116
117 // TestConcurrentReadsSameKey tests race conditions when reading the same key.
118 func TestConcurrentReadsSameKey(t *testing.T) {
119 t.Parallel()
120
121 td := t.TempDir()
122 configPath := filepath.Join(td, "config")
123
124 content := "[user]\n\tname = Concurrent Test"
125 err := os.WriteFile(configPath, []byte(content), 0o644)
126 require.NoError(t, err)
127
128 cfg, err := LoadConfig(configPath)
129 require.NoError(t, err)
130 require.NotNil(t, cfg)
131
132 // Many goroutines reading the same key
133 var wg sync.WaitGroup
134 iterations := 50
135 goroutines := 20
136
137 for range goroutines {
138 wg.Add(1)
139 go func() {
140 defer wg.Done()
141 for range iterations {
142 name, ok := cfg.Get("user.name")
143 assert.True(t, ok)
144 assert.Equal(t, "Concurrent Test", name)
145 }
146 }()
147 }
148
149 wg.Wait()
150 }
151
152 // TestConcurrentGetAll tests concurrent access to multi-valued keys.
153 func TestConcurrentGetAll(t *testing.T) {
154 t.Parallel()
155
156 td := t.TempDir()
157 configPath := filepath.Join(td, "config")
158
159 content := `[remote "origin"]
160 fetch = +refs/heads/*:refs/remotes/origin/*
161 fetch = +refs/tags/*:refs/tags/*
162 fetch = +refs/pull/*/head:refs/remotes/origin/pr/*
163 `
164 err := os.WriteFile(configPath, []byte(content), 0o644)
165 require.NoError(t, err)
166
167 cfg, err := LoadConfig(configPath)
168 require.NoError(t, err)
169 require.NotNil(t, cfg)
170
171 var wg sync.WaitGroup
172 iterations := 50
173 goroutines := 10
174
175 for range goroutines {
176 wg.Add(1)
177 go func() {
178 defer wg.Done()
179 for range iterations {
180 values, ok := cfg.GetAll("remote.origin.fetch")
181 assert.True(t, ok)
182 assert.Len(t, values, 3)
183 }
184 }()
185 }
186
187 wg.Wait()
188 }
189
190 // TestSerialWrites tests that writes are properly serialized (no concurrent write support expected).
191 func TestSerialWrites(t *testing.T) {
192 t.Parallel()
193
194 td := t.TempDir()
195 configPath := filepath.Join(td, "config")
196
197 content := "[user]\n\tname = Initial"
198 err := os.WriteFile(configPath, []byte(content), 0o644)
199 require.NoError(t, err)
200
201 // Load separate config instances for each write
202 configs := make([]*Config, 5)
203 for i := range configs {
204 cfg, err := LoadConfig(configPath)
205 require.NoError(t, err)
206 configs[i] = cfg
207 }
208
209 // Write sequentially (not concurrently, as that would cause data loss)
210 // Set automatically writes to disk
211 for i, cfg := range configs {
212 err := cfg.Set("user.id", string(rune('0'+i)))
213 require.NoError(t, err)
214 }
215
216 // Load final state
217 finalCfg, err := LoadConfig(configPath)
218 require.NoError(t, err)
219
220 // Last write should win
221 id, ok := finalCfg.Get("user.id")
222 assert.True(t, ok)
223 assert.Equal(t, "4", id)
224 }
225
226 // TestConcurrentMultiScopeReads tests concurrent reads across multiple scopes.
227 func TestConcurrentMultiScopeReads(t *testing.T) {
228 // Note: not using t.Parallel() because we need t.Setenv()
229
230 td := t.TempDir()
231 t.Setenv("GOPASS_HOMEDIR", td)
232
233 gitDir := filepath.Join(td, ".git")
234 require.NoError(t, os.MkdirAll(gitDir, 0o755))
235
236 // Create local config
237 localPath := filepath.Join(gitDir, "config")
238 localContent := "[user]\n\tname = Local User\n\temail = [email protected]"
239 err := os.WriteFile(localPath, []byte(localContent), 0o644)
240 require.NoError(t, err)
241
242 // Create global config
243 globalPath := filepath.Join(td, "global-config")
244 globalContent := "[user]\n\tname = Global User\n[core]\n\teditor = vim"
245 err = os.WriteFile(globalPath, []byte(globalContent), 0o644)
246 require.NoError(t, err)
247
248 // Load configs
249 cs := New()
250 cs.GlobalConfig = "global-config"
251 cs.LocalConfig = ".git/config"
252 cs.NoWrites = true
253 cs.LoadAll(td)
254
255 // Concurrent reads from different scopes
256 var wg sync.WaitGroup
257 iterations := 50
258 goroutines := 10
259
260 for g := range goroutines {
261 wg.Add(1)
262 go func(id int) {
263 defer wg.Done()
264 for range iterations {
265 switch id % 3 {
266 case 0:
267 // Read value that exists in local scope
268 name := cs.GetLocal("user.name")
269 assert.Equal(t, "Local User", name)
270 case 1:
271 // Read value from global scope
272 editor := cs.GetGlobal("core.editor")
273 assert.Equal(t, "vim", editor)
274 case 2:
275 // Read with precedence (local wins)
276 name := cs.Get("user.name")
277 assert.Equal(t, "Local User", name)
278 }
279 }
280 }(g)
281 }
282
283 wg.Wait()
284 }
285
286 // TestConcurrentConfigCreation tests creating multiple config instances concurrently.
287 func TestConcurrentConfigCreation(t *testing.T) {
288 t.Parallel()
289
290 var wg sync.WaitGroup
291 goroutines := 10
292
293 results := make([]*Configs, goroutines)
294
295 for i := range goroutines {
296 wg.Add(1)
297 go func(index int) {
298 defer wg.Done()
299 results[index] = New()
300 }(i)
301 }
302
303 wg.Wait()
304
305 // Verify all instances were created successfully
306 for i := range goroutines {
307 assert.NotNil(t, results[i], "config instance %d should not be nil", i)
308 assert.NotEmpty(t, results[i].LocalConfig)
309 assert.NotEmpty(t, results[i].WorktreeConfig)
310 }
311 }
312
313 // TestConcurrentEnvConfigLoad tests loading environment configs concurrently.
314 func TestConcurrentEnvConfigLoad(t *testing.T) {
315 // Set up test environment variables
316 testPrefix := "GITCONFIG_CONCURRENT"
317 t.Setenv(testPrefix+"_COUNT", "2")
318 t.Setenv(testPrefix+"_KEY_0", "user.name")
319 t.Setenv(testPrefix+"_VALUE_0", "Env User")
320 t.Setenv(testPrefix+"_KEY_1", "user.email")
321 t.Setenv(testPrefix+"_VALUE_1", "[email protected]")
322
323 var wg sync.WaitGroup
324 goroutines := 10
325 results := make([]*Config, goroutines)
326
327 for i := range goroutines {
328 wg.Add(1)
329 go func(index int) {
330 defer wg.Done()
331 results[index] = LoadConfigFromEnv(testPrefix)
332 }(i)
333 }
334
335 wg.Wait()
336
337 // Verify all loads succeeded
338 for i := range goroutines {
339 require.NotNil(t, results[i], "env config %d should not be nil", i)
340
341 name, ok := results[i].Get("user.name")
342 assert.True(t, ok)
343 assert.Equal(t, "Env User", name)
344
345 email, ok := results[i].Get("user.email")
346 assert.True(t, ok)
347 assert.Equal(t, "[email protected]", email)
348 }
349 }
350
351 // TestConcurrentReadDuringLoad tests reading while other configs are being loaded.
352 func TestConcurrentReadDuringLoad(t *testing.T) {
353 t.Parallel()
354
355 td := t.TempDir()
356 configPath := filepath.Join(td, "config")
357
358 content := "[user]\n\tname = Load Test User"
359 err := os.WriteFile(configPath, []byte(content), 0o644)
360 require.NoError(t, err)
361
362 // Load initial config
363 cfg, err := LoadConfig(configPath)
364 require.NoError(t, err)
365 require.NotNil(t, cfg)
366
367 var wg sync.WaitGroup
368 readGoroutines := 5
369 loadGoroutines := 5
370 duration := 100 * time.Millisecond
371
372 // Goroutines continuously reading from existing config
373 for range readGoroutines {
374 wg.Add(1)
375 go func() {
376 defer wg.Done()
377 end := time.Now().Add(duration)
378 for time.Now().Before(end) {
379 name, ok := cfg.Get("user.name")
380 assert.True(t, ok)
381 assert.Equal(t, "Load Test User", name)
382 }
383 }()
384 }
385
386 // Goroutines loading new config instances
387 for range loadGoroutines {
388 wg.Add(1)
389 go func() {
390 defer wg.Done()
391 end := time.Now().Add(duration)
392 for time.Now().Before(end) {
393 newCfg, err := LoadConfig(configPath)
394 assert.NoError(t, err)
395 if newCfg != nil {
396 name, ok := newCfg.Get("user.name")
397 assert.True(t, ok)
398 assert.Equal(t, "Load Test User", name)
399 }
400 }
401 }()
402 }
403
404 wg.Wait()
405 }
406
407 // TestNoDataRacesInGet tests that Get operations don't cause data races.
408 func TestNoDataRacesInGet(t *testing.T) {
409 t.Parallel()
410
411 td := t.TempDir()
412 configPath := filepath.Join(td, "config")
413
414 content := `[user]
415 name = Race Test
416 [core]
417 editor = vim
418 [remote "origin"]
419 url = https://github.com/test/repo.git
420 `
421 err := os.WriteFile(configPath, []byte(content), 0o644)
422 require.NoError(t, err)
423
424 cfg, err := LoadConfig(configPath)
425 require.NoError(t, err)
426 require.NotNil(t, cfg)
427
428 // Run with race detector enabled: go test -race
429 var wg sync.WaitGroup
430 for range 50 {
431 wg.Add(1)
432 go func() {
433 defer wg.Done()
434 for range 100 {
435 _, _ = cfg.Get("user.name")
436 _, _ = cfg.Get("core.editor")
437 _, _ = cfg.Get("remote.origin.url")
438 }
439 }()
440 }
441
442 wg.Wait()
443 }