Debian Codegraph @

pubsub/azuresb/azuresb_test.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 package azuresb
15
16 import (
17 "context"
18 "fmt"
19 "os"
20 "strings"
21 "sync/atomic"
22 "testing"
23
24 "gocloud.dev/internal/testing/setup"
25 "gocloud.dev/pubsub"
26 "gocloud.dev/pubsub/driver"
27 "gocloud.dev/pubsub/drivertest"
28
29 "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
30 servicebus "github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus"
31 "github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/admin"
32 )
33
34 var (
35 // See docs below on how to provision an Azure Service Bus Namespace and obtaining the connection string.
36 // https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues
37 connString = os.Getenv("SERVICEBUS_CONNECTION_STRING")
38 sbHostname = os.Getenv("AZURE_SERVICEBUS_HOSTNAME")
39 )
40
41 const (
42 nonexistentTopicName = "nonexistent-topic"
43
44 // Try to keep the entity name under Azure limits.
45 // https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-quotas
46 // says 50, but there appears to be some additional overhead. 40 works.
47 maxNameLen = 40
48 )
49
50 type harness struct {
51 adminClient *admin.Client
52 sbClient *servicebus.Client
53 numTopics uint32 // atomic
54 numSubs uint32 // atomic
55 closer func()
56 autodelete bool
57 topics map[driver.Topic]string
58 }
59
60 func newHarness(ctx context.Context, t *testing.T) (drivertest.Harness, error) {
61 t.Helper()
62
63 if connString == "" && sbHostname == "" {
64 return nil, fmt.Errorf("azuresb: test harness requires environment variable SERVICEBUS_CONNECTION_STRING or AZURE_SERVICEBUS_HOSTNAME to run")
65 }
66 adminClient, err := admin.NewClientFromConnectionString(connString, nil)
67 if err != nil {
68 return nil, err
69 }
70 sbClient, err := NewClientFromConnectionString(connString, nil)
71 if err != nil {
72 return nil, err
73 }
74 noop := func() {}
75 return &harness{
76 adminClient: adminClient,
77 sbClient: sbClient,
78 closer: noop,
79 topics: map[driver.Topic]string{},
80 }, nil
81 }
82
83 func newHarnessUsingAutodelete(ctx context.Context, t *testing.T) (drivertest.Harness, error) {
84 t.Helper()
85
86 h, err := newHarness(ctx, t)
87 if err == nil {
88 h.(*harness).autodelete = true
89 }
90 return h, err
91 }
92
93 func (h *harness) CreateTopic(ctx context.Context, testName string) (dt driver.Topic, cleanup func(), err error) {
94 topicName := sanitize(fmt.Sprintf("%s-top-%d", testName, atomic.AddUint32(&h.numTopics, 1)))
95 if err := createTopic(ctx, topicName, h.adminClient, nil); err != nil {
96 return nil, nil, err
97 }
98
99 sbSender, err := NewSender(h.sbClient, topicName, nil)
100 dt, err = openTopic(ctx, sbSender, nil)
101 if err != nil {
102 return nil, nil, err
103 }
104 h.topics[dt] = topicName
105 cleanup = func() {
106 sbSender.Close(ctx)
107 deleteTopic(ctx, topicName, h.adminClient)
108 }
109 return dt, cleanup, nil
110 }
111
112 func (h *harness) MakeNonexistentTopic(ctx context.Context) (driver.Topic, error) {
113 sbSender, err := NewSender(h.sbClient, nonexistentTopicName, nil)
114 if err != nil {
115 return nil, err
116 }
117 dt, err := openTopic(ctx, sbSender, nil)
118 if err != nil {
119 return nil, err
120 }
121 h.topics[dt] = nonexistentTopicName
122 return dt, nil
123 }
124
125 func (h *harness) CreateSubscription(ctx context.Context, dt driver.Topic, testName string) (ds driver.Subscription, cleanup func(), err error) {
126 subName := sanitize(fmt.Sprintf("%s-sub-%d", testName, atomic.AddUint32(&h.numSubs, 1)))
127 topicName := h.topics[dt]
128 err = createSubscription(ctx, topicName, subName, h.adminClient, nil)
129 if err != nil {
130 return nil, nil, err
131 }
132
133 var opts servicebus.ReceiverOptions
134 if h.autodelete {
135 opts.ReceiveMode = servicebus.ReceiveModeReceiveAndDelete
136 }
137 sbReceiver, err := NewReceiver(h.sbClient, topicName, subName, &opts)
138 if err != nil {
139 return nil, nil, err
140 }
141
142 sopts := SubscriptionOptions{}
143 if h.autodelete {
144 sopts.ReceiveAndDelete = true
145 }
146 ds, err = openSubscription(ctx, h.sbClient, sbReceiver, &sopts)
147 if err != nil {
148 return nil, nil, err
149 }
150
151 cleanup = func() {
152 sbReceiver.Close(ctx)
153 deleteSubscription(ctx, topicName, subName, h.adminClient)
154 }
155 return ds, cleanup, nil
156 }
157
158 func (h *harness) MakeNonexistentSubscription(ctx context.Context) (driver.Subscription, func(), error) {
159 const topicName = "topic-for-nonexistent-sub"
160 _, cleanup, err := h.CreateTopic(ctx, topicName)
161 if err != nil {
162 return nil, nil, err
163 }
164 sbReceiver, err := NewReceiver(h.sbClient, topicName, "nonexistent-subscription", nil)
165 if err != nil {
166 return nil, cleanup, err
167 }
168 sub, err := openSubscription(ctx, h.sbClient, sbReceiver, nil)
169 return sub, cleanup, err
170 }
171
172 func (h *harness) Close() {
173 h.closer()
174 }
175
176 func (h *harness) MaxBatchSizes() (int, int) { return sendBatcherOpts.MaxBatchSize, 0 }
177
178 func (h *harness) SupportsMultipleSubscriptions() bool { return true }
179
180 // Please run the TestConformance with an extended timeout since each test needs to perform CRUD for ServiceBus Topics and Subscriptions.
181 // Example: C:\Go\bin\go.exe test -timeout 60s gocloud.dev/pubsub/azuresb -run ^TestConformance$
182 func TestConformance(t *testing.T) {
183 if !*setup.Record {
184 t.Skip("replaying is not yet supported for Azure pubsub")
185 }
186 asTests := []drivertest.AsTest{sbAsTest{}}
187 drivertest.RunConformanceTests(t, newHarness, asTests)
188 }
189
190 func TestConformanceWithAutodelete(t *testing.T) {
191 if !*setup.Record {
192 t.Skip("replaying is not yet supported for Azure pubsub")
193 }
194 asTests := []drivertest.AsTest{sbAsTest{}}
195 drivertest.RunConformanceTests(t, newHarnessUsingAutodelete, asTests)
196 }
197
198 type sbAsTest struct{}
199
200 func (sbAsTest) Name() string {
201 return "azure"
202 }
203
204 func (sbAsTest) TopicCheck(topic *pubsub.Topic) error {
205 var t2 servicebus.Sender
206 if topic.As(&t2) {
207 return fmt.Errorf("cast succeeded for %T, want failure", &t2)
208 }
209 var t3 *servicebus.Sender
210 if !topic.As(&t3) {
211 return fmt.Errorf("cast failed for %T", &t3)
212 }
213 return nil
214 }
215
216 func (sbAsTest) SubscriptionCheck(sub *pubsub.Subscription) error {
217 var s2 servicebus.Receiver
218 if sub.As(&s2) {
219 return fmt.Errorf("cast succeeded for %T, want failure", &s2)
220 }
221 var s3 *servicebus.Receiver
222 if !sub.As(&s3) {
223 return fmt.Errorf("cast failed for %T", &s3)
224 }
225 return nil
226 }
227
228 func (sbAsTest) TopicErrorCheck(t *pubsub.Topic, err error) error {
229 return nil
230 }
231
232 func (sbAsTest) SubscriptionErrorCheck(s *pubsub.Subscription, err error) error {
233 return nil
234 }
235
236 func (sbAsTest) MessageCheck(m *pubsub.Message) error {
237 var m2 servicebus.ReceivedMessage
238 if m.As(&m2) {
239 return fmt.Errorf("cast succeeded for %T, want failure", &m2)
240 }
241 var m3 *servicebus.ReceivedMessage
242 if !m.As(&m3) {
243 return fmt.Errorf("cast failed for %T", &m3)
244 }
245 return nil
246 }
247
248 func (sbAsTest) BeforeSend(as func(any) bool) error {
249 var m *servicebus.Message
250 if !as(&m) {
251 return fmt.Errorf("cast failed for %T", &m)
252 }
253 return nil
254 }
255
256 func (sbAsTest) AfterSend(as func(any) bool) error {
257 return nil
258 }
259
260 func sanitize(s string) string {
261 // First trim some not-so-useful strings that are part of all test names.
262 s = strings.Replace(s, "TestConformance/Test", "", 1)
263 s = strings.Replace(s, "TestConformanceWithAutodelete/Test", "", 1)
264 s = strings.Replace(s, "/", "_", -1)
265 if len(s) > maxNameLen {
266 // Drop prefix, not suffix, because suffix includes something to make
267 // entities unique within a test.
268 s = s[len(s)-maxNameLen:]
269 }
270 return s
271 }
272
273 // createTopic ensures the existence of a Service Bus Topic on a given Namespace.
274 func createTopic(ctx context.Context, topicName string, adminClient *admin.Client, properties *admin.TopicProperties) error {
275 t, _ := adminClient.GetTopic(ctx, topicName, nil)
276 if t != nil {
277 _, _ = adminClient.DeleteTopic(ctx, topicName, nil)
278 }
279 opts := admin.CreateTopicOptions{
280 Properties: properties,
281 }
282 _, err := adminClient.CreateTopic(ctx, topicName, &opts)
283 return err
284 }
285
286 // deleteTopic removes a Service Bus Topic on a given Namespace.
287 func deleteTopic(ctx context.Context, topicName string, adminClient *admin.Client) error {
288 t, _ := adminClient.GetTopic(ctx, topicName, nil)
289 if t != nil {
290 _, err := adminClient.DeleteTopic(ctx, topicName, nil)
291 return err
292 }
293 return nil
294 }
295
296 // createSubscription ensures the existence of a Service Bus Subscription on a given Namespace and Topic.
297 func createSubscription(ctx context.Context, topicName, subscriptionName string, adminClient *admin.Client, properties *admin.SubscriptionProperties) error {
298 s, _ := adminClient.GetSubscription(ctx, topicName, subscriptionName, nil)
299 if s != nil {
300 _, _ = adminClient.DeleteSubscription(ctx, topicName, subscriptionName, nil)
301 }
302 opts := admin.CreateSubscriptionOptions{
303 Properties: properties,
304 }
305 _, err := adminClient.CreateSubscription(ctx, topicName, subscriptionName, &opts)
306 return err
307 }
308
309 // deleteSubscription removes a Service Bus Subscription on a given Namespace and Topic.
310 func deleteSubscription(ctx context.Context, topicName, subscriptionName string, adminClient *admin.Client) error {
311 se, _ := adminClient.GetSubscription(ctx, topicName, subscriptionName, nil)
312 if se != nil {
313 _, err := adminClient.DeleteSubscription(ctx, topicName, subscriptionName, nil)
314 return err
315 }
316 return nil
317 }
318
319 // to run test using Azure Entra credentials:
320 // 1. grant access to ${AZURE_CLIENT_ID} to Service Bus namespace
321 // 2. run test:
322 // AZURE_CLIENT_SECRET='secret' \
323 // AZURE_CLIENT_ID=client_id_uud \
324 // AZURE_TENANT_ID=tenant_id_uuid \
325 // AZURE_SERVICEBUS_HOSTNAME=hostname go test -benchmem -run=^$ -bench ^BenchmarkAzureServiceBusPubSub$ gocloud.dev/pubsub/azuresb
326 func BenchmarkAzureServiceBusPubSub(b *testing.B) {
327 const (
328 benchmarkTopicName = "benchmark-topic"
329 benchmarkSubscriptionName = "benchmark-subscription"
330 )
331 ctx := context.Background()
332
333 var adminClient *admin.Client
334 var sbClient *servicebus.Client
335 var err error
336
337 if connString == "" && sbHostname == "" {
338 b.Fatal("azuresb: benchmark requires environment variable SERVICEBUS_CONNECTION_STRING or AZURE_SERVICEBUS_HOSTNAME to run")
339 }
340
341 if connString != "" {
342 adminClient, err = admin.NewClientFromConnectionString(connString, nil)
343 if err != nil {
344 b.Fatal(err)
345 }
346 sbClient, err = NewClientFromConnectionString(connString, nil)
347 if err != nil {
348 b.Fatal(err)
349 }
350 } else if sbHostname != "" {
351 cred, err := azidentity.NewDefaultAzureCredential(nil)
352 if err != nil {
353 b.Fatal(err)
354 }
355 adminClient, err = admin.NewClient(sbHostname, cred, nil)
356 if err != nil {
357 b.Fatal(err)
358 }
359 sbClient, err = NewClientFromServiceBusHostname(sbHostname, nil)
360 if err != nil {
361 b.Fatal(err)
362 }
363 }
364
365 // Make topic.
366 if err := createTopic(ctx, benchmarkTopicName, adminClient, nil); err != nil {
367 b.Fatal(err)
368 }
369 defer deleteTopic(ctx, benchmarkTopicName, adminClient)
370
371 sbSender, err := NewSender(sbClient, benchmarkTopicName, nil)
372 if err != nil {
373 b.Fatal(err)
374 }
375 defer sbSender.Close(ctx)
376 topic, err := OpenTopic(ctx, sbSender, nil)
377 if err != nil {
378 b.Fatal(err)
379 }
380 defer topic.Shutdown(ctx)
381
382 // Make subscription.
383 if err := createSubscription(ctx, benchmarkTopicName, benchmarkSubscriptionName, adminClient, nil); err != nil {
384 b.Fatal(err)
385 }
386 sbReceiver, err := NewReceiver(sbClient, benchmarkTopicName, benchmarkSubscriptionName, nil)
387 if err != nil {
388 b.Fatal(err)
389 }
390 sub, err := OpenSubscription(ctx, sbClient, sbReceiver, nil)
391 if err != nil {
392 b.Fatal(err)
393 }
394 defer sub.Shutdown(ctx)
395
396 drivertest.RunBenchmarks(b, topic, sub)
397 }
398
399 func fakeConnectionStringInEnv() func() {
400 oldEnvVal := os.Getenv("SERVICEBUS_CONNECTION_STRING")
401 os.Setenv("SERVICEBUS_CONNECTION_STRING", "Endpoint=sb://foo.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=mykey")
402 return func() {
403 os.Setenv("SERVICEBUS_CONNECTION_STRING", oldEnvVal)
404 }
405 }
406
407 func TestOpenTopicFromURL(t *testing.T) {
408 cleanup := fakeConnectionStringInEnv()
409 defer cleanup()
410
411 tests := []struct {
412 URL string
413 WantErr bool
414 }{
415 // OK.
416 {"azuresb://mytopic", false},
417 // Invalid parameter.
418 {"azuresb://mytopic?param=value", true},
419 }
420
421 ctx := context.Background()
422 for _, test := range tests {
423 topic, err := pubsub.OpenTopic(ctx, test.URL)
424 if (err != nil) != test.WantErr {
425 t.Errorf("%s: got error %v, want error %v", test.URL, err, test.WantErr)
426 }
427 if topic != nil {
428 topic.Shutdown(ctx)
429 }
430 }
431 }
432
433 func TestOpenSubscriptionFromURL(t *testing.T) {
434 cleanup := fakeConnectionStringInEnv()
435 defer cleanup()
436
437 tests := []struct {
438 URL string
439 WantErr bool
440 }{
441 // OK.
442 {"azuresb://mytopic?subscription=mysub", false},
443 // Missing subscription.
444 {"azuresb://mytopic", true},
445 // Setting listener_timeout.
446 {"azuresb://mytopic?subscription=mysub&listener_timeout=10s", false},
447 // Invalid listener_timeout.
448 {"azuresb://mytopic?subscription=mysub&listener_timeout=xxx", true},
449 // Invalid parameter.
450 {"azuresb://mytopic?subscription=mysub&param=value", true},
451 }
452
453 ctx := context.Background()
454 for _, test := range tests {
455 sub, err := pubsub.OpenSubscription(ctx, test.URL)
456 if (err != nil) != test.WantErr {
457 t.Errorf("%s: got error %v, want error %v", test.URL, err, test.WantErr)
458 }
459 if sub != nil {
460 sub.Shutdown(ctx)
461 }
462 }
463 }