forked from hashicorp/go-tfe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkspace_integration_test.go
3029 lines (2541 loc) · 100 KB
/
workspace_integration_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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package tfe
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"sort"
"strings"
"testing"
"time"
retryablehttp "github.com/hashicorp/go-retryablehttp"
"github.com/hashicorp/jsonapi"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type WorkspaceTableOptions struct {
createOptions *WorkspaceCreateOptions
updateOptions *WorkspaceUpdateOptions
}
type WorkspaceTableTest struct {
scenario string
options *WorkspaceTableOptions
setup func(t *testing.T, options *WorkspaceTableOptions) (w *Workspace, cleanup func())
assertion func(t *testing.T, w *Workspace, options *WorkspaceTableOptions, err error)
}
func TestWorkspacesList(t *testing.T) {
client := testClient(t)
ctx := context.Background()
orgTest, orgTestCleanup := createOrganization(t, client)
t.Cleanup(orgTestCleanup)
wTest1, wTest1Cleanup := createWorkspace(t, client, orgTest)
t.Cleanup(wTest1Cleanup)
wTest2, wTest2Cleanup := createWorkspace(t, client, orgTest)
t.Cleanup(wTest2Cleanup)
wTest3, wTest3Cleanup := createWorkspace(t, client, orgTest)
t.Cleanup(wTest3Cleanup)
t.Run("without list options", func(t *testing.T) {
wl, err := client.Workspaces.List(ctx, orgTest.Name, nil)
require.NoError(t, err)
assert.Contains(t, wl.Items, wTest1)
assert.Contains(t, wl.Items, wTest2)
assert.Equal(t, 1, wl.CurrentPage)
assert.Equal(t, 3, wl.TotalCount)
})
t.Run("with list options", func(t *testing.T) {
// Request a page number which is out of range. The result should
// be successful, but return no results if the paging options are
// properly passed along.
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
ListOptions: ListOptions{
PageNumber: 999,
PageSize: 100,
},
})
require.NoError(t, err)
assert.Empty(t, wl.Items)
assert.Equal(t, 999, wl.CurrentPage)
assert.Equal(t, 3, wl.TotalCount)
})
t.Run("when sorting by workspace names", func(t *testing.T) {
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
Sort: "name",
})
require.NoError(t, err)
require.NotEmpty(t, wl.Items)
require.GreaterOrEqual(t, len(wl.Items), 2)
assert.Equal(t, wl.Items[0].Name < wl.Items[1].Name, true)
})
t.Run("when sorting workspaces on current-run.created-at", func(t *testing.T) {
_, unappliedCleanup1 := createRunUnapplied(t, client, wTest2)
t.Cleanup(unappliedCleanup1)
_, unappliedCleanup2 := createRunUnapplied(t, client, wTest3)
t.Cleanup(unappliedCleanup2)
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
Include: []WSIncludeOpt{WSCurrentRun},
Sort: "current-run.created-at",
})
require.NoError(t, err)
require.NotEmpty(t, wl.Items)
require.GreaterOrEqual(t, len(wl.Items), 2)
assert.True(t, wl.Items[1].CurrentRun.CreatedAt.After(wl.Items[0].CurrentRun.CreatedAt))
})
t.Run("when searching a known workspace", func(t *testing.T) {
// Use a known workspace prefix as search attribute. The result
// should be successful and only contain the matching workspace.
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
Search: wTest1.Name[:len(wTest1.Name)-5],
})
require.NoError(t, err)
assert.Contains(t, wl.Items, wTest1)
assert.NotContains(t, wl.Items, wTest2)
assert.Equal(t, 1, wl.CurrentPage)
assert.Equal(t, 1, wl.TotalCount)
})
t.Run("when searching using a tag", func(t *testing.T) {
tagName := "tagtest"
// Add the tag to the first workspace for searching.
err := client.Workspaces.AddTags(ctx, wTest1.ID, WorkspaceAddTagsOptions{
Tags: []*Tag{
{
Name: tagName,
},
},
})
require.NoError(t, err)
// The result should be successful and only contain the workspace with the
// new tag.
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
Tags: tagName,
})
require.NoError(t, err)
assert.Equal(t, wl.Items[0].ID, wTest1.ID)
assert.Equal(t, 1, wl.CurrentPage)
assert.Equal(t, 1, wl.TotalCount)
})
t.Run("when searching using exclude-tags", func(t *testing.T) {
for wsID, tag := range map[string]string{wTest1.ID: "foo", wTest2.ID: "bar", wTest3.ID: "foo"} {
err := client.Workspaces.AddTags(ctx, wsID, WorkspaceAddTagsOptions{
Tags: []*Tag{
{
Name: tag,
},
},
})
require.NoError(t, err)
}
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
ExcludeTags: "foo",
})
require.NoError(t, err)
assert.Contains(t, wl.Items[0].ID, wTest2.ID)
assert.Equal(t, 1, wl.CurrentPage)
assert.Equal(t, 1, wl.TotalCount)
})
t.Run("when searching an unknown workspace", func(t *testing.T) {
// Use a nonexisting workspace name as search attribute. The result
// should be successful, but return no results.
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
Search: "nonexisting",
})
require.NoError(t, err)
assert.Empty(t, wl.Items)
assert.Equal(t, 1, wl.CurrentPage)
assert.Equal(t, 0, wl.TotalCount)
})
t.Run("without a valid organization", func(t *testing.T) {
wl, err := client.Workspaces.List(ctx, badIdentifier, nil)
assert.Nil(t, wl)
assert.EqualError(t, err, ErrInvalidOrg.Error())
})
t.Run("with organization included", func(t *testing.T) {
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
Include: []WSIncludeOpt{WSOrganization},
})
require.NoError(t, err)
require.NotEmpty(t, wl.Items)
require.NotNil(t, wl.Items[0].Organization)
assert.NotEmpty(t, wl.Items[0].Organization.Email)
})
t.Run("with current-state-version,current-run included", func(t *testing.T) {
_, rCleanup := createRunApply(t, client, wTest1)
t.Cleanup(rCleanup)
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
Include: []WSIncludeOpt{WSCurrentStateVer, WSCurrentRun},
})
require.NoError(t, err)
require.NotEmpty(t, wl.Items)
foundWTest1 := false
for _, ws := range wl.Items {
if ws.ID != wTest1.ID {
continue
}
foundWTest1 = true
require.NotNil(t, wl.Items[0].CurrentStateVersion)
assert.NotEmpty(t, wl.Items[0].CurrentStateVersion.DownloadURL)
require.NotNil(t, wl.Items[0].CurrentRun)
assert.NotEmpty(t, wl.Items[0].CurrentRun.Message)
}
assert.True(t, foundWTest1)
})
t.Run("when searching a known substring", func(t *testing.T) {
wildcardSearch := "*-prod"
// should be successful, and return 1 result
wTest, wTestCleanup := createWorkspaceWithOptions(t, client, orgTest, WorkspaceCreateOptions{
Name: String("hashicorp-prod"),
})
t.Cleanup(wTestCleanup)
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
WildcardName: wildcardSearch,
})
require.NoError(t, err)
assert.NotEmpty(t, wTest.ID)
assert.Equal(t, 1, wl.TotalCount)
})
t.Run("when wildcard match does not exist", func(t *testing.T) {
wildcardSearch := "*-dev"
// should be successful, but return no results
wTest, wTestCleanup := createWorkspaceWithOptions(t, client, orgTest, WorkspaceCreateOptions{
Name: String("hashicorp-staging"),
})
t.Cleanup(wTestCleanup)
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
WildcardName: wildcardSearch,
})
require.NoError(t, err)
assert.NotEmpty(t, wTest.ID)
assert.Equal(t, 0, wl.TotalCount)
})
t.Run("when using a tags filter", func(t *testing.T) {
skipUnlessBeta(t)
w1, wTestCleanup1 := createWorkspaceWithOptions(t, client, orgTest, WorkspaceCreateOptions{
Name: String(randomString(t)),
TagBindings: []*TagBinding{
{Key: "key1", Value: "value1"},
{Key: "key2", Value: "value2a"},
},
})
w2, wTestCleanup2 := createWorkspaceWithOptions(t, client, orgTest, WorkspaceCreateOptions{
Name: String(randomString(t)),
TagBindings: []*TagBinding{
{Key: "key2", Value: "value2b"},
{Key: "key3", Value: "value3"},
},
})
t.Cleanup(wTestCleanup1)
t.Cleanup(wTestCleanup2)
// List all the workspaces under the given tag
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
TagBindings: []*TagBinding{
{Key: "key1"},
},
})
assert.NoError(t, err)
assert.Len(t, wl.Items, 1)
assert.Contains(t, wl.Items, w1)
wl2, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
TagBindings: []*TagBinding{
{Key: "key2"},
},
})
assert.NoError(t, err)
assert.Len(t, wl2.Items, 2)
assert.Contains(t, wl2.Items, w1, w2)
wl3, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
TagBindings: []*TagBinding{
{Key: "key2", Value: "value2b"},
},
})
assert.NoError(t, err)
assert.Len(t, wl3.Items, 1)
assert.Contains(t, wl3.Items, w2)
})
t.Run("when using project id filter and project contains workspaces", func(t *testing.T) {
// create a project in the orgTest
p, pTestCleanup := createProject(t, client, orgTest)
defer pTestCleanup()
// create a workspace with project
w, wTestCleanup := createWorkspaceWithOptions(t, client, orgTest, WorkspaceCreateOptions{
Name: String(randomString(t)),
Project: p,
})
defer wTestCleanup()
// List all the workspaces under the given ProjectID
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
ProjectID: p.ID,
})
require.NoError(t, err)
assert.Contains(t, wl.Items, w)
})
t.Run("when using project id filter but project contains no workspaces", func(t *testing.T) {
// create a project in the orgTest
p, pTestCleanup := createProject(t, client, orgTest)
defer pTestCleanup()
// List all the workspaces under the given ProjectID
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
ProjectID: p.ID,
})
require.NoError(t, err)
assert.Empty(t, wl.Items)
})
t.Run("when filter workspaces by current run status", func(t *testing.T) {
wTest, wTestCleanup := createWorkspace(t, client, orgTest)
t.Cleanup(wTestCleanup)
rn, appliedCleanup := createRunApply(t, client, wTest)
t.Cleanup(appliedCleanup)
wl, err := client.Workspaces.List(ctx, orgTest.Name, &WorkspaceListOptions{
CurrentRunStatus: string(RunApplied),
})
require.NoError(t, err)
require.NotEmpty(t, wl.Items)
require.GreaterOrEqual(t, len(wl.Items), 1)
found := false
for _, ws := range wl.Items {
if ws.ID != wTest.ID {
continue
}
assert.Equal(t, ws.CurrentRun.ID, rn.ID)
found = true
}
assert.True(t, found)
})
}
func TestWorkspacesCreateTableDriven(t *testing.T) {
client := testClient(t)
ctx := context.Background()
orgTest, orgTestCleanup := createOrganization(t, client)
t.Cleanup(orgTestCleanup)
oc, oaCleanup := createOAuthToken(t, client, orgTest)
t.Cleanup(oaCleanup)
workspaceTableTests := []WorkspaceTableTest{
{
scenario: "when options include vcs-repo",
options: &WorkspaceTableOptions{
createOptions: &WorkspaceCreateOptions{
Name: String("foobar"),
VCSRepo: &VCSRepoOptions{
Identifier: String("hashicorp/terraform-random-module"),
OAuthTokenID: &oc.ID,
Branch: String("main"),
},
},
},
assertion: func(t *testing.T, w *Workspace, options *WorkspaceTableOptions, err error) {
require.NoError(t, err)
require.NotNil(t, w)
require.NotEmpty(t, w.VCSRepo.Identifier)
require.NotEmpty(t, w.VCSRepo.OAuthTokenID)
require.NotEmpty(t, w.VCSRepo.Branch)
wRead, err := client.Workspaces.ReadByID(ctx, w.ID)
require.NoError(t, err)
require.Equal(t, w.VCSRepo.Identifier, wRead.VCSRepo.Identifier)
require.Equal(t, w.VCSRepo.OAuthTokenID, wRead.VCSRepo.OAuthTokenID)
require.Equal(t, w.VCSRepo.Branch, wRead.VCSRepo.Branch)
},
},
{
scenario: "when options include tags-regex",
options: &WorkspaceTableOptions{
createOptions: &WorkspaceCreateOptions{
Name: String("foobar"),
FileTriggersEnabled: Bool(false),
VCSRepo: &VCSRepoOptions{
TagsRegex: String("barfoo")},
},
},
setup: func(t *testing.T, options *WorkspaceTableOptions) (w *Workspace, cleanup func()) {
// Remove the below organization creation and use the one from the outer scope once the feature flag is removed
orgTest, orgTestCleanup := createOrganizationWithOptions(t, client, OrganizationCreateOptions{
Name: String("tst-" + randomString(t)[0:20]),
Email: String(fmt.Sprintf("%s@tfe.local", randomString(t))),
})
w, wTestCleanup := createWorkspaceWithVCS(t, client, orgTest, *options.createOptions)
return w, func() {
t.Cleanup(orgTestCleanup)
t.Cleanup(wTestCleanup)
}
},
assertion: func(t *testing.T, w *Workspace, options *WorkspaceTableOptions, err error) {
assert.Equal(t, *options.createOptions.VCSRepo.TagsRegex, w.VCSRepo.TagsRegex)
// Get a refreshed view from the API.
refreshed, readErr := client.Workspaces.Read(ctx, w.Organization.Name, *options.createOptions.Name)
require.NoError(t, readErr)
for _, item := range []*Workspace{
w,
refreshed,
} {
assert.Equal(t, *options.createOptions.VCSRepo.TagsRegex, item.VCSRepo.TagsRegex)
}
},
},
{
scenario: "when options include both non-empty tags-regex and trigger-patterns error is returned",
options: &WorkspaceTableOptions{
createOptions: &WorkspaceCreateOptions{
Name: String("foobar"),
FileTriggersEnabled: Bool(false),
VCSRepo: &VCSRepoOptions{TagsRegex: String("foobar")},
TriggerPatterns: []string{"/module-1/**/*", "/**/networking/*"},
},
},
assertion: func(t *testing.T, w *Workspace, options *WorkspaceTableOptions, err error) {
assert.Nil(t, w)
assert.EqualError(t, err, ErrUnsupportedBothTagsRegexAndTriggerPatterns.Error())
},
},
{
scenario: "when options include both non-empty tags-regex and trigger-prefixes error is returned",
options: &WorkspaceTableOptions{
createOptions: &WorkspaceCreateOptions{
Name: String("foobar"),
FileTriggersEnabled: Bool(false),
VCSRepo: &VCSRepoOptions{TagsRegex: String("foobar")},
TriggerPrefixes: []string{"/module-1", "/module-2"},
},
},
assertion: func(t *testing.T, w *Workspace, options *WorkspaceTableOptions, err error) {
assert.Nil(t, w)
assert.EqualError(t, err, ErrUnsupportedBothTagsRegexAndTriggerPrefixes.Error())
},
},
{
scenario: "when options include both non-empty tags-regex and file-triggers-enabled as true an error is returned",
options: &WorkspaceTableOptions{
createOptions: &WorkspaceCreateOptions{
Name: String("foobar"),
FileTriggersEnabled: Bool(true),
VCSRepo: &VCSRepoOptions{TagsRegex: String("foobar")},
},
},
assertion: func(t *testing.T, w *Workspace, options *WorkspaceTableOptions, err error) {
assert.Nil(t, w)
assert.EqualError(t, err, ErrUnsupportedBothTagsRegexAndFileTriggersEnabled.Error())
},
},
{
scenario: "when options include both non-empty tags-regex and file-triggers-enabled as false an error is not returned",
options: &WorkspaceTableOptions{
createOptions: &WorkspaceCreateOptions{
Name: String("foobar"),
FileTriggersEnabled: Bool(false),
VCSRepo: &VCSRepoOptions{TagsRegex: String("foobar")},
},
},
setup: func(t *testing.T, options *WorkspaceTableOptions) (w *Workspace, cleanup func()) {
w, wTestCleanup := createWorkspaceWithVCS(t, client, orgTest, *options.createOptions)
return w, func() {
t.Cleanup(wTestCleanup)
}
},
assertion: func(t *testing.T, w *Workspace, options *WorkspaceTableOptions, err error) {
require.NotNil(t, w)
require.NoError(t, err)
},
},
}
for _, tableTest := range workspaceTableTests {
t.Run(tableTest.scenario, func(t *testing.T) {
var workspace *Workspace
var cleanup func()
var err error
if tableTest.setup != nil {
workspace, cleanup = tableTest.setup(t, tableTest.options)
defer cleanup()
} else {
workspace, err = client.Workspaces.Create(ctx, orgTest.Name, *tableTest.options.createOptions)
}
tableTest.assertion(t, workspace, tableTest.options, err)
})
}
}
func TestWorkspacesCreateTableDrivenWithGithubApp(t *testing.T) {
gHAInstallationID := os.Getenv("GITHUB_APP_INSTALLATION_ID")
if gHAInstallationID == "" {
t.Skip("Export a valid GITHUB_APP_INSTALLATION_ID before running this test!")
}
client := testClient(t)
ctx := context.Background()
orgTest1, orgTestCleanup := createOrganization(t, client)
t.Cleanup(orgTestCleanup)
workspaceTableTests := []WorkspaceTableTest{
{
scenario: "when options include tags-regex",
options: &WorkspaceTableOptions{
createOptions: &WorkspaceCreateOptions{
Name: String("foobar"),
FileTriggersEnabled: Bool(false),
VCSRepo: &VCSRepoOptions{
TagsRegex: String("barfoo")},
},
},
setup: func(t *testing.T, options *WorkspaceTableOptions) (w *Workspace, cleanup func()) {
// Remove the below organization creation and use the one from the outer scope once the feature flag is removed
orgTest, orgTestCleanup := createOrganizationWithOptions(t, client, OrganizationCreateOptions{
Name: String("tst-" + randomString(t)[0:20]),
Email: String(fmt.Sprintf("%s@tfe.local", randomString(t))),
})
w, wTestCleanup := createWorkspaceWithGithubApp(t, client, orgTest, *options.createOptions)
return w, func() {
t.Cleanup(orgTestCleanup)
t.Cleanup(wTestCleanup)
}
},
assertion: func(t *testing.T, w *Workspace, options *WorkspaceTableOptions, err error) {
assert.Equal(t, *options.createOptions.VCSRepo.TagsRegex, w.VCSRepo.TagsRegex)
// Get a refreshed view from the API.
refreshed, readErr := client.Workspaces.Read(ctx, w.Organization.Name, *options.createOptions.Name)
require.NoError(t, readErr)
for _, item := range []*Workspace{
w,
refreshed,
} {
assert.Equal(t, *options.createOptions.VCSRepo.TagsRegex, item.VCSRepo.TagsRegex)
}
},
},
}
for _, tableTest := range workspaceTableTests {
t.Run(tableTest.scenario, func(t *testing.T) {
var workspace *Workspace
var cleanup func()
var err error
if tableTest.setup != nil {
workspace, cleanup = tableTest.setup(t, tableTest.options)
defer cleanup()
} else {
workspace, err = client.Workspaces.Create(ctx, orgTest1.Name, *tableTest.options.createOptions)
}
tableTest.assertion(t, workspace, tableTest.options, err)
})
}
}
func TestWorkspacesCreate(t *testing.T) {
client := testClient(t)
ctx := context.Background()
orgTest, orgTestCleanup := createOrganization(t, client)
t.Cleanup(orgTestCleanup)
t.Run("with valid project option", func(t *testing.T) {
skipUnlessBeta(t)
options := WorkspaceCreateOptions{
Name: String(fmt.Sprintf("foo-%s", randomString(t))),
AllowDestroyPlan: Bool(false),
AutoApply: Bool(true),
Description: String("qux"),
AssessmentsEnabled: Bool(false),
FileTriggersEnabled: Bool(true),
Operations: Bool(true),
QueueAllRuns: Bool(true),
SpeculativeEnabled: Bool(true),
SourceName: String("my-app"),
SourceURL: String("http://my-app-hostname.io"),
StructuredRunOutputEnabled: Bool(true),
TerraformVersion: String("0.11.0"),
TriggerPrefixes: []string{"/modules", "/shared"},
WorkingDirectory: String("bar/"),
Project: orgTest.DefaultProject,
Tags: []*Tag{
{
Name: "tag1",
},
{
Name: "tag2",
},
},
}
w, err := client.Workspaces.Create(ctx, orgTest.Name, options)
require.NoError(t, err)
// Get a refreshed view from the API.
refreshed, err := client.Workspaces.Read(ctx, orgTest.Name, *options.Name)
require.NoError(t, err)
for _, item := range []*Workspace{
w,
refreshed,
} {
assert.NotEmpty(t, item.ID)
assert.Equal(t, *options.Name, item.Name)
assert.Equal(t, options.Project.ID, item.Project.ID)
}
})
t.Run("with valid auto-apply-run-trigger option", func(t *testing.T) {
skipIfEnterprise(t)
// FEATURE FLAG: auto-apply-run-trigger
// Once un-flagged, delete this test and add an AutoApplyRunTrigger field
// to the basic "with valid options" test below.
options := WorkspaceCreateOptions{
Name: String(fmt.Sprintf("foo-%s", randomString(t))),
AutoApplyRunTrigger: Bool(true),
}
w, err := client.Workspaces.Create(ctx, orgTest.Name, options)
require.NoError(t, err)
// Get a refreshed view from the API.
refreshed, err := client.Workspaces.Read(ctx, orgTest.Name, *options.Name)
require.NoError(t, err)
for _, item := range []*Workspace{
w,
refreshed,
} {
assert.NotEmpty(t, item.ID)
assert.Equal(t, *options.Name, item.Name)
assert.Equal(t, *options.AutoApplyRunTrigger, item.AutoApplyRunTrigger)
}
})
t.Run("with valid options", func(t *testing.T) {
options := WorkspaceCreateOptions{
Name: String(fmt.Sprintf("foo-%s", randomString(t))),
AllowDestroyPlan: Bool(true),
AutoApply: Bool(true),
AutoDestroyAt: NullableTime(time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)),
Description: String("qux"),
AssessmentsEnabled: Bool(false),
FileTriggersEnabled: Bool(true),
Operations: Bool(true),
QueueAllRuns: Bool(true),
SpeculativeEnabled: Bool(true),
SourceName: String("my-app"),
SourceURL: String("http://my-app-hostname.io"),
StructuredRunOutputEnabled: Bool(true),
TerraformVersion: String("0.11.0"),
TriggerPrefixes: []string{"/modules", "/shared"},
WorkingDirectory: String("bar/"),
Tags: []*Tag{
{
Name: "tag1",
},
{
Name: "tag2",
},
},
}
w, err := client.Workspaces.Create(ctx, orgTest.Name, options)
require.NoError(t, err)
// Get a refreshed view from the API.
refreshed, err := client.Workspaces.Read(ctx, orgTest.Name, *options.Name)
require.NoError(t, err)
for _, item := range []*Workspace{
w,
refreshed,
} {
assert.NotEmpty(t, item.ID)
assert.Equal(t, *options.Name, item.Name)
assert.Equal(t, *options.Description, item.Description)
assert.Equal(t, *options.AllowDestroyPlan, item.AllowDestroyPlan)
assert.Equal(t, *options.AutoApply, item.AutoApply)
assert.Equal(t, options.AutoDestroyAt, item.AutoDestroyAt)
assert.Equal(t, *options.AssessmentsEnabled, item.AssessmentsEnabled)
assert.Equal(t, *options.FileTriggersEnabled, item.FileTriggersEnabled)
assert.Equal(t, *options.Operations, item.Operations)
assert.Equal(t, *options.QueueAllRuns, item.QueueAllRuns)
assert.Equal(t, *options.SpeculativeEnabled, item.SpeculativeEnabled)
assert.Equal(t, *options.SourceName, item.SourceName)
assert.Equal(t, *options.SourceURL, item.SourceURL)
assert.Equal(t, *options.StructuredRunOutputEnabled, item.StructuredRunOutputEnabled)
assert.Equal(t, options.Tags[0].Name, item.TagNames[0])
assert.Equal(t, options.Tags[1].Name, item.TagNames[1])
assert.Equal(t, *options.TerraformVersion, item.TerraformVersion)
assert.Equal(t, options.TriggerPrefixes, item.TriggerPrefixes)
assert.Equal(t, *options.WorkingDirectory, item.WorkingDirectory)
}
})
t.Run("when options is missing name", func(t *testing.T) {
w, err := client.Workspaces.Create(ctx, "foo", WorkspaceCreateOptions{})
assert.Nil(t, w)
assert.EqualError(t, err, ErrRequiredName.Error())
})
t.Run("when options has an invalid name", func(t *testing.T) {
w, err := client.Workspaces.Create(ctx, "foo", WorkspaceCreateOptions{
Name: String(badIdentifier),
})
assert.Nil(t, w)
assert.EqualError(t, err, ErrInvalidName.Error())
})
t.Run("when options has an invalid organization", func(t *testing.T) {
w, err := client.Workspaces.Create(ctx, badIdentifier, WorkspaceCreateOptions{
Name: String(fmt.Sprintf("foo-%s", randomString(t))),
})
assert.Nil(t, w)
assert.EqualError(t, err, ErrInvalidOrg.Error())
})
t.Run("when options includes both an operations value and an enforcement mode value", func(t *testing.T) {
options := WorkspaceCreateOptions{
Name: String(fmt.Sprintf("foo-%s", randomString(t))),
ExecutionMode: String("remote"),
Operations: Bool(true),
}
w, err := client.Workspaces.Create(ctx, orgTest.Name, options)
assert.Nil(t, w)
assert.Equal(t, err, ErrUnsupportedOperations)
})
t.Run("when an agent pool ID is specified without 'agent' execution mode", func(t *testing.T) {
options := WorkspaceCreateOptions{
Name: String(fmt.Sprintf("foo-%s", randomString(t))),
AgentPoolID: String("apool-xxxxx"),
}
w, err := client.Workspaces.Create(ctx, orgTest.Name, options)
assert.Nil(t, w)
assert.Equal(t, err, ErrRequiredAgentMode)
})
t.Run("when 'agent' execution mode is specified without an an agent pool ID", func(t *testing.T) {
options := WorkspaceCreateOptions{
Name: String(fmt.Sprintf("foo-%s", randomString(t))),
ExecutionMode: String("agent"),
}
w, err := client.Workspaces.Create(ctx, orgTest.Name, options)
assert.Nil(t, w)
assert.Equal(t, err, ErrRequiredAgentPoolID)
})
t.Run("when no execution mode is specified, in an organization with local as default execution mode", func(t *testing.T) {
// Remove the below organization creation and use the one from the outer scope once the feature flag is removed
orgTest, orgTestCleanup := createOrganizationWithOptions(t, client, OrganizationCreateOptions{
Name: String("tst-" + randomString(t)[0:20] + "-ff-on"),
Email: String(fmt.Sprintf("%s@tfe.local", randomString(t))),
DefaultExecutionMode: String("local"),
})
t.Cleanup(orgTestCleanup)
options := WorkspaceCreateOptions{
Name: String(fmt.Sprintf("foo-%s", randomString(t))),
SettingOverwrites: &WorkspaceSettingOverwritesOptions{
ExecutionMode: Bool(false),
},
}
_, err := client.Workspaces.Create(ctx, orgTest.Name, options)
require.NoError(t, err)
// Get a refreshed view from the API.
refreshed, err := client.Workspaces.Read(ctx, orgTest.Name, *options.Name)
require.NoError(t, err)
assert.Equal(t, "local", refreshed.ExecutionMode)
})
t.Run("when an error is returned from the API", func(t *testing.T) {
w, err := client.Workspaces.Create(ctx, "bar", WorkspaceCreateOptions{
Name: String(fmt.Sprintf("bar-%s", randomString(t))),
TerraformVersion: String("nonexisting"),
})
assert.Nil(t, w)
assert.Error(t, err)
})
t.Run("when options include trigger-patterns (behind a feature flag)", func(t *testing.T) {
// Remove the below organization creation and use the one from the outer scope once the feature flag is removed
orgTest, orgTestCleanup := createOrganizationWithOptions(t, client, OrganizationCreateOptions{
Name: String("tst-" + randomString(t)[0:20] + "-ff-on"),
Email: String(fmt.Sprintf("%s@tfe.local", randomString(t))),
})
t.Cleanup(orgTestCleanup)
options := WorkspaceCreateOptions{
Name: String("foobar"),
FileTriggersEnabled: Bool(true),
TriggerPatterns: []string{"/module-1/**/*", "/**/networking/*"},
}
w, err := client.Workspaces.Create(ctx, orgTest.Name, options)
require.NoError(t, err)
assert.Equal(t, options.TriggerPatterns, w.TriggerPatterns)
// Get a refreshed view from the API.
refreshed, err := client.Workspaces.Read(ctx, orgTest.Name, *options.Name)
require.NoError(t, err)
for _, item := range []*Workspace{
w,
refreshed,
} {
assert.Equal(t, options.TriggerPatterns, item.TriggerPatterns)
}
})
t.Run("when options include both non-empty trigger-patterns and trigger-paths error is returned", func(t *testing.T) {
options := WorkspaceCreateOptions{
Name: String(fmt.Sprintf("foobar-%s", randomString(t))),
FileTriggersEnabled: Bool(true),
TriggerPrefixes: []string{"/module-1", "/module-2"},
TriggerPatterns: []string{"/module-1/**/*", "/**/networking/*"},
}
w, err := client.Workspaces.Create(ctx, orgTest.Name, options)
assert.Nil(t, w)
assert.EqualError(t, err, ErrUnsupportedBothTriggerPatternsAndPrefixes.Error())
})
t.Run("when options include trigger-patterns populated and empty trigger-paths workspace is created", func(t *testing.T) {
// Remove the below organization creation and use the one from the outer scope once the feature flag is removed
orgTest, orgTestCleanup := createOrganizationWithOptions(t, client, OrganizationCreateOptions{
Name: String("tst-" + randomString(t)[0:20] + "-ff-on"),
Email: String(fmt.Sprintf("%s@tfe.local", randomString(t))),
})
t.Cleanup(orgTestCleanup)
options := WorkspaceCreateOptions{
Name: String(fmt.Sprintf("foobar-%s", randomString(t))),
FileTriggersEnabled: Bool(true),
TriggerPrefixes: []string{},
TriggerPatterns: []string{"/module-1/**/*", "/**/networking/*"},
}
w, err := client.Workspaces.Create(ctx, orgTest.Name, options)
require.NoError(t, err)
assert.Equal(t, options.TriggerPatterns, w.TriggerPatterns)
})
t.Run("when organization has a default execution mode", func(t *testing.T) {
defaultExecutionOrgTest, defaultExecutionOrgTestCleanup := createOrganizationWithDefaultAgentPool(t, client)
t.Cleanup(defaultExecutionOrgTestCleanup)
t.Run("with setting overwrites set to false, workspace inherits the default execution mode", func(t *testing.T) {
options := WorkspaceCreateOptions{
Name: String(fmt.Sprintf("tst-agent-cody-banks-%s", randomString(t))),
SettingOverwrites: &WorkspaceSettingOverwritesOptions{
ExecutionMode: Bool(false),
AgentPool: Bool(false),
},
}
w, err := client.Workspaces.Create(ctx, defaultExecutionOrgTest.Name, options)
require.NoError(t, err)
assert.Equal(t, "agent", w.ExecutionMode)
})
t.Run("with setting overwrites set to true, workspace ignores the default execution mode", func(t *testing.T) {
options := WorkspaceCreateOptions{
Name: String(fmt.Sprintf("tst-agent-tony-tanks-%s", randomString(t))),
ExecutionMode: String("local"),
SettingOverwrites: &WorkspaceSettingOverwritesOptions{
ExecutionMode: Bool(true),
AgentPool: Bool(true),
},
}
w, err := client.Workspaces.Create(ctx, defaultExecutionOrgTest.Name, options)
require.NoError(t, err)
assert.Equal(t, "local", w.ExecutionMode)
})
t.Run("when explicitly setting execution mode, workspace ignores the default execution mode", func(t *testing.T) {
options := WorkspaceCreateOptions{
Name: String(fmt.Sprintf("tst-remotely-interesting-workspace-%s", randomString(t))),
ExecutionMode: String("remote"),
}
w, err := client.Workspaces.Create(ctx, defaultExecutionOrgTest.Name, options)
require.NoError(t, err)
assert.Equal(t, "remote", w.ExecutionMode)
})
})
}
func TestWorkspacesRead(t *testing.T) {
client := testClient(t)
ctx := context.Background()
orgTest, orgTestCleanup := createOrganization(t, client)
t.Cleanup(orgTestCleanup)
wTest, wTestCleanup := createWorkspace(t, client, orgTest)
t.Cleanup(wTestCleanup)
t.Run("when the workspace exists", func(t *testing.T) {
w, err := client.Workspaces.Read(ctx, orgTest.Name, wTest.Name)
require.NoError(t, err)
assert.Equal(t, wTest, w)
assert.True(t, w.Permissions.CanDestroy)
assert.NotEmpty(t, w.Actions)
assert.Equal(t, orgTest.Name, w.Organization.Name)
assert.NotEmpty(t, w.CreatedAt)
assert.NotEmpty(t, wTest.SettingOverwrites)
})
t.Run("links are properly decoded", func(t *testing.T) {
w, err := client.Workspaces.Read(ctx, orgTest.Name, wTest.Name)
require.NoError(t, err)
assert.NotEmpty(t, w.Links["self-html"])
assert.Contains(t, w.Links["self-html"], fmt.Sprintf("/app/%s/workspaces/%s", orgTest.Name, wTest.Name))
assert.NotEmpty(t, w.Links["self"])
assert.Contains(t, w.Links["self"], fmt.Sprintf("/api/v2/organizations/%s/workspaces/%s", orgTest.Name, wTest.Name))
})
t.Run("when the workspace does not exist", func(t *testing.T) {
w, err := client.Workspaces.Read(ctx, orgTest.Name, "nonexisting")
assert.Nil(t, w)
assert.Error(t, err)
})
t.Run("when the organization does not exist", func(t *testing.T) {
w, err := client.Workspaces.Read(ctx, "nonexisting", "nonexisting")
assert.Nil(t, w)
assert.Error(t, err)
})
t.Run("without a valid organization", func(t *testing.T) {
w, err := client.Workspaces.Read(ctx, badIdentifier, wTest.Name)
assert.Nil(t, w)
assert.EqualError(t, err, ErrInvalidOrg.Error())
})
t.Run("without a valid workspace", func(t *testing.T) {
w, err := client.Workspaces.Read(ctx, orgTest.Name, badIdentifier)
assert.Nil(t, w)
assert.EqualError(t, err, ErrInvalidWorkspaceValue.Error())
})
t.Run("when workspace is inheriting the default execution mode", func(t *testing.T) {
defaultExecutionOrgTest, defaultExecutionOrgTestCleanup := createOrganizationWithDefaultAgentPool(t, client)
t.Cleanup(defaultExecutionOrgTestCleanup)
options := WorkspaceCreateOptions{
Name: String(fmt.Sprintf("tst-agent-cody-banks-%s", randomString(t))),
SettingOverwrites: &WorkspaceSettingOverwritesOptions{
ExecutionMode: Bool(false),
AgentPool: Bool(false),
},
}