-
Notifications
You must be signed in to change notification settings - Fork 0
/
provider_test.go
646 lines (563 loc) · 16.1 KB
/
provider_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
package cloudfoundry
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"testing"
"time"
"code.cloudfoundry.org/cli/api/cloudcontroller/ccv2"
"code.cloudfoundry.org/cli/api/cloudcontroller/ccv2/constant"
"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3"
"github.com/terraform-providers/terraform-provider-cloudfoundry/cloudfoundry/managers"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
var testAccProviders map[string]*schema.Provider
var testAccProvidersFactories map[string]func() (*schema.Provider, error)
var testAccProvider *schema.Provider
var tstSession *managers.Session
var testOrgID string
var testOrgName string
var testSpaceID string
var testSpaceName string
var helperTest *HelpersTest
func init() {
testAccProvider = Provider()
testAccProviders = map[string]*schema.Provider{
"cloudfoundry": testAccProvider,
}
testAccProvidersFactories = map[string]func() (*schema.Provider, error){
"cloudfoundry": func() (*schema.Provider, error) {
return testAccProvider, nil
},
}
}
func TestProvider(t *testing.T) {
if err := Provider().InternalValidate(); err != nil {
t.Fatalf("err: %s", err)
}
}
func TestProvider_impl(t *testing.T) {
var _ *schema.Provider = Provider()
}
func testAccPreCheck(t *testing.T) {
if !testAccEnvironmentSet() {
t.Fatal("Acceptance environment has not been set.")
}
}
func testAccEnvironmentSet() bool {
endpoint := os.Getenv("CF_API_URL")
user := os.Getenv("CF_USER")
password := os.Getenv("CF_PASSWORD")
if endpoint == "" ||
user == "" ||
password == "" {
fmt.Println("CF_API_URL, CF_USER, CF_PASSWORD, " +
" must be set for acceptance tests to work.")
return false
}
return true
}
func testSession() *managers.Session {
if !testAccEnvironmentSet() {
panic(fmt.Errorf("ERROR! test CF_* environment variables have not been set"))
}
if tstSession == nil {
quotaName := "default"
if os.Getenv("CF_DEFAULT_QUOTA_NAME") != "" {
quotaName = os.Getenv("CF_DEFAULT_QUOTA_NAME")
}
c := managers.Config{
Endpoint: os.Getenv("CF_API_URL"),
User: os.Getenv("CF_USER"),
Password: os.Getenv("CF_PASSWORD"),
CFClientID: os.Getenv("CF_CLIENT_ID"),
CFClientSecret: os.Getenv("CF_CLIENT_SECRET"),
UaaClientID: os.Getenv("CF_UAA_CLIENT_ID"),
UaaClientSecret: os.Getenv("CF_UAA_CLIENT_SECRET"),
DefaultQuotaName: quotaName,
}
c.SkipSslValidation, _ = strconv.ParseBool(os.Getenv("CF_SKIP_SSL_VALIDATION"))
if c.User == "" && c.CFClientID == "" {
panic(fmt.Errorf("Couple of user/password or uaa_client_id/uaa_client_secret must be set"))
}
if c.User != "" && c.CFClientID == "" {
c.CFClientID = "cf"
c.CFClientSecret = ""
}
var (
err error
session *managers.Session
)
if session, err = managers.NewSession(c); err != nil {
fmt.Printf("ERROR! Error creating a new session: %s\n", err.Error())
panic(err.Error())
}
tstSession = session
helperTest = &HelpersTest{tstSession}
}
return tstSession
}
func apiURL() string {
return os.Getenv("CF_API_URL")
}
func defaultSysDomain() (domain string) {
apiURL := apiURL()
return apiURL[strings.Index(apiURL, ".")+1:]
}
func defaultAppDomain() (domain string) {
if domain = os.Getenv("TEST_APP_DOMAIN"); len(domain) == 0 {
domain = defaultSysDomain()
}
return domain
}
func defaultBaseDir() string {
_, file, _, _ := runtime.Caller(1)
return filepath.Dir(filepath.Dir(file))
}
func testDir() string {
return filepath.Join(defaultBaseDir(), "tests")
}
func assetDir() string {
return filepath.Join(testDir(), "cf-acceptance-tests", "assets")
}
func asset(a ...string) string {
return filepath.Join(assetDir(), filepath.Join(a...))
}
func defaultTestOrg(t *testing.T) (string, string) {
testOrgName := os.Getenv("TEST_ORG_NAME")
if len(testOrgName) > 0 {
var (
err error
orgs []ccv2.Organization
)
session := testSession()
client := session.ClientV2
if orgs, _, err = client.GetOrganizations(ccv2.FilterByName(testOrgName)); err != nil {
t.Fatal(err.Error())
}
testOrgID = orgs[0].GUID
} else {
t.Fatal("Environment variable TEST_ORG_NAME must be set for acceptance tests to work.")
}
return testOrgID, testOrgName
}
func defaultTestSpace(t *testing.T) (string, string) {
testSpaceName := os.Getenv("TEST_SPACE_NAME")
if len(testSpaceName) > 0 {
var (
err error
spaces []ccv2.Space
)
orgID, _ := defaultTestOrg(t)
session := testSession()
client := session.ClientV2
if spaces, _, err = client.GetSpaces(
ccv2.FilterByName(testSpaceName),
ccv2.FilterEqual(constant.OrganizationGUIDFilter, orgID),
); err != nil {
t.Fatal(err.Error())
}
testSpaceID = spaces[0].GUID
} else {
t.Fatal("Environment variable TEST_SPACE_NAME must be set for acceptance tests to work.")
}
return testSpaceID, testSpaceName
}
func deleteServiceBroker(name string) {
session := testSession()
client := session.ClientV2
sbs, _, err := client.GetServiceBrokers(ccv2.FilterByName(name))
if err != nil {
panic(err)
}
for _, sb := range sbs {
helperTest.ForceDeleteServiceBroker(sb.GUID)
}
}
func getTestSecurityGroup() string {
defaultAsg := os.Getenv("TEST_DEFAULT_ASG")
if len(defaultAsg) == 0 {
defaultAsg = "public_networks"
}
return defaultAsg
}
func getTestDefaultIsolationSegment(t *testing.T) (string, string) {
if os.Getenv("TEST_DEFAULT_SEGMENT") != "" {
session := testSession()
client := session.ClientV3
segments, _, err := client.GetIsolationSegments(ccv3.Query{
Key: ccv3.NameFilter,
Values: []string{os.Getenv("TEST_DEFAULT_SEGMENT")},
})
if err != nil {
t.Fatal(err.Error())
}
return segments[0].GUID, segments[0].Name
}
t.Fatal("Environment variable TEST_DEFAULT_SEGMENT must be set for acceptance tests to work.")
return "", ""
}
func getTestBrokerCredentials(t *testing.T) (
serviceBrokerURL string,
serviceBrokerUser string,
serviceBrokerPassword string,
serviceBrokerPlanPath string) {
serviceBrokerURL = os.Getenv("TEST_SERVICE_BROKER_URL")
serviceBrokerUser = os.Getenv("TEST_SERVICE_BROKER_USER")
serviceBrokerPassword = os.Getenv("TEST_SERVICE_BROKER_PASSWORD")
serviceBrokerPlanPath = os.Getenv("TEST_SERVICE_PLAN_PATH")
if len(serviceBrokerURL) == 0 ||
len(serviceBrokerUser) == 0 ||
len(serviceBrokerPassword) == 0 ||
len(serviceBrokerPlanPath) == 0 {
t.Fatal("TEST_SERVICE_BROKER_URL, TEST_SERVICE_BROKER_USER, TEST_SERVICE_BROKER_PASSWORD " +
"and TEST_SERVICE_PLAN_PATH must be set for acceptance tests to work.")
}
return
}
func getTestServiceBrokers(t *testing.T) (
serviceName1 string,
serviceName2 string,
servicePlan string) {
serviceName1 = os.Getenv("TEST_SERVICE_1")
serviceName2 = os.Getenv("TEST_SERVICE_2")
servicePlan = os.Getenv("TEST_SERVICE_PLAN")
if len(serviceName1) == 0 ||
len(serviceName2) == 0 ||
len(servicePlan) == 0 {
t.Fatal("TEST_SERVICE_1, TEST_SERVICE_2 and TEST_SERVICE_PLAN must be set for acceptance tests to work.")
}
return serviceName1, serviceName2, servicePlan
}
// func assertContains(str string, list []string) bool {
// for _, s := range list {
// if str == s {
// return true
// }
// }
// return false
// }
func assertSame(actual interface{}, expected interface{}) error {
if actual != expected {
return fmt.Errorf("expected '%s' found '%s' ", expected, actual)
}
return nil
}
func assertEquals(attributes map[string]string,
key string, expected interface{}) error {
v, ok := attributes[key]
expectedValue := reflect.ValueOf(expected)
if ok {
var s string
if expectedValue.Kind() == reflect.Ptr {
if expectedValue.IsNil() {
return fmt.Errorf("expected resource '%s' to not be present but it was '%s'", key, v)
}
expectedValueContent := reflect.Indirect(reflect.ValueOf(expected))
switch expectedValueContent.Kind() {
case reflect.String:
s = expectedValueContent.String()
case reflect.Int:
s = fmt.Sprintf("%d", expectedValueContent.Int())
case reflect.Bool:
s = fmt.Sprintf("%t", expectedValueContent.Bool())
default:
return fmt.Errorf("unable to determine underlying content of expected value: %s", expectedValueContent.Kind())
}
} else {
switch expected.(type) {
case string:
s = fmt.Sprintf("%s", expected)
case int:
s = fmt.Sprintf("%d", expected)
case bool:
s = fmt.Sprintf("%t", expected)
default:
s = fmt.Sprintf("%v", expected)
}
}
if v != s {
return fmt.Errorf("expected resource '%s' to be '%s' but it was '%s'", key, expected, v)
}
} else if expectedValue.Kind() == reflect.Ptr && !expectedValue.IsNil() {
return fmt.Errorf("expected resource '%s' to be '%s' but it was not present", key, reflect.Indirect(reflect.ValueOf(expected)))
}
return nil
}
func assertListEquals(attributes map[string]string,
key string, actualLen int,
match func(map[string]string, int) bool) (err error) {
var n int
num := attributes[key+".#"]
if len(num) > 0 {
n, err = strconv.Atoi(num)
if err != nil {
return
}
} else {
n = 0
}
if actualLen > 0 && n == 0 {
return fmt.Errorf(
"expected resource '%s' to be empty but it has '%d' elements", key, actualLen)
}
if actualLen != n {
return fmt.Errorf(
"expected resource '%s' to have '%d' elements but it has '%d' elements",
key, n, actualLen)
}
if n > 0 {
found := 0
var (
values map[string]string
ok bool
)
keyValues := make(map[string]map[string]string)
for k, v := range attributes {
keyParts := strings.Split(k, ".")
if key == keyParts[0] && keyParts[1] != "#" {
i := keyParts[1]
if values, ok = keyValues[i]; !ok {
values = make(map[string]string)
keyValues[i] = values
}
if len(keyParts) == 2 {
values["value"] = v
} else {
values[strings.Join(keyParts[2:], ".")] = v
}
}
}
for _, values := range keyValues {
for j := 0; j < actualLen; j++ {
if match(values, j) {
found++
break
}
}
}
if n != found {
return fmt.Errorf(
"expected list resource '%s' to match '%d' elements but matched only '%d' elements",
key, n, found)
}
}
return nil
}
func assertSetEquals(
attributes map[string]string,
key string,
expected []interface{}) (err error) {
var n int
num := attributes[key+".#"]
if len(num) > 0 {
n, err = strconv.Atoi(num)
if err != nil {
return err
}
} else {
n = 0
}
if len(expected) > 0 && n == 0 {
return fmt.Errorf(
"expected resource '%s' to be '%v' but it was empty", key, expected)
}
if len(expected) != n {
return fmt.Errorf(
"expected resource '%s' to have '%d' elements but it has '%d' elements",
key, len(expected), n)
}
if n > 0 {
found := 0
for i, _ := range expected {
if _, ok := attributes[key+"."+strconv.Itoa(i)]; ok {
found++
}
}
if n != found {
return fmt.Errorf(
"expected set resource '%s' to have elements '%v' but matched only '%d' elements",
key, expected, found)
}
}
return err
}
func assertMapEquals(key string, attributes map[string]string, actual map[string]interface{}) error {
expected := make(map[string]interface{})
for k, v := range attributes {
keyParts := strings.Split(k, ".")
if keyParts[0] == key && keyParts[1] != "%" {
l := len(keyParts)
m := expected
for _, kk := range keyParts[1 : l-1] {
if _, ok := m[kk]; !ok {
m[kk] = make(map[string]interface{})
}
m = m[kk].(map[string]interface{})
}
m[keyParts[l-1]] = v
}
}
normExpected := normalizeMap(expected, make(map[string]interface{}), "", "_")
normActual := normalizeMap(actual, make(map[string]interface{}), "", "_")
if !reflect.DeepEqual(normExpected, normActual) {
return fmt.Errorf("map with key '%s' expected to be:\n%# v\nbut was:%# v", key, expected, actual)
}
return nil
}
func assertHTTPResponse(url string, expectedStatusCode int, expectedResponses *[]string) error {
client := testSession().HttpClient
var finalErr error
// this assert is used to get on a route from gorouter
// delay and retry is necessary in case of the route not yet registered in gorouter
fn := func(url string, expectedStatusCode int, expectedResponses *[]string) error {
finalErr = nil
time.Sleep(1 * time.Second)
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if expectedStatusCode != resp.StatusCode {
return fmt.Errorf(
"expected response status code from url '%s' to be '%d', but actual was: %s",
url, expectedStatusCode, resp.Status)
}
if expectedResponses != nil {
in := resp.Body
out := bytes.NewBuffer(nil)
if _, err = io.Copy(out, in); err != nil {
return err
}
content := out.String()
found := false
for _, e := range *expectedResponses {
if e == content {
found = true
break
}
}
if !found {
return fmt.Errorf(
"expected response from url '%s' to be one of '%v', but actual was '%s'",
url, *expectedResponses, content)
}
}
return nil
}
for i := 0; i < 9; i++ {
err := fn(url, expectedStatusCode, expectedResponses)
if err != nil {
finalErr = err
continue
}
}
return finalErr
}
func TestMain(m *testing.M) {
fmt.Println("Running pre-hook...")
// defer and os.Exit are not friends :(
clean := make([]func(), 0)
// Create binary_buildpack if not found in cf
// This is used for cloudfoundry_app test and other test needing dummy-app.zip
bps, _, err := testSession().ClientV2.GetBuildpacks(ccv2.FilterByName("binary_buildpack"))
if err != nil {
panic(err)
}
if len(bps) == 0 {
fmt.Println("Creating binary_buildpack ...")
bp, _, err := testSession().ClientV2.CreateBuildpack(ccv2.Buildpack{
Name: "binary_buildpack",
Enabled: BoolToNullBool(true),
})
if err != nil {
panic(err)
}
err = testSession().BitsManager.UploadBuildpack(bp.GUID, asset("buildpacks", "binary_buildpack-cached-v1.0.32.zip"))
if err != nil {
panic(err)
}
clean = append(clean, func() {
fmt.Println("Deleting binary_buildpack ...")
_, err := testSession().ClientV2.DeleteBuildpack(bp.GUID)
if err != nil {
panic(err)
}
})
}
// if os.Getenv("DISABLE_ISOLATION_SEGMENTS") == "" {
// fmt.Println("Creating isolation segment segment-acc-tf ...")
// segment, _, err := testSession().ClientV3.CreateIsolationSegment(ccv3.IsolationSegment{
// Name: "segment-acc-tf",
// })
// if err != nil {
// if strings.Contains(err.Error(), "must be unique") {
// segments, _, err := testSession().ClientV3.GetIsolationSegments(ccv3.Query{Key: ccv3.NameFilter, Values: []string{"segment-acc-tf"}})
// if err != nil {
// panic(err)
// }
// segment = segments[0]
// } else {
// panic(err)
// }
// }
// os.Setenv("TEST_DEFAULT_SEGMENT", segment.Name)
// clean = append(clean, func() {
// fmt.Println("Deleting isolation segment segment-acc-tf ...")
// _, err := testSession().ClientV3.DeleteIsolationSegment(segment.GUID)
// if err != nil {
// panic(err)
// }
// })
// if os.Getenv("TF_ACC_CREATE") != "" {
// fmt.Println("Creating org tf-acc-org ...")
// org, _, err := testSession().ClientV2.CreateOrganization("tf-acc-org", "")
// if err != nil {
// panic(err)
// }
// os.Setenv("TEST_ORG_NAME", org.Name)
// clean = append(clean, func() {
// fmt.Println("Deleting org tf-acc-org ...")
// j, _, err := testSession().ClientV2.DeleteOrganization(org.GUID)
// if err != nil {
// panic(err)
// }
// _, err = testSession().ClientV2.PollJob(j)
// if err != nil {
// panic(err)
// }
// })
// fmt.Println("Creating space tf-acc-space ...")
// space, _, err := testSession().ClientV2.CreateSpace("tf-acc-space", org.GUID)
// if err != nil {
// panic(err)
// }
// os.Setenv("TEST_SPACE_NAME", space.Name)
// clean = append(clean, func() {
// fmt.Println("Deleting space tf-acc-space ...")
// j, _, err := testSession().ClientV2.DeleteSpace(space.GUID)
// if err != nil {
// panic(err)
// }
// _, err = testSession().ClientV2.PollJob(j)
// if err != nil {
// panic(err)
// }
// })
// }
// }
fmt.Println("Finished running pre-hook.")
exitCode := m.Run()
fmt.Println("Running post-hook...")
for i := len(clean) - 1; i >= 0; i-- {
clean[i]()
}
fmt.Println("Finished running post-hook.")
os.Exit(exitCode)
}