-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv_testing.go
More file actions
71 lines (56 loc) · 1.21 KB
/
env_testing.go
File metadata and controls
71 lines (56 loc) · 1.21 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
package utils
import (
"maps"
"path/filepath"
"sync"
"testing"
"github.com/joho/godotenv"
)
type mapEnvProvider struct {
prefix string
env map[string]string
mu sync.Mutex
}
func (p *mapEnvProvider) Get(key string) (string, bool) {
p.mu.Lock()
defer p.mu.Unlock()
v, ok := p.env[p.prefix+key]
return v, ok
}
func (p *mapEnvProvider) Set(key, value string) {
p.mu.Lock()
defer p.mu.Unlock()
p.env[p.prefix+key] = value
}
func NewTestEnv(tb testing.TB, prefix ...string) Env {
tb.Helper()
p := ""
if len(prefix) > 0 {
p = prefix[0]
}
provider := &mapEnvProvider{
prefix: p,
env: make(map[string]string),
}
root := ProjectRootDir(tb)
files := []string{".env", ".env.local", ".env.test", ".env.testing"}
for _, file := range files {
file = filepath.Join(root, file)
if !FileExists(file) {
// Removed slog.Debug to avoid race conditions in parallel tests
continue
}
vals, err := godotenv.Read(file)
if err != nil {
tb.Fatal(err)
}
// Lock only for the map operation
provider.mu.Lock()
maps.Copy(provider.env, vals)
provider.mu.Unlock()
}
// Removed slog.Info and slog.Warn to avoid race conditions in parallel tests
return Env{
EnvProvider: provider,
}
}