Skip to content

Conversation

@NelsonBN
Copy link
Contributor

@NelsonBN NelsonBN commented Jan 17, 2026

What does this PR do?

Added a new method to retrieve the HTTP connection string from Azure Service Bus.

Why is it important?

Azure Service Bus released a new version of the emulator image with support for ServiceBusAdministrationClient when the connection is made through the HTTP endpoint. So it's useful to have a method to build it based on the internal state of the container

Announcement
ConnectionStrings

How to test this PR

var adminClient = new ServiceBusAdministrationClient(_serviceBusContainer.GetHttpConnectionString());
await adminClient.CreateQueueAsync(new CreateQueueOptions("<queue-name>"));

Summary by CodeRabbit

  • New Features

    • Added a public method that returns an HTTP-style Service Bus connection string (includes HTTP port and related fields).
  • Tests

    • Added integration tests for Service Bus administration and runtime: create queue, send/receive message, end-to-end verification.
    • Added a global using for Service Bus administration APIs in the test project.
    • Strengthened tests with a null-check for received messages before asserting payload.

✏️ Tip: You can customize this high-level summary in your review settings.

Copilot AI review requested due to automatic review settings January 17, 2026 00:11
@netlify
Copy link

netlify bot commented Jan 17, 2026

Deploy Preview for testcontainers-dotnet ready!

Name Link
🔨 Latest commit 39e4ecd
🔍 Latest deploy log https://app.netlify.com/projects/testcontainers-dotnet/deploys/696b808db01daa0008157c57
😎 Deploy Preview https://deploy-preview-1622--testcontainers-dotnet.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link

coderabbitai bot commented Jan 17, 2026

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds ServiceBusContainer.GetHttpConnectionString(), constructs an HTTP-style Service Bus connection string, adds integration tests that create a queue via ServiceBusAdministrationClient and exchange messages using ServiceBusClient, and adds a global using for ServiceBus administration types; a test also adds a null-check for received messages.

Changes

Cohort / File(s) Summary
Service Bus Container Enhancement
src/Testcontainers.ServiceBus/ServiceBusContainer.cs
Adds public string GetHttpConnectionString() that builds an HTTP-style Service Bus connection string using Endpoint (sb scheme + HTTP port), SharedAccessKeyName, SharedAccessKey, and UseDevelopmentEmulator, returned as a semicolon-delimited string.
Service Bus Administration Integration Tests
tests/Testcontainers.ServiceBus.Tests/ServiceBusAdministrationClientTest.cs
Adds abstract test base ServiceBusAdministrationClientTest : IAsyncLifetime with lifecycle handling and CreateQueueViaServiceBusAdministrationClient which uses ServiceBusAdministrationClient to create a queue, then ServiceBusClient to send/receive a message; includes concrete subclass wired to container image.
Test Project Usings
tests/Testcontainers.ServiceBus.Tests/Usings.cs
Adds a global using for Azure.Messaging.ServiceBus.Administration.
Service Bus Container Tests
tests/Testcontainers.ServiceBus.Tests/ServiceBusContainerTest.cs
Adds a null-check assertion for the received message before validating its body to avoid null-reference failures.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Flow
    participant Container as ServiceBus Container
    participant Admin as ServiceBusAdministrationClient
    participant Client as ServiceBusClient

    Test->>Container: Start container
    Note over Container: GetHttpConnectionString() returns HTTP-style connection string
    Test->>Admin: Initialize administration client using HTTP conn str
    Admin->>Admin: Create queue via admin API
    Admin-->>Test: Queue created
    Note over Test,Client: Use AMQP connection string for runtime client
    Test->>Client: Initialize ServiceBusClient (AMQP)
    Test->>Client: Send message to queue
    Client-->>Test: Message sent
    Test->>Client: Create receiver and receive message
    Client-->>Test: Received message
    Test->>Test: Assert received message is not null and payload matches
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

enhancement

Poem

🐇 I nibble bytes beneath the moon,
I craft an HTTP string in tune.
Queues arise with gentle cheer,
Messages hop and then appear,
A rabbit claps — tests pass soon!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: adding a method to get an HTTP connection string for Service Bus, which aligns with the primary modification in the changeset.
Description check ✅ Passed The description covers the mandatory 'What does this PR do?' and 'Why is it important?' sections with clear explanations. It includes relevant links to Microsoft documentation and provides a concrete usage example in the 'How to test this PR' section.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@tests/Testcontainers.ServiceBus.Tests/ServiceBusAdministrationClientTest.cs`:
- Around line 35-43: Rename the nested test class
ServiceBusDefaultMsSqlConfiguration to remove the mistaken "MsSql" token (e.g.,
ServiceBusDefaultConfiguration) and update any references; locate the class
declaration and its constructor that call new ServiceBusBuilder(...) and change
the type name accordingly so the class name matches the Service Bus test context
and avoids the copy-paste artifact.
- Around line 59-64: The adminClient, sender, and receiver are not being
disposed; since ServiceBusAdministrationClient, ServiceBusSender, and
ServiceBusReceiver implement IAsyncDisposable, replace their declarations with
asynchronous disposals (e.g. use "await using var adminClient = new
ServiceBusAdministrationClient(...)", "await using var sender =
client.CreateSender(queueName)", and "await using var receiver =
client.CreateReceiver(queueName)") so they are properly disposed before exiting
the test; ensure disposal happens before the existing "await using var client =
new ServiceBusClient(...)" scope ends.
🧹 Nitpick comments (2)
src/Testcontainers.ServiceBus/ServiceBusContainer.cs (1)

35-43: LGTM! Consider extracting shared logic to reduce duplication.

The method correctly builds the HTTP connection string using the appropriate ServiceBusHttpPort. The implementation mirrors GetConnectionString() with only the scheme and port differing.

♻️ Optional: Extract shared logic
+    private string BuildConnectionString(string scheme, int port)
+    {
+        var properties = new Dictionary<string, string>
+        {
+            { "Endpoint", new UriBuilder(scheme, Hostname, GetMappedPublicPort(port)).ToString() },
+            { "SharedAccessKeyName", "RootManageSharedAccessKey" },
+            { "SharedAccessKey", "SAS_KEY_VALUE" },
+            { "UseDevelopmentEmulator", "true" }
+        };
+        return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value)));
+    }
+
     public string GetConnectionString()
-    {
-        var properties = new Dictionary<string, string>();
-        properties.Add("Endpoint", new UriBuilder("amqp", Hostname, GetMappedPublicPort(ServiceBusBuilder.ServiceBusPort)).ToString());
-        properties.Add("SharedAccessKeyName", "RootManageSharedAccessKey");
-        properties.Add("SharedAccessKey", "SAS_KEY_VALUE");
-        properties.Add("UseDevelopmentEmulator", "true");
-        return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value)));
-    }
+        => BuildConnectionString("amqp", ServiceBusBuilder.ServiceBusPort);

     public string GetHttpConnectionString()
-    {
-        var properties = new Dictionary<string, string>();
-        properties.Add("Endpoint", new UriBuilder("sb", Hostname, GetMappedPublicPort(ServiceBusBuilder.ServiceBusHttpPort)).ToString());
-        properties.Add("SharedAccessKeyName", "RootManageSharedAccessKey");
-        properties.Add("SharedAccessKey", "SAS_KEY_VALUE");
-        properties.Add("UseDevelopmentEmulator", "true");
-        return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value)));
-    }
+        => BuildConnectionString("sb", ServiceBusBuilder.ServiceBusHttpPort);
tests/Testcontainers.ServiceBus.Tests/ServiceBusAdministrationClientTest.cs (1)

20-26: GC.SuppressFinalize is unnecessary without a finalizer.

This class doesn't define a finalizer (~destructor), so calling GC.SuppressFinalize(this) has no effect. Consider removing it for clarity.

♻️ Simplified disposal
     public async ValueTask DisposeAsync()
     {
         await DisposeAsyncCore()
             .ConfigureAwait(false);
-
-        GC.SuppressFinalize(this);
     }

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds support for retrieving HTTP connection strings from the Azure Service Bus container, enabling the use of ServiceBusAdministrationClient with the emulator's newly supported HTTP endpoint. This is aligned with recent Azure Service Bus emulator updates that now support administration operations via HTTP.

Changes:

  • Added GetHttpConnectionString() method to ServiceBusContainer that returns an HTTP-based connection string (using "sb" scheme and port 5300)
  • Added comprehensive test coverage for the new method with ServiceBusAdministrationClientTest demonstrating queue creation via the admin client

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 7 comments.

File Description
src/Testcontainers.ServiceBus/ServiceBusContainer.cs Adds new GetHttpConnectionString() method that constructs HTTP connection strings for ServiceBusAdministrationClient usage
tests/Testcontainers.ServiceBus.Tests/ServiceBusAdministrationClientTest.cs New test file demonstrating HTTP connection string usage with ServiceBusAdministrationClient for queue creation

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

NelsonBN and others added 7 commits January 17, 2026 01:15
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@tests/Testcontainers.ServiceBus.Tests/ServiceBusAdministrationClientTest.cs`:
- Around line 54-58: The test assumes receiver.ReceiveMessageAsync(...) always
returns a message; guard against null to avoid flakiness by checking the
receivedMessage variable returned from ReceiveMessageAsync (using
TestContext.Current.CancellationToken) before asserting its Body: if
receivedMessage is null, fail the test with a clear message (or Retry/timeout
accordingly) instead of dereferencing it in Assert.Equal(helloServiceBus,
receivedMessage.Body.ToString()); update the assertion block around
receivedMessage to handle the null case explicitly.
♻️ Duplicate comments (2)
tests/Testcontainers.ServiceBus.Tests/ServiceBusAdministrationClientTest.cs (2)

40-45: Dispose sender/receiver to avoid leaked AMQP links.

ServiceBusSender and ServiceBusReceiver are disposable resources; they should be disposed when the test completes.

♻️ Proposed fix
-    var sender = client.CreateSender(queueName);
+    await using var sender = client.CreateSender(queueName);

-    var receiver = client.CreateReceiver(queueName);
+    await using var receiver = client.CreateReceiver(queueName);
Azure.Messaging.ServiceBus ServiceBusSender ServiceBusReceiver IAsyncDisposable

66-72: Rename the MsSql-suffixed nested class.

The name appears to be a copy‑paste artifact and doesn’t match the Service Bus context.

✏️ Proposed fix
-    public sealed class ServiceBusDefaultMsSqlConfiguration : ServiceBusAdministrationClientTest
+    public sealed class ServiceBusDefaultConfiguration : ServiceBusAdministrationClientTest
     {
-        public ServiceBusDefaultMsSqlConfiguration()
+        public ServiceBusDefaultConfiguration()
             : base(new ServiceBusBuilder(TestSession.GetImageFromDockerfile())
                 .WithAcceptLicenseAgreement(true)
                 .Build())

@HofmeisterAn HofmeisterAn changed the title feat(ServiceBusContainer): add method to get HTTP connection string feat(ServiceBus): Add method to get HTTP connection string Jan 17, 2026
@HofmeisterAn HofmeisterAn added the enhancement New feature or request label Jan 17, 2026
Copy link
Collaborator

@HofmeisterAn HofmeisterAn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot! Unfortunately, we've had quite a few issues with the recent (latest) releases/versions of Event Hubs and Service Bus (Azure/azure-event-hubs-emulator-installer#69 (comment))...

@HofmeisterAn HofmeisterAn merged commit 568b975 into testcontainers:develop Jan 17, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants