-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathserver_test.go
881 lines (821 loc) · 23.5 KB
/
server_test.go
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
// Copyright 2017 HootSuite Media Inc.
//
// Licensed under the Apache License, Version 2.0 (the License);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an AS IS BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Modified hereafter by contributors to runatlantis/atlantis.
package cmd
import (
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gopkg.in/yaml.v2"
"github.com/runatlantis/atlantis/server"
"github.com/runatlantis/atlantis/server/events/vcs/testdata"
"github.com/runatlantis/atlantis/server/logging"
. "github.com/runatlantis/atlantis/testing"
)
// passedConfig is set to whatever config ended up being passed to NewServer.
// Used for testing.
var passedConfig server.UserConfig
type ServerCreatorMock struct{}
func (s *ServerCreatorMock) NewServer(userConfig server.UserConfig, _ server.Config) (ServerStarter, error) {
passedConfig = userConfig
return &ServerStarterMock{}, nil
}
type ServerStarterMock struct{}
func (s *ServerStarterMock) Start() error {
return nil
}
// Adding a new flag? Add it to this slice for testing in alphabetical
// order.
var testFlags = map[string]interface{}{
ADTokenFlag: "ad-token",
ADUserFlag: "ad-user",
ADWebhookPasswordFlag: "ad-wh-pass",
ADWebhookUserFlag: "ad-wh-user",
AtlantisURLFlag: "url",
AllowCommandsFlag: "version,plan,apply,unlock,import,approve_policies",
AllowForkPRsFlag: true,
AutoDiscoverModeFlag: "auto",
AutomergeFlag: true,
AutoplanFileListFlag: "**/*.tf,**/*.yml",
BitbucketBaseURLFlag: "https://bitbucket-base-url.com",
BitbucketTokenFlag: "bitbucket-token",
BitbucketUserFlag: "bitbucket-user",
BitbucketWebhookSecretFlag: "bitbucket-secret",
CheckoutStrategyFlag: CheckoutStrategyMerge,
DataDirFlag: "/path",
DefaultTFVersionFlag: "v0.11.0",
DisableApplyAllFlag: true,
DisableMarkdownFoldingFlag: true,
DisableRepoLockingFlag: true,
DiscardApprovalOnPlanFlag: true,
GHHostnameFlag: "ghhostname",
GHTokenFlag: "token",
GHUserFlag: "user",
GHAppIDFlag: int64(0),
GHAppKeyFlag: "",
GHAppKeyFileFlag: "",
GHAppSlugFlag: "atlantis",
GHOrganizationFlag: "",
GHWebhookSecretFlag: "secret",
GitlabHostnameFlag: "gitlab-hostname",
GitlabTokenFlag: "gitlab-token",
GitlabUserFlag: "gitlab-user",
GitlabWebhookSecretFlag: "gitlab-secret",
LockingDBType: "boltdb",
LogLevelFlag: "debug",
MarkdownTemplateOverridesDirFlag: "/path2",
StatsNamespace: "atlantis",
AllowDraftPRs: true,
PortFlag: 8181,
ParallelPoolSize: 100,
ParallelPlanFlag: true,
ParallelApplyFlag: true,
RepoAllowlistFlag: "github.com/runatlantis/atlantis",
RequireApprovalFlag: true,
RequireMergeableFlag: true,
SilenceNoProjectsFlag: false,
SilenceForkPRErrorsFlag: true,
SilenceAllowlistErrorsFlag: true,
SilenceVCSStatusNoPlans: true,
SkipCloneNoChanges: true,
SlackTokenFlag: "slack-token",
SSLCertFileFlag: "cert-file",
SSLKeyFileFlag: "key-file",
RestrictFileList: false,
TFDownloadURLFlag: "https://my-hostname.com",
TFEHostnameFlag: "my-hostname",
TFELocalExecutionModeFlag: true,
TFETokenFlag: "my-token",
VCSStatusName: "my-status",
WriteGitCredsFlag: true,
DisableAutoplanFlag: true,
DisableAutoplanLabelFlag: "no-auto-plan",
DisableUnlockLabelFlag: "do-not-unlock",
EnablePolicyChecksFlag: false,
EnableRegExpCmdFlag: false,
EnableDiffMarkdownFormat: false,
}
func TestExecute_Defaults(t *testing.T) {
t.Log("Should set the defaults for all unspecified flags.")
c := setup(map[string]interface{}{
GHUserFlag: "user",
GHTokenFlag: "token",
RepoAllowlistFlag: "*",
}, t)
err := c.Execute()
Ok(t, err)
// Get our hostname since that's what atlantis-url gets defaulted to.
hostname, err := os.Hostname()
Ok(t, err)
// Get our home dir since that's what data-dir and markdown-template-overrides-dir defaulted to.
dataDir, err := homedir.Expand("~/.atlantis")
Ok(t, err)
markdownTemplateOverridesDir, err := homedir.Expand("~/.markdown_templates")
Ok(t, err)
strExceptions := map[string]string{
GHUserFlag: "user",
GHTokenFlag: "token",
DataDirFlag: dataDir,
MarkdownTemplateOverridesDirFlag: markdownTemplateOverridesDir,
AtlantisURLFlag: "http://" + hostname + ":4141",
RepoAllowlistFlag: "*",
VarFileAllowlistFlag: dataDir,
}
strIgnore := map[string]bool{
"config": true,
}
for flag, cfg := range stringFlags {
t.Log(flag)
if _, ok := strIgnore[flag]; ok {
continue
} else if excep, ok := strExceptions[flag]; ok {
Equals(t, excep, configVal(t, passedConfig, flag))
} else {
Equals(t, cfg.defaultValue, configVal(t, passedConfig, flag))
}
}
for flag, cfg := range boolFlags {
t.Log(flag)
Equals(t, cfg.defaultValue, configVal(t, passedConfig, flag))
}
for flag, cfg := range intFlags {
t.Log(flag)
Equals(t, cfg.defaultValue, configVal(t, passedConfig, flag))
}
}
func TestExecute_Flags(t *testing.T) {
t.Log("Should use all flags that are set.")
c := setup(testFlags, t)
err := c.Execute()
Ok(t, err)
for flag, exp := range testFlags {
Equals(t, exp, configVal(t, passedConfig, flag))
}
}
func TestExecute_ConfigFile(t *testing.T) {
t.Log("Should use all the values from the config file.")
// Use yaml package to quote values that need quoting
cfgContents, yamlErr := yaml.Marshal(&testFlags)
Ok(t, yamlErr)
tmpFile := tempFile(t, string(cfgContents))
defer os.Remove(tmpFile) // nolint: errcheck
c := setup(map[string]interface{}{
ConfigFlag: tmpFile,
}, t)
err := c.Execute()
Ok(t, err)
for flag, exp := range testFlags {
Equals(t, exp, configVal(t, passedConfig, flag))
}
}
func TestExecute_EnvironmentVariables(t *testing.T) {
t.Log("Environment variables should work.")
for flag, value := range testFlags {
envKey := "ATLANTIS_" + strings.ToUpper(strings.ReplaceAll(flag, "-", "_"))
os.Setenv(envKey, fmt.Sprintf("%v", value)) // nolint: errcheck
defer func(key string) { os.Unsetenv(key) }(envKey)
}
c := setup(nil, t)
err := c.Execute()
Ok(t, err)
for flag, exp := range testFlags {
Equals(t, exp, configVal(t, passedConfig, flag))
}
}
func TestExecute_NoConfigFlag(t *testing.T) {
t.Log("If there is no config flag specified Execute should return nil.")
c := setupWithDefaults(map[string]interface{}{
ConfigFlag: "",
}, t)
err := c.Execute()
Ok(t, err)
}
func TestExecute_ConfigFileExtension(t *testing.T) {
t.Log("If the config file doesn't have an extension then error.")
c := setupWithDefaults(map[string]interface{}{
ConfigFlag: "does-not-exist",
}, t)
err := c.Execute()
Equals(t, "invalid config: reading does-not-exist: Unsupported Config Type \"\"", err.Error())
}
func TestExecute_ConfigFileMissing(t *testing.T) {
t.Log("If the config file doesn't exist then error.")
c := setupWithDefaults(map[string]interface{}{
ConfigFlag: "does-not-exist.yaml",
}, t)
err := c.Execute()
Equals(t, "invalid config: reading does-not-exist.yaml: open does-not-exist.yaml: no such file or directory", err.Error())
}
func TestExecute_ConfigFileExists(t *testing.T) {
t.Log("If the config file exists then there should be no error.")
tmpFile := tempFile(t, "")
defer os.Remove(tmpFile) // nolint: errcheck
c := setupWithDefaults(map[string]interface{}{
ConfigFlag: tmpFile,
}, t)
err := c.Execute()
Ok(t, err)
}
func TestExecute_InvalidConfig(t *testing.T) {
t.Log("If the config file contains invalid yaml there should be an error.")
tmpFile := tempFile(t, "invalidyaml")
defer os.Remove(tmpFile) // nolint: errcheck
c := setupWithDefaults(map[string]interface{}{
ConfigFlag: tmpFile,
}, t)
err := c.Execute()
Assert(t, strings.Contains(err.Error(), "unmarshal errors"), "should be an unmarshal error")
}
// Should error if the repo allowlist contained a scheme.
func TestExecute_RepoAllowlistScheme(t *testing.T) {
c := setup(map[string]interface{}{
GHUserFlag: "user",
GHTokenFlag: "token",
RepoAllowlistFlag: "http://github.com/*",
}, t)
err := c.Execute()
Assert(t, err != nil, "should be an error")
Equals(t, "--repo-allowlist cannot contain ://, should be hostnames only", err.Error())
}
func TestExecute_ValidateLogLevel(t *testing.T) {
cases := []struct {
description string
flags map[string]interface{}
expectError bool
}{
{
"log level is invalid",
map[string]interface{}{
LogLevelFlag: "invalid",
},
true,
},
{
"log level is valid uppercase",
map[string]interface{}{
LogLevelFlag: "DEBUG",
},
false,
},
}
for _, testCase := range cases {
t.Log("Should validate log level when " + testCase.description)
c := setupWithDefaults(testCase.flags, t)
err := c.Execute()
if testCase.expectError {
Assert(t, err != nil, "should be an error")
} else {
Ok(t, err)
}
}
}
func TestExecute_ValidateCheckoutStrategy(t *testing.T) {
c := setupWithDefaults(map[string]interface{}{
CheckoutStrategyFlag: "invalid",
}, t)
err := c.Execute()
ErrEquals(t, "invalid checkout strategy: not one of branch or merge", err)
}
func TestExecute_ValidateSSLConfig(t *testing.T) {
expErr := "--ssl-key-file and --ssl-cert-file are both required for ssl"
cases := []struct {
description string
flags map[string]interface{}
expectError bool
}{
{
"neither option set",
make(map[string]interface{}),
false,
},
{
"just ssl-key-file set",
map[string]interface{}{
SSLKeyFileFlag: "file",
},
true,
},
{
"just ssl-cert-file set",
map[string]interface{}{
SSLCertFileFlag: "flag",
},
true,
},
{
"both flags set",
map[string]interface{}{
SSLCertFileFlag: "cert",
SSLKeyFileFlag: "key",
},
false,
},
}
for _, testCase := range cases {
t.Log("Should validate ssl config when " + testCase.description)
c := setupWithDefaults(testCase.flags, t)
err := c.Execute()
if testCase.expectError {
Assert(t, err != nil, "should be an error")
Equals(t, expErr, err.Error())
} else {
Ok(t, err)
}
}
}
func TestExecute_ValidateVCSConfig(t *testing.T) {
expErr := "--gh-user/--gh-token or --gh-app-id/--gh-app-key-file or --gh-app-id/--gh-app-key or --gitlab-user/--gitlab-token or --bitbucket-user/--bitbucket-token or --azuredevops-user/--azuredevops-token must be set"
cases := []struct {
description string
flags map[string]interface{}
expectError bool
}{
{
"no config set",
make(map[string]interface{}),
true,
},
{
"just github token set",
map[string]interface{}{
GHTokenFlag: "token",
},
true,
},
{
"just gitlab token set",
map[string]interface{}{
GitlabTokenFlag: "token",
},
true,
},
{
"just bitbucket token set",
map[string]interface{}{
BitbucketTokenFlag: "token",
},
true,
},
{
"just azuredevops token set",
map[string]interface{}{
ADTokenFlag: "token",
},
true,
},
{
"just github user set",
map[string]interface{}{
GHUserFlag: "user",
},
true,
},
{
"just github app set",
map[string]interface{}{
GHAppIDFlag: "1",
},
true,
},
{
"just github app key file set",
map[string]interface{}{
GHAppKeyFileFlag: "key.pem",
},
true,
},
{
"just github app key set",
map[string]interface{}{
GHAppKeyFlag: testdata.GithubPrivateKey,
},
true,
},
{
"just gitlab user set",
map[string]interface{}{
GitlabUserFlag: "user",
},
true,
},
{
"just bitbucket user set",
map[string]interface{}{
BitbucketUserFlag: "user",
},
true,
},
{
"just azuredevops user set",
map[string]interface{}{
ADUserFlag: "user",
},
true,
},
{
"github user and gitlab token set",
map[string]interface{}{
GHUserFlag: "user",
GitlabTokenFlag: "token",
},
true,
},
{
"gitlab user and github token set",
map[string]interface{}{
GitlabUserFlag: "user",
GHTokenFlag: "token",
},
true,
},
{
"github user and bitbucket token set",
map[string]interface{}{
GHUserFlag: "user",
BitbucketTokenFlag: "token",
},
true,
},
{
"github user and github token set and should be successful",
map[string]interface{}{
GHUserFlag: "user",
GHTokenFlag: "token",
},
false,
},
{
"github app and key file set and should be successful",
map[string]interface{}{
GHAppIDFlag: "1",
GHAppKeyFileFlag: "key.pem",
},
false,
},
{
"github app and key set and should be successful",
map[string]interface{}{
GHAppIDFlag: "1",
GHAppKeyFlag: testdata.GithubPrivateKey,
},
false,
},
{
"gitlab user and gitlab token set and should be successful",
map[string]interface{}{
GitlabUserFlag: "user",
GitlabTokenFlag: "token",
},
false,
},
{
"bitbucket user and bitbucket token set and should be successful",
map[string]interface{}{
BitbucketUserFlag: "user",
BitbucketTokenFlag: "token",
},
false,
},
{
"azuredevops user and azuredevops token set and should be successful",
map[string]interface{}{
ADUserFlag: "user",
ADTokenFlag: "token",
},
false,
},
{
"all set should be successful",
map[string]interface{}{
GHUserFlag: "user",
GHTokenFlag: "token",
GitlabUserFlag: "user",
GitlabTokenFlag: "token",
BitbucketUserFlag: "user",
BitbucketTokenFlag: "token",
ADUserFlag: "user",
ADTokenFlag: "token",
},
false,
},
}
for _, testCase := range cases {
t.Log("Should validate vcs config when " + testCase.description)
testCase.flags[RepoAllowlistFlag] = "*"
c := setup(testCase.flags, t)
err := c.Execute()
if testCase.expectError {
Assert(t, err != nil, "should be an error")
Equals(t, expErr, err.Error())
} else {
Ok(t, err)
}
}
}
func TestExecute_ValidateAllowCommands(t *testing.T) {
cases := []struct {
name string
allowCommandsFlag string
expErr string
}{
{
name: "invalid allow commands",
allowCommandsFlag: "noallow",
expErr: "invalid --allow-commands: unknown command name: noallow",
},
{
name: "success with empty allow commands",
allowCommandsFlag: "",
expErr: "",
},
}
for _, testCase := range cases {
c := setupWithDefaults(map[string]interface{}{
AllowCommandsFlag: testCase.allowCommandsFlag,
}, t)
err := c.Execute()
if testCase.expErr != "" {
ErrEquals(t, testCase.expErr, err)
} else {
Ok(t, err)
}
}
}
func TestExecute_ExpandHomeInDataDir(t *testing.T) {
t.Log("If ~ is used as a data-dir path, should expand to absolute home path")
c := setup(map[string]interface{}{
GHUserFlag: "user",
GHTokenFlag: "token",
RepoAllowlistFlag: "*",
DataDirFlag: "~/this/is/a/path",
}, t)
err := c.Execute()
Ok(t, err)
home, err := homedir.Dir()
Ok(t, err)
Equals(t, home+"/this/is/a/path", passedConfig.DataDir)
}
func TestExecute_RelativeDataDir(t *testing.T) {
t.Log("Should convert relative dir to absolute.")
c := setupWithDefaults(map[string]interface{}{
DataDirFlag: "../",
}, t)
// Figure out what ../ should be as an absolute path.
expectedAbsolutePath, err := filepath.Abs("../")
Ok(t, err)
err = c.Execute()
Ok(t, err)
Equals(t, expectedAbsolutePath, passedConfig.DataDir)
}
func TestExecute_GithubUser(t *testing.T) {
t.Log("Should remove the @ from the github username if it's passed.")
c := setup(map[string]interface{}{
GHUserFlag: "@user",
GHTokenFlag: "token",
RepoAllowlistFlag: "*",
}, t)
err := c.Execute()
Ok(t, err)
Equals(t, "user", passedConfig.GithubUser)
}
func TestExecute_GithubApp(t *testing.T) {
t.Log("Should remove the @ from the github username if it's passed.")
c := setup(map[string]interface{}{
GHAppKeyFlag: testdata.GithubPrivateKey,
GHAppIDFlag: "1",
RepoAllowlistFlag: "*",
}, t)
err := c.Execute()
Ok(t, err)
Equals(t, int64(1), passedConfig.GithubAppID)
}
func TestExecute_GitlabUser(t *testing.T) {
t.Log("Should remove the @ from the gitlab username if it's passed.")
c := setup(map[string]interface{}{
GitlabUserFlag: "@user",
GitlabTokenFlag: "token",
RepoAllowlistFlag: "*",
}, t)
err := c.Execute()
Ok(t, err)
Equals(t, "user", passedConfig.GitlabUser)
}
func TestExecute_BitbucketUser(t *testing.T) {
t.Log("Should remove the @ from the bitbucket username if it's passed.")
c := setup(map[string]interface{}{
BitbucketUserFlag: "@user",
BitbucketTokenFlag: "token",
RepoAllowlistFlag: "*",
}, t)
err := c.Execute()
Ok(t, err)
Equals(t, "user", passedConfig.BitbucketUser)
}
func TestExecute_ADUser(t *testing.T) {
t.Log("Should remove the @ from the azure devops username if it's passed.")
c := setup(map[string]interface{}{
ADUserFlag: "@user",
ADTokenFlag: "token",
RepoAllowlistFlag: "*",
}, t)
err := c.Execute()
Ok(t, err)
Equals(t, "user", passedConfig.AzureDevopsUser)
}
// If using bitbucket cloud, webhook secrets are not supported.
func TestExecute_BitbucketCloudWithWebhookSecret(t *testing.T) {
c := setup(map[string]interface{}{
BitbucketUserFlag: "user",
BitbucketTokenFlag: "token",
RepoAllowlistFlag: "*",
BitbucketWebhookSecretFlag: "my secret",
}, t)
err := c.Execute()
ErrEquals(t, "--bitbucket-webhook-secret cannot be specified for Bitbucket Cloud because it is not supported by Bitbucket", err)
}
// Base URL must have a scheme.
func TestExecute_BitbucketServerBaseURLScheme(t *testing.T) {
c := setup(map[string]interface{}{
BitbucketUserFlag: "user",
BitbucketTokenFlag: "token",
RepoAllowlistFlag: "*",
BitbucketBaseURLFlag: "mydomain.com",
}, t)
ErrEquals(t, "--bitbucket-base-url must have http:// or https://, got \"mydomain.com\"", c.Execute())
c = setup(map[string]interface{}{
BitbucketUserFlag: "user",
BitbucketTokenFlag: "token",
RepoAllowlistFlag: "*",
BitbucketBaseURLFlag: "://mydomain.com",
}, t)
ErrEquals(t, "error parsing --bitbucket-webhook-secret flag value \"://mydomain.com\": parse \"://mydomain.com\": missing protocol scheme", c.Execute())
}
// Port should be retained on base url.
func TestExecute_BitbucketServerBaseURLPort(t *testing.T) {
c := setup(map[string]interface{}{
BitbucketUserFlag: "user",
BitbucketTokenFlag: "token",
RepoAllowlistFlag: "*",
BitbucketBaseURLFlag: "http://mydomain.com:7990",
}, t)
Ok(t, c.Execute())
Equals(t, "http://mydomain.com:7990", passedConfig.BitbucketBaseURL)
}
// Can't use both --repo-config and --repo-config-json.
func TestExecute_RepoCfgFlags(t *testing.T) {
c := setup(map[string]interface{}{
GHUserFlag: "user",
GHTokenFlag: "token",
RepoAllowlistFlag: "github.com",
RepoConfigFlag: "repos.yaml",
RepoConfigJSONFlag: "{}",
}, t)
err := c.Execute()
ErrEquals(t, "cannot use --repo-config and --repo-config-json at the same time", err)
}
// Can't use both --tfe-hostname flag without --tfe-token.
func TestExecute_TFEHostnameOnly(t *testing.T) {
c := setup(map[string]interface{}{
GHUserFlag: "user",
GHTokenFlag: "token",
RepoAllowlistFlag: "github.com",
TFEHostnameFlag: "not-app.terraform.io",
}, t)
err := c.Execute()
ErrEquals(t, "if setting --tfe-hostname, must set --tfe-token", err)
}
// Must set allow or whitelist.
func TestExecute_AllowAndWhitelist(t *testing.T) {
c := setup(map[string]interface{}{
GHUserFlag: "user",
GHTokenFlag: "token",
}, t)
err := c.Execute()
ErrEquals(t, "--repo-allowlist must be set for security purposes", err)
}
func TestExecute_AutoDetectModulesFromProjects_Env(t *testing.T) {
t.Setenv("ATLANTIS_AUTOPLAN_MODULES_FROM_PROJECTS", "**/init.tf")
c := setupWithDefaults(map[string]interface{}{}, t)
err := c.Execute()
Ok(t, err)
Equals(t, "**/init.tf", passedConfig.AutoplanModulesFromProjects)
}
func TestExecute_AutoDetectModulesFromProjects(t *testing.T) {
c := setupWithDefaults(map[string]interface{}{
AutoplanModulesFromProjects: "**/*.tf",
}, t)
err := c.Execute()
Ok(t, err)
Equals(t, "**/*.tf", passedConfig.AutoplanModulesFromProjects)
}
func TestExecute_AutoplanFileList(t *testing.T) {
cases := []struct {
description string
flags map[string]interface{}
expectErr string
}{
{
"default value",
map[string]interface{}{
AutoplanFileListFlag: DefaultAutoplanFileList,
},
"",
},
{
"valid value",
map[string]interface{}{
AutoplanFileListFlag: "**/*.tf",
},
"",
},
{
"invalid exclusion pattern",
map[string]interface{}{
AutoplanFileListFlag: "**/*.yml,!",
},
"invalid pattern in --autoplan-file-list, **/*.yml,!: illegal exclusion pattern: \"!\"",
},
{
"invalid pattern",
map[string]interface{}{
AutoplanFileListFlag: "[^]",
},
"invalid pattern in --autoplan-file-list, [^]: syntax error in pattern",
},
}
for _, testCase := range cases {
t.Log("Should validate autoplan file list when " + testCase.description)
c := setupWithDefaults(testCase.flags, t)
err := c.Execute()
if testCase.expectErr != "" {
ErrEquals(t, testCase.expectErr, err)
} else {
Ok(t, err)
}
}
}
func setup(flags map[string]interface{}, t *testing.T) *cobra.Command {
vipr := viper.New()
for k, v := range flags {
vipr.Set(k, v)
}
c := &ServerCmd{
ServerCreator: &ServerCreatorMock{},
Viper: vipr,
SilenceOutput: true,
Logger: logging.NewNoopLogger(t),
}
return c.Init()
}
func setupWithDefaults(flags map[string]interface{}, t *testing.T) *cobra.Command {
vipr := viper.New()
flags[GHUserFlag] = "user"
flags[GHTokenFlag] = "token"
flags[RepoAllowlistFlag] = "*"
for k, v := range flags {
vipr.Set(k, v)
}
c := &ServerCmd{
ServerCreator: &ServerCreatorMock{},
Viper: vipr,
SilenceOutput: true,
Logger: logging.NewNoopLogger(t),
}
return c.Init()
}
func tempFile(t *testing.T, contents string) string {
f, err := os.CreateTemp("", "")
Ok(t, err)
newName := f.Name() + ".yaml"
err = os.Rename(f.Name(), newName)
Ok(t, err)
os.WriteFile(newName, []byte(contents), 0600) // nolint: errcheck
return newName
}
func configVal(t *testing.T, u server.UserConfig, tag string) interface{} {
t.Helper()
v := reflect.ValueOf(u)
typeOfS := v.Type()
for i := 0; i < v.NumField(); i++ {
if typeOfS.Field(i).Tag.Get("mapstructure") == tag {
return v.Field(i).Interface()
}
}
t.Fatalf("no field with tag %q found", tag)
return nil
}