-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathteststate_test.go
More file actions
275 lines (211 loc) · 8.52 KB
/
Copy pathteststate_test.go
File metadata and controls
275 lines (211 loc) · 8.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
package teststate_test
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"github.com/gruntwork-io/terratest/modules/core/v2/logger"
gotesting "github.com/gruntwork-io/terratest/modules/core/v2/testing"
"github.com/gruntwork-io/terratest/modules/core/v2/teststate"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// tStringLogger captures everything written to the logger so a test can assert on what was, and was not, logged.
type tStringLogger struct {
sb strings.Builder
}
func (l *tStringLogger) Logf(t gotesting.TestingT, format string, args ...any) {
t.Helper()
fmt.Fprintf(&l.sb, format, args...)
l.sb.WriteRune('\n')
}
// captureLog swaps logger.Default for the duration of the test. Tests using it must not call t.Parallel.
func captureLog(t *testing.T) *tStringLogger {
t.Helper()
def, slogger := logger.Default, &tStringLogger{}
logger.Default = logger.New(slogger)
t.Cleanup(func() { logger.Default = def })
return slogger
}
func TestFormatPath(t *testing.T) {
t.Parallel()
assert.Equal(t, filepath.Join("/foo", ".test-data", "Bar.json"), teststate.FormatPath("/foo", "Bar.json"))
}
func TestSaveAndLoadRoundTrip(t *testing.T) {
t.Parallel()
type payload struct {
Name string
Count int
}
path := teststate.FormatPath(t.TempDir(), "Payload.json")
expected := payload{Name: "terratest", Count: 3}
teststate.Save(t, path, true, expected)
var actual payload
teststate.Load(t, path, &actual)
assert.Equal(t, expected, actual)
}
func TestSaveOverwriteSemantics(t *testing.T) {
t.Parallel()
path := teststate.FormatPath(t.TempDir(), "Value.json")
teststate.Save(t, path, true, "first")
// overwrite=false must leave the existing value alone.
teststate.Save(t, path, false, "second")
var got string
teststate.Load(t, path, &got)
assert.Equal(t, "first", got, "overwrite=false must not clobber an existing value")
// overwrite=true must replace it.
teststate.Save(t, path, true, "third")
teststate.Load(t, path, &got)
assert.Equal(t, "third", got)
}
// TestSaveLogsValueAndSaveRedactedDoesNot is the behavioural contract that callers holding secrets depend on.
func TestSaveLogsValueAndSaveRedactedDoesNot(t *testing.T) {
const secret = "-----BEGIN RSA PRIVATE KEY-----sentinel-----END RSA PRIVATE KEY-----"
t.Run("Save logs the marshalled value", func(t *testing.T) {
slogger := captureLog(t)
teststate.Save(t, teststate.FormatPath(t.TempDir(), "Plain.json"), true, secret)
assert.Contains(t, slogger.sb.String(), secret, "Save is expected to log the marshalled JSON")
})
t.Run("SaveRedacted does not", func(t *testing.T) {
slogger := captureLog(t)
teststate.SaveRedacted(t, teststate.FormatPath(t.TempDir(), "Secret.json"), true, secret)
assert.NotContains(t, slogger.sb.String(), secret, "SaveRedacted must not log the marshalled JSON")
})
}
// TestSaveRedactedDoesNotLeakViaOverwriteWarning covers the second log statement in the save path. The overwrite
// warning renders the value with %v, which is not suppressed by the redacted flag, so a redacted save over an
// existing file could still leak. Values reaching SaveRedacted are secrets by definition.
func TestSaveRedactedDoesNotLeakViaOverwriteWarning(t *testing.T) {
const secret = "-----BEGIN RSA PRIVATE KEY-----sentinel-----END RSA PRIVATE KEY-----"
path := teststate.FormatPath(t.TempDir(), "Secret.json")
// First save creates the file, so the second one takes the overwrite-warning branch.
teststate.SaveRedacted(t, path, true, secret)
slogger := captureLog(t)
teststate.SaveRedacted(t, path, true, secret)
assert.NotContains(t, slogger.sb.String(), secret,
"the overwrite warning must not render a redacted value")
}
func TestIsPresent(t *testing.T) {
t.Parallel()
path := teststate.FormatPath(t.TempDir(), "Maybe.json")
assert.False(t, teststate.IsPresent(t, path), "a missing file is not present")
teststate.Save(t, path, true, "value")
assert.True(t, teststate.IsPresent(t, path))
// An empty JSON value counts as absent, so a stage can re-create it.
teststate.Save(t, path, true, "")
assert.False(t, teststate.IsPresent(t, path), "an empty value counts as absent")
}
func TestIsEmptyJSON(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
bytes string
empty bool
}{
{"no bytes", "", true},
{"null", "null", true},
{"false", "false", true},
{"zero", "0", true},
{"empty string", `""`, true},
{"empty array", "[]", true},
{"empty object", "{}", true},
{"true", "true", false},
{"non-zero", "42", false},
{"string", `"value"`, false},
{"array", `[1]`, false},
{"object", `{"a":1}`, false},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()
assert.Equal(t, testCase.empty, teststate.IsEmptyJSON(t, []byte(testCase.bytes)))
})
}
}
func TestCleanup(t *testing.T) {
t.Parallel()
folder := t.TempDir()
path := teststate.FormatPath(folder, "Value.json")
teststate.Save(t, path, true, "value")
require.FileExists(t, path)
teststate.Cleanup(t, path)
assert.NoFileExists(t, path)
// Cleaning up an already-absent path is a no-op, not a failure.
assert.NotPanics(t, func() { teststate.Cleanup(t, path) })
}
func TestCleanupFolder(t *testing.T) {
t.Parallel()
folder := t.TempDir()
teststate.Save(t, teststate.FormatPath(folder, "One.json"), true, "1")
teststate.Save(t, teststate.FormatPath(folder, "Two.json"), true, "2")
require.NoError(t, teststate.CleanupFolderE(t, folder))
assert.NoDirExists(t, filepath.Join(folder, ".test-data"))
// Cleaning an absent folder is a no-op.
require.NoError(t, teststate.CleanupFolderE(t, folder))
}
// TestSaveWritesOwnerOnlyPermissions pins the file mode. Saved state can hold private keys, so it must not be
// world readable.
func TestSaveWritesOwnerOnlyPermissions(t *testing.T) {
t.Parallel()
path := teststate.FormatPath(t.TempDir(), "Value.json")
teststate.Save(t, path, true, "value")
info, err := os.Stat(path)
require.NoError(t, err)
assert.Equal(t, os.FileMode(0o600), info.Mode().Perm(), "saved test data must be owner read/write only")
}
// nonStoppingT is a TestingT whose FailNow returns rather than calling runtime.Goexit, so these tests can assert
// that the package stops doing work after it reports a failure.
type nonStoppingT struct {
failed bool
msgs []string
}
func (r *nonStoppingT) Fail() { r.failed = true }
func (r *nonStoppingT) FailNow() { r.failed = true }
func (r *nonStoppingT) Error(args ...any) { r.failed = true }
func (r *nonStoppingT) Errorf(string, ...any) { r.failed = true }
func (r *nonStoppingT) Fatal(args ...any) { r.msgs = append(r.msgs, fmt.Sprint(args...)); r.FailNow() }
func (r *nonStoppingT) Name() string { return "nonStoppingT" }
func (r *nonStoppingT) Helper() {}
func (r *nonStoppingT) Fatalf(f string, a ...any) {
r.msgs = append(r.msgs, fmt.Sprintf(f, a...))
r.FailNow()
}
// unmarshalable fails json.Marshal: encoding/json always rejects a func field.
type unmarshalable struct {
Fn func()
}
// Before the fix, a marshal failure was reported and os.WriteFile still ran with a nil slice, leaving a zero byte
// file for a later stage to load.
func TestSaveWritesNothingAfterAMarshalFailure(t *testing.T) {
t.Parallel()
folder := t.TempDir()
path := teststate.FormatPath(folder, "Broken.json")
recorder := &nonStoppingT{}
teststate.Save(recorder, path, true, unmarshalable{})
assert.True(t, recorder.failed, "the marshal failure must be reported")
assert.NoFileExists(t, path, "no file may be written after a marshal failure")
}
// A read failure must be reported, not reported as "absent", which would invite a caller to overwrite state it
// could not read.
func TestIsPresentDoesNotMaskAnUnreadableFile(t *testing.T) {
t.Parallel()
// A directory where a file is expected: FileExistsE succeeds, os.ReadFile fails with EISDIR.
folder := t.TempDir()
path := teststate.FormatPath(folder, "IsADirectory.json")
require.NoError(t, os.MkdirAll(path, 0o755))
recorder := &nonStoppingT{}
present := teststate.IsPresent(recorder, path)
assert.True(t, recorder.failed, "the read failure must be reported")
assert.False(t, present)
require.NotEmpty(t, recorder.msgs)
assert.Contains(t, recorder.msgs[0], "unexpected error")
}
// Invalid JSON must be reported, not called empty.
func TestIsEmptyJSONReportsAParseFailure(t *testing.T) {
t.Parallel()
recorder := &nonStoppingT{}
empty := teststate.IsEmptyJSON(recorder, []byte("{not json"))
assert.True(t, recorder.failed, "the parse failure must be reported")
assert.False(t, empty, "invalid JSON is not the same as empty JSON")
}