Repository navigation
Expand file tree
/
Copy pathmodule_update_test.go
More file actions
656 lines (607 loc) · 28.6 KB
/
Copy pathmodule_update_test.go
File metadata and controls
656 lines (607 loc) · 28.6 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
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
package main
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
type capturedStreams struct {
stdout string
stderr string
}
type moduleCase struct {
name string
input string
source string
version string
from []string
ignoreVersions []string
ignoreModules []string
forceAdd bool
dryRun bool
verbose bool
wantUpdated bool
wantContent string
}
func captureStdoutAndStderr(t *testing.T, fn func()) capturedStreams {
t.Helper()
testOutputMu.Lock()
defer testOutputMu.Unlock()
stdoutReader, stdoutWriter, err := os.Pipe()
if err != nil {
t.Fatalf("create stdout pipe: %v", err)
}
t.Cleanup(func() {
_ = stdoutWriter.Close()
_ = stdoutReader.Close()
})
stderrReader, stderrWriter, err := os.Pipe()
if err != nil {
t.Fatalf("create stderr pipe: %v", err)
}
t.Cleanup(func() {
_ = stderrWriter.Close()
_ = stderrReader.Close()
})
originalStdout, originalStderr := os.Stdout, os.Stderr
restore := func() { os.Stdout, os.Stderr = originalStdout, originalStderr }
t.Cleanup(restore)
defer restore()
os.Stdout, os.Stderr = stdoutWriter, stderrWriter
stdout, stdoutDone := startPipeDrain(stdoutReader)
stderr, stderrDone := startPipeDrain(stderrReader)
fn()
restore()
if err := stdoutWriter.Close(); err != nil {
t.Fatalf("close stdout writer: %v", err)
}
if err := stderrWriter.Close(); err != nil {
t.Fatalf("close stderr writer: %v", err)
}
<-stdoutDone
<-stderrDone
if err := stdoutReader.Close(); err != nil {
t.Fatalf("close stdout reader: %v", err)
}
if err := stderrReader.Close(); err != nil {
t.Fatalf("close stderr reader: %v", err)
}
return capturedStreams{stdout: stdout.String(), stderr: stderr.String()}
}
func TestUpdateModuleVersionContract(t *testing.T) {
const registry = "terraform-aws-modules/vpc/aws"
cases := []moduleCase{
{"matching registry module updates", "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n", registry, "5.0.0", nil, nil, nil, false, false, false, true, "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"5.0.0\"\n}\n"},
{"non-matching source unchanged", "module \"vpc\" {\n source = \"terraform-aws-modules/s3-bucket/aws\"\n version = \"3.14.0\"\n}\n", registry, "5.0.0", nil, nil, nil, false, false, false, false, "module \"vpc\" {\n source = \"terraform-aws-modules/s3-bucket/aws\"\n version = \"3.14.0\"\n}\n"},
{"force-add missing version", "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n}\n", registry, "5.0.0", nil, nil, nil, true, false, false, true, "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"5.0.0\"\n}\n"},
{"existing Git version remains updateable", "module \"vpc\" {\n source = \"git::https://github.com/example/vpc.git\"\n version = \"1.0.0\"\n}\n", "git::https://github.com/example/vpc.git", "2.0.0", nil, nil, nil, false, false, false, true, "module \"vpc\" {\n source = \"git::https://github.com/example/vpc.git\"\n version = \"2.0.0\"\n}\n"},
{"force-add does not block an existing HTTP version", "module \"vpc\" {\n source = \"https://example.com/vpc.zip\"\n version = \"1.0.0\"\n}\n", "https://example.com/vpc.zip", "2.0.0", nil, nil, nil, true, false, false, true, "module \"vpc\" {\n source = \"https://example.com/vpc.zip\"\n version = \"2.0.0\"\n}\n"},
{"relative local source skipped", "module \"vpc\" {\n source = \"./modules/vpc\"\n}\n", "./modules/vpc", "5.0.0", nil, nil, nil, true, false, false, false, "module \"vpc\" {\n source = \"./modules/vpc\"\n}\n"},
{"matching from filter updates", "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n", registry, "5.0.0", []string{"3.14.0"}, nil, nil, false, false, false, true, "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"5.0.0\"\n}\n"},
{"updates every eligible block with the same source", "module \"primary\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n\nmodule \"secondary\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"4.0.0\"\n}\n", registry, "5.0.0", nil, nil, nil, false, false, false, true, "module \"primary\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"5.0.0\"\n}\n\nmodule \"secondary\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"5.0.0\"\n}\n"},
{"second from entry matches", "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n", registry, "5.0.0", []string{"4.0.0", "3.14.0"}, nil, nil, false, false, false, true, "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"5.0.0\"\n}\n"},
{"second ignore version entry matches", "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n", registry, "5.0.0", nil, []string{"4.0.0", "3.14.0"}, nil, false, false, false, false, "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n"},
{"non-matching from preserves version", "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n", registry, "5.0.0", []string{"4.0.0"}, nil, nil, false, false, true, false, "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n"},
{"matching ignore version preserves version", "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n", registry, "5.0.0", nil, []string{"3.14.0"}, nil, false, false, false, false, "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n"},
{"mixed ignored and eligible modules", "module \"ignored\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n\nmodule \"eligible\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"4.0.0\"\n}\n", registry, "5.0.0", nil, []string{"3.14.0"}, nil, false, false, false, true, "module \"ignored\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n\nmodule \"eligible\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"5.0.0\"\n}\n"},
{"ignore takes precedence over from", "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n", registry, "5.0.0", []string{"4.0.0"}, []string{"3.14.0"}, nil, false, false, true, false, "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n"},
{"module name ignore preserves unchanged content", "module \"legacy-vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n", registry, "5.0.0", nil, nil, []string{"legacy-*"}, false, false, true, false, "module \"legacy-vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n}\n"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
file := writeTestFile(t, t.TempDir(), "main.tf", tc.input)
var updated bool
var err error
output := captureStdoutAndStderr(t, func() {
updated, err = updateModuleVersion(file, tc.source, tc.version, tc.from, tc.ignoreVersions, tc.ignoreModules, tc.forceAdd, tc.dryRun, tc.verbose, "text")
})
if err != nil {
t.Fatalf("updateModuleVersion: %v", err)
}
if updated != tc.wantUpdated {
t.Fatalf("updated = %v, want %v", updated, tc.wantUpdated)
}
if got := readTestFile(t, file); got != tc.wantContent {
t.Errorf("content = %q, want %q", got, tc.wantContent)
}
switch {
case tc.verbose:
want := wantModuleVerboseDiagnostic(&tc, file)
if output.stdout != want || output.stderr != "" {
t.Errorf("streams = stdout %q stderr %q, want stdout %q and empty stderr", output.stdout, output.stderr, want)
}
case strings.Contains(tc.name, "local source"):
want := fmt.Sprintf("Warning: Module 'vpc' in %s (source: './modules/vpc') is a local module and cannot be version-bumped, skipping\n", file)
if output.stdout != "" || output.stderr != want {
t.Errorf("streams = stdout %q stderr %q, want stdout empty stderr %q", output.stdout, output.stderr, want)
}
case output.stdout != "" || output.stderr != "":
t.Errorf("unexpected output: stdout=%q stderr=%q", output.stdout, output.stderr)
}
})
}
}
func wantModuleVerboseDiagnostic(tc *moduleCase, file string) string {
switch {
case len(tc.ignoreVersions) > 0:
return fmt.Sprintf(" ⊗ Skipped module 'vpc' in %s (current version '3.14.0' matches 'ignore-version' filter [3.14.0])\n", file)
case len(tc.from) > 0:
return fmt.Sprintf(" ⊗ Skipped module 'vpc' in %s (current version '3.14.0' does not match any 'from' filter [4.0.0])\n", file)
case len(tc.ignoreModules) > 0:
return fmt.Sprintf(" ⊗ Skipped module 'legacy-vpc' in %s (matches ignore pattern)\n", file)
default:
return ""
}
}
func TestUpdateModuleVersionWarnsWhenVersionMissing(t *testing.T) {
input := "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n}\n"
file := writeTestFile(t, t.TempDir(), "main.tf", input)
want := fmt.Sprintf("Warning: Module 'vpc' in %s (source: 'terraform-aws-modules/vpc/aws') has no version attribute, skipping\n", file)
var updated bool
var err error
stderr := captureStderr(t, func() {
updated, err = updateModuleVersion(file, "terraform-aws-modules/vpc/aws", "5.0.0", nil, nil, nil, false, false, false, "text")
})
if err != nil || updated {
t.Fatalf("updated=%v err=%v", updated, err)
}
if stderr != want {
t.Errorf("stderr = %q, want %q", stderr, want)
}
if got := readTestFile(t, file); got != input {
t.Errorf("content changed: %q", got)
}
}
func TestUpdateModuleVersionForceAddRequiresRegistrySource(t *testing.T) {
tests := []struct {
name string
source string
}{
{name: "Git URL", source: "git::https://github.com/example/vpc.git"},
{name: "GitHub shorthand", source: "github.com/example/vpc"},
{name: "HTTP URL", source: "https://example.com/vpc.zip"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
input := fmt.Sprintf("module \"vpc\" {\n source = %q\n}\n", tt.source)
file := writeTestFile(t, t.TempDir(), "main.tf", input)
wantWarning := fmt.Sprintf("Warning: Module 'vpc' in %s (source: '%s') is not a registry module and cannot use a version attribute, skipping\n", file, tt.source)
var updated bool
var err error
stderr := captureStderr(t, func() {
updated, err = updateModuleVersion(file, tt.source, "2.0.0", nil, nil, nil, true, false, false, "text")
})
if err != nil || updated {
t.Fatalf("updated=%v err=%v", updated, err)
}
if stderr != wantWarning {
t.Errorf("stderr = %q, want %q", stderr, wantWarning)
}
if got := readTestFile(t, file); got != input {
t.Errorf("content = %q, want unchanged %q", got, input)
}
})
}
}
func TestUpdateModuleVersionForceAddSupportsPrivateRegistrySource(t *testing.T) {
input := "module \"vpc\" {\n source = \"app.terraform.io/example/vpc/aws\"\n}\n"
file := writeTestFile(t, t.TempDir(), "main.tf", input)
updated, err := updateModuleVersion(file, "app.terraform.io/example/vpc/aws", "2.0.0", nil, nil, nil, true, false, false, "text")
if err != nil || !updated {
t.Fatalf("updated=%v err=%v", updated, err)
}
want := "module \"vpc\" {\n source = \"app.terraform.io/example/vpc/aws\"\n version = \"2.0.0\"\n}\n"
if got := readTestFile(t, file); got != want {
t.Errorf("content = %q, want %q", got, want)
}
}
func TestUpdateModuleVersionPreservesHCL(t *testing.T) {
input := "# This is a comment\nmodule \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"3.14.0\"\n\n # Another comment\n name = \"my-vpc\"\n cidr = var.vpc_cidr\n}\n\nmodule \"other\" {\n source = \"terraform-aws-modules/s3-bucket/aws\"\n version = \"1.0.0\"\n}\n"
want := "# This is a comment\nmodule \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"5.0.0\"\n\n # Another comment\n name = \"my-vpc\"\n cidr = var.vpc_cidr\n}\n\nmodule \"other\" {\n source = \"terraform-aws-modules/s3-bucket/aws\"\n version = \"1.0.0\"\n}\n"
file := writeTestFile(t, t.TempDir(), "main.tf", input)
updated, err := updateModuleVersion(file, "terraform-aws-modules/vpc/aws", "5.0.0", nil, nil, nil, false, false, false, "text")
if err != nil || !updated {
t.Fatalf("updated=%v err=%v", updated, err)
}
if got := readTestFile(t, file); got != want {
t.Errorf("content = %q, want %q", got, want)
}
}
func TestUpdateModuleVersionMatchingVersionDoesNotWrite(t *testing.T) {
input := `module "vpc" {
source="terraform-aws-modules/vpc/aws"
version="5.0.0"
}
`
filename := writeTestFile(t, t.TempDir(), "main.tf", input)
wantModTime := time.Unix(1, 0)
if err := os.Chtimes(filename, wantModTime, wantModTime); err != nil {
t.Fatalf("chtimes: %v", err)
}
updated, err := updateModuleVersion(filename, "terraform-aws-modules/vpc/aws", "5.0.0", nil, nil, nil, false, false, false, "text")
if err != nil {
t.Fatalf("updateModuleVersion returned error: %v", err)
}
if updated {
t.Fatal("updated = true, want false")
}
if got := readTestFile(t, filename); got != input {
t.Errorf("content = %q, want unchanged %q", got, input)
}
info, err := os.Stat(filename)
if err != nil {
t.Fatalf("stat: %v", err)
}
if got := info.ModTime(); !got.Equal(wantModTime) {
t.Errorf("modification time = %v, want unchanged %v", got, wantModTime)
}
}
func TestUpdateModuleVersionReplacesMatchingNonLiteralExpression(t *testing.T) {
input := `module "example" {
source = "example/module"
version = var.constraint
}
`
filename := writeTestFile(t, t.TempDir(), "main.tf", input)
updated, err := updateModuleVersion(filename, "example/module", "var.constraint", nil, nil, nil, false, false, false, "text")
if err != nil {
t.Fatalf("updateModuleVersion returned error: %v", err)
}
if !updated {
t.Fatal("updated = false, want true")
}
want := `module "example" {
source = "example/module"
version = "var.constraint"
}
`
if got := readTestFile(t, filename); got != want {
t.Errorf("content = %q, want %q", got, want)
}
}
func TestUpdateModuleVersionDryRunContract(t *testing.T) {
input := "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"1.0.0\"\n}\n"
file := writeTestFile(t, t.TempDir(), "main.tf", input)
var updated bool
var err error
output := captureStdoutAndStderr(t, func() {
updated, err = updateModuleVersion(file, "terraform-aws-modules/vpc/aws", "2.0.0", nil, nil, nil, false, true, false, "text")
})
if err != nil || !updated {
t.Fatalf("updated=%v err=%v", updated, err)
}
if output.stdout != "" || output.stderr != "" {
t.Errorf("output = stdout %q stderr %q, want both empty", output.stdout, output.stderr)
}
if got := readTestFile(t, file); got != input {
t.Errorf("dry run changed content")
}
}
func TestIsLocalModuleContract(t *testing.T) {
for _, tc := range []struct {
name, source string
want bool
}{{"relative", "./modules/vpc", true}, {"parent-relative", "../shared", true}, {"absolute", "/opt/module", true}, {"registry", "terraform-aws-modules/vpc/aws", false}, {"git", "git::https://github.com/example/vpc.git", false}} {
t.Run(tc.name, func(t *testing.T) {
if got := isLocalModule(tc.source); got != tc.want {
t.Errorf("isLocalModule(%q)=%v, want %v", tc.source, got, tc.want)
}
})
}
}
func TestUpdateModuleVersionErrors(t *testing.T) {
t.Run("missing file", func(t *testing.T) {
updated, err := updateModuleVersion(filepath.Join(t.TempDir(), "missing.tf"), "x", "1.0.0", nil, nil, nil, false, false, false, "text")
if updated || err == nil || !strings.Contains(err.Error(), "failed to stat file:") {
t.Errorf("updated=%v err=%v", updated, err)
}
})
t.Run("directory read error", func(t *testing.T) {
directory := t.TempDir()
updated, err := updateModuleVersion(directory, "x", "1.0.0", nil, nil, nil, false, false, false, "text")
if updated || err == nil || !strings.Contains(err.Error(), "failed to read file:") {
t.Errorf("updated=%v err=%v", updated, err)
}
})
t.Run("malformed HCL", func(t *testing.T) {
file := writeTestFile(t, t.TempDir(), "bad.tf", "module \\\"vpc\\\" {")
updated, err := updateModuleVersion(file, "x", "1.0.0", nil, nil, nil, false, false, false, "text")
if updated || err == nil || !strings.Contains(err.Error(), "failed to parse HCL:") {
t.Errorf("updated=%v err=%v", updated, err)
}
})
t.Run("write error", func(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("root can write read-only files")
}
file := writeTestFile(t, t.TempDir(), "readonly.tf", "module \"vpc\" {\n source = \"terraform-aws-modules/vpc/aws\"\n version = \"1.0.0\"\n}\n")
if err := os.Chmod(file, 0o400); err != nil {
t.Fatal(err)
}
updated, err := updateModuleVersion(file, "terraform-aws-modules/vpc/aws", "2.0.0", nil, nil, nil, false, false, false, "text")
if updated || err == nil || !strings.Contains(err.Error(), "failed to write file:") {
t.Errorf("updated=%v err=%v", updated, err)
}
})
}
const vpcSource = "terraform-aws-modules/vpc/aws"
// moduleAt is a formatted Terraform file pinning the VPC module at version.
func moduleAt(version string) string {
return "module \"vpc\" {\n source = \"" + vpcSource + "\"\n version = \"" + version + "\"\n}\n"
}
func TestTerraformFileWrite_SucceedsWithoutLeavingBackup(t *testing.T) {
backups := useTempDir(t)
file := writeTestFile(t, t.TempDir(), "main.tf", moduleAt("1.0.0"))
updated, err := updateModuleVersion(file, vpcSource, "2.0.0", nil, nil, nil, false, false, false, "text")
if !updated || err != nil {
t.Fatalf("updated=%v err=%v", updated, err)
}
if got := readTestFile(t, file); got != moduleAt("2.0.0") {
t.Errorf("content = %q, want %q", got, moduleAt("2.0.0"))
}
if kept := backupsIn(t, backups); len(kept) != 0 {
t.Errorf("backups = %v, want none", kept)
}
}
// A write rewrites the file rather than replacing it, which is what keeps hard links shared and
// leaves the permission bits, owner and extended attributes that a rename would take over.
func TestTerraformFileWrite_KeepsFileIdentityAndPermissions(t *testing.T) {
file := writeTestFile(t, t.TempDir(), "main.tf", moduleAt("1.0.0"))
if err := os.Chmod(file, 0o640); err != nil {
t.Fatal(err)
}
before, err := os.Stat(file)
if err != nil {
t.Fatal(err)
}
updated, err := updateModuleVersion(file, vpcSource, "2.0.0", nil, nil, nil, false, false, false, "text")
if !updated || err != nil {
t.Fatalf("updated=%v err=%v", updated, err)
}
after, err := os.Stat(file)
if err != nil {
t.Fatal(err)
}
if !os.SameFile(before, after) {
t.Error("the write replaced the file instead of rewriting it")
}
if got := readTestFile(t, file); got != moduleAt("2.0.0") {
t.Errorf("content = %q, want %q", got, moduleAt("2.0.0"))
}
if runtime.GOOS == "windows" {
return // Windows maps only the read-only bit onto the permission bits.
}
if got := after.Mode().Perm(); got != 0o640 {
t.Errorf("permissions = %v, want %v", got, os.FileMode(0o640))
}
}
// Rewriting in place follows a symlink to its target, so the link stays a link and the file it
// names holds the update.
func TestTerraformFileWrite_UpdatesThroughSymlink(t *testing.T) {
directory := t.TempDir()
target := writeTestFile(t, directory, "main.tf", moduleAt("1.0.0"))
link := filepath.Join(directory, "link.tf")
createSymlinkOrSkip(t, target, link)
updated, err := updateModuleVersion(link, vpcSource, "2.0.0", nil, nil, nil, false, false, false, "text")
if !updated || err != nil {
t.Fatalf("updated=%v err=%v", updated, err)
}
linkInfo, err := os.Lstat(link)
if err != nil {
t.Fatal(err)
}
if linkInfo.Mode()&os.ModeSymlink == 0 {
t.Error("the write replaced the symlink with a regular file")
}
if got := readTestFile(t, target); got != moduleAt("2.0.0") {
t.Errorf("target content = %q, want %q", got, moduleAt("2.0.0"))
}
}
// Every failure here leaves the file holding its original bytes, so the backup is removed.
func TestTerraformFileWrite_RestoresOriginalAfterFailedRewrite(t *testing.T) {
const restored = "failed to write file: injected failure; original content restored"
tests := []struct {
name string
from string // a longer original makes a complete WriteAt leave a stale tail
failOn map[string][]int
partial int
wantErr string
}{
{name: "write fails part way", from: "1.0.0", failOn: map[string][]int{"WriteAt": {1}}, partial: len(moduleAt("2.0.0")) - 1, wantErr: restored},
{name: "truncate fails after shorter content", from: "10.0.0", failOn: map[string][]int{"Truncate": {1}}, wantErr: restored},
{name: "sync fails after shorter content", from: "10.0.0", failOn: map[string][]int{"Sync": {1}}, wantErr: restored},
{name: "write fails before any byte", from: "1.0.0", failOn: map[string][]int{"WriteAt": {1}}, wantErr: "failed to write file: injected failure"},
{name: "read fails before backup", from: "1.0.0", failOn: map[string][]int{"Read": {1}}, wantErr: "failed to write file: injected failure"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
backups := useTempDir(t)
file := writeTestFile(t, t.TempDir(), "main.tf", moduleAt(tt.from))
failRewrite(t, &failingFile{failOn: tt.failOn, partial: tt.partial})
updated, err := updateModuleVersion(file, vpcSource, "2.0.0", nil, nil, nil, false, false, false, "text")
if updated || err == nil || err.Error() != tt.wantErr {
t.Fatalf("updated=%v err=%v, want error %q", updated, err, tt.wantErr)
}
if got := readTestFile(t, file); got != moduleAt(tt.from) {
t.Errorf("content = %q, want the original %q", got, moduleAt(tt.from))
}
if kept := backupsIn(t, backups); len(kept) != 0 {
t.Errorf("backups = %v, want none", kept)
}
})
}
}
func TestTerraformFileWrite_FailsBeforeRewriteWhenBackupFails(t *testing.T) {
t.Run("temporary directory missing", func(t *testing.T) {
file := writeTestFile(t, t.TempDir(), "main.tf", moduleAt("1.0.0"))
setTempDir(t, filepath.Join(t.TempDir(), "missing"))
_, err := updateModuleVersion(file, vpcSource, "2.0.0", nil, nil, nil, false, false, false, "text")
// The error quotes CreateTemp's random name and the platform's wording, so only its prefix is exact.
wantPrefix := "failed to write file: cannot back up " + file + ": "
if err == nil || !strings.HasPrefix(err.Error(), wantPrefix) || !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("err = %v, want prefix %q wrapping fs.ErrNotExist", err, wantPrefix)
}
if got := readTestFile(t, file); got != moduleAt("1.0.0") {
t.Errorf("content = %q, want the original", got)
}
})
for _, method := range []string{"Write", "Sync", "Close"} {
t.Run("backup "+method+" fails", func(t *testing.T) {
backups := useTempDir(t)
file := writeTestFile(t, t.TempDir(), "main.tf", moduleAt("1.0.0"))
failBackup(t, &failingFile{failOn: map[string][]int{method: {1}}})
_, err := updateModuleVersion(file, vpcSource, "2.0.0", nil, nil, nil, false, false, false, "text")
want := "failed to write file: cannot back up " + file + ": injected failure"
if err == nil || err.Error() != want {
t.Fatalf("err = %v, want %q", err, want)
}
if got := readTestFile(t, file); got != moduleAt("1.0.0") {
t.Errorf("content = %q, want the original", got)
}
if kept := backupsIn(t, backups); len(kept) != 0 {
t.Errorf("backups = %v, want the partial backup removed", kept)
}
})
}
}
// When the file cannot be shown to hold either version, the backup is kept and the error names it.
func TestTerraformFileWrite_KeepsBackupWhenFileStateIsUncertain(t *testing.T) {
tests := []struct {
name string
failOn map[string][]int
wantCause string
wantContent string // empty when the partial restore leaves no meaningful content to assert
}{
{name: "restore fails", failOn: map[string][]int{"WriteAt": {1, 2}}, wantCause: "injected failure; restoring the original also failed: injected failure"},
{name: "close fails after rewrite", failOn: map[string][]int{"Close": {1}}, wantCause: "injected failure", wantContent: moduleAt("2.0.0")},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
backups := useTempDir(t)
dir := t.TempDir()
file := writeTestFile(t, dir, "main.tf", moduleAt("1.0.0"))
names := []string{file}
if linked := filepath.Join(dir, "linked.tf"); os.Link(file, linked) == nil {
names = append(names, linked)
}
failRewrite(t, &failingFile{failOn: tt.failOn, partial: len(moduleAt("2.0.0")) - 1})
_, err := updateModuleVersion(file, vpcSource, "2.0.0", nil, nil, nil, false, false, false, "text")
kept := backupsIn(t, backups)
if len(kept) != 1 {
t.Fatalf("backups = %v, want exactly one; err = %v", kept, err)
}
want := "failed to write file: " + tt.wantCause + "; original content is in " + kept[0]
if err == nil || err.Error() != want {
t.Fatalf("err = %v, want %q", err, want)
}
if got := readTestFile(t, kept[0]); got != moduleAt("1.0.0") {
t.Errorf("backup = %q, want the original", got)
}
if tt.wantContent != "" {
if got := readTestFile(t, file); got != tt.wantContent {
t.Errorf("content = %q, want %q", got, tt.wantContent)
}
}
wantRefusal := "file left untrusted by an earlier failed write; original content is in " + kept[0]
for _, name := range names {
if _, readErr := readTerraformFile(name); readErr == nil || readErr.Error() != wantRefusal {
t.Errorf("readTerraformFile(%s) err = %v, want %q", name, readErr, wantRefusal)
}
}
})
}
}
func TestTerraformFileWrite_WarnsWhenBackupCannotBeRemoved(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("a read-only directory does not block removing a file on Windows")
}
if os.Geteuid() == 0 {
t.Skip("root ignores directory permissions")
}
backups := useTempDir(t)
file := writeTestFile(t, t.TempDir(), "main.tf", moduleAt("1.0.0"))
// Closing the rewritten file makes the backup's directory read-only, so the removal that follows fails.
failRewrite(t, &failingFile{afterClose: func() {
if err := os.Chmod(backups, 0o500); err != nil {
t.Fatal(err)
}
}})
t.Cleanup(func() {
if err := os.Chmod(backups, 0o700); err != nil {
t.Error(err)
}
})
var updated bool
var err error
stderr := captureStderr(t, func() {
updated, err = updateModuleVersion(file, vpcSource, "2.0.0", nil, nil, nil, false, false, false, "text")
})
if !updated || err != nil {
t.Fatalf("updated=%v err=%v, want a successful write", updated, err)
}
kept := backupsIn(t, backups)
if len(kept) != 1 {
t.Fatalf("backups = %v, want the one that could not be removed", kept)
}
want := "Warning: could not remove backup " + kept[0] + ": remove " + kept[0] + ": permission denied\n"
if stderr != want {
t.Errorf("stderr = %q, want %q", stderr, want)
}
if got := readTestFile(t, file); got != moduleAt("2.0.0") {
t.Errorf("content = %q, want %q", got, moduleAt("2.0.0"))
}
}
// The skip count reports the modules left unpinned, which is what the run's summary turns into a
// line of its own. A -force-add that cannot be honoured is such a skip; a module already at the
// target version was skipped as asked and does not count.
func TestUpdateModuleVersionWithCount_CountsSkipsThatLeaveBlocksUnpinned(t *testing.T) {
tests := []struct {
name, module, source string
forceAdd bool
wantSkipped int
wantWarning string
}{
{
name: "force-add cannot add a version", module: "module \"vpc\" {\n source = \"github.com/example/module\"\n}\n",
source: "github.com/example/module", forceAdd: true, wantSkipped: 1,
wantWarning: "is not a registry module and cannot use a version attribute, skipping",
},
{
name: "already at the target version", module: "module \"vpc\" {\n source = \"example/module\"\n version = \"2.0.0\"\n}\n",
source: "example/module", wantSkipped: 0,
},
{
// Warned about, but nothing is left outstanding: Terraform gives a local module no
// version attribute, so there is nothing the operator could pin.
name: "local module", module: "module \"vpc\" {\n source = \"./modules/vpc\"\n}\n",
source: "./modules/vpc", wantSkipped: 0,
wantWarning: "is a local module and cannot be version-bumped, skipping",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
file := writeTestFile(t, t.TempDir(), "main.tf", tt.module)
var updated bool
var skippedBlocks []int
var err error
warnings := captureStderr(t, func() {
updated, _, skippedBlocks, err = updateModuleVersionWithCount(file, tt.source, "2.0.0",
nil, nil, nil, tt.forceAdd, true, false, "text")
})
if err != nil || updated || len(skippedBlocks) != tt.wantSkipped {
t.Fatalf("updated=%v skippedBlocks=%v err=%v, want no update and %d skip(s)", updated, skippedBlocks, err, tt.wantSkipped)
}
if tt.wantWarning == "" && warnings != "" {
t.Fatalf("warnings = %q, want none", warnings)
}
if tt.wantWarning != "" && !strings.Contains(warnings, tt.wantWarning) {
t.Fatalf("warnings = %q, want one containing %q", warnings, tt.wantWarning)
}
})
}
}