/
test_utils.go
100 lines (82 loc) · 2.24 KB
/
test_utils.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
package testutils
import (
"context"
"errors"
"fmt"
"github.com/Juniper/apstra-go-sdk/apstra"
"github.com/Juniper/terraform-provider-apstra/apstra/utils"
"github.com/hashicorp/hcl/v2/hclsimple"
"net/http"
"os"
"path/filepath"
"sync"
"testing"
"time"
)
const (
testConfigFile = "../.testconfig.hcl"
timeout = 60 * time.Second // probably should be added to env vars and to test hcl file
)
var sharedClient *apstra.Client
var testClientMutex sync.Mutex
type testConfig struct {
Url string `hcl:"url,optional"`
Username string `hcl:"username,optional"`
Password string `hcl:"password,optional"`
}
func GetTestClient(t testing.TB, ctx context.Context) *apstra.Client {
t.Helper()
testClientMutex.Lock()
defer testClientMutex.Unlock()
if sharedClient == nil {
err := testCfgFileToEnv()
if err != nil {
t.Fatal(err)
}
clientCfg, err := utils.NewClientConfig("")
if err != nil {
t.Fatal(err)
}
clientCfg.Timeout = timeout
clientCfg.Experimental = true
clientCfg.HttpClient.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true
sharedClient, err = clientCfg.NewClient(ctx)
if err != nil {
t.Fatal(err)
}
}
return sharedClient
}
func testCfgFileToEnv() error {
absPath, err := filepath.Abs(testConfigFile)
if err != nil {
return fmt.Errorf("error expanding config file path %s - %w", testConfigFile, err)
}
if _, err = os.Stat(absPath); errors.Is(err, os.ErrNotExist) {
return nil
}
testCfg := new(testConfig)
err = hclsimple.DecodeFile(absPath, nil, testCfg)
if err != nil {
return fmt.Errorf("failed to parse configuration from %q - %w", absPath, err)
}
if testCfg.Url != "" {
err = os.Setenv(utils.EnvApstraUrl, testCfg.Url)
if err != nil {
return fmt.Errorf("failed setting environment variable %q - %w", utils.EnvApstraUrl, err)
}
}
if testCfg.Username != "" {
err = os.Setenv(utils.EnvApstraUsername, testCfg.Username)
if err != nil {
return fmt.Errorf("failed setting environment variable %q - %w", utils.EnvApstraUsername, err)
}
}
if testCfg.Password != "" {
err = os.Setenv(utils.EnvApstraPassword, testCfg.Password)
if err != nil {
return fmt.Errorf("failed setting environment variable %q - %w", utils.EnvApstraPassword, err)
}
}
return nil
}