From 2da2080d9761d89189d8db9f52202ca8ca5a0289 Mon Sep 17 00:00:00 2001 From: Andre Hofmeister <9199345+HofmeisterAn@users.noreply.github.com> Date: Fri, 30 Aug 2024 19:32:12 +0200 Subject: [PATCH] docs: Use codeinclude in module examples (#1245) --- docs/examples/aspnet.md | 2 +- docs/modules/_call_out_test_projects.md | 3 + docs/modules/elasticsearch.md | 50 +++-------- docs/modules/index.md | 1 + docs/modules/mongodb.md | 56 +++++-------- docs/modules/mssql.md | 57 ++++--------- docs/modules/neo4j.md | 50 +++-------- docs/modules/postgres.md | 53 +++++------- docs/modules/pulsar.md | 84 +++++-------------- docs/modules/rabbitmq.md | 78 +++-------------- mkdocs.yml | 3 + .../ElasticsearchContainerTest.cs | 2 + .../Testcontainers.Elasticsearch.Tests.csproj | 2 + .../MongoDbContainerTest.cs | 6 ++ .../Testcontainers.MongoDb.Tests.csproj | 2 + .../MsSqlContainerTest.cs | 4 + .../Testcontainers.MsSql.Tests.csproj | 2 + .../Neo4jContainerTest.cs | 2 + .../Testcontainers.Neo4j.Tests.csproj | 2 + .../PostgreSqlContainerTest.cs | 2 + .../Testcontainers.PostgreSql.Tests.csproj | 2 + .../PulsarContainerTest.cs | 39 +++++---- .../Testcontainers.Pulsar.Tests.csproj | 2 + .../RabbitMqContainerTest.cs | 2 + .../Testcontainers.RabbitMq.Tests.csproj | 2 + 25 files changed, 177 insertions(+), 331 deletions(-) create mode 100644 docs/modules/_call_out_test_projects.md diff --git a/docs/examples/aspnet.md b/docs/examples/aspnet.md index 7c5ffda29..dfde6a277 100644 --- a/docs/examples/aspnet.md +++ b/docs/examples/aspnet.md @@ -81,7 +81,7 @@ dotnet add package Testcontainers.MsSql --version 3.0.0 !!! note - The Microsoft SQL Server Docker image is not compatible with ARM devices, such as Macs with Apple Silicon. Instead, you can use the [SqlEdge](https://www.nuget.org/packages/Testcontainers.SqlEdge) module or [Testcontainers Cloud](https://www.testcontainers.cloud/). + When running on Macs with Apple Silicon, make sure that you are using Docker Desktop for macOS version 4.16 or newer, and that the Virtualization Framework is enabled, with Rosetta 2 installed to run [x86-64](https://techcommunity.microsoft.com/t5/sql-server-blog/azure-sql-edge-update-september-2023/ba-p/3930827) based containers. The `WeatherForecastContainer` class configures in the default constructor all dependencies to start the container that hosts our application. diff --git a/docs/modules/_call_out_test_projects.md b/docs/modules/_call_out_test_projects.md new file mode 100644 index 000000000..460d8c855 --- /dev/null +++ b/docs/modules/_call_out_test_projects.md @@ -0,0 +1,3 @@ +!!!tip + + For the complete source code of this example and additional information, please refer to our [test projects](https://github.com/testcontainers/testcontainers-dotnet/tree/develop/tests). \ No newline at end of file diff --git a/docs/modules/elasticsearch.md b/docs/modules/elasticsearch.md index 3d141524d..24c7ffcda 100644 --- a/docs/modules/elasticsearch.md +++ b/docs/modules/elasticsearch.md @@ -2,52 +2,28 @@ [Elasticsearch](https://www.elastic.co/elasticsearch/) is a distributed, RESTful search and analytics engine capable of addressing a growing number of use cases. As the heart of the Elastic Stack, it centrally stores data for lightning fast search, fine‑tuned relevancy, and powerful analytics that scale with ease. -The following example uses the following NuGet packages: +Add the following dependency to your project file: -```console title="Install the NuGet dependencies" +```console title="NuGet" dotnet add package Testcontainers.Elasticsearch -dotnet add package Elastic.Clients.Elasticsearch -dotnet add package xunit ``` -IDEs and editors may also require the following packages to run tests: `xunit.runner.visualstudio` and `Microsoft.NET.Test.Sdk`. +You can start an Elasticsearch container instance from any .NET application. This example uses xUnit.net's `IAsyncLifetime` interface to manage the lifecycle of the container. The container is started in the `InitializeAsync` method before the test method runs, ensuring that the environment is ready for testing. After the test completes, the container is removed in the `DisposeAsync` method. -Copy and paste the following code into a new `.cs` test file within an existing test project. + +[Usage Example](../../tests/Testcontainers.Elasticsearch.Tests/ElasticsearchContainerTest.cs) inside_block:UseElasticsearchContainer + -```csharp -using Elastic.Clients.Elasticsearch; -using Elastic.Transport; -using Testcontainers.Elasticsearch; -using Xunit; +The test example uses the following NuGet dependencies: -public sealed class ElasticsearchContainerTest : IAsyncLifetime -{ - private readonly ElasticsearchContainer _elasticsearch - = new ElasticsearchBuilder().Build(); - - [Fact] - public async Task ReadFromElasticsearch() - { - var settings = new ElasticsearchClientSettings(new Uri(_elasticsearch.GetConnectionString())); - settings.ServerCertificateValidationCallback(CertificateValidations.AllowAll); - - var client = new ElasticsearchClient(settings); - - var stats = await client.PingAsync(); - - Assert.True(stats.IsValidResponse); - } - - public Task InitializeAsync() - => _elasticsearch.StartAsync(); - - public Task DisposeAsync() - => _elasticsearch.DisposeAsync().AsTask(); -} -``` + +[Package References](../../tests/Testcontainers.Elasticsearch.Tests/Testcontainers.Elasticsearch.Tests.csproj) inside_block:PackageReferences + To execute the tests, use the command `dotnet test` from a terminal. +--8<-- "docs/modules/_call_out_test_projects.md" + ## A Note To Developers -The Testcontainers module creates a container that listens to requests over **HTTPS**. To communicate with the Elasticsearch instance, developers must create a `ElasticsearchClientSettings` instance and set the `ServerCertificateValidationCallback` delegate to `CertificateValidations.AllowAll`. Failing to do so will result in a communication failure as the .NET will reject the certificate coming from the container. +The Testcontainers module creates a container that listens to requests over **HTTPS**. To communicate with the Elasticsearch instance, developers must create a `ElasticsearchClientSettings` instance and set the `ServerCertificateValidationCallback` delegate to `CertificateValidations.AllowAll`. Failing to do so will result in a communication failure as the .NET will reject the certificate coming from the container. \ No newline at end of file diff --git a/docs/modules/index.md b/docs/modules/index.md index 2c2cf5ea2..e7455d187 100644 --- a/docs/modules/index.md +++ b/docs/modules/index.md @@ -47,6 +47,7 @@ await moduleNameContainer.StartAsync(); | Kusto emulator | `mcr.microsoft.com/azuredataexplorer/kustainer-linux:latest` | [NuGet](https://www.nuget.org/packages/Testcontainers.Kusto) | [Source](https://github.com/testcontainers/testcontainers-dotnet/tree/develop/src/Testcontainers.Kusto) | | LocalStack | `localstack/localstack:2.0` | [NuGet](https://www.nuget.org/packages/Testcontainers.LocalStack) | [Source](https://github.com/testcontainers/testcontainers-dotnet/tree/develop/src/Testcontainers.LocalStack) | | MariaDB | `mariadb:10.10` | [NuGet](https://www.nuget.org/packages/Testcontainers.MariaDb) | [Source](https://github.com/testcontainers/testcontainers-dotnet/tree/develop/src/Testcontainers.MariaDb) | +| Milvus | `milvusdb/milvus:v2.3.10` | [NuGet](https://www.nuget.org/packages/Testcontainers.Milvus) | [Source](https://github.com/testcontainers/testcontainers-dotnet/tree/develop/src/Testcontainers.Milvus) | | MinIO | `minio/minio:RELEASE.2023-01-31T02-24-19Z` | [NuGet](https://www.nuget.org/packages/Testcontainers.Minio) | [Source](https://github.com/testcontainers/testcontainers-dotnet/tree/develop/src/Testcontainers.Minio) | | MongoDB | `mongo:6.0` | [NuGet](https://www.nuget.org/packages/Testcontainers.MongoDb) | [Source](https://github.com/testcontainers/testcontainers-dotnet/tree/develop/src/Testcontainers.MongoDb) | | MySQL | `mysql:8.0` | [NuGet](https://www.nuget.org/packages/Testcontainers.MySql) | [Source](https://github.com/testcontainers/testcontainers-dotnet/tree/develop/src/Testcontainers.MySql) | diff --git a/docs/modules/mongodb.md b/docs/modules/mongodb.md index 7ebbdc6b1..ff4be3cb8 100644 --- a/docs/modules/mongodb.md +++ b/docs/modules/mongodb.md @@ -2,54 +2,38 @@ [MongoDB](https://www.mongodb.com/what-is-mongodb) is a cross-platform document-oriented database. MongoDB's document model is simple for developers to use within their applications, while still providing all the complex capabilities of traditional relational databases. -The following example uses the following NuGet packages: +Add the following dependency to your project file: -```console title="Install the NuGet dependencies" +```console title="NuGet" dotnet add package Testcontainers.MongoDb -dotnet add package MongoDB.Driver -dotnet add package xunit ``` -IDEs and editors may also require the following packages to run tests: `xunit.runner.visualstudio` and `Microsoft.NET.Test.Sdk`. +You can start a MongoDB container instance from any .NET application. Here, we create different container instances and pass them to the base test class. This allows us to test different configurations. -Copy and paste the following code into a new `.cs` test file within an existing test project. + +[Create Container Instance](../../tests/Testcontainers.MongoDb.Tests/MongoDbContainerTest.cs) inside_block:CreateMongoDbContainer + -```csharp -using MongoDB.Driver; -using Testcontainers.MongoDb; -using Xunit; +This example uses xUnit.net's `IAsyncLifetime` interface to manage the lifecycle of the container. The container is started in the `InitializeAsync` method before the test method runs, ensuring that the environment is ready for testing. After the test completes, the container is removed in the `DisposeAsync` method. -namespace TestcontainersModules; + +[Usage Example](../../tests/Testcontainers.MongoDb.Tests/MongoDbContainerTest.cs) inside_block:UseMongoDbContainer + -public sealed class MongoDbContainerTest : IAsyncLifetime -{ - private readonly MongoDbContainer _mongoDbContainer = - new MongoDbBuilder().Build(); +The test example uses the following NuGet dependencies: - [Fact] - public async Task ReadFromMongoDbDatabase() - { - var client = new MongoClient(_mongoDbContainer.GetConnectionString()); - - using var databases = await client.ListDatabasesAsync(); - - Assert.True(await databases.AnyAsync()); - } - - public Task InitializeAsync() - => _mongoDbContainer.StartAsync(); - - public Task DisposeAsync() - => _mongoDbContainer.DisposeAsync().AsTask(); -} -``` + +[Package References](../../tests/Testcontainers.MongoDb.Tests/Testcontainers.MongoDb.Tests.csproj) inside_block:PackageReferences + To execute the tests, use the command `dotnet test` from a terminal. +--8<-- "docs/modules/_call_out_test_projects.md" + ## MongoDb Replica Set -By default, MongoDB runs as a standalone instance. If your tests require a MongoDB replica set, use the code below which will initialize it as a single-node replica set: +By default, MongoDB runs as a standalone instance. If your tests require a MongoDB replica set, use the following configuration which will initialize a single-node replica set: -```csharp -MongoDbContainer _mongoDbContainer = new MongoDbBuilder().WithReplicaSet().Build(); -``` + +[Replica Set Configuration](../../tests/Testcontainers.MongoDb.Tests/MongoDbContainerTest.cs) inside_block:ReplicaSetContainerConfiguration + \ No newline at end of file diff --git a/docs/modules/mssql.md b/docs/modules/mssql.md index 63ff6c70d..30f4f9bfe 100644 --- a/docs/modules/mssql.md +++ b/docs/modules/mssql.md @@ -1,56 +1,35 @@ # Microsoft SQL Server -[Microsoft SQL Server](https://www.microsoft.com/en-us/sql-server), also known as MSSQL, is a relational database engine developed by Microsoft and is a popular choice in enterprise systems. The following example provides .NET developers with a starting point to use a Microsoft SQL Server instance in the [xUnit][xunit] tests. +[Microsoft SQL Server](https://www.microsoft.com/en-us/sql-server), also known as MSSQL, is a relational database engine developed by Microsoft and is a popular choice in enterprise systems. -The following example uses the following NuGet packages: +Add the following dependency to your project file: -```console title="Install the NuGet dependencies" +```console title="NuGet" dotnet add package Testcontainers.MsSql -dotnet add package Microsoft.Data.SqlClient -dotnet add package xunit ``` -IDEs and editors may also require the following packages to run tests: `xunit.runner.visualstudio` and `Microsoft.NET.Test.Sdk`. +You can start a MSSQL container instance from any .NET application. Here, we create different container instances and pass them to the base test class. This allows us to test different configurations. -Copy and paste the following code into a new `.cs` test file within an existing test project. + +[Create Container Instance](../../tests/Testcontainers.MsSql.Tests/MsSqlContainerTest.cs) inside_block:CreateMsSqlContainer + -```csharp -using Microsoft.Data.SqlClient; -using Testcontainers.MsSql; -using Xunit; +This example uses xUnit.net's `IAsyncLifetime` interface to manage the lifecycle of the container. The container is started in the `InitializeAsync` method before the test method runs, ensuring that the environment is ready for testing. After the test completes, the container is removed in the `DisposeAsync` method. -namespace TestcontainersModules; + +[Usage Example](../../tests/Testcontainers.MsSql.Tests/MsSqlContainerTest.cs) inside_block:UseMsSqlContainer + -public sealed class MsSqlServerContainerTest : IAsyncLifetime -{ - private readonly MsSqlContainer _msSqlContainer - = new MsSqlBuilder().Build(); +The test example uses the following NuGet dependencies: - [Fact] - public async Task ReadFromMsSqlDatabase() - { - await using var connection = new SqlConnection(_msSqlContainer.GetConnectionString()); - await connection.OpenAsync(); - - await using var command = connection.CreateCommand(); - command.CommandText = "SELECT 1;"; - - var actual = await command.ExecuteScalarAsync() as int?; - Assert.Equal(1, actual.GetValueOrDefault()); - } - - public Task InitializeAsync() - => _msSqlContainer.StartAsync(); - - public Task DisposeAsync() - => _msSqlContainer.DisposeAsync().AsTask(); -} -``` + +[Package References](../../tests/Testcontainers.MsSql.Tests/Testcontainers.MsSql.Tests.csproj) inside_block:PackageReferences + To execute the tests, use the command `dotnet test` from a terminal. -## A Note To Developers +--8<-- "docs/modules/_call_out_test_projects.md" -Once Testcontainers creates a server instance, developers may use the connection string with any of the popular data-access technologies found in the .NET Ecosystem. Some of these libraries include [Entity Framework Core](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore), [Dapper](https://www.nuget.org/packages/Dapper), and [NHibernate](https://www.nuget.org/packages/NHibernate). At which point, developers can execute database migrations and SQL scripts. +## A Note To Developers -[xunit]: https://xunit.net/ +Once Testcontainers creates a server instance, developers may use the connection string with any of the popular data-access technologies found in the .NET ecosystem. Some of these libraries include [Entity Framework Core](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore), [Dapper](https://www.nuget.org/packages/Dapper), and [NHibernate](https://www.nuget.org/packages/NHibernate). At which point, developers can execute database migrations and SQL scripts. \ No newline at end of file diff --git a/docs/modules/neo4j.md b/docs/modules/neo4j.md index c93e7189a..2e0038c2e 100644 --- a/docs/modules/neo4j.md +++ b/docs/modules/neo4j.md @@ -1,49 +1,25 @@ # Neo4j -[Neo4j](https://neo4j.com/product/neo4j-graph-database/) is a graph database designed to work with nodes and edges. It is a ACID-compliant transactional graph database engine, and developers can communicate with it using the HTTP endpoint or by using the **Bolt** protocol. +[Neo4j](https://neo4j.com/product/neo4j-graph-database/) is a graph database designed to work with nodes and edges. It is an ACID-compliant transactional graph database engine, and developers can communicate with it using the HTTP endpoint or by using the **Bolt** protocol. -The following example uses the following NuGet packages: +Add the following dependency to your project file: -```console title="Install the NuGet dependencies" +```console title="NuGet" dotnet add package Testcontainers.Neo4j -dotnet add package Neo4j.Driver -dotnet add package xunit ``` -IDEs and editors may also require the following packages to run tests: `xunit.runner.visualstudio` and `Microsoft.NET.Test.Sdk`. +You can start an Neo4j container instance from any .NET application. This example uses xUnit.net's `IAsyncLifetime` interface to manage the lifecycle of the container. The container is started in the `InitializeAsync` method before the test method runs, ensuring that the environment is ready for testing. After the test completes, the container is removed in the `DisposeAsync` method. -Copy and paste the following code into a new `.cs` test file within an existing test project. + +[Usage Example](../../tests/Testcontainers.Neo4j.Tests/Neo4jContainerTest.cs) inside_block:UseNeo4jContainer + -```csharp -using Neo4j.Driver; -using Testcontainers.Neo4j; -using Xunit; +The test example uses the following NuGet dependencies: -namespace TestcontainersModules; - -public sealed class Neo4jContainerTest : IAsyncLifetime -{ - private readonly Neo4jContainer _neo4jContainer - = new Neo4jBuilder().Build(); - - [Fact] - public async Task CanReadNeo4jDatabase() - { - const string database = "neo4j"; - - await using var client = GraphDatabase.Driver(_neo4jContainer.GetConnectionString()); - - await using var session = client.AsyncSession(cfg => cfg.WithDatabase(database)); - - Assert.Equal(database, session.SessionConfig.Database); - } - - public Task InitializeAsync() - => _neo4jContainer.StartAsync(); - - public Task DisposeAsync() - => _neo4jContainer.DisposeAsync().AsTask(); -} -``` + +[Package References](../../tests/Testcontainers.Neo4j.Tests/Testcontainers.Neo4j.Tests.csproj) inside_block:PackageReferences + To execute the tests, use the command `dotnet test` from a terminal. + +--8<-- "docs/modules/_call_out_test_projects.md" \ No newline at end of file diff --git a/docs/modules/postgres.md b/docs/modules/postgres.md index 9d0567b51..eeff3f1e3 100644 --- a/docs/modules/postgres.md +++ b/docs/modules/postgres.md @@ -1,36 +1,25 @@ # PostgreSQL -Here is an example of a pre-configured PostgreSQL [module](https://www.nuget.org/packages/Testcontainers.PostgreSql). In the example, Testcontainers starts a PostgreSQL database in a [xUnit.net][xunit] test and executes a SQL query against it. - -```csharp -public sealed class PostgreSqlContainerTest : IAsyncLifetime -{ - private readonly PostgreSqlContainer _postgreSqlContainer = new PostgreSqlBuilder().Build(); - - public Task InitializeAsync() - { - return _postgreSqlContainer.StartAsync(); - } - - public Task DisposeAsync() - { - return _postgreSqlContainer.DisposeAsync().AsTask(); - } - - [Fact] - public void ExecuteCommand() - { - using (DbConnection connection = new NpgsqlConnection(_postgreSqlContainer.GetConnectionString())) - { - using (DbCommand command = new NpgsqlCommand()) - { - connection.Open(); - command.Connection = connection; - command.CommandText = "SELECT 1"; - } - } - } -} +[PostgreSQL](https://www.postgresql.org/) is a powerful, open-source relational database management system (RDBMS) used to store, manage, and retrieve structured data. + +Add the following dependency to your project file: + +```console title="NuGet" +dotnet add package Testcontainers.PostgreSql ``` -[xunit]: https://xunit.net/ +You can start an PostgreSQL container instance from any .NET application. This example uses xUnit.net's `IAsyncLifetime` interface to manage the lifecycle of the container. The container is started in the `InitializeAsync` method before the test method runs, ensuring that the environment is ready for testing. After the test completes, the container is removed in the `DisposeAsync` method. + + +[Usage Example](../../tests/Testcontainers.PostgreSql.Tests/PostgreSqlContainerTest.cs) inside_block:UsePostgreSqlContainer + + +The test example uses the following NuGet dependencies: + + +[Package References](../../tests/Testcontainers.PostgreSql.Tests/Testcontainers.PostgreSql.Tests.csproj) inside_block:PackageReferences + + +To execute the tests, use the command `dotnet test` from a terminal. + +--8<-- "docs/modules/_call_out_test_projects.md" \ No newline at end of file diff --git a/docs/modules/pulsar.md b/docs/modules/pulsar.md index 39b582a23..05818ccd7 100644 --- a/docs/modules/pulsar.md +++ b/docs/modules/pulsar.md @@ -1,86 +1,42 @@ # Apache Pulsar -Testcontainers can be used to automatically create [Apache Pulsar](https://pulsar.apache.org) containers without the need for external services. Based on the official Apache Pulsar Docker image, it is recommended to read the official [getting started](https://pulsar.apache.org/docs/next/getting-started-docker/) guide. +[Apache Pulsar](https://pulsar.apache.org/) is a distributed messaging and event streaming platform designed for high-throughput, low-latency data processing across multiple topics. -The following example uses the following NuGet packages: +Add the following dependency to your project file: -```console title="Install the NuGet dependencies" +```console title="NuGet" dotnet add package Testcontainers.Pulsar -dotnet add package DotPulsar -dotnet add package xunit ``` -IDEs and editors may also require the following packages to run tests: `xunit.runner.visualstudio` and `Microsoft.NET.Test.Sdk`. +You can start a Apache Pulsar container instance from any .NET application. Here, we create different container instances and pass them to the base test class. This allows us to test different configurations. -Copy and paste the following code into a new `.cs` test file within an existing test project. + +[Create Container Instance](../../tests/Testcontainers.Pulsar.Tests/PulsarContainerTest.cs) inside_block:CreatePulsarContainer + -```csharp -using System; -using System.Text; -using System.Threading.Tasks; -using DotPulsar; -using DotPulsar.Extensions; -using Xunit; - -namespace Testcontainers.Pulsar; - -public sealed class PulsarContainerTest : IAsyncLifetime -{ - private readonly PulsarContainer _pulsarContainer = - new PulsarBuilder().Build(); - - [Fact] - public async Task ConsumerReceivesSendMessage() - { - const string helloPulsar = "Hello, Pulsar!"; - - var topic = $"persistent://public/default/{Guid.NewGuid():D}"; - - var name = Guid.NewGuid().ToString("D"); - - await using var client = PulsarClient.Builder() - .ServiceUrl(new Uri(_pulsarContainer.GetBrokerAddress())) - .Build(); - - await using var producer = client.NewProducer(Schema.String) - .Topic(topic) - .Create(); +This example uses xUnit.net's `IAsyncLifetime` interface to manage the lifecycle of the container. The container is started in the `InitializeAsync` method before the test method runs, ensuring that the environment is ready for testing. After the test completes, the container is removed in the `DisposeAsync` method. - await using var consumer = client.NewConsumer(Schema.String) - .Topic(topic) - .SubscriptionName(name) - .InitialPosition(SubscriptionInitialPosition.Earliest) - .Create(); + +[Usage Example](../../tests/Testcontainers.Pulsar.Tests/PulsarContainerTest.cs) inside_block:UsePulsarContainer + - _ = await producer.Send(helloPulsar) - .ConfigureAwait(true); +The test example uses the following NuGet dependencies: - var message = await consumer.Receive() - .ConfigureAwait(true); - - Assert.Equal(helloPulsar, Encoding.Default.GetString(message.Data)); - } - - public Task InitializeAsync() - => _pulsarContainer.StartAsync(); - - public Task DisposeAsync() - => _pulsarContainer.DisposeAsync().AsTask(); -} -``` + +[Package References](../../tests/Testcontainers.Pulsar.Tests/Testcontainers.Pulsar.Tests.csproj) inside_block:PackageReferences + To execute the tests, use the command `dotnet test` from a terminal. -## Access Pulsar +--8<-- "docs/modules/_call_out_test_projects.md" -To get the Pulsar broker URL use: +## Access Apache Pulsar -```csharp +```csharp title="Gets the Pulsar broker URL" string pulsarBrokerUrl = _pulsarContainer.GetPulsarBrokerUrl(); ``` -To get the Pulsar service URL use: -```csharp +```csharp title="Gets the Pulsar service URL" string pulsarServiceUrl = _pulsarContainer.GetHttpServiceUrl(); ``` @@ -112,4 +68,4 @@ If you need to use Pulsar Functions, use the following builder configuration to ```csharp PulsarContainer _pulsarContainer = PulsarBuilder().WithFunctions().Build(); -``` +``` \ No newline at end of file diff --git a/docs/modules/rabbitmq.md b/docs/modules/rabbitmq.md index 16b6f89d6..39ac69d33 100644 --- a/docs/modules/rabbitmq.md +++ b/docs/modules/rabbitmq.md @@ -1,77 +1,25 @@ # RabbitMQ -Here is an example of a pre-configured RabbitMQ [module](https://www.nuget.org/packages/Testcontainers.RabbitMq). In this example, Testcontainers is utilized to launch a RabbitMQ server within an [xUnit.net](https://xunit.net/) test. The purpose is to establish a connection to the server, send a message, and subsequently validate the successful transmission and consumption of the message. The process also ensures that the received message corresponds accurately to the originally sent message. +[RabbitMQ](https://www.rabbitmq.com/) is a message broker that enables reliable communication between distributed applications by managing and routing messages between them. -Before running the test, make sure to install the required dependencies: +Add the following dependency to your project file: -```console title="Install the NuGet dependencies" +```console title="NuGet" dotnet add package Testcontainers.RabbitMq -dotnet add package RabbitMQ.Client -dotnet add package xunit ``` -Copy and paste the following code into a new `.cs` test file: +You can start a RabbitMQ container instance from any .NET application. This example uses xUnit.net's `IAsyncLifetime` interface to manage the lifecycle of the container. The container is started in the `InitializeAsync` method before the test method runs, ensuring that the environment is ready for testing. After the test completes, the container is removed in the `DisposeAsync` method. -```csharp -using System.Text; -using System.Threading; -using RabbitMQ.Client; -using RabbitMQ.Client.Events; -using Testcontainers.RabbitMq; -using Xunit; + +[Usage Example](../../tests/Testcontainers.RabbitMq.Tests/RabbitMqContainerTest.cs) inside_block:UseRabbitMqContainer + -public sealed class RabbitMqContainerTest : IAsyncLifetime -{ - private readonly RabbitMqContainer _rabbitMqContainer = new RabbitMqBuilder().Build(); +The test example uses the following NuGet dependencies: - public Task InitializeAsync() - { - return _rabbitMqContainer.StartAsync(); - } + +[Package References](../../tests/Testcontainers.RabbitMq.Tests/Testcontainers.RabbitMq.Tests.csproj) inside_block:PackageReferences + - public Task DisposeAsync() - { - return _rabbitMqContainer.DisposeAsync().AsTask(); - } +To execute the tests, use the command `dotnet test` from a terminal. - [Fact] - public void ConsumeMessageFromQueue() - { - const string queue = "hello"; - - const string message = "Hello World!"; - - string actualMessage = null; - - // Signal the completion of message reception. - EventWaitHandle waitHandle = new ManualResetEvent(false); - - // Create and establish a connection. - var connectionFactory = new ConnectionFactory(); - connectionFactory.Uri = new Uri(_rabbitMqContainer.GetConnectionString()); - using var connection = connectionFactory.CreateConnection(); - - // Send a message to the channel. - using var channel = connection.CreateModel(); - channel.QueueDeclare(queue, false, false, false, null); - channel.BasicPublish(string.Empty, queue, null, Encoding.Default.GetBytes(message)); - - // Consume a message from the channel. - var consumer = new EventingBasicConsumer(channel); - consumer.Received += (_, eventArgs) => - { - actualMessage = Encoding.Default.GetString(eventArgs.Body.ToArray()); - waitHandle.Set(); - }; - - channel.BasicConsume(queue, true, consumer); - waitHandle.WaitOne(TimeSpan.FromSeconds(1)); - - Assert.Equal(message, actualMessage); - } -} -``` - -To execute the tests, use the command `dotnet test` from your terminal. - -Read more about the usage of RabbitMQ and .NET [here](https://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html). +--8<-- "docs/modules/_call_out_test_projects.md" \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml index 8c43c04de..1eb519b0b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -23,7 +23,10 @@ plugins: markdown_extensions: - admonition - pymdownx.details + - pymdownx.snippets - pymdownx.superfences + - pymdownx.tabbed: + alternate_style: true nav: - index.md - cicd/index.md diff --git a/tests/Testcontainers.Elasticsearch.Tests/ElasticsearchContainerTest.cs b/tests/Testcontainers.Elasticsearch.Tests/ElasticsearchContainerTest.cs index 146df0e04..974f628c4 100644 --- a/tests/Testcontainers.Elasticsearch.Tests/ElasticsearchContainerTest.cs +++ b/tests/Testcontainers.Elasticsearch.Tests/ElasticsearchContainerTest.cs @@ -2,6 +2,7 @@ namespace Testcontainers.Elasticsearch; public sealed class ElasticsearchContainerTest : IAsyncLifetime { + // UseElasticsearchContainer { private readonly ElasticsearchContainer _elasticsearchContainer = new ElasticsearchBuilder().Build(); public Task InitializeAsync() @@ -30,4 +31,5 @@ public void PingReturnsValidResponse() // Then Assert.True(response.IsValidResponse); } + // } } \ No newline at end of file diff --git a/tests/Testcontainers.Elasticsearch.Tests/Testcontainers.Elasticsearch.Tests.csproj b/tests/Testcontainers.Elasticsearch.Tests/Testcontainers.Elasticsearch.Tests.csproj index 1af74e878..a6224b845 100644 --- a/tests/Testcontainers.Elasticsearch.Tests/Testcontainers.Elasticsearch.Tests.csproj +++ b/tests/Testcontainers.Elasticsearch.Tests/Testcontainers.Elasticsearch.Tests.csproj @@ -5,11 +5,13 @@ false + + diff --git a/tests/Testcontainers.MongoDb.Tests/MongoDbContainerTest.cs b/tests/Testcontainers.MongoDb.Tests/MongoDbContainerTest.cs index 81cfa2e46..c71557072 100644 --- a/tests/Testcontainers.MongoDb.Tests/MongoDbContainerTest.cs +++ b/tests/Testcontainers.MongoDb.Tests/MongoDbContainerTest.cs @@ -12,6 +12,7 @@ private MongoDbContainerTest(MongoDbContainer mongoDbContainer, bool replicaSetE _replicaSetEnabled = replicaSetEnabled; } + // UseMongoDbContainer { public Task InitializeAsync() { return _mongoDbContainer.StartAsync(); @@ -51,6 +52,7 @@ public async Task ExecScriptReturnsSuccessful() Assert.True(0L.Equals(execResult.ExitCode), execResult.Stderr); Assert.Empty(execResult.Stderr); } + // } [Fact] [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] @@ -76,6 +78,7 @@ public async Task ReplicaSetStatus() } } + // CreateMongoDbContainer { [UsedImplicitly] public sealed class MongoDbDefaultConfiguration : MongoDbContainerTest { @@ -93,6 +96,7 @@ public MongoDbNoAuthConfiguration() { } } + // } [UsedImplicitly] public sealed class MongoDbV5Configuration : MongoDbContainerTest @@ -121,6 +125,7 @@ public MongoDbReplicaSetDefaultConfiguration() } } + // ReplicaSetContainerConfiguration { [UsedImplicitly] public sealed class MongoDbNamedReplicaSetConfiguration : MongoDbContainerTest { @@ -129,4 +134,5 @@ public MongoDbNamedReplicaSetConfiguration() { } } + // } } \ No newline at end of file diff --git a/tests/Testcontainers.MongoDb.Tests/Testcontainers.MongoDb.Tests.csproj b/tests/Testcontainers.MongoDb.Tests/Testcontainers.MongoDb.Tests.csproj index 1051176ee..d50ee4594 100644 --- a/tests/Testcontainers.MongoDb.Tests/Testcontainers.MongoDb.Tests.csproj +++ b/tests/Testcontainers.MongoDb.Tests/Testcontainers.MongoDb.Tests.csproj @@ -5,11 +5,13 @@ false + + diff --git a/tests/Testcontainers.MsSql.Tests/MsSqlContainerTest.cs b/tests/Testcontainers.MsSql.Tests/MsSqlContainerTest.cs index 1f94c3b82..3e65695cc 100644 --- a/tests/Testcontainers.MsSql.Tests/MsSqlContainerTest.cs +++ b/tests/Testcontainers.MsSql.Tests/MsSqlContainerTest.cs @@ -9,6 +9,7 @@ public MsSqlContainerTest(MsSqlContainer msSqlContainer) _msSqlContainer = msSqlContainer; } + // UseMsSqlContainer { public Task InitializeAsync() { return _msSqlContainer.StartAsync(); @@ -48,7 +49,9 @@ public async Task ExecScriptReturnsSuccessful() Assert.True(0L.Equals(execResult.ExitCode), execResult.Stderr); Assert.Empty(execResult.Stderr); } + // } + // CreateMsSqlContainer { [UsedImplicitly] public sealed class MsSqlDefaultConfiguration : MsSqlContainerTest { @@ -57,6 +60,7 @@ public MsSqlDefaultConfiguration() { } } + // } [UsedImplicitly] public sealed class MsSqlTools18Configuration : MsSqlContainerTest diff --git a/tests/Testcontainers.MsSql.Tests/Testcontainers.MsSql.Tests.csproj b/tests/Testcontainers.MsSql.Tests/Testcontainers.MsSql.Tests.csproj index 1d4ec0882..2ef4d6469 100644 --- a/tests/Testcontainers.MsSql.Tests/Testcontainers.MsSql.Tests.csproj +++ b/tests/Testcontainers.MsSql.Tests/Testcontainers.MsSql.Tests.csproj @@ -5,11 +5,13 @@ false + + diff --git a/tests/Testcontainers.Neo4j.Tests/Neo4jContainerTest.cs b/tests/Testcontainers.Neo4j.Tests/Neo4jContainerTest.cs index 0e08ff3e3..9609e557b 100644 --- a/tests/Testcontainers.Neo4j.Tests/Neo4jContainerTest.cs +++ b/tests/Testcontainers.Neo4j.Tests/Neo4jContainerTest.cs @@ -2,6 +2,7 @@ namespace Testcontainers.Neo4j; public sealed class Neo4jContainerTest : IAsyncLifetime { + // UseNeo4jContainer { private readonly Neo4jContainer _neo4jContainer = new Neo4jBuilder().Build(); public Task InitializeAsync() @@ -29,4 +30,5 @@ public void SessionReturnsDatabase() // Then Assert.Equal(database, session.SessionConfig.Database); } + // } } \ No newline at end of file diff --git a/tests/Testcontainers.Neo4j.Tests/Testcontainers.Neo4j.Tests.csproj b/tests/Testcontainers.Neo4j.Tests/Testcontainers.Neo4j.Tests.csproj index f1b09b5b7..91d78f450 100644 --- a/tests/Testcontainers.Neo4j.Tests/Testcontainers.Neo4j.Tests.csproj +++ b/tests/Testcontainers.Neo4j.Tests/Testcontainers.Neo4j.Tests.csproj @@ -5,11 +5,13 @@ false + + diff --git a/tests/Testcontainers.PostgreSql.Tests/PostgreSqlContainerTest.cs b/tests/Testcontainers.PostgreSql.Tests/PostgreSqlContainerTest.cs index a92461dbd..ab03d8aa9 100644 --- a/tests/Testcontainers.PostgreSql.Tests/PostgreSqlContainerTest.cs +++ b/tests/Testcontainers.PostgreSql.Tests/PostgreSqlContainerTest.cs @@ -2,6 +2,7 @@ namespace Testcontainers.PostgreSql; public sealed class PostgreSqlContainerTest : IAsyncLifetime { + // UsePostgreSqlContainer { private readonly PostgreSqlContainer _postgreSqlContainer = new PostgreSqlBuilder().Build(); public Task InitializeAsync() @@ -43,6 +44,7 @@ public async Task ExecScriptReturnsSuccessful() Assert.True(0L.Equals(execResult.ExitCode), execResult.Stderr); Assert.Empty(execResult.Stderr); } + // } public sealed class ReuseContainerTest : IClassFixture, IDisposable { diff --git a/tests/Testcontainers.PostgreSql.Tests/Testcontainers.PostgreSql.Tests.csproj b/tests/Testcontainers.PostgreSql.Tests/Testcontainers.PostgreSql.Tests.csproj index d254639c5..6c20b7979 100644 --- a/tests/Testcontainers.PostgreSql.Tests/Testcontainers.PostgreSql.Tests.csproj +++ b/tests/Testcontainers.PostgreSql.Tests/Testcontainers.PostgreSql.Tests.csproj @@ -5,11 +5,13 @@ false + + diff --git a/tests/Testcontainers.Pulsar.Tests/PulsarContainerTest.cs b/tests/Testcontainers.Pulsar.Tests/PulsarContainerTest.cs index 997ccfd59..41b71f6cf 100644 --- a/tests/Testcontainers.Pulsar.Tests/PulsarContainerTest.cs +++ b/tests/Testcontainers.Pulsar.Tests/PulsarContainerTest.cs @@ -4,13 +4,15 @@ public abstract class PulsarContainerTest : IAsyncLifetime { private readonly PulsarContainer _pulsarContainer; - private PulsarContainerTest(PulsarContainer pulsarContainer) + private readonly bool _authenticationEnabled; + + private PulsarContainerTest(PulsarContainer pulsarContainer, bool authenticationEnabled) { _pulsarContainer = pulsarContainer; + _authenticationEnabled = authenticationEnabled; } - protected abstract Task CreateClientAsync(CancellationToken ct = default); - + // UsePulsarContainer { public Task InitializeAsync() { return _pulsarContainer.StartAsync(); @@ -31,8 +33,15 @@ public async Task ConsumerReceivesSendMessage() var name = Guid.NewGuid().ToString("D"); - await using var client = await CreateClientAsync() - .ConfigureAwait(true); + var clientBuilder = PulsarClient.Builder().ServiceUrl(new Uri(_pulsarContainer.GetBrokerAddress())); + + if (_authenticationEnabled) + { + var authToken = await _pulsarContainer.CreateAuthenticationTokenAsync(Timeout.InfiniteTimeSpan); + _ = clientBuilder.Authentication(new TokenAuthentication(authToken)); + } + + var client = clientBuilder.Build(); await using var producer = client.NewProducer(Schema.String) .Topic(topic) @@ -54,35 +63,25 @@ public async Task ConsumerReceivesSendMessage() // Then Assert.Equal(helloPulsar, Encoding.Default.GetString(message.Data)); } + // } + // CreatePulsarContainer { [UsedImplicitly] public sealed class PulsarDefaultConfiguration : PulsarContainerTest { public PulsarDefaultConfiguration() - : base(new PulsarBuilder().Build()) + : base(new PulsarBuilder().Build(), false) { } - - protected override Task CreateClientAsync(CancellationToken ct = default) - { - return Task.FromResult(PulsarClient.Builder().ServiceUrl(new Uri(_pulsarContainer.GetBrokerAddress())).Build()); - } } + // } [UsedImplicitly] public sealed class PulsarAuthConfiguration : PulsarContainerTest { public PulsarAuthConfiguration() - : base(new PulsarBuilder().WithAuthentication().Build()) + : base(new PulsarBuilder().WithAuthentication().Build(), true) { } - - protected override async Task CreateClientAsync(CancellationToken ct = default) - { - var authToken = await _pulsarContainer.CreateAuthenticationTokenAsync(Timeout.InfiniteTimeSpan, ct) - .ConfigureAwait(false); - - return PulsarClient.Builder().ServiceUrl(new Uri(_pulsarContainer.GetBrokerAddress())).Authentication(new TokenAuthentication(authToken)).Build(); - } } } \ No newline at end of file diff --git a/tests/Testcontainers.Pulsar.Tests/Testcontainers.Pulsar.Tests.csproj b/tests/Testcontainers.Pulsar.Tests/Testcontainers.Pulsar.Tests.csproj index 7faabcd5d..63d41e13c 100644 --- a/tests/Testcontainers.Pulsar.Tests/Testcontainers.Pulsar.Tests.csproj +++ b/tests/Testcontainers.Pulsar.Tests/Testcontainers.Pulsar.Tests.csproj @@ -5,11 +5,13 @@ false + + diff --git a/tests/Testcontainers.RabbitMq.Tests/RabbitMqContainerTest.cs b/tests/Testcontainers.RabbitMq.Tests/RabbitMqContainerTest.cs index 7e1a08f6f..d745848d2 100644 --- a/tests/Testcontainers.RabbitMq.Tests/RabbitMqContainerTest.cs +++ b/tests/Testcontainers.RabbitMq.Tests/RabbitMqContainerTest.cs @@ -2,6 +2,7 @@ namespace Testcontainers.RabbitMq; public sealed class RabbitMqContainerTest : IAsyncLifetime { + // UseRabbitMqContainer { private readonly RabbitMqContainer _rabbitMqContainer = new RabbitMqBuilder().Build(); public Task InitializeAsync() @@ -28,4 +29,5 @@ public void IsOpenReturnsTrue() // Then Assert.True(connection.IsOpen); } + // } } \ No newline at end of file diff --git a/tests/Testcontainers.RabbitMq.Tests/Testcontainers.RabbitMq.Tests.csproj b/tests/Testcontainers.RabbitMq.Tests/Testcontainers.RabbitMq.Tests.csproj index ad9f4d6f0..71fd05fb9 100644 --- a/tests/Testcontainers.RabbitMq.Tests/Testcontainers.RabbitMq.Tests.csproj +++ b/tests/Testcontainers.RabbitMq.Tests/Testcontainers.RabbitMq.Tests.csproj @@ -5,11 +5,13 @@ false + +