This repository has been archived by the owner on Oct 12, 2023. It is now read-only.
/
test.go
217 lines (190 loc) · 6.66 KB
/
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
package test
// MIT License
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
import (
"context"
"io"
"math/rand"
"os"
"time"
"github.com/Azure/azure-amqp-common-go/v3/conn"
rm "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources"
sbmgmt "github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/joho/godotenv"
"github.com/stretchr/testify/suite"
)
type (
// BaseSuite encapsulates a end to end test of Service Bus with build up and tear down of all SB resources
BaseSuite struct {
suite.Suite
TenantID string
SubscriptionID string
ClientID string
ClientSecret string
ConnStr string
Location string
Namespace string
ResourceGroup string
Token *adal.ServicePrincipalToken
Environment azure.Environment
TagID string
closer io.Closer
}
)
var (
letterRunes = []rune("abcdefghijklmnopqrstuvwxyz123456789")
)
func init() {
rand.Seed(time.Now().Unix())
}
// SetupSuite prepares the test suite and provisions a standard Service Bus Namespace
func (suite *BaseSuite) SetupSuite() {
if err := godotenv.Load(); err != nil {
suite.T().Log(err)
}
setFromEnv := func(key string, target *string) {
v := os.Getenv(key)
if v == "" {
suite.FailNowf("missing environment variable", "%q required for integration tests.", key)
}
*target = v
}
setFromEnv("AZURE_TENANT_ID", &suite.TenantID)
setFromEnv("AZURE_SUBSCRIPTION_ID", &suite.SubscriptionID)
setFromEnv("AZURE_CLIENT_ID", &suite.ClientID)
setFromEnv("AZURE_CLIENT_SECRET", &suite.ClientSecret)
setFromEnv("SERVICEBUS_CONNECTION_STRING", &suite.ConnStr)
setFromEnv("TEST_SERVICEBUS_RESOURCE_GROUP", &suite.ResourceGroup)
// TODO: automatically infer the location from the resource group, if it's not specified.
// https://github.com/Azure/azure-service-bus-go/issues/40
setFromEnv("TEST_SERVICEBUS_LOCATION", &suite.Location)
parsed, err := conn.ParsedConnectionFromStr(suite.ConnStr)
if !suite.NoError(err) {
suite.FailNowf("connection string could not be parsed", "Connection String: %q", suite.ConnStr)
}
suite.Namespace = parsed.Namespace
suite.Token = suite.servicePrincipalToken()
suite.Environment = azure.PublicCloud
suite.TagID = RandomString("tag", 10)
//suite.setupTracing()
if !suite.NoError(suite.ensureProvisioned(sbmgmt.SkuTierStandard)) {
suite.FailNow("failed to ensure provisioned")
}
}
// TearDownSuite destroys created resources during the run of the suite
func (suite *BaseSuite) TearDownSuite() {
if suite.closer != nil {
_ = suite.closer.Close()
}
}
func (suite *BaseSuite) servicePrincipalToken() *adal.ServicePrincipalToken {
oauthConfig, err := adal.NewOAuthConfig(azure.PublicCloud.ActiveDirectoryEndpoint, suite.TenantID)
if err != nil {
suite.T().Fatal(err)
}
tokenProvider, err := adal.NewServicePrincipalToken(*oauthConfig,
suite.ClientID,
suite.ClientSecret,
azure.PublicCloud.ResourceManagerEndpoint)
if err != nil {
suite.T().Fatal(err)
}
return tokenProvider
}
func (suite *BaseSuite) getRmGroupClient() *rm.GroupsClient {
groupsClient := rm.NewGroupsClient(suite.SubscriptionID)
groupsClient.Authorizer = autorest.NewBearerAuthorizer(suite.Token)
return &groupsClient
}
func (suite *BaseSuite) getNamespaceClient() *sbmgmt.NamespacesClient {
nsClient := sbmgmt.NewNamespacesClient(suite.SubscriptionID)
nsClient.Authorizer = autorest.NewBearerAuthorizer(suite.Token)
return &nsClient
}
func (suite *BaseSuite) ensureProvisioned(tier sbmgmt.SkuTier) error {
groupsClient := suite.getRmGroupClient()
_, err := groupsClient.CreateOrUpdate(context.Background(), suite.ResourceGroup, rm.Group{Location: &suite.Location})
if err != nil {
return err
}
nsClient := suite.getNamespaceClient()
_, err = nsClient.Get(context.Background(), suite.ResourceGroup, suite.Namespace)
if err != nil {
ns := sbmgmt.SBNamespace{
Sku: &sbmgmt.SBSku{
Name: sbmgmt.SkuName(tier),
Tier: tier,
},
Location: &suite.Location,
}
res, err := nsClient.CreateOrUpdate(context.Background(), suite.ResourceGroup, suite.Namespace, ns)
if err != nil {
return err
}
return res.WaitForCompletionRef(context.Background(), nsClient.Client)
}
return nil
}
//func (suite *BaseSuite) setupTracing() error {
// if os.Getenv("TRACING") == "true" {
// // Sample configuration for testing. Use constant sampling to sample every trace
// // and enable LogSpan to log every span via configured Logger.
// cfg := config.Configuration{
// Sampler: &config.SamplerConfig{
// Type: jaeger.SamplerTypeConst,
// Param: 1,
// },
// Reporter: &config.ReporterConfig{
// LocalAgentHostPort: "0.0.0.0:6831",
// },
// }
//
// // Example logger and metrics factory. Use github.com/uber/jaeger-client-go/log
// // and github.com/uber/jaeger-lib/metrics respectively to bind to real logging and metrics
// // frameworks.
// jLogger := jaegerlog.StdLogger
//
// closer, err := cfg.InitGlobalTracer(
// "ehtests",
// config.Logger(jLogger),
// )
//
// suite.closer = closer
// return err
// }
// return nil
//}
// RandomName generates a random Event Hub name tagged with the suite id
func (suite *BaseSuite) RandomName(prefix string, length int) string {
return RandomString(prefix, length) + "-" + suite.TagID
}
// RandomString generates a random string with prefix
func RandomString(prefix string, length int) string {
b := make([]rune, length)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return prefix + string(b)
}