From 3565f10e00bb39d472e8f79c91249a7cff96cf82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Ma=CC=88der?= Date: Wed, 13 Aug 2025 15:43:29 +0200 Subject: [PATCH 1/2] Add csharpier --- .config/dotnet-tools.json | 13 +++++++++++++ .csharpierignore | 1 + .github/workflows/csharpier.yml | 14 ++++++++++++++ .gitignore | 4 +++- build.ps1 | 2 +- build.sh | 6 +++++- build/Tasks.cs | 21 +++++++++++++++++++++ 7 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 .config/dotnet-tools.json create mode 100644 .csharpierignore create mode 100644 .github/workflows/csharpier.yml diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 000000000..017fac759 --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "csharpier": { + "version": "1.1.1", + "commands": [ + "csharpier" + ], + "rollForward": false + } + } +} \ No newline at end of file diff --git a/.csharpierignore b/.csharpierignore new file mode 100644 index 000000000..fd8b50f69 --- /dev/null +++ b/.csharpierignore @@ -0,0 +1 @@ +cake.config diff --git a/.github/workflows/csharpier.yml b/.github/workflows/csharpier.yml new file mode 100644 index 000000000..5e35ddb26 --- /dev/null +++ b/.github/workflows/csharpier.yml @@ -0,0 +1,14 @@ +name: Formatting check + +on: + workflow_dispatch: + pull_request: + +jobs: + formatting-check: + runs-on: ubuntu-latest + permissions: + pull-requests: write + steps: + - name: CSharpier Linter + uses: guibranco/github-csharpier-linter-action@v1.0.5 diff --git a/.gitignore b/.gitignore index b50736e50..a597823c4 100644 --- a/.gitignore +++ b/.gitignore @@ -402,4 +402,6 @@ FodyWeavers.xsd # JetBrains Rider .idea/ -*.sln.iml \ No newline at end of file +*.sln.iml + +test-results/ diff --git a/build.ps1 b/build.ps1 index a7077190a..49560a7fc 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,2 +1,2 @@ dotnet run --project build/Build.csproj -- $args -exit $LASTEXITCODE; \ No newline at end of file +exit $LASTEXITCODE; diff --git a/build.sh b/build.sh index b311fae84..be742860a 100755 --- a/build.sh +++ b/build.sh @@ -1 +1,5 @@ -dotnet run --project ./build/Build.csproj -- "$@" \ No newline at end of file +#!/bin/sh + +set -e + +dotnet run --project ./build/Build.csproj -- "$@" diff --git a/build/Tasks.cs b/build/Tasks.cs index 30e53b693..38f916294 100644 --- a/build/Tasks.cs +++ b/build/Tasks.cs @@ -129,6 +129,25 @@ public override void Run(BuildContext context) } } +[TaskName("Format")] +public sealed class CheckFormatTask : FrostingTask +{ public override void Run(BuildContext context) + { + var param = context.Parameters; + context.DotNetTool("./", "csharpier", "format ."); + } +} + +[TaskName("Check-Format")] +public sealed class FormatTask : FrostingTask +{ + public override void Run(BuildContext context) + { + var param = context.Parameters; + context.DotNetTool("./", "csharpier", "check ."); + } +} + [TaskName("Sonar-Begin")] public sealed class SonarBeginTask : FrostingTask { @@ -241,6 +260,7 @@ public override void Run(BuildContext context) [TaskName("Default")] [IsDependentOn(typeof(CleanTask))] [IsDependentOn(typeof(RestoreNuGetPackagesTask))] +[IsDependentOn(typeof(FormatTask))] [IsDependentOn(typeof(BuildTask))] [IsDependentOn(typeof(TestsTask))] public sealed class DefaultTask : FrostingTask; @@ -249,6 +269,7 @@ public sealed class DefaultTask : FrostingTask; [IsDependentOn(typeof(CleanTask))] [IsDependentOn(typeof(RestoreNuGetPackagesTask))] [IsDependentOn(typeof(SonarBeginTask))] +[IsDependentOn(typeof(FormatTask))] [IsDependentOn(typeof(BuildTask))] [IsDependentOn(typeof(TestsTask))] [IsDependentOn(typeof(SonarEndTask))] From ff77f28c75b5541e94b67d7fe11b9553b3bfe511 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Ma=CC=88der?= Date: Sun, 31 Aug 2025 14:30:08 +0200 Subject: [PATCH 2/2] Apply csharpier --- Directory.Build.props | 21 +- Directory.Packages.props | 174 ++++---- build/Build.csproj | 24 +- build/Credentials.cs | 11 +- build/Parameters.cs | 14 +- build/Paths.cs | 9 +- build/Program.cs | 2 +- build/Projects.cs | 6 +- build/Tasks.cs | 215 ++++++---- build/Usings.cs | 2 +- build/Version.cs | 32 +- examples/Flyway/Directory.Build.props | 46 +-- examples/Flyway/Directory.Packages.props | 26 +- .../Flyway/tests/Flyway.Tests/DbFixture.cs | 9 +- .../tests/Flyway.Tests/Flyway.Tests.csproj | 34 +- .../Flyway/tests/Flyway.Tests/FlywayTest.cs | 2 +- examples/Flyway/tests/Flyway.Tests/Usings.cs | 2 +- examples/Respawn/Directory.Build.props | 46 +-- examples/Respawn/Directory.Packages.props | 28 +- .../Respawn/tests/Respawn.Tests/DbFixture.cs | 5 +- .../tests/Respawn.Tests/Respawn.Tests.csproj | 36 +- .../tests/Respawn.Tests/RespawnTest.cs | 9 +- .../Respawn/tests/Respawn.Tests/Usings.cs | 2 +- .../WeatherForecast/Directory.Packages.props | 20 +- .../WeatherDataContext.cs | 27 +- .../WeatherDataReadOnlyContext.cs | 14 +- .../WeatherForecast.Contexts.csproj | 10 +- .../WeatherForecast.Entities/Temperature.cs | 10 +- .../WeatherForecast.Entities/WeatherData.cs | 16 +- .../WeatherForecast.Entities.csproj | 6 +- .../src/WeatherForecast.Interactors/Error.cs | 3 +- .../WeatherForecast.Interactors/Failure.cs | 4 +- .../WeatherForecast.Interactors/Failure`1.cs | 4 +- .../ISearchCityOrZipCode.cs | 6 +- .../SearchCityOrZipCode.cs | 8 +- .../WeatherForecast.Interactors/StatusCode.cs | 2 +- .../WeatherForecast.Interactors/Success.cs | 4 +- .../WeatherForecast.Interactors/Success`1.cs | 4 +- .../WeatherForecast.Interactors.csproj | 10 +- .../IWeatherDataReadOnlyRepository.cs | 7 +- .../WeatherDataReadOnlyRepository.cs | 30 +- .../WeatherForecast.Repositories.csproj | 8 +- .../Controllers/WeatherForecastController.cs | 11 +- .../src/WeatherForecast/Program.cs | 20 +- .../WeatherForecast/WeatherForecast.csproj | 14 +- .../WeatherForecast.InProcess.Tests.csproj | 16 +- .../WeatherForecastTest.cs | 15 +- .../WeatherForecast.Tests.csproj | 18 +- .../WeatherForecastContainer.cs | 68 ++-- .../WeatherForecastImage.cs | 13 +- .../WeatherForecastTest.cs | 39 +- .../ModuleNameBuilder.cs | 24 +- .../ModuleNameConfiguration.cs | 11 +- .../ModuleNameContainer.cs | 6 +- .../Testcontainers.ModuleName.csproj | 26 +- .../Testcontainers.ModuleName/Usings.cs | 2 +- .../ActiveMqConfiguration.cs | 10 +- src/Testcontainers.ActiveMq/ArtemisBuilder.cs | 26 +- .../ArtemisContainer.cs | 8 +- .../Testcontainers.ActiveMq.csproj | 26 +- src/Testcontainers.ActiveMq/Usings.cs | 2 +- .../ArangoDbBuilder.cs | 20 +- .../ArangoDbConfiguration.cs | 9 +- .../ArangoDbContainer.cs | 12 +- .../Testcontainers.ArangoDb.csproj | 26 +- src/Testcontainers.ArangoDb/Usings.cs | 2 +- src/Testcontainers.Azurite/AzuriteBuilder.cs | 49 ++- .../AzuriteConfiguration.cs | 14 +- .../AzuriteContainer.cs | 32 +- src/Testcontainers.Azurite/AzuriteService.cs | 2 +- .../Testcontainers.Azurite.csproj | 26 +- src/Testcontainers.Azurite/Usings.cs | 2 +- .../BigQueryBuilder.cs | 16 +- .../BigQueryConfiguration.cs | 14 +- .../BigQueryContainer.cs | 12 +- .../Testcontainers.BigQuery.csproj | 26 +- src/Testcontainers.BigQuery/Usings.cs | 2 +- .../BigtableBuilder.cs | 26 +- .../BigtableConfiguration.cs | 14 +- .../BigtableContainer.cs | 12 +- .../Testcontainers.Bigtable.csproj | 26 +- src/Testcontainers.Bigtable/Usings.cs | 2 +- .../CassandraBuilder.cs | 29 +- .../CassandraConfiguration.cs | 14 +- .../CassandraContainer.cs | 31 +- .../Testcontainers.Cassandra.csproj | 26 +- src/Testcontainers.Cassandra/Usings.cs | 6 +- .../ClickHouseBuilder.cs | 41 +- .../ClickHouseConfiguration.cs | 14 +- .../ClickHouseContainer.cs | 39 +- .../Testcontainers.ClickHouse.csproj | 26 +- src/Testcontainers.ClickHouse/Usings.cs | 2 +- .../CockroachDbBuilder.cs | 38 +- .../CockroachDbConfiguration.cs | 14 +- .../CockroachDbContainer.cs | 32 +- .../Testcontainers.CockroachDb.csproj | 26 +- src/Testcontainers.CockroachDb/Usings.cs | 2 +- src/Testcontainers.Consul/ConsulBuilder.cs | 22 +- .../ConsulConfiguration.cs | 14 +- src/Testcontainers.Consul/ConsulContainer.cs | 12 +- .../Testcontainers.Consul.csproj | 26 +- src/Testcontainers.Consul/Usings.cs | 2 +- .../CosmosDbBuilder.cs | 23 +- .../CosmosDbConfiguration.cs | 14 +- .../CosmosDbContainer.cs | 42 +- .../Testcontainers.CosmosDb.csproj | 26 +- src/Testcontainers.CosmosDb/Usings.cs | 2 +- src/Testcontainers.CouchDb/CouchDbBuilder.cs | 34 +- .../CouchDbConfiguration.cs | 10 +- .../CouchDbContainer.cs | 8 +- .../Testcontainers.CouchDb.csproj | 26 +- src/Testcontainers.CouchDb/Usings.cs | 2 +- .../CouchbaseBucket.cs | 9 +- .../CouchbaseBuilder.cs | 235 +++++++---- .../CouchbaseConfiguration.cs | 6 +- .../CouchbaseContainer.cs | 19 +- .../CouchbaseService.cs | 2 +- .../Testcontainers.Couchbase.csproj | 26 +- src/Testcontainers.Couchbase/Usings.cs | 2 +- src/Testcontainers.Db2/Db2Builder.cs | 39 +- src/Testcontainers.Db2/Db2Configuration.cs | 7 +- src/Testcontainers.Db2/Db2Container.cs | 39 +- .../Testcontainers.Db2.csproj | 26 +- src/Testcontainers.Db2/Usings.cs | 2 +- .../DynamoDbBuilder.cs | 25 +- .../DynamoDbConfiguration.cs | 14 +- .../DynamoDbContainer.cs | 12 +- .../Testcontainers.DynamoDb.csproj | 26 +- src/Testcontainers.DynamoDb/Usings.cs | 2 +- .../ElasticsearchBuilder.cs | 62 ++- .../ElasticsearchConfiguration.cs | 15 +- .../ElasticsearchContainer.cs | 28 +- .../Testcontainers.Elasticsearch.csproj | 26 +- src/Testcontainers.Elasticsearch/Usings.cs | 2 +- .../EventHubsBuilder.cs | 73 +++- .../EventHubsConfiguration.cs | 22 +- .../EventHubsContainer.cs | 20 +- .../EventHubsServiceConfiguration.cs | 64 ++- .../Testcontainers.EventHubs.csproj | 28 +- src/Testcontainers.EventHubs/Usings.cs | 2 +- .../EventStoreDbBuilder.cs | 24 +- .../EventStoreDbConfiguration.cs | 19 +- .../EventStoreDbContainer.cs | 12 +- .../Testcontainers.EventStoreDb.csproj | 26 +- src/Testcontainers.EventStoreDb/Usings.cs | 2 +- .../FakeGcsServerBuilder.cs | 77 +++- .../FakeGcsServerConfiguration.cs | 19 +- .../FakeGcsServerContainer.cs | 13 +- .../Testcontainers.FakeGcsServer.csproj | 26 +- src/Testcontainers.FakeGcsServer/Usings.cs | 2 +- .../FirebirdSqlBuilder.cs | 42 +- .../FirebirdSqlConfiguration.cs | 19 +- .../FirebirdSqlContainer.cs | 42 +- .../Testcontainers.FirebirdSql.csproj | 26 +- src/Testcontainers.FirebirdSql/Usings.cs | 2 +- .../FirestoreBuilder.cs | 36 +- .../FirestoreConfiguration.cs | 14 +- .../FirestoreContainer.cs | 12 +- .../Testcontainers.Firestore.csproj | 26 +- src/Testcontainers.Firestore/Usings.cs | 2 +- .../Testcontainers.GCloud.csproj | 22 +- .../InfluxDbBuilder.cs | 54 ++- .../InfluxDbConfiguration.cs | 9 +- .../InfluxDbContainer.cs | 12 +- .../Testcontainers.InfluxDb.csproj | 26 +- src/Testcontainers.InfluxDb/Usings.cs | 2 +- .../JanusGraphBuilder.cs | 28 +- .../JanusGraphConfiguration.cs | 19 +- .../JanusGraphContainer.cs | 6 +- .../Testcontainers.JanusGraph.csproj | 26 +- src/Testcontainers.JanusGraph/Usings.cs | 2 +- src/Testcontainers.K3s/K3sBuilder.cs | 14 +- src/Testcontainers.K3s/K3sConfiguration.cs | 10 +- src/Testcontainers.K3s/K3sContainer.cs | 20 +- .../Testcontainers.K3s.csproj | 26 +- src/Testcontainers.K3s/Usings.cs | 2 +- .../ApacheConfiguration.cs | 64 ++- .../ConfluentConfiguration.cs | 82 ++-- .../IKafkaVendorConfiguration.cs | 7 +- src/Testcontainers.Kafka/KafkaBuilder.cs | 122 ++++-- .../KafkaConfiguration.cs | 19 +- .../KafkaConsensusProtocol.cs | 2 +- src/Testcontainers.Kafka/KafkaContainer.cs | 13 +- src/Testcontainers.Kafka/KafkaVendor.cs | 2 +- .../Testcontainers.Kafka.csproj | 26 +- src/Testcontainers.Kafka/Usings.cs | 2 +- .../KeycloakBuilder.cs | 41 +- .../KeycloakConfiguration.cs | 6 +- .../KeycloakContainer.cs | 12 +- .../Testcontainers.Keycloak.csproj | 26 +- src/Testcontainers.Keycloak/Usings.cs | 2 +- src/Testcontainers.Kusto/KustoBuilder.cs | 30 +- .../KustoConfiguration.cs | 14 +- src/Testcontainers.Kusto/KustoContainer.cs | 12 +- .../Testcontainers.Kusto.csproj | 26 +- src/Testcontainers.Kusto/Usings.cs | 2 +- .../LocalStackBuilder.cs | 32 +- .../LocalStackConfiguration.cs | 19 +- .../LocalStackContainer.cs | 12 +- .../Testcontainers.LocalStack.csproj | 26 +- src/Testcontainers.LocalStack/Usings.cs | 2 +- .../LowkeyVaultBuilder.cs | 38 +- .../LowkeyVaultConfiguration.cs | 11 +- .../LowkeyVaultContainer.cs | 48 ++- .../Testcontainers.LowkeyVault.csproj | 26 +- src/Testcontainers.LowkeyVault/Usings.cs | 2 +- src/Testcontainers.MariaDb/MariaDbBuilder.cs | 53 ++- .../MariaDbConfiguration.cs | 9 +- .../MariaDbContainer.cs | 39 +- .../Testcontainers.MariaDb.csproj | 26 +- src/Testcontainers.MariaDb/Usings.cs | 2 +- src/Testcontainers.Milvus/MilvusBuilder.cs | 30 +- .../MilvusConfiguration.cs | 14 +- src/Testcontainers.Milvus/MilvusContainer.cs | 12 +- .../Testcontainers.Milvus.csproj | 26 +- src/Testcontainers.Milvus/Usings.cs | 2 +- src/Testcontainers.Minio/MinioBuilder.cs | 29 +- .../MinioConfiguration.cs | 10 +- src/Testcontainers.Minio/MinioContainer.cs | 8 +- .../Testcontainers.Minio.csproj | 26 +- src/Testcontainers.Minio/Usings.cs | 2 +- src/Testcontainers.MongoDb/MongoDbBuilder.cs | 97 +++-- .../MongoDbConfiguration.cs | 14 +- .../MongoDbContainer.cs | 37 +- .../Testcontainers.MongoDb.csproj | 26 +- src/Testcontainers.MongoDb/Usings.cs | 2 +- src/Testcontainers.MsSql/MsSqlBuilder.cs | 21 +- .../MsSqlConfiguration.cs | 9 +- src/Testcontainers.MsSql/MsSqlContainer.cs | 55 ++- .../Testcontainers.MsSql.csproj | 26 +- src/Testcontainers.MsSql/Usings.cs | 2 +- src/Testcontainers.MySql/MySqlBuilder.cs | 56 ++- .../MySqlConfiguration.cs | 9 +- src/Testcontainers.MySql/MySqlContainer.cs | 39 +- .../Testcontainers.MySql.csproj | 26 +- src/Testcontainers.MySql/Usings.cs | 2 +- src/Testcontainers.Nats/NatsBuilder.cs | 31 +- src/Testcontainers.Nats/NatsConfiguration.cs | 10 +- src/Testcontainers.Nats/NatsContainer.cs | 14 +- .../Testcontainers.Nats.csproj | 26 +- src/Testcontainers.Nats/Usings.cs | 2 +- src/Testcontainers.Neo4j/Neo4jBuilder.cs | 67 ++- .../Neo4jConfiguration.cs | 14 +- src/Testcontainers.Neo4j/Neo4jContainer.cs | 12 +- .../Testcontainers.Neo4j.csproj | 26 +- src/Testcontainers.Neo4j/Usings.cs | 2 +- src/Testcontainers.Ollama/OllamaBuilder.cs | 22 +- .../OllamaConfiguration.cs | 14 +- src/Testcontainers.Ollama/OllamaContainer.cs | 12 +- .../Testcontainers.Ollama.csproj | 26 +- src/Testcontainers.Ollama/Usings.cs | 2 +- .../OpenSearchBuilder.cs | 51 ++- .../OpenSearchConfiguration.cs | 26 +- .../OpenSearchContainer.cs | 12 +- .../Testcontainers.OpenSearch.csproj | 26 +- src/Testcontainers.OpenSearch/Usings.cs | 2 +- src/Testcontainers.Oracle/OracleBuilder.cs | 61 ++- .../OracleConfiguration.cs | 9 +- src/Testcontainers.Oracle/OracleContainer.cs | 44 +- .../Testcontainers.Oracle.csproj | 26 +- src/Testcontainers.Oracle/Usings.cs | 2 +- .../PapercutBuilder.cs | 33 +- .../PapercutConfiguration.cs | 14 +- .../PapercutContainer.cs | 12 +- .../Testcontainers.Papercut.csproj | 26 +- src/Testcontainers.Papercut/Usings.cs | 2 +- .../PostgreSqlBuilder.cs | 56 ++- .../PostgreSqlConfiguration.cs | 14 +- .../PostgreSqlContainer.cs | 41 +- .../Testcontainers.PostgreSql.csproj | 26 +- src/Testcontainers.PostgreSql/Usings.cs | 2 +- src/Testcontainers.PubSub/PubSubBuilder.cs | 26 +- .../PubSubConfiguration.cs | 14 +- src/Testcontainers.PubSub/PubSubContainer.cs | 12 +- .../Testcontainers.PubSub.csproj | 26 +- src/Testcontainers.PubSub/Usings.cs | 2 +- src/Testcontainers.Pulsar/PulsarBuilder.cs | 71 +++- .../PulsarConfiguration.cs | 17 +- src/Testcontainers.Pulsar/PulsarContainer.cs | 74 +++- .../Testcontainers.Pulsar.csproj | 26 +- src/Testcontainers.Pulsar/Usings.cs | 2 +- src/Testcontainers.Qdrant/QdrantBuilder.cs | 30 +- .../QdrantConfiguration.cs | 14 +- src/Testcontainers.Qdrant/QdrantContainer.cs | 14 +- .../Testcontainers.Qdrant.csproj | 26 +- src/Testcontainers.Qdrant/Usings.cs | 2 +- .../RabbitMqBuilder.cs | 30 +- .../RabbitMqConfiguration.cs | 10 +- .../RabbitMqContainer.cs | 8 +- .../Testcontainers.RabbitMq.csproj | 26 +- src/Testcontainers.RabbitMq/Usings.cs | 2 +- src/Testcontainers.RavenDb/RavenDbBuilder.cs | 14 +- .../RavenDbConfiguration.cs | 14 +- .../RavenDbContainer.cs | 12 +- .../Testcontainers.RavenDb.csproj | 26 +- src/Testcontainers.RavenDb/Usings.cs | 2 +- src/Testcontainers.Redis/RedisBuilder.cs | 9 +- .../RedisConfiguration.cs | 14 +- src/Testcontainers.Redis/RedisContainer.cs | 30 +- .../Testcontainers.Redis.csproj | 26 +- src/Testcontainers.Redis/Usings.cs | 2 +- .../RedpandaBuilder.cs | 67 ++- .../RedpandaConfiguration.cs | 14 +- .../RedpandaContainer.cs | 18 +- .../Testcontainers.Redpanda.csproj | 26 +- src/Testcontainers.Redpanda/Usings.cs | 4 +- .../ServiceBusBuilder.cs | 55 ++- .../ServiceBusConfiguration.cs | 16 +- .../ServiceBusContainer.cs | 20 +- .../Testcontainers.ServiceBus.csproj | 28 +- src/Testcontainers.ServiceBus/Usings.cs | 2 +- src/Testcontainers.Sftp/SftpBuilder.cs | 50 ++- src/Testcontainers.Sftp/SftpConfiguration.cs | 14 +- src/Testcontainers.Sftp/SftpContainer.cs | 6 +- .../Testcontainers.Sftp.csproj | 26 +- src/Testcontainers.Sftp/Usings.cs | 2 +- .../Testcontainers.Typesense.csproj | 26 +- .../TypesenseBuilder.cs | 47 ++- .../TypesenseConfiguration.cs | 14 +- .../TypesenseContainer.cs | 12 +- src/Testcontainers.Typesense/Usings.cs | 2 +- .../Testcontainers.Weaviate.csproj | 26 +- src/Testcontainers.Weaviate/Usings.cs | 2 +- .../WeaviateBuilder.cs | 46 ++- .../WeaviateConfiguration.cs | 14 +- .../WeaviateContainer.cs | 11 +- .../Testcontainers.WebDriver.csproj | 26 +- src/Testcontainers.WebDriver/Usings.cs | 2 +- .../WebDriverBrowser.cs | 18 +- .../WebDriverBuilder.cs | 61 ++- .../WebDriverConfiguration.cs | 11 +- .../WebDriverContainer.cs | 77 ++-- src/Testcontainers.Xunit/ContainerFixture.cs | 2 +- src/Testcontainers.Xunit/ContainerLifetime.cs | 18 +- src/Testcontainers.Xunit/ContainerTest.cs | 11 +- .../DbContainerFixture.cs | 26 +- src/Testcontainers.Xunit/DbContainerTest.cs | 31 +- .../DbContainerTestMethods.cs | 26 +- .../IDbContainerTestMethods.cs | 2 +- src/Testcontainers.Xunit/Logger.cs | 26 +- src/Testcontainers.Xunit/MessageSinkLogger.cs | 8 +- src/Testcontainers.Xunit/NullScope.cs | 6 +- src/Testcontainers.Xunit/TestOutputLogger.cs | 12 +- .../Testcontainers.Xunit.csproj | 30 +- src/Testcontainers.Xunit/Usings.cs | 2 +- .../Testcontainers.XunitV3.csproj | 38 +- .../Builders/AbstractBuilder`4.cs | 111 +++-- src/Testcontainers/Builders/Base64Provider.cs | 47 ++- .../Builders/BuildConfiguration.cs | 14 +- .../Builders/CommonDirectoryPath.cs | 46 ++- .../Builders/ContainerBuilder.cs | 12 +- .../Builders/ContainerBuilder`3.cs | 150 +++++-- .../Builders/CredsHelperProvider.cs | 23 +- .../Builders/CredsStoreProvider.cs | 16 +- src/Testcontainers/Builders/DockerConfig.cs | 68 +++- .../Builders/DockerConfigurationException.cs | 9 +- ...erDesktopEndpointAuthenticationProvider.cs | 8 +- .../DockerEndpointAuthenticationProvider.cs | 22 +- .../DockerRegistryAuthenticationProvider.cs | 38 +- .../Builders/DockerUnavailableException.cs | 9 +- ...vironmentEndpointAuthenticationProvider.cs | 11 +- .../Builders/IAbstractBuilder`3.cs | 10 +- .../Builders/IContainerBuilder`2.cs | 43 +- .../Builders/IImageFromDockerfileBuilder`1.cs | 5 +- .../Builders/ImageFromDockerfileBuilder.cs | 109 ++++- .../MTlsEndpointAuthenticationProvider.cs | 47 ++- src/Testcontainers/Builders/NetworkBuilder.cs | 16 +- .../NpipeEndpointAuthenticationProvider.cs | 3 +- ...tlessUnixEndpointAuthenticationProvider.cs | 23 +- ...ontainersEndpointAuthenticationProvider.cs | 23 +- src/Testcontainers/Builders/TlsCredentials.cs | 4 +- .../TlsEndpointAuthenticationProvider.cs | 50 ++- .../UnixEndpointAuthenticationProvider.cs | 3 +- src/Testcontainers/Builders/VolumeBuilder.cs | 16 +- .../Clients/CollectionConverter.cs | 7 +- .../ContainerConfigurationConverter.cs | 108 +++-- src/Testcontainers/Clients/DefaultLabels.cs | 33 +- .../Clients/DictionaryConverter.cs | 7 +- src/Testcontainers/Clients/DockerApiClient.cs | 54 ++- .../Clients/DockerContainerOperations.cs | 153 +++++-- .../Clients/DockerImageOperations.cs | 86 ++-- .../Clients/DockerNetworkOperations.cs | 46 ++- .../Clients/DockerSystemOperations.cs | 13 +- .../Clients/DockerVolumeOperations.cs | 40 +- .../Clients/FilterByProperty.cs | 12 +- .../Clients/IDockerContainerOperations.cs | 26 +- .../Clients/IDockerImageOperations.cs | 15 +- .../Clients/IHasListOperations.cs | 5 +- .../Clients/ITestcontainersClient.cs | 29 +- .../Clients/TestcontainersClient.cs | 239 +++++++---- ...ckerEndpointAuthenticationConfiguration.cs | 15 +- ...ckerRegistryAuthenticationConfiguration.cs | 17 +- .../Commons/AppendDictionary`2.cs | 10 +- .../Commons/AppendEnumerable`1.cs | 6 +- .../Commons/ComposableDictionary`2.cs | 7 +- .../JsonIgnoreRuntimeResourceLabels.cs | 26 +- .../Commons/OverwriteDictionary`2.cs | 8 +- .../Commons/OverwriteEnumerable`1.cs | 4 +- .../Commons/ResourceConfiguration.cs | 47 ++- .../Containers/ContainerConfiguration.cs | 62 ++- .../Configurations/CustomConfiguration.cs | 30 +- .../EnvironmentConfiguration.cs | 19 +- .../ImageFromDockerfileConfiguration.cs | 38 +- .../Networks/NetworkConfiguration.cs | 19 +- .../RedirectStdoutAndStderrToNull.cs | 3 +- .../RedirectStdoutAndStderrToStream.cs | 10 +- .../PropertiesFileConfiguration.cs | 48 +-- .../Configurations/TestcontainersSettings.cs | 101 +++-- src/Testcontainers/Configurations/Unix.cs | 75 ++-- .../Volumes/BinaryResourceMapping.cs | 6 +- .../Volumes/UriResourceMapping.cs | 6 +- .../Volumes/VolumeConfiguration.cs | 19 +- .../WaitStrategies/HttpWaitStrategy.cs | 53 ++- .../WaitStrategies/IWaitForContainerOS.cs | 65 ++- .../RetryLimitExceededException.cs | 4 +- .../WaitStrategies/UntilContainerIsHealthy.cs | 4 +- .../WaitStrategies/UntilContainerIsRunning.cs | 3 +- .../UntilDatabaseIsAvailable.cs | 11 +- .../UntilExternalTcpPortIsAvailable.cs | 3 +- .../UntilFileExistsInContainer.cs | 3 +- .../UntilInternalTcpPortIsAvailableOnUnix.cs | 9 +- ...ntilInternalTcpPortIsAvailableOnWindows.cs | 6 +- .../WaitStrategies/UntilMessageIsLogged.cs | 12 +- .../UntilUnixCommandIsCompleted.cs | 7 +- .../UntilWindowsCommandIsCompleted.cs | 8 +- .../WaitStrategies/WaitForContainerOS.cs | 81 +++- .../WaitStrategies/WaitForContainerUnix.cs | 30 +- .../WaitStrategies/WaitForContainerWindows.cs | 35 +- .../WaitStrategies/WaitStrategy.cs | 76 ++-- src/Testcontainers/Configurations/Windows.cs | 19 +- .../Containers/DockerContainer.cs | 248 +++++++----- .../Containers/ExecFailedException.cs | 8 +- .../Containers/ExecResultExtensions.cs | 13 +- src/Testcontainers/Containers/IContainer.cs | 35 +- .../Containers/PortForwarding.cs | 76 +++- .../Containers/ResourceReaper.cs | 233 +++++++---- .../Containers/ResourceReaperException.cs | 4 +- .../ResourceReaperStateEventArgs.cs | 5 +- src/Testcontainers/Containers/SocatBuilder.cs | 33 +- .../Containers/SocatConfiguration.cs | 7 +- .../Containers/SocatContainer.cs | 4 +- .../Containers/TarOutputMemoryStream.cs | 62 +-- src/Testcontainers/Guard.Null.cs | 26 +- src/Testcontainers/Guard.String.cs | 30 +- src/Testcontainers/Images/DockerIgnoreFile.cs | 32 +- src/Testcontainers/Images/DockerImage.cs | 38 +- .../Images/DockerfileArchive.cs | 94 +++-- .../Images/FutureDockerImage.cs | 30 +- .../Images/IFutureDockerImage.cs | 4 +- src/Testcontainers/Images/IImageExtensions.cs | 8 +- src/Testcontainers/Images/IgnoreFile.cs | 126 +++--- src/Testcontainers/Images/MatchImage.cs | 37 +- src/Testcontainers/Images/PullPolicy.cs | 15 +- src/Testcontainers/Logger.cs | 43 +- src/Testcontainers/Logging.cs | 383 ++++++++++++------ src/Testcontainers/Networks/DockerNetwork.cs | 42 +- .../Polyfills/X509Certificate2.cs | 15 +- src/Testcontainers/Resource.cs | 27 +- src/Testcontainers/Testcontainers.csproj | 22 +- src/Testcontainers/Volumes/DockerVolume.cs | 42 +- tests/Directory.Build.props | 2 +- .../ArtemisContainerTest.cs | 69 ++-- .../Testcontainers.ActiveMq.Tests.csproj | 40 +- tests/Testcontainers.ActiveMq.Tests/Usings.cs | 2 +- .../ArangoDbContainerTest.cs | 14 +- .../Testcontainers.ArangoDb.Tests.csproj | 36 +- tests/Testcontainers.ArangoDb.Tests/Usings.cs | 2 +- .../AzuriteContainerTest.cs | 45 +- .../Testcontainers.Azurite.Tests.csproj | 40 +- tests/Testcontainers.Azurite.Tests/Usings.cs | 2 +- .../BigQueryContainerTest.cs | 50 ++- .../Testcontainers.BigQuery.Tests.csproj | 36 +- tests/Testcontainers.BigQuery.Tests/Usings.cs | 6 +- .../BigtableContainerTest.cs | 14 +- .../Testcontainers.Bigtable.Tests.csproj | 36 +- tests/Testcontainers.Bigtable.Tests/Usings.cs | 2 +- .../CassandraContainerTest.cs | 31 +- .../Testcontainers.Cassandra.Tests.csproj | 42 +- .../Testcontainers.Cassandra.Tests/Usings.cs | 2 +- .../ClickHouseContainerTest.cs | 26 +- .../ClickHouseContainerTest.docs.cs | 17 +- .../Testcontainers.ClickHouse.Tests.csproj | 42 +- .../Testcontainers.ClickHouse.Tests/Usings.cs | 2 +- .../CockroachDbContainerTest.cs | 26 +- .../Testcontainers.CockroachDb.Tests.csproj | 38 +- .../Usings.cs | 2 +- .../Testcontainers.Commons/CommonCommands.cs | 9 +- .../CommonCredentials.cs | 2 +- tests/Testcontainers.Commons/CommonImages.cs | 6 +- tests/Testcontainers.Commons/DockerCli.cs | 39 +- tests/Testcontainers.Commons/TestSession.cs | 8 +- .../Testcontainers.Commons.csproj | 30 +- tests/Testcontainers.Commons/Usings.cs | 2 +- .../ConsulContainerTest.cs | 11 +- .../Testcontainers.Consul.Tests.csproj | 36 +- tests/Testcontainers.Consul.Tests/Usings.cs | 2 +- .../CosmosDbContainerTest.cs | 17 +- .../Testcontainers.CosmosDb.Tests.csproj | 36 +- tests/Testcontainers.CosmosDb.Tests/Usings.cs | 2 +- .../CouchDbContainerTest.cs | 8 +- .../Testcontainers.CouchDb.Tests.csproj | 36 +- tests/Testcontainers.CouchDb.Tests/Usings.cs | 2 +- .../CouchbaseContainerTest.cs | 14 +- .../Testcontainers.Couchbase.Tests.csproj | 36 +- .../Testcontainers.Couchbase.Tests/Usings.cs | 2 +- .../DatabasesContainerTest.cs | 65 ++- .../Testcontainers.Databases.Tests.csproj | 38 +- .../Testcontainers.Databases.Tests/Usings.cs | 2 +- .../Db2ContainerTest.cs | 26 +- .../DeclineLicenseAgreementTest.cs | 6 +- .../Testcontainers.Db2.Tests.csproj | 63 +-- .../Testcontainers.Db2.Tests.targets | 42 +- tests/Testcontainers.Db2.Tests/Usings.cs | 4 +- .../DynamoDbContainerTest.cs | 43 +- .../Testcontainers.DynamoDb.Tests.csproj | 36 +- tests/Testcontainers.DynamoDb.Tests/Usings.cs | 2 +- .../ElasticsearchContainerTest.cs | 12 +- .../Testcontainers.Elasticsearch.Tests.csproj | 40 +- .../Usings.cs | 2 +- .../EventHubsContainerTest.cs | 80 ++-- .../Testcontainers.EventHubs.Tests.csproj | 40 +- .../Testcontainers.EventHubs.Tests/Usings.cs | 2 +- .../EventStoreDbContainerTest.cs | 30 +- .../Testcontainers.EventStoreDb.Tests.csproj | 36 +- .../Usings.cs | 2 +- .../FakeGcsServerContainerTest.cs | 35 +- .../Testcontainers.FakeGcsServer.Tests.csproj | 36 +- .../Usings.cs | 2 +- .../FirebirdSqlContainerTest.cs | 54 ++- .../Testcontainers.FirebirdSql.Tests.csproj | 38 +- .../Usings.cs | 2 +- .../FirestoreContainerTest.cs | 24 +- .../Testcontainers.Firestore.Tests.csproj | 36 +- .../Testcontainers.Firestore.Tests/Usings.cs | 2 +- .../InfluxDbContainerTest.cs | 30 +- .../Testcontainers.InfluxDb.Tests.csproj | 36 +- tests/Testcontainers.InfluxDb.Tests/Usings.cs | 2 +- .../JanusGraphContainerTest.cs | 23 +- .../Testcontainers.JanusGraph.Tests.csproj | 36 +- .../Testcontainers.JanusGraph.Tests/Usings.cs | 2 +- .../K3sContainerTest.cs | 23 +- .../Testcontainers.K3s.Tests.csproj | 36 +- tests/Testcontainers.K3s.Tests/Usings.cs | 2 +- .../KafkaBuilderTest.cs | 18 +- .../KafkaContainerNetworkTest.cs | 32 +- .../KafkaContainerRegistryTest.cs | 48 ++- .../KafkaContainerTest.cs | 39 +- .../Testcontainers.Kafka.Tests.csproj | 40 +- tests/Testcontainers.Kafka.Tests/Usings.cs | 2 +- .../KeycloakContainerTest.cs | 35 +- .../Testcontainers.Keycloak.Tests.csproj | 36 +- tests/Testcontainers.Keycloak.Tests/Usings.cs | 2 +- .../KustoContainerTest.cs | 15 +- .../Testcontainers.Kusto.Tests.csproj | 30 +- tests/Testcontainers.Kusto.Tests/Usings.cs | 2 +- .../LocalStackContainerTest.cs | 63 ++- .../Testcontainers.LocalStack.Tests.csproj | 44 +- .../Testcontainers.LocalStack.Tests/Usings.cs | 4 +- .../LowkeyVaultContainerTest.cs | 64 ++- .../Testcontainers.LowkeyVault.Tests.csproj | 40 +- .../Usings.cs | 2 +- .../MariaDbContainerTest.cs | 20 +- .../Testcontainers.MariaDb.Tests.csproj | 38 +- tests/Testcontainers.MariaDb.Tests/Usings.cs | 2 +- .../MilvusContainerTest.cs | 64 +-- .../Testcontainers.Milvus.Tests.csproj | 36 +- tests/Testcontainers.Milvus.Tests/Usings.cs | 2 +- .../MinioContainerTest.cs | 33 +- .../Testcontainers.Minio.Tests.csproj | 36 +- tests/Testcontainers.Minio.Tests/Usings.cs | 2 +- .../MongoDbContainerTest.cs | 53 ++- .../Testcontainers.MongoDb.Tests.csproj | 40 +- tests/Testcontainers.MongoDb.Tests/Usings.cs | 2 +- .../MsSqlContainerTest.cs | 21 +- .../Testcontainers.MsSql.Tests.csproj | 42 +- tests/Testcontainers.MsSql.Tests/Usings.cs | 2 +- .../MySqlContainerTest.cs | 37 +- .../Testcontainers.MySql.Tests.csproj | 38 +- tests/Testcontainers.MySql.Tests/Usings.cs | 2 +- .../NatsContainerTest.cs | 33 +- .../Testcontainers.Nats.Tests.csproj | 36 +- tests/Testcontainers.Nats.Tests/Usings.cs | 2 +- .../Neo4jBuilderTest.cs | 21 +- .../Neo4jContainerTest.cs | 27 +- .../Testcontainers.Neo4j.Tests.csproj | 40 +- tests/Testcontainers.Neo4j.Tests/Usings.cs | 2 +- .../OllamaContainerTest.cs | 18 +- .../Testcontainers.Ollama.Tests.csproj | 36 +- tests/Testcontainers.Ollama.Tests/Usings.cs | 2 +- .../OpenSearchBuilderTest.cs | 2 +- .../OpenSearchContainerTest.cs | 66 +-- .../Testcontainers.OpenSearch.Tests.csproj | 40 +- .../Testcontainers.OpenSearch.Tests/Usings.cs | 2 +- .../OracleContainerTest.cs | 151 +++++-- .../Testcontainers.Oracle.Tests.csproj | 40 +- tests/Testcontainers.Oracle.Tests/Usings.cs | 2 +- .../Testcontainers.Oracle11.Tests.csproj | 46 +-- .../Testcontainers.Oracle18.Tests.csproj | 46 +-- .../Testcontainers.Oracle21.Tests.csproj | 46 +-- .../Testcontainers.Oracle23.Tests.csproj | 46 +-- .../PapercutContainerTest.cs | 13 +- .../Testcontainers.Papercut.Tests.csproj | 34 +- tests/Testcontainers.Papercut.Tests/Usings.cs | 2 +- .../AcceptLicenseAgreementTest.cs | 11 +- .../ComposableTest.cs | 36 +- .../DependsOnTest.cs | 39 +- .../ExecFailedExceptionTest.cs | 57 ++- .../ExecResultExtensionsTest.cs | 19 +- .../LoggerTest.cs | 21 +- .../PauseUnpauseTest.cs | 15 +- .../PortBindingTest.cs | 25 +- .../PortForwardingTest.cs | 88 ++-- .../ReusableResourceTest.cs | 91 +++-- .../SocatContainerTest.cs | 32 +- .../TarOutputMemoryStreamTest.cs | 128 ++++-- ...Testcontainers.Platform.Linux.Tests.csproj | 36 +- .../Usings.cs | 2 +- .../WaitStrategyTest.cs | 50 ++- .../SkipOnLinuxEngineAttribute.cs | 6 +- ...stcontainers.Platform.Windows.Tests.csproj | 32 +- .../Usings.cs | 2 +- .../WindowsContainerTest.cs | 69 ++-- .../PostgreSqlContainerTest.cs | 37 +- .../Testcontainers.PostgreSql.Tests.csproj | 42 +- .../Testcontainers.PostgreSql.Tests/Usings.cs | 2 +- .../PubSubContainerTest.cs | 29 +- .../Testcontainers.PubSub.Tests.csproj | 36 +- tests/Testcontainers.PubSub.Tests/Usings.cs | 2 +- .../PulsarContainerTest.cs | 98 +++-- .../Testcontainers.Pulsar.Tests.csproj | 40 +- tests/Testcontainers.Pulsar.Tests/Usings.cs | 2 +- .../PemCertificate.cs | 21 +- .../QdrantDefaultContainerTest.cs | 12 +- .../QdrantSecureContainerTest.cs | 34 +- .../Testcontainers.Qdrant.Tests.csproj | 40 +- tests/Testcontainers.Qdrant.Tests/Usings.cs | 2 +- .../RabbitMqContainerTest.cs | 5 +- .../Testcontainers.RabbitMq.Tests.csproj | 40 +- tests/Testcontainers.RabbitMq.Tests/Usings.cs | 2 +- .../RavenDbContainerTest.cs | 5 +- .../Testcontainers.RavenDb.Tests.csproj | 36 +- tests/Testcontainers.RavenDb.Tests/Usings.cs | 2 +- .../RedisContainerTest.cs | 8 +- .../Testcontainers.Redis.Tests.csproj | 36 +- tests/Testcontainers.Redis.Tests/Usings.cs | 2 +- .../RedpandaContainerTest.cs | 8 +- .../Testcontainers.Redpanda.Tests.csproj | 36 +- tests/Testcontainers.Redpanda.Tests/Usings.cs | 2 +- .../DefaultResourceReaperTest.cs | 23 +- ...Testcontainers.ResourceReaper.Tests.csproj | 10 +- .../DeclineLicenseAgreementTest.cs | 6 +- .../ServiceBusContainerTest.cs | 69 ++-- .../Testcontainers.ServiceBus.Tests.csproj | 50 +-- .../Testcontainers.ServiceBus.Tests/Usings.cs | 2 +- .../SftpContainerTest.cs | 15 +- .../Testcontainers.Sftp.Tests.csproj | 34 +- tests/Testcontainers.Sftp.Tests/Usings.cs | 2 +- .../ContinuousIntegration/JobsTest.cs | 24 +- .../WaitUntilFiveSecondsPassedFixture.cs | 4 +- .../Fixtures/Containers/Unix/AlpineFixture.cs | 4 +- .../Fixtures/Containers/Unix/DockerMTls.cs | 4 +- .../Containers/Unix/DockerTlsFixture.cs | 5 +- .../Containers/Unix/NetworkFixture.cs | 10 +- .../Containers/Unix/OpenSsl1_1_1Fixture.cs | 5 +- .../Containers/Unix/OpenSsl3_1Fixture.cs | 5 +- .../Unix/ProtectDockerDaemonSocket.cs | 38 +- .../Fixtures/Containers/Unix/VolumeFixture.cs | 12 +- .../Fixtures/Images/DockerImageFixture.cs | 130 +++++- .../Images/DockerImageFixtureSerializable.cs | 4 +- .../Fixtures/Images/HealthCheckFixture.cs | 10 +- .../Fixtures/Images/IgnoreFileFixture.cs | 20 +- .../Testcontainers.Tests.csproj | 12 +- .../Unit/Builders/BuildConfigurationTest.cs | 345 ++++++++-------- .../Unit/Builders/CommonDirectoryPathTest.cs | 14 +- .../Unit/Builders/DockerConfigTest.cs | 71 +++- .../ContainerConfigurationConverterTest.cs | 32 +- .../Configurations/CustomConfigurationTest.cs | 201 +++++++-- ...ockerEndpointAuthenticationProviderTest.cs | 172 ++++++-- .../DockerImageNameSubstitutionTest.cs | 44 +- ...ockerRegistryAuthenticationProviderTest.cs | 151 +++++-- .../Configurations/ResourcePropertiesTest.cs | 60 +-- .../TestcontainersWaitStrategyTest.cs | 56 ++- .../WaitUntilContainerIsHealthyTest.cs | 6 +- .../WaitUntilExternalTcpPortIsAvailable.cs | 13 +- .../WaitUntilFileExistsInContainerTest.cs | 17 +- .../WaitUntilHttpRequestIsSucceededTest.cs | 61 +-- .../WaitUntilMessageIsLoggedTest.cs | 7 +- .../Containers/Unix/GetContainerLogsTest.cs | 15 +- .../Unix/ProtectDockerDaemonSocketTest.cs | 25 +- .../Unix/ReadFileFromContainerTest.cs | 20 +- ...TestcontainersContainerCancellationTest.cs | 11 +- .../Unix/TestcontainersContainerTest.cs | 170 ++++---- tests/Testcontainers.Tests/Unit/GuardTest.cs | 44 +- .../Unit/Images/ImageFromDockerfileTest.cs | 91 ++++- .../Unit/Images/TestcontainersImageTest.cs | 21 +- .../TestcontainerNetworkBuilderTest.cs | 58 ++- .../Networks/TestcontainersNetworkTest.cs | 14 +- .../TestcontainersVolumeBuilderTest.cs | 44 +- .../Unit/Volumes/TestcontainersVolumeTest.cs | 53 ++- .../Testcontainers.Typesense.Tests.csproj | 34 +- .../TypesenseContainerTest.cs | 11 +- .../Testcontainers.Typesense.Tests/Usings.cs | 2 +- .../Testcontainers.Weaviate.Tests.csproj | 34 +- tests/Testcontainers.Weaviate.Tests/Usings.cs | 2 +- .../WeaviateContainerTest.cs | 8 +- .../Testcontainers.WebDriver.Tests.csproj | 36 +- .../Testcontainers.WebDriver.Tests/Usings.cs | 2 +- .../WebDriverContainerTest.cs | 71 ++-- .../AlphabeticalTestCaseOrderer.cs | 6 +- .../PostgreSqlContainer.cs | 11 +- .../RedisContainerTest`1.cs | 7 +- .../RedisContainerTest`2.cs | 16 +- .../Testcontainers.Xunit.Tests.csproj | 52 +-- tests/Testcontainers.Xunit.Tests/Usings.cs | 2 +- .../Testcontainers.XunitV3.Tests.csproj | 62 +-- 715 files changed, 12556 insertions(+), 7223 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index bd9487ff1..0703330f3 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -36,10 +36,25 @@ - - + + - + diff --git a/Directory.Packages.props b/Directory.Packages.props index e6f7d7ac9..cf03c847a 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -1,90 +1,90 @@ - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build/Build.csproj b/build/Build.csproj index d980d599c..0e266c94a 100644 --- a/build/Build.csproj +++ b/build/Build.csproj @@ -1,13 +1,13 @@ - - net9.0 - Exe - false - $(MSBuildProjectDirectory)/.. - - - - - - - \ No newline at end of file + + net9.0 + Exe + false + $(MSBuildProjectDirectory)/.. + + + + + + + diff --git a/build/Credentials.cs b/build/Credentials.cs index 817050b62..873144f10 100644 --- a/build/Credentials.cs +++ b/build/Credentials.cs @@ -13,8 +13,7 @@ private BuildCredentials(string username, string password) public static BuildCredentials GetCodeSigningCertificateCredentials(ICakeContext context) { - return new BuildCredentials - ( + return new BuildCredentials( null, context.EnvironmentVariable("CODE_SIGNING_CERTIFICATE_PASSWORD") ); @@ -38,8 +37,7 @@ private SonarQubeCredentials(string url, string key, string token, string organi public static SonarQubeCredentials GetSonarQubeCredentials(ICakeContext context) { - return new SonarQubeCredentials - ( + return new SonarQubeCredentials( context.EnvironmentVariable("SONARCLOUD_URL"), context.EnvironmentVariable("SONARCLOUD_KEY"), context.EnvironmentVariable("SONARCLOUD_TOKEN"), @@ -61,10 +59,9 @@ private NuGetCredentials(string source, string apiKey) public static NuGetCredentials GetNuGetCredentials(ICakeContext context) { - return new NuGetCredentials - ( + return new NuGetCredentials( context.EnvironmentVariable("FEED_SOURCE"), context.EnvironmentVariable("FEED_API_KEY") ); } -} \ No newline at end of file +} diff --git a/build/Parameters.cs b/build/Parameters.cs index ecb4a8930..e37893172 100644 --- a/build/Parameters.cs +++ b/build/Parameters.cs @@ -2,9 +2,7 @@ namespace Testcontainers.Build; internal sealed class BuildParameters { - private BuildParameters() - { - } + private BuildParameters() { } public string Solution { get; private set; } public string Target { get; private set; } @@ -39,7 +37,10 @@ public static BuildParameters Instance(ICakeContext context) { Solution = context.MakeAbsolute(new DirectoryPath(solutionFilePath)).FullPath, Target = context.Argument("target", "Default"), - Configuration = context.Argument("configuration", buildInformation.IsReleaseBuild ? "Release" : "Debug"), + Configuration = context.Argument( + "configuration", + buildInformation.IsReleaseBuild ? "Release" : "Debug" + ), Sha = buildInformation.Sha, Branch = buildInformation.Branch, SourceBranch = buildInformation.SourceBranch, @@ -53,11 +54,12 @@ public static BuildParameters Instance(ICakeContext context) IsPullRequest = buildInformation.IsPullRequest, ShouldPublish = !buildInformation.IsLocalBuild && buildInformation.ShouldPublish, Verbosity = DotNetVerbosity.Minimal, - CodeSigningCertificateCredentials = BuildCredentials.GetCodeSigningCertificateCredentials(context), + CodeSigningCertificateCredentials = + BuildCredentials.GetCodeSigningCertificateCredentials(context), SonarQubeCredentials = SonarQubeCredentials.GetSonarQubeCredentials(context), NuGetCredentials = NuGetCredentials.GetNuGetCredentials(context), Projects = BuildProjects.Instance(context, solutionFilePath), Paths = BuildPaths.Instance(context, buildInformation.Version), }; } -} \ No newline at end of file +} diff --git a/build/Paths.cs b/build/Paths.cs index e9f320049..771f9f8b4 100644 --- a/build/Paths.cs +++ b/build/Paths.cs @@ -2,9 +2,7 @@ namespace Testcontainers.Build; internal sealed class BuildPaths { - private BuildPaths() - { - } + private BuildPaths() { } public BuildFiles Files { get; private set; } public BuildDirectories Directories { get; private set; } @@ -55,7 +53,8 @@ public BuildDirectories( DirectoryPath testResultsDir, DirectoryPath testCoverageDir, DirectoryPath nugetDir, - DirectoryPath artifactsDir) + DirectoryPath artifactsDir + ) { TestResultsDirectoryPath = testResultsDir; TestCoverageDirectoryPath = testCoverageDir; @@ -70,4 +69,4 @@ public BuildDirectories( new DirectoryPath(".sonarqube"), }; } -} \ No newline at end of file +} diff --git a/build/Program.cs b/build/Program.cs index a3e410daf..673f68628 100644 --- a/build/Program.cs +++ b/build/Program.cs @@ -10,4 +10,4 @@ public static int Main(string[] args) .UseLifetime() .Run(args); } -} \ No newline at end of file +} diff --git a/build/Projects.cs b/build/Projects.cs index 7dbd8f0e4..5192c9bfc 100644 --- a/build/Projects.cs +++ b/build/Projects.cs @@ -2,9 +2,7 @@ namespace Testcontainers.Build; internal sealed class BuildProjects { - private BuildProjects() - { - } + private BuildProjects() { } public ICollection All { get; private set; } public ICollection NoneTests { get; private set; } @@ -23,4 +21,4 @@ public static BuildProjects Instance(ICakeContext context, string solutionFilePa Testcontainers = allProjects.Single(project => "Testcontainers".Equals(project.Name)), }; } -} \ No newline at end of file +} diff --git a/build/Tasks.cs b/build/Tasks.cs index 38f916294..72252fb5b 100644 --- a/build/Tasks.cs +++ b/build/Tasks.cs @@ -6,18 +6,21 @@ public sealed class BuildContext(ICakeContext context) : FrostingContext(context public void DotNetTest(SolutionProject project) { - this.DotNetTest(project.Path.FullPath, new DotNetTestSettings - { - Configuration = Parameters.Configuration, - Verbosity = Parameters.Verbosity, - NoRestore = true, - NoBuild = true, - Collectors = ["XPlat Code Coverage;Format=opencover"], - Filter = Parameters.TestFilter, - ResultsDirectory = Parameters.Paths.Directories.TestResultsDirectoryPath, - ArgumentCustomization = args => args - .AppendSwitchQuoted("--blame-hang-timeout", "5m"), - }); + this.DotNetTest( + project.Path.FullPath, + new DotNetTestSettings + { + Configuration = Parameters.Configuration, + Verbosity = Parameters.Verbosity, + NoRestore = true, + NoBuild = true, + Collectors = ["XPlat Code Coverage;Format=opencover"], + Filter = Parameters.TestFilter, + ResultsDirectory = Parameters.Paths.Directories.TestResultsDirectoryPath, + ArgumentCustomization = args => + args.AppendSwitchQuoted("--blame-hang-timeout", "5m"), + } + ); } } @@ -26,12 +29,15 @@ public sealed class BuildLifetime : FrostingLifetime public override void Setup(BuildContext context, ISetupContext info) { var param = context.Parameters; - context.Information("Building version {0} of Testcontainers ({1}@{2})", param.Version, param.Branch, param.Sha); + context.Information( + "Building version {0} of Testcontainers ({1}@{2})", + param.Version, + param.Branch, + param.Sha + ); } - public override void Teardown(BuildContext context, ITeardownContext info) - { - } + public override void Teardown(BuildContext context, ITeardownContext info) { } } [TaskName("Clean")] @@ -61,10 +67,10 @@ public sealed class RestoreNuGetPackagesTask : FrostingTask public override void Run(BuildContext context) { var param = context.Parameters; - context.DotNetRestore(param.Solution, new DotNetRestoreSettings - { - Verbosity = param.Verbosity, - }); + context.DotNetRestore( + param.Solution, + new DotNetRestoreSettings { Verbosity = param.Verbosity } + ); } } @@ -92,16 +98,22 @@ public override void Run(BuildContext context) // save build time. var solutionOrProjectFilePath = string.IsNullOrEmpty(param.TestProject) ? param.Solution - : param.Projects.OnlyTests.Single(testProject => testProject.Path.FullPath.EndsWith(param.TestProject + ".Tests.csproj")).Path.FullPath; + : param + .Projects.OnlyTests.Single(testProject => + testProject.Path.FullPath.EndsWith(param.TestProject + ".Tests.csproj") + ) + .Path.FullPath; - context.DotNetBuild(solutionOrProjectFilePath, new DotNetBuildSettings - { - Configuration = param.Configuration, - Verbosity = param.Verbosity, - NoRestore = true, - ArgumentCustomization = args => args - .Append("/p:ContinuousIntegrationBuild=true"), - }); + context.DotNetBuild( + solutionOrProjectFilePath, + new DotNetBuildSettings + { + Configuration = param.Configuration, + Verbosity = param.Verbosity, + NoRestore = true, + ArgumentCustomization = args => args.Append("/p:ContinuousIntegrationBuild=true"), + } + ); } } @@ -111,7 +123,9 @@ public sealed class TestTask : FrostingTask public override void Run(BuildContext context) { var param = context.Parameters; - var testProject = param.Projects.OnlyTests.Single(testProject => testProject.Path.FullPath.EndsWith(param.TestProject + ".Tests.csproj")); + var testProject = param.Projects.OnlyTests.Single(testProject => + testProject.Path.FullPath.EndsWith(param.TestProject + ".Tests.csproj") + ); context.DotNetTest(testProject); } } @@ -131,7 +145,8 @@ public override void Run(BuildContext context) [TaskName("Format")] public sealed class CheckFormatTask : FrostingTask -{ public override void Run(BuildContext context) +{ + public override void Run(BuildContext context) { var param = context.Parameters; context.DotNetTool("./", "csharpier", "format ."); @@ -154,29 +169,36 @@ public sealed class SonarBeginTask : FrostingTask public override void Run(BuildContext context) { var param = context.Parameters; - context.SonarBegin(new SonarBeginSettings - { - Url = param.SonarQubeCredentials.Url, - Key = param.SonarQubeCredentials.Key, - Token = param.SonarQubeCredentials.Token, - Organization = param.SonarQubeCredentials.Organization, - // A pull request analysis cannot have the branch analysis parameter 'sonar.branch.name'. - Branch = param.IsPullRequest ? null : param.Branch, - UseCoreClr = true, - Silent = true, - Version = param.Version[..5], - PullRequestProvider = "GitHub", - PullRequestGithubEndpoint = "https://api.github.com/", - PullRequestGithubRepository = "testcontainers/testcontainers-dotnet", - PullRequestKey = param.IsPullRequest && int.TryParse(param.PullRequestId, out var id) ? id : null, - PullRequestBranch = param.SourceBranch, - PullRequestBase = param.TargetBranch, - OpenCoverReportsPath = $"{context.MakeAbsolute(param.Paths.Directories.TestResultsDirectoryPath)}/**/*.opencover.xml", - VsTestReportsPath = $"{context.MakeAbsolute(param.Paths.Directories.TestResultsDirectoryPath)}/**/*.trx", - ArgumentCustomization = args => args - .Append("/d:sonar.scanner.scanAll=\"false\"") - .Append("/d:sonar.scanner.skipJreProvisioning=\"true\""), - }); + context.SonarBegin( + new SonarBeginSettings + { + Url = param.SonarQubeCredentials.Url, + Key = param.SonarQubeCredentials.Key, + Token = param.SonarQubeCredentials.Token, + Organization = param.SonarQubeCredentials.Organization, + // A pull request analysis cannot have the branch analysis parameter 'sonar.branch.name'. + Branch = param.IsPullRequest ? null : param.Branch, + UseCoreClr = true, + Silent = true, + Version = param.Version[..5], + PullRequestProvider = "GitHub", + PullRequestGithubEndpoint = "https://api.github.com/", + PullRequestGithubRepository = "testcontainers/testcontainers-dotnet", + PullRequestKey = + param.IsPullRequest && int.TryParse(param.PullRequestId, out var id) + ? id + : null, + PullRequestBranch = param.SourceBranch, + PullRequestBase = param.TargetBranch, + OpenCoverReportsPath = + $"{context.MakeAbsolute(param.Paths.Directories.TestResultsDirectoryPath)}/**/*.opencover.xml", + VsTestReportsPath = + $"{context.MakeAbsolute(param.Paths.Directories.TestResultsDirectoryPath)}/**/*.trx", + ArgumentCustomization = args => + args.Append("/d:sonar.scanner.scanAll=\"false\"") + .Append("/d:sonar.scanner.skipJreProvisioning=\"true\""), + } + ); } } @@ -186,11 +208,9 @@ public sealed class SonarEndTask : FrostingTask public override void Run(BuildContext context) { var param = context.Parameters; - context.SonarEnd(new SonarEndSettings - { - Token = param.SonarQubeCredentials.Token, - UseCoreClr = true, - }); + context.SonarEnd( + new SonarEndSettings { Token = param.SonarQubeCredentials.Token, UseCoreClr = true } + ); } } @@ -202,16 +222,18 @@ public sealed class CreateNuGetPackagesTask : FrostingTask public override void Run(BuildContext context) { var param = context.Parameters; - context.DotNetPack(param.Solution, new DotNetPackSettings - { - Configuration = param.Configuration, - Verbosity = param.Verbosity, - NoRestore = true, - NoBuild = true, - OutputDirectory = param.Paths.Directories.NuGetDirectoryPath, - ArgumentCustomization = args => args - .Append($"/p:Version={param.Version}"), - }); + context.DotNetPack( + param.Solution, + new DotNetPackSettings + { + Configuration = param.Configuration, + Verbosity = param.Verbosity, + NoRestore = true, + NoBuild = true, + OutputDirectory = param.Paths.Directories.NuGetDirectoryPath, + ArgumentCustomization = args => args.Append($"/p:Version={param.Version}"), + } + ); } } @@ -219,21 +241,33 @@ public override void Run(BuildContext context) public sealed class SignNuGetPackagesTask : FrostingTask { // We do not have access to a valid code signing certificate anymore. - public override bool ShouldRun(BuildContext context) => /* context.Parameters.ShouldPublish */ false; + public override bool ShouldRun(BuildContext context) => /* context.Parameters.ShouldPublish */ + false; public override void Run(BuildContext context) { var param = context.Parameters; - context.StartProcess("dotnet", new ProcessSettings - { - Arguments = new ProcessArgumentBuilder() - .Append("nuget") - .Append("sign") - .AppendSwitchQuoted("--certificate-path", param.Paths.Files.CodeSigningCertificateFilePath.FullPath) - .AppendSwitchQuoted("--certificate-password", param.CodeSigningCertificateCredentials.Password) - .AppendSwitchQuoted("--timestamper", "http://ts.quovadisglobal.com/eu") - .Append($"{context.MakeAbsolute(param.Paths.Directories.NuGetDirectoryPath)}/**/*.nupkg"), - }); + context.StartProcess( + "dotnet", + new ProcessSettings + { + Arguments = new ProcessArgumentBuilder() + .Append("nuget") + .Append("sign") + .AppendSwitchQuoted( + "--certificate-path", + param.Paths.Files.CodeSigningCertificateFilePath.FullPath + ) + .AppendSwitchQuoted( + "--certificate-password", + param.CodeSigningCertificateCredentials.Password + ) + .AppendSwitchQuoted("--timestamper", "http://ts.quovadisglobal.com/eu") + .Append( + $"{context.MakeAbsolute(param.Paths.Directories.NuGetDirectoryPath)}/**/*.nupkg" + ), + } + ); } } @@ -245,14 +279,19 @@ public sealed class PublishNuGetPackagesTask : FrostingTask public override void Run(BuildContext context) { var param = context.Parameters; - foreach (var package in context.GetFiles($"{param.Paths.Directories.NuGetDirectoryPath}/*.nupkg")) + foreach ( + var package in context.GetFiles($"{param.Paths.Directories.NuGetDirectoryPath}/*.nupkg") + ) { - context.DotNetNuGetPush(package.FullPath, new DotNetNuGetPushSettings - { - Source = param.NuGetCredentials.Source, - ApiKey = param.NuGetCredentials.ApiKey, - SkipDuplicate = true, - }); + context.DotNetNuGetPush( + package.FullPath, + new DotNetNuGetPushSettings + { + Source = param.NuGetCredentials.Source, + ApiKey = param.NuGetCredentials.ApiKey, + SkipDuplicate = true, + } + ); } } } @@ -279,4 +318,4 @@ public sealed class SonarTask : FrostingTask; [IsDependentOn(typeof(CreateNuGetPackagesTask))] [IsDependentOn(typeof(SignNuGetPackagesTask))] [IsDependentOn(typeof(PublishNuGetPackagesTask))] -public sealed class PublishTask : FrostingTask; \ No newline at end of file +public sealed class PublishTask : FrostingTask; diff --git a/build/Usings.cs b/build/Usings.cs index a2cde15ca..c787c8fb1 100644 --- a/build/Usings.cs +++ b/build/Usings.cs @@ -17,4 +17,4 @@ global using Cake.Core.IO; global using Cake.Frosting; global using Cake.Git; -global using Cake.Sonar; \ No newline at end of file +global using Cake.Sonar; diff --git a/build/Version.cs b/build/Version.cs index 753bc3799..1eac86538 100644 --- a/build/Version.cs +++ b/build/Version.cs @@ -2,9 +2,7 @@ namespace Testcontainers.Build; internal sealed class BuildInformation { - private BuildInformation() - { - } + private BuildInformation() { } public string Sha { get; private set; } public string Branch { get; private set; } @@ -27,7 +25,10 @@ public static BuildInformation Instance(ICakeContext context, string propertiesF var publishNuGetPackage = context.EnvironmentVariable("PUBLISH_NUGET_PACKAGE"); - var version = context.XmlPeek(propertiesFilePath, "/Project/PropertyGroup[1]/Version/text()"); + var version = context.XmlPeek( + propertiesFilePath, + "/Project/PropertyGroup[1]/Version/text()" + ); var git = context.GitBranchCurrent("."); @@ -51,11 +52,17 @@ public static BuildInformation Instance(ICakeContext context, string propertiesF { branch = environment.Workflow.RefName; isPullRequest = environment.PullRequest.IsPullRequest; - isFork = "fork".Equals(environment.Workflow.EventName, StringComparison.OrdinalIgnoreCase); + isFork = "fork".Equals( + environment.Workflow.EventName, + StringComparison.OrdinalIgnoreCase + ); buildId = environment.Workflow.RunId; // Set build system environment variables and parameters. - buildSystem.GitHubActions.Commands.SetEnvironmentVariable("semVer", version.Substring(0, 5)); + buildSystem.GitHubActions.Commands.SetEnvironmentVariable( + "semVer", + version.Substring(0, 5) + ); } if (isPullRequest) @@ -67,11 +74,18 @@ public static BuildInformation Instance(ICakeContext context, string propertiesF var isReleaseBuild = GetIsReleaseBuild(branch); - var shouldPublish = GetShouldPublish(branch) && ("1".Equals(publishNuGetPackage, StringComparison.Ordinal) || (bool.TryParse(publishNuGetPackage, out var result) && result)); + var shouldPublish = + GetShouldPublish(branch) + && ( + "1".Equals(publishNuGetPackage, StringComparison.Ordinal) + || (bool.TryParse(publishNuGetPackage, out var result) && result) + ); if (isFork && isPullRequest && shouldPublish) { - throw new ArgumentException("Use 'feature/' or 'bugfix/' prefix for pull request branches."); + throw new ArgumentException( + "Use 'feature/' or 'bugfix/' prefix for pull request branches." + ); } if (!isReleaseBuild) @@ -110,4 +124,4 @@ private static bool GetShouldPublish(string branch) var branches = new[] { "main", "develop" }; return branches.Any(b => StringComparer.OrdinalIgnoreCase.Equals(b, branch)); } -} \ No newline at end of file +} diff --git a/examples/Flyway/Directory.Build.props b/examples/Flyway/Directory.Build.props index 1bf52aaea..088a103d1 100644 --- a/examples/Flyway/Directory.Build.props +++ b/examples/Flyway/Directory.Build.props @@ -1,25 +1,25 @@ - - 0.1.0 - $(AssemblyName) - $(Version) - $(Version) - $(Version) - en-US - Andre Hofmeister - - - - - - - - git - https://github.com/testcontainers/testcontainers-dotnet-sample - - - 10.0 - enable - - \ No newline at end of file + + 0.1.0 + $(AssemblyName) + $(Version) + $(Version) + $(Version) + en-US + Andre Hofmeister + + + + + + + + git + https://github.com/testcontainers/testcontainers-dotnet-sample + + + 10.0 + enable + + diff --git a/examples/Flyway/Directory.Packages.props b/examples/Flyway/Directory.Packages.props index 07fab9a1f..befe7cb2f 100644 --- a/examples/Flyway/Directory.Packages.props +++ b/examples/Flyway/Directory.Packages.props @@ -1,15 +1,15 @@ - - true - - - - - - - - - - - \ No newline at end of file + + true + + + + + + + + + + + diff --git a/examples/Flyway/tests/Flyway.Tests/DbFixture.cs b/examples/Flyway/tests/Flyway.Tests/DbFixture.cs index 7359c0350..40f2a5e9c 100644 --- a/examples/Flyway/tests/Flyway.Tests/DbFixture.cs +++ b/examples/Flyway/tests/Flyway.Tests/DbFixture.cs @@ -40,11 +40,14 @@ public DbFixture() .WithCommand("migrate") .WithNetwork(_network) .DependsOn(_postgreSqlContainer) - .WithWaitStrategy(Wait.ForUnixContainer().AddCustomWaitStrategy(new MigrationCompleted())) + .WithWaitStrategy( + Wait.ForUnixContainer().AddCustomWaitStrategy(new MigrationCompleted()) + ) .Build(); } - public DbConnection DbConnection => new NpgsqlConnection(((PostgreSqlContainer)_postgreSqlContainer).GetConnectionString()); + public DbConnection DbConnection => + new NpgsqlConnection(((PostgreSqlContainer)_postgreSqlContainer).GetConnectionString()); public Task InitializeAsync() { @@ -71,4 +74,4 @@ public Task UntilAsync(IContainer container) return Task.FromResult(TestcontainersStates.Exited.Equals(container.State)); } } -} \ No newline at end of file +} diff --git a/examples/Flyway/tests/Flyway.Tests/Flyway.Tests.csproj b/examples/Flyway/tests/Flyway.Tests/Flyway.Tests.csproj index 479e035aa..15d3b1213 100644 --- a/examples/Flyway/tests/Flyway.Tests/Flyway.Tests.csproj +++ b/examples/Flyway/tests/Flyway.Tests/Flyway.Tests.csproj @@ -1,16 +1,20 @@ - - net8.0 - - - - - - - - - - - - - \ No newline at end of file + + net8.0 + + + + + + + + + + + + + diff --git a/examples/Flyway/tests/Flyway.Tests/FlywayTest.cs b/examples/Flyway/tests/Flyway.Tests/FlywayTest.cs index 5aa7804bb..3de679f7e 100644 --- a/examples/Flyway/tests/Flyway.Tests/FlywayTest.cs +++ b/examples/Flyway/tests/Flyway.Tests/FlywayTest.cs @@ -31,4 +31,4 @@ public void UsersTableContainsJohnDoe() Assert.Equal("john@example.com", dataReader.GetString(1)); Assert.Equal(30, dataReader.GetInt32(2)); } -} \ No newline at end of file +} diff --git a/examples/Flyway/tests/Flyway.Tests/Usings.cs b/examples/Flyway/tests/Flyway.Tests/Usings.cs index 557c05167..5400dae86 100644 --- a/examples/Flyway/tests/Flyway.Tests/Usings.cs +++ b/examples/Flyway/tests/Flyway.Tests/Usings.cs @@ -8,4 +8,4 @@ global using JetBrains.Annotations; global using Npgsql; global using Testcontainers.PostgreSql; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/examples/Respawn/Directory.Build.props b/examples/Respawn/Directory.Build.props index 1bf52aaea..088a103d1 100644 --- a/examples/Respawn/Directory.Build.props +++ b/examples/Respawn/Directory.Build.props @@ -1,25 +1,25 @@ - - 0.1.0 - $(AssemblyName) - $(Version) - $(Version) - $(Version) - en-US - Andre Hofmeister - - - - - - - - git - https://github.com/testcontainers/testcontainers-dotnet-sample - - - 10.0 - enable - - \ No newline at end of file + + 0.1.0 + $(AssemblyName) + $(Version) + $(Version) + $(Version) + en-US + Andre Hofmeister + + + + + + + + git + https://github.com/testcontainers/testcontainers-dotnet-sample + + + 10.0 + enable + + diff --git a/examples/Respawn/Directory.Packages.props b/examples/Respawn/Directory.Packages.props index df90779b6..511adf9f8 100644 --- a/examples/Respawn/Directory.Packages.props +++ b/examples/Respawn/Directory.Packages.props @@ -1,16 +1,16 @@ - - true - - - - - - - - - - - - \ No newline at end of file + + true + + + + + + + + + + + + diff --git a/examples/Respawn/tests/Respawn.Tests/DbFixture.cs b/examples/Respawn/tests/Respawn.Tests/DbFixture.cs index f381a6129..96acfadb1 100644 --- a/examples/Respawn/tests/Respawn.Tests/DbFixture.cs +++ b/examples/Respawn/tests/Respawn.Tests/DbFixture.cs @@ -16,7 +16,8 @@ public DbFixture() .Build(); } - public DbConnection DbConnection => new NpgsqlConnection(((PostgreSqlContainer)_postgreSqlContainer).GetConnectionString()); + public DbConnection DbConnection => + new NpgsqlConnection(((PostgreSqlContainer)_postgreSqlContainer).GetConnectionString()); public Task InitializeAsync() { @@ -27,4 +28,4 @@ public Task DisposeAsync() { return _postgreSqlContainer.DisposeAsync().AsTask(); } -} \ No newline at end of file +} diff --git a/examples/Respawn/tests/Respawn.Tests/Respawn.Tests.csproj b/examples/Respawn/tests/Respawn.Tests/Respawn.Tests.csproj index ca9da0248..9205cb799 100644 --- a/examples/Respawn/tests/Respawn.Tests/Respawn.Tests.csproj +++ b/examples/Respawn/tests/Respawn.Tests/Respawn.Tests.csproj @@ -1,17 +1,21 @@ - - net8.0 - - - - - - - - - - - - - - \ No newline at end of file + + net8.0 + + + + + + + + + + + + + + diff --git a/examples/Respawn/tests/Respawn.Tests/RespawnTest.cs b/examples/Respawn/tests/Respawn.Tests/RespawnTest.cs index ca3a417a1..7ad6ad994 100644 --- a/examples/Respawn/tests/Respawn.Tests/RespawnTest.cs +++ b/examples/Respawn/tests/Respawn.Tests/RespawnTest.cs @@ -28,8 +28,8 @@ public async Task UsersTableContainsOneUser(string username, string email, int a var respawner = await Respawner.CreateAsync(_dbConnection, respawnerOptions); await respawner.ResetAsync(_dbConnection); - // This test runs twice and inserts a record into the `users` table for each run. - // The test counts the number of users and expects it to always be 1. If the database + // This test runs twice and inserts a record into the `users` table for each run. + // The test counts the number of users and expects it to always be 1. If the database // state is not clean, the assertion fails. using var insertCommand = _dbConnection.CreateCommand(); @@ -45,7 +45,8 @@ public async Task UsersTableContainsOneUser(string username, string email, int a dbParamAge.ParameterName = "@age"; dbParamAge.Value = age; - insertCommand.CommandText = "INSERT INTO users (username, email, age) VALUES (@username, @email, @age)"; + insertCommand.CommandText = + "INSERT INTO users (username, email, age) VALUES (@username, @email, @age)"; insertCommand.Parameters.Add(dbParamUsername); insertCommand.Parameters.Add(dbParamEmail); insertCommand.Parameters.Add(dbParamAge); @@ -57,4 +58,4 @@ public async Task UsersTableContainsOneUser(string username, string email, int a Assert.Equal(1, userCount); } -} \ No newline at end of file +} diff --git a/examples/Respawn/tests/Respawn.Tests/Usings.cs b/examples/Respawn/tests/Respawn.Tests/Usings.cs index a6f03e666..193b23871 100644 --- a/examples/Respawn/tests/Respawn.Tests/Usings.cs +++ b/examples/Respawn/tests/Respawn.Tests/Usings.cs @@ -6,4 +6,4 @@ global using JetBrains.Annotations; global using Npgsql; global using Testcontainers.PostgreSql; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/examples/WeatherForecast/Directory.Packages.props b/examples/WeatherForecast/Directory.Packages.props index 9521eb455..df4f4cfa6 100644 --- a/examples/WeatherForecast/Directory.Packages.props +++ b/examples/WeatherForecast/Directory.Packages.props @@ -4,17 +4,17 @@ true - - - + + + - - - - - + + + + + - - + + diff --git a/examples/WeatherForecast/src/WeatherForecast.Contexts/WeatherDataContext.cs b/examples/WeatherForecast/src/WeatherForecast.Contexts/WeatherDataContext.cs index 8a58a4a76..b097420c9 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Contexts/WeatherDataContext.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Contexts/WeatherDataContext.cs @@ -3,9 +3,8 @@ namespace WeatherForecast.Contexts; [PublicAPI] public sealed class WeatherDataContext : DbContext { - public WeatherDataContext(DbContextOptions options) : base(options) - { - } + public WeatherDataContext(DbContextOptions options) + : base(options) { } public DbSet WeatherData { get; set; } = null!; @@ -19,10 +18,26 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().Property(temperature => temperature.UnitSymbol); modelBuilder.Entity().Property(temperature => temperature.Value); modelBuilder.Entity().Property(temperature => temperature.Measured); - modelBuilder.Entity().HasMany(weatherData => weatherData.Temperatures).WithOne().HasForeignKey(temperature => temperature.BelongsTo); + modelBuilder + .Entity() + .HasMany(weatherData => weatherData.Temperatures) + .WithOne() + .HasForeignKey(temperature => temperature.BelongsTo); - var weatherDataSeed = Enumerable.Range(0, 30).Select(_ => Guid.NewGuid()).Select((id, day) => new WeatherData(id, DateTimeOffset.Now.AddDays(day))).ToList(); - var temperatureSeed = weatherDataSeed.SelectMany(data => Enumerable.Range(0, 23).Select(hour => Temperature.Celsius(data.Id, Random.Shared.Next(-10, 30), data.Period.AddHours(hour)))).ToList(); + var weatherDataSeed = Enumerable + .Range(0, 30) + .Select(_ => Guid.NewGuid()) + .Select((id, day) => new WeatherData(id, DateTimeOffset.Now.AddDays(day))) + .ToList(); + var temperatureSeed = weatherDataSeed + .SelectMany(data => + Enumerable + .Range(0, 23) + .Select(hour => + Temperature.Celsius(data.Id, Random.Shared.Next(-10, 30), data.Period.AddHours(hour)) + ) + ) + .ToList(); modelBuilder.Entity().HasData(temperatureSeed); modelBuilder.Entity().HasData(weatherDataSeed); diff --git a/examples/WeatherForecast/src/WeatherForecast.Contexts/WeatherDataReadOnlyContext.cs b/examples/WeatherForecast/src/WeatherForecast.Contexts/WeatherDataReadOnlyContext.cs index e9f1846e4..9c89a3814 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Contexts/WeatherDataReadOnlyContext.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Contexts/WeatherDataReadOnlyContext.cs @@ -16,9 +16,19 @@ public Task> GetAllAsync() throw new NotImplementedException(); } - public Task> GetAllAsync(string latitude, string longitude, DateTime from, DateTime to) + public Task> GetAllAsync( + string latitude, + string longitude, + DateTime from, + DateTime to + ) { - return Task.FromResult>(_context.WeatherData.Include(property => property.Temperatures).OrderBy(weatherData => weatherData.Period).Take(to.Subtract(from).Days)); + return Task.FromResult>( + _context + .WeatherData.Include(property => property.Temperatures) + .OrderBy(weatherData => weatherData.Period) + .Take(to.Subtract(from).Days) + ); } public Task GetAsync(Guid id) diff --git a/examples/WeatherForecast/src/WeatherForecast.Contexts/WeatherForecast.Contexts.csproj b/examples/WeatherForecast/src/WeatherForecast.Contexts/WeatherForecast.Contexts.csproj index 032e31cec..7cad7fa91 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Contexts/WeatherForecast.Contexts.csproj +++ b/examples/WeatherForecast/src/WeatherForecast.Contexts/WeatherForecast.Contexts.csproj @@ -3,10 +3,14 @@ net8.0 - - + + - + diff --git a/examples/WeatherForecast/src/WeatherForecast.Entities/Temperature.cs b/examples/WeatherForecast/src/WeatherForecast.Entities/Temperature.cs index 4c37b5bc5..037405cb1 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Entities/Temperature.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Entities/Temperature.cs @@ -4,7 +4,15 @@ namespace WeatherForecast.Entities; public sealed class Temperature : HasId { [JsonConstructor] - public Temperature(Guid id, Guid belongsTo, string unitName, string unitSymbol, double value, DateTimeOffset measured) : base(id) + public Temperature( + Guid id, + Guid belongsTo, + string unitName, + string unitSymbol, + double value, + DateTimeOffset measured + ) + : base(id) { BelongsTo = belongsTo; UnitName = unitName; diff --git a/examples/WeatherForecast/src/WeatherForecast.Entities/WeatherData.cs b/examples/WeatherForecast/src/WeatherForecast.Entities/WeatherData.cs index ca13c0511..411dc42a3 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Entities/WeatherData.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Entities/WeatherData.cs @@ -3,17 +3,25 @@ namespace WeatherForecast.Entities; [PublicAPI] public sealed class WeatherData : HasId { - public WeatherData(Guid id, DateTimeOffset period) : this(id, period, new List()) + public WeatherData(Guid id, DateTimeOffset period) + : this(id, period, new List()) { // Entity Framework constructor. } [JsonConstructor] - public WeatherData(Guid id, DateTimeOffset period, IList temperatures) : base(id) + public WeatherData(Guid id, DateTimeOffset period, IList temperatures) + : base(id) { Period = period; - Minimum = temperatures.OrderBy(temperature => temperature.Value).DefaultIfEmpty(Temperature.AbsoluteZero).First(); - Maximum = temperatures.OrderBy(temperature => temperature.Value).DefaultIfEmpty(Temperature.AbsoluteZero).Last(); + Minimum = temperatures + .OrderBy(temperature => temperature.Value) + .DefaultIfEmpty(Temperature.AbsoluteZero) + .First(); + Maximum = temperatures + .OrderBy(temperature => temperature.Value) + .DefaultIfEmpty(Temperature.AbsoluteZero) + .Last(); Temperatures = temperatures; } diff --git a/examples/WeatherForecast/src/WeatherForecast.Entities/WeatherForecast.Entities.csproj b/examples/WeatherForecast/src/WeatherForecast.Entities/WeatherForecast.Entities.csproj index e9a4c1a1d..c6bfb2042 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Entities/WeatherForecast.Entities.csproj +++ b/examples/WeatherForecast/src/WeatherForecast.Entities/WeatherForecast.Entities.csproj @@ -3,6 +3,10 @@ net8.0 - + diff --git a/examples/WeatherForecast/src/WeatherForecast.Interactors/Error.cs b/examples/WeatherForecast/src/WeatherForecast.Interactors/Error.cs index fe38e7670..7a6e65601 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Interactors/Error.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Interactors/Error.cs @@ -3,6 +3,5 @@ namespace WeatherForecast.Interactors; [PublicAPI] public sealed class Error { - public string LocalizedDescription { get; } - = string.Empty; + public string LocalizedDescription { get; } = string.Empty; } diff --git a/examples/WeatherForecast/src/WeatherForecast.Interactors/Failure.cs b/examples/WeatherForecast/src/WeatherForecast.Interactors/Failure.cs index 43c4bdcba..91b7bcc84 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Interactors/Failure.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Interactors/Failure.cs @@ -4,7 +4,5 @@ namespace WeatherForecast.Interactors; public sealed class Failure : ResultInfo { public Failure() - : base(StatusCode.Failure, new Error()) - { - } + : base(StatusCode.Failure, new Error()) { } } diff --git a/examples/WeatherForecast/src/WeatherForecast.Interactors/Failure`1.cs b/examples/WeatherForecast/src/WeatherForecast.Interactors/Failure`1.cs index 7626a60ad..7c4ff4a23 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Interactors/Failure`1.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Interactors/Failure`1.cs @@ -4,7 +4,5 @@ namespace WeatherForecast.Interactors; public sealed class Failure : ResultInfo { public Failure(TValue value) - : base(StatusCode.Failure, new Error(), value) - { - } + : base(StatusCode.Failure, new Error(), value) { } } diff --git a/examples/WeatherForecast/src/WeatherForecast.Interactors/SearchCityOrZipCode/ISearchCityOrZipCode.cs b/examples/WeatherForecast/src/WeatherForecast.Interactors/SearchCityOrZipCode/ISearchCityOrZipCode.cs index d0e0a7654..df9108ac1 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Interactors/SearchCityOrZipCode/ISearchCityOrZipCode.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Interactors/SearchCityOrZipCode/ISearchCityOrZipCode.cs @@ -1,6 +1,6 @@ namespace WeatherForecast.Interactors.SearchCityOrZipCode; [PublicAPI] -public interface ISearchCityOrZipCode : ICommand, INotifyInteractorResult>> -{ -} +public interface ISearchCityOrZipCode + : ICommand, + INotifyInteractorResult>> { } diff --git a/examples/WeatherForecast/src/WeatherForecast.Interactors/SearchCityOrZipCode/SearchCityOrZipCode.cs b/examples/WeatherForecast/src/WeatherForecast.Interactors/SearchCityOrZipCode/SearchCityOrZipCode.cs index a0ca602e6..31f16285a 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Interactors/SearchCityOrZipCode/SearchCityOrZipCode.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Interactors/SearchCityOrZipCode/SearchCityOrZipCode.cs @@ -7,7 +7,10 @@ public sealed class SearchCityOrZipCode : ISearchCityOrZipCode private readonly IWeatherDataWriteOnlyRepository _writeOnlyRepository; - public SearchCityOrZipCode(IWeatherDataReadOnlyRepository readOnlyRepository, IWeatherDataWriteOnlyRepository writeOnlyRepository) + public SearchCityOrZipCode( + IWeatherDataReadOnlyRepository readOnlyRepository, + IWeatherDataWriteOnlyRepository writeOnlyRepository + ) { _readOnlyRepository = readOnlyRepository; _writeOnlyRepository = writeOnlyRepository; @@ -21,7 +24,8 @@ public async Task ExecuteAsync(string cityOrZipCode) try { - var weatherData = await _readOnlyRepository.GetAllAsync(string.Empty, string.Empty, DateTime.Today, DateTime.Today.AddDays(7)) + var weatherData = await _readOnlyRepository + .GetAllAsync(string.Empty, string.Empty, DateTime.Today, DateTime.Today.AddDays(7)) .ConfigureAwait(false); result = new Success>(weatherData); diff --git a/examples/WeatherForecast/src/WeatherForecast.Interactors/StatusCode.cs b/examples/WeatherForecast/src/WeatherForecast.Interactors/StatusCode.cs index b7913eddb..81078d8b8 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Interactors/StatusCode.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Interactors/StatusCode.cs @@ -5,5 +5,5 @@ public enum StatusCode { Success, - Failure + Failure, } diff --git a/examples/WeatherForecast/src/WeatherForecast.Interactors/Success.cs b/examples/WeatherForecast/src/WeatherForecast.Interactors/Success.cs index f31df667e..e877ffc6a 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Interactors/Success.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Interactors/Success.cs @@ -4,7 +4,5 @@ namespace WeatherForecast.Interactors; public sealed class Success : ResultInfo { public Success() - : base(StatusCode.Success, new Error()) - { - } + : base(StatusCode.Success, new Error()) { } } diff --git a/examples/WeatherForecast/src/WeatherForecast.Interactors/Success`1.cs b/examples/WeatherForecast/src/WeatherForecast.Interactors/Success`1.cs index dee5f3e13..2fb80313e 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Interactors/Success`1.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Interactors/Success`1.cs @@ -4,7 +4,5 @@ namespace WeatherForecast.Interactors; public sealed class Success : ResultInfo { public Success(TValue value) - : base(StatusCode.Success, new Error(), value) - { - } + : base(StatusCode.Success, new Error(), value) { } } diff --git a/examples/WeatherForecast/src/WeatherForecast.Interactors/WeatherForecast.Interactors.csproj b/examples/WeatherForecast/src/WeatherForecast.Interactors/WeatherForecast.Interactors.csproj index 49925d9b5..a25a7fcfc 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Interactors/WeatherForecast.Interactors.csproj +++ b/examples/WeatherForecast/src/WeatherForecast.Interactors/WeatherForecast.Interactors.csproj @@ -3,10 +3,14 @@ net8.0 - + - - + + diff --git a/examples/WeatherForecast/src/WeatherForecast.Repositories/IWeatherDataReadOnlyRepository.cs b/examples/WeatherForecast/src/WeatherForecast.Repositories/IWeatherDataReadOnlyRepository.cs index 4cda8f47a..635ba39cd 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Repositories/IWeatherDataReadOnlyRepository.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Repositories/IWeatherDataReadOnlyRepository.cs @@ -5,7 +5,12 @@ public interface IWeatherDataReadOnlyRepository { Task> GetAllAsync(); - Task> GetAllAsync(string latitude, string longitude, DateTime from, DateTime to); + Task> GetAllAsync( + string latitude, + string longitude, + DateTime from, + DateTime to + ); Task GetAsync(Guid id); } diff --git a/examples/WeatherForecast/src/WeatherForecast.Repositories/WeatherDataReadOnlyRepository.cs b/examples/WeatherForecast/src/WeatherForecast.Repositories/WeatherDataReadOnlyRepository.cs index 2319bf2ed..221dd8a62 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Repositories/WeatherDataReadOnlyRepository.cs +++ b/examples/WeatherForecast/src/WeatherForecast.Repositories/WeatherDataReadOnlyRepository.cs @@ -8,9 +8,35 @@ public Task> GetAllAsync() throw new NotImplementedException(); } - public Task> GetAllAsync(string latitude, string longitude, DateTime from, DateTime to) + public Task> GetAllAsync( + string latitude, + string longitude, + DateTime from, + DateTime to + ) { - return Task.FromResult(Enumerable.Range(0, to.Subtract(from).Days).Select(_ => Guid.NewGuid()).Select((id, day) => new WeatherData(id, DateTime.Today.AddDays(day), Enumerable.Range(0, 23).Select(hour => Temperature.Celsius(id, StaticRandom.Next(-10, 30), DateTime.Today.AddDays(day).AddHours(hour))).ToList()))); + return Task.FromResult( + Enumerable + .Range(0, to.Subtract(from).Days) + .Select(_ => Guid.NewGuid()) + .Select( + (id, day) => + new WeatherData( + id, + DateTime.Today.AddDays(day), + Enumerable + .Range(0, 23) + .Select(hour => + Temperature.Celsius( + id, + StaticRandom.Next(-10, 30), + DateTime.Today.AddDays(day).AddHours(hour) + ) + ) + .ToList() + ) + ) + ); } public Task GetAsync(Guid id) diff --git a/examples/WeatherForecast/src/WeatherForecast.Repositories/WeatherForecast.Repositories.csproj b/examples/WeatherForecast/src/WeatherForecast.Repositories/WeatherForecast.Repositories.csproj index 2ece4da82..3b0c46c49 100644 --- a/examples/WeatherForecast/src/WeatherForecast.Repositories/WeatherForecast.Repositories.csproj +++ b/examples/WeatherForecast/src/WeatherForecast.Repositories/WeatherForecast.Repositories.csproj @@ -3,9 +3,13 @@ net8.0 - + - + diff --git a/examples/WeatherForecast/src/WeatherForecast/Controllers/WeatherForecastController.cs b/examples/WeatherForecast/src/WeatherForecast/Controllers/WeatherForecastController.cs index 7d31e6543..a7cffe37d 100644 --- a/examples/WeatherForecast/src/WeatherForecast/Controllers/WeatherForecastController.cs +++ b/examples/WeatherForecast/src/WeatherForecast/Controllers/WeatherForecastController.cs @@ -26,16 +26,17 @@ public void Dispose() [HttpGet] public async Task>> GetWeatherForecast() { - await _searchCityOrZipCode.ExecuteAsync(string.Empty) - .ConfigureAwait(false); + await _searchCityOrZipCode.ExecuteAsync(string.Empty).ConfigureAwait(false); - await _wait.WaitAsync() - .ConfigureAwait(false); + await _wait.WaitAsync().ConfigureAwait(false); return Ok(_weatherData); } - private void SearchCityOrZipCodeResultPublished(object? sender, ResultInfo> result) + private void SearchCityOrZipCodeResultPublished( + object? sender, + ResultInfo> result + ) { if (result.IsSuccessful) { diff --git a/examples/WeatherForecast/src/WeatherForecast/Program.cs b/examples/WeatherForecast/src/WeatherForecast/Program.cs index 2f09b2989..a227ff5e3 100644 --- a/examples/WeatherForecast/src/WeatherForecast/Program.cs +++ b/examples/WeatherForecast/src/WeatherForecast/Program.cs @@ -11,16 +11,20 @@ // The application configuration does not include a database connection string, use Testcontainers for .NET to create, start and seed the dependent database. builder.Services.AddSingleton(); builder.Services.AddHostedService(services => services.GetRequiredService()); - builder.Services.AddDbContext((services, options) => - { - var databaseContainer = services.GetRequiredService(); - options.UseNpgsql(databaseContainer.GetConnectionString()); - }); + builder.Services.AddDbContext( + (services, options) => + { + var databaseContainer = services.GetRequiredService(); + options.UseNpgsql(databaseContainer.GetConnectionString()); + } + ); } else { // The application configuration includes a database connection string, use it to establish a connection and seed the database. - builder.Services.AddDbContext((_, options) => options.UseNpgsql(postgreSqlConnectionString)); + builder.Services.AddDbContext( + (_, options) => options.UseNpgsql(postgreSqlConnectionString) + ); } builder.Services.AddScoped(); @@ -41,7 +45,5 @@ namespace WeatherForecast { - public sealed class Program - { - } + public sealed class Program { } } diff --git a/examples/WeatherForecast/src/WeatherForecast/WeatherForecast.csproj b/examples/WeatherForecast/src/WeatherForecast/WeatherForecast.csproj index 01cbc5b4d..6cff44049 100644 --- a/examples/WeatherForecast/src/WeatherForecast/WeatherForecast.csproj +++ b/examples/WeatherForecast/src/WeatherForecast/WeatherForecast.csproj @@ -3,18 +3,18 @@ net8.0 - - - + + + - - - + + + - + diff --git a/examples/WeatherForecast/tests/WeatherForecast.InProcess.Tests/WeatherForecast.InProcess.Tests.csproj b/examples/WeatherForecast/tests/WeatherForecast.InProcess.Tests/WeatherForecast.InProcess.Tests.csproj index 167892fe1..aa08774fd 100644 --- a/examples/WeatherForecast/tests/WeatherForecast.InProcess.Tests/WeatherForecast.InProcess.Tests.csproj +++ b/examples/WeatherForecast/tests/WeatherForecast.InProcess.Tests/WeatherForecast.InProcess.Tests.csproj @@ -3,13 +3,17 @@ net8.0 - - - - - + + + + + - + diff --git a/examples/WeatherForecast/tests/WeatherForecast.InProcess.Tests/WeatherForecastTest.cs b/examples/WeatherForecast/tests/WeatherForecast.InProcess.Tests/WeatherForecastTest.cs index d41a4c80c..8b996ce80 100644 --- a/examples/WeatherForecast/tests/WeatherForecast.InProcess.Tests/WeatherForecastTest.cs +++ b/examples/WeatherForecast/tests/WeatherForecast.InProcess.Tests/WeatherForecastTest.cs @@ -40,13 +40,12 @@ public async Task Get_WeatherForecast_ReturnsSevenDays() using var httpClient = CreateClient(); // When - var response = await httpClient.GetAsync(path) - .ConfigureAwait(true); + var response = await httpClient.GetAsync(path).ConfigureAwait(true); - var weatherForecastStream = await response.Content.ReadAsStreamAsync() - .ConfigureAwait(true); + var weatherForecastStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(true); - var weatherForecast = await JsonSerializer.DeserializeAsync>(weatherForecastStream) + var weatherForecast = await JsonSerializer + .DeserializeAsync>(weatherForecastStream) .ConfigureAwait(true); // Then @@ -63,10 +62,12 @@ public async Task Get_WeatherForecast_ReturnsThreeDays() using var serviceScope = Services.CreateScope(); - var weatherDataReadOnlyRepository = serviceScope.ServiceProvider.GetRequiredService(); + var weatherDataReadOnlyRepository = + serviceScope.ServiceProvider.GetRequiredService(); // When - var weatherForecast = await weatherDataReadOnlyRepository.GetAllAsync(string.Empty, string.Empty, DateTime.Today, DateTime.Today.AddDays(threeDays)) + var weatherForecast = await weatherDataReadOnlyRepository + .GetAllAsync(string.Empty, string.Empty, DateTime.Today, DateTime.Today.AddDays(threeDays)) .ConfigureAwait(true); // Then diff --git a/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecast.Tests.csproj b/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecast.Tests.csproj index 1c824cbb5..8713db8b4 100644 --- a/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecast.Tests.csproj +++ b/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecast.Tests.csproj @@ -3,14 +3,18 @@ net8.0 - - - - - - + + + + + + - + diff --git a/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecastContainer.cs b/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecastContainer.cs index 613693737..fa09e2833 100644 --- a/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecastContainer.cs +++ b/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecastContainer.cs @@ -3,7 +3,10 @@ namespace WeatherForecast.Tests; [UsedImplicitly] public sealed class WeatherForecastContainer : HttpClient, IAsyncLifetime { - private static readonly X509Certificate Certificate = new X509Certificate2(WeatherForecastImage.CertificateFilePath, WeatherForecastImage.CertificatePassword); + private static readonly X509Certificate Certificate = new X509Certificate2( + WeatherForecastImage.CertificateFilePath, + WeatherForecastImage.CertificatePassword + ); private static readonly WeatherForecastImage Image = new WeatherForecastImage(); @@ -14,18 +17,21 @@ public sealed class WeatherForecastContainer : HttpClient, IAsyncLifetime private readonly IContainer _weatherForecastContainer; public WeatherForecastContainer() - : base(new HttpClientHandler - { - // Trust the development certificate. - ServerCertificateCustomValidationCallback = (_, certificate, _, _) => Certificate.Equals(certificate) - }) + : base( + new HttpClientHandler + { + // Trust the development certificate. + ServerCertificateCustomValidationCallback = (_, certificate, _, _) => + Certificate.Equals(certificate), + } + ) { const string weatherForecastStorage = "weatherForecastStorage"; - const string postgreSqlConnectionString = $"Host={weatherForecastStorage};Username={PostgreSqlBuilder.DefaultUsername};Password={PostgreSqlBuilder.DefaultPassword};Database={PostgreSqlBuilder.DefaultDatabase}"; + const string postgreSqlConnectionString = + $"Host={weatherForecastStorage};Username={PostgreSqlBuilder.DefaultUsername};Password={PostgreSqlBuilder.DefaultPassword};Database={PostgreSqlBuilder.DefaultDatabase}"; - _weatherForecastNetwork = new NetworkBuilder() - .Build(); + _weatherForecastNetwork = new NetworkBuilder().Build(); _postgreSqlContainer = new PostgreSqlBuilder() .WithNetwork(_weatherForecastNetwork) @@ -37,49 +43,53 @@ public WeatherForecastContainer() .WithNetwork(_weatherForecastNetwork) .WithPortBinding(WeatherForecastImage.HttpsPort, true) .WithEnvironment("ASPNETCORE_URLS", "https://+") - .WithEnvironment("ASPNETCORE_Kestrel__Certificates__Default__Path", WeatherForecastImage.CertificateFilePath) - .WithEnvironment("ASPNETCORE_Kestrel__Certificates__Default__Password", WeatherForecastImage.CertificatePassword) + .WithEnvironment( + "ASPNETCORE_Kestrel__Certificates__Default__Path", + WeatherForecastImage.CertificateFilePath + ) + .WithEnvironment( + "ASPNETCORE_Kestrel__Certificates__Default__Password", + WeatherForecastImage.CertificatePassword + ) .WithEnvironment("ConnectionStrings__PostgreSQL", postgreSqlConnectionString) - .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(WeatherForecastImage.HttpsPort)) + .WithWaitStrategy( + Wait.ForUnixContainer().UntilPortIsAvailable(WeatherForecastImage.HttpsPort) + ) .Build(); } public async Task InitializeAsync() { - await Image.InitializeAsync() - .ConfigureAwait(false); + await Image.InitializeAsync().ConfigureAwait(false); - await _weatherForecastNetwork.CreateAsync() - .ConfigureAwait(false); + await _weatherForecastNetwork.CreateAsync().ConfigureAwait(false); - await _postgreSqlContainer.StartAsync() - .ConfigureAwait(false); + await _postgreSqlContainer.StartAsync().ConfigureAwait(false); - await _weatherForecastContainer.StartAsync() - .ConfigureAwait(false); + await _weatherForecastContainer.StartAsync().ConfigureAwait(false); } public async Task DisposeAsync() { // It is not necessary to clean up resources immediately (still good practice). The Resource Reaper will take care of orphaned resources. - await Image.DisposeAsync() - .ConfigureAwait(false); + await Image.DisposeAsync().ConfigureAwait(false); - await _weatherForecastContainer.DisposeAsync() - .ConfigureAwait(false); + await _weatherForecastContainer.DisposeAsync().ConfigureAwait(false); - await _postgreSqlContainer.DisposeAsync() - .ConfigureAwait(false); + await _postgreSqlContainer.DisposeAsync().ConfigureAwait(false); - await _weatherForecastNetwork.DeleteAsync() - .ConfigureAwait(false); + await _weatherForecastNetwork.DeleteAsync().ConfigureAwait(false); } public void SetBaseAddress() { try { - var uriBuilder = new UriBuilder("https", _weatherForecastContainer.Hostname, _weatherForecastContainer.GetMappedPublicPort(WeatherForecastImage.HttpsPort)); + var uriBuilder = new UriBuilder( + "https", + _weatherForecastContainer.Hostname, + _weatherForecastContainer.GetMappedPublicPort(WeatherForecastImage.HttpsPort) + ); BaseAddress = uriBuilder.Uri; } catch diff --git a/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecastImage.cs b/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecastImage.cs index b2db3c98d..029bbab1f 100644 --- a/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecastImage.cs +++ b/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecastImage.cs @@ -11,7 +11,10 @@ public sealed class WeatherForecastImage : IImage, IAsyncLifetime private readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1); - private readonly IImage _image = new DockerImage("localhost/testcontainers/weather-forecast", tag: DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()); + private readonly IImage _image = new DockerImage( + "localhost/testcontainers/weather-forecast", + tag: DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() + ); public string Repository => _image.Repository; @@ -25,8 +28,7 @@ public sealed class WeatherForecastImage : IImage, IAsyncLifetime public async Task InitializeAsync() { - await _semaphoreSlim.WaitAsync() - .ConfigureAwait(false); + await _semaphoreSlim.WaitAsync().ConfigureAwait(false); try { @@ -34,7 +36,10 @@ await _semaphoreSlim.WaitAsync() .WithName(this) .WithDockerfileDirectory(CommonDirectoryPath.GetSolutionDirectory(), string.Empty) .WithDockerfile("Dockerfile") - .WithBuildArgument("RESOURCE_REAPER_SESSION_ID", ResourceReaper.DefaultSessionId.ToString("D")) // https://github.com/testcontainers/testcontainers-dotnet/issues/602. + .WithBuildArgument( + "RESOURCE_REAPER_SESSION_ID", + ResourceReaper.DefaultSessionId.ToString("D") + ) // https://github.com/testcontainers/testcontainers-dotnet/issues/602. .WithDeleteIfExists(false) .Build() .CreateAsync() diff --git a/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecastTest.cs b/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecastTest.cs index 0910bcce1..82e704183 100644 --- a/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecastTest.cs +++ b/examples/WeatherForecast/tests/WeatherForecast.Tests/WeatherForecastTest.cs @@ -24,13 +24,12 @@ public async Task Get_WeatherForecast_ReturnsSevenDays() const string path = "api/WeatherForecast"; // When - var response = await _weatherForecastContainer.GetAsync(path) - .ConfigureAwait(true); + var response = await _weatherForecastContainer.GetAsync(path).ConfigureAwait(true); - var weatherForecastStream = await response.Content.ReadAsStreamAsync() - .ConfigureAwait(true); + var weatherForecastStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(true); - var weatherForecast = await JsonSerializer.DeserializeAsync>(weatherForecastStream) + var weatherForecast = await JsonSerializer + .DeserializeAsync>(weatherForecastStream) .ConfigureAwait(true); // Then @@ -62,24 +61,46 @@ public Web(WeatherForecastContainer weatherForecastContainer) public void Get_WeatherForecast_ReturnsSevenDays() { // Given - string ScreenshotFileName() => $"{nameof(Get_WeatherForecast_ReturnsSevenDays)}_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}.png"; + string ScreenshotFileName() => + $"{nameof(Get_WeatherForecast_ReturnsSevenDays)}_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}.png"; using var chrome = new ChromeDriver(ChromeOptions); // When chrome.Navigate().GoToUrl(_weatherForecastContainer.BaseAddress); - chrome.GetScreenshot().SaveAsFile(Path.Combine(CommonDirectoryPath.GetSolutionDirectory().DirectoryPath, ScreenshotFileName())); + chrome + .GetScreenshot() + .SaveAsFile( + Path.Combine( + CommonDirectoryPath.GetSolutionDirectory().DirectoryPath, + ScreenshotFileName() + ) + ); chrome.FindElement(By.TagName("fluent-button")).Click(); var wait = new WebDriverWait(chrome, TimeSpan.FromSeconds(10)); wait.Until(webDriver => 1.Equals(webDriver.FindElements(By.TagName("span")).Count)); - chrome.GetScreenshot().SaveAsFile(Path.Combine(CommonDirectoryPath.GetSolutionDirectory().DirectoryPath, ScreenshotFileName())); + chrome + .GetScreenshot() + .SaveAsFile( + Path.Combine( + CommonDirectoryPath.GetSolutionDirectory().DirectoryPath, + ScreenshotFileName() + ) + ); // Then - Assert.Equal(7, int.Parse(chrome.FindElement(By.TagName("span")).Text, NumberStyles.Integer, CultureInfo.InvariantCulture)); + Assert.Equal( + 7, + int.Parse( + chrome.FindElement(By.TagName("span")).Text, + NumberStyles.Integer, + CultureInfo.InvariantCulture + ) + ); } } } diff --git a/src/Templates/CSharp/Testcontainers.ModuleName/ModuleNameBuilder.cs b/src/Templates/CSharp/Testcontainers.ModuleName/ModuleNameBuilder.cs index e0f4db0ee..1e8d2dbeb 100644 --- a/src/Templates/CSharp/Testcontainers.ModuleName/ModuleNameBuilder.cs +++ b/src/Templates/CSharp/Testcontainers.ModuleName/ModuleNameBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.ModuleName; /// [PublicAPI] -public sealed class ModuleNameBuilder : ContainerBuilder +public sealed class ModuleNameBuilder + : ContainerBuilder { /// /// Initializes a new instance of the class. @@ -67,20 +68,31 @@ public override ModuleNameContainer Build() // } /// - protected override ModuleNameBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override ModuleNameBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new ModuleNameConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new ModuleNameConfiguration(resourceConfiguration) + ); } /// protected override ModuleNameBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new ModuleNameConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new ModuleNameConfiguration(resourceConfiguration) + ); } /// - protected override ModuleNameBuilder Merge(ModuleNameConfiguration oldValue, ModuleNameConfiguration newValue) + protected override ModuleNameBuilder Merge( + ModuleNameConfiguration oldValue, + ModuleNameConfiguration newValue + ) { return new ModuleNameBuilder(new ModuleNameConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Templates/CSharp/Testcontainers.ModuleName/ModuleNameConfiguration.cs b/src/Templates/CSharp/Testcontainers.ModuleName/ModuleNameConfiguration.cs index 92afea8dc..4c818ec12 100644 --- a/src/Templates/CSharp/Testcontainers.ModuleName/ModuleNameConfiguration.cs +++ b/src/Templates/CSharp/Testcontainers.ModuleName/ModuleNameConfiguration.cs @@ -18,7 +18,9 @@ public ModuleNameConfiguration(object config = null) /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public ModuleNameConfiguration(IResourceConfiguration resourceConfiguration) + public ModuleNameConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -49,7 +51,10 @@ public ModuleNameConfiguration(ModuleNameConfiguration resourceConfiguration) /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public ModuleNameConfiguration(ModuleNameConfiguration oldValue, ModuleNameConfiguration newValue) + public ModuleNameConfiguration( + ModuleNameConfiguration oldValue, + ModuleNameConfiguration newValue + ) : base(oldValue, newValue) { // // Create an updated immutable copy of the module configuration. @@ -60,4 +65,4 @@ public ModuleNameConfiguration(ModuleNameConfiguration oldValue, ModuleNameConfi // /// Gets the ModuleName config. // /// // public object Config { get; } -} \ No newline at end of file +} diff --git a/src/Templates/CSharp/Testcontainers.ModuleName/ModuleNameContainer.cs b/src/Templates/CSharp/Testcontainers.ModuleName/ModuleNameContainer.cs index 4b2137d2a..30dcfabbe 100644 --- a/src/Templates/CSharp/Testcontainers.ModuleName/ModuleNameContainer.cs +++ b/src/Templates/CSharp/Testcontainers.ModuleName/ModuleNameContainer.cs @@ -9,7 +9,5 @@ public sealed class ModuleNameContainer : DockerContainer /// /// The container configuration. public ModuleNameContainer(ModuleNameConfiguration configuration) - : base(configuration) - { - } -} \ No newline at end of file + : base(configuration) { } +} diff --git a/src/Templates/CSharp/Testcontainers.ModuleName/Testcontainers.ModuleName.csproj b/src/Templates/CSharp/Testcontainers.ModuleName/Testcontainers.ModuleName.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Templates/CSharp/Testcontainers.ModuleName/Testcontainers.ModuleName.csproj +++ b/src/Templates/CSharp/Testcontainers.ModuleName/Testcontainers.ModuleName.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Templates/CSharp/Testcontainers.ModuleName/Usings.cs b/src/Templates/CSharp/Testcontainers.ModuleName/Usings.cs index f889bad0a..3ef152398 100644 --- a/src/Templates/CSharp/Testcontainers.ModuleName/Usings.cs +++ b/src/Templates/CSharp/Testcontainers.ModuleName/Usings.cs @@ -7,4 +7,4 @@ global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; global using JetBrains.Annotations; -global using Microsoft.Extensions.Logging; \ No newline at end of file +global using Microsoft.Extensions.Logging; diff --git a/src/Testcontainers.ActiveMq/ActiveMqConfiguration.cs b/src/Testcontainers.ActiveMq/ActiveMqConfiguration.cs index 82d7ae292..3fcbd329c 100644 --- a/src/Testcontainers.ActiveMq/ActiveMqConfiguration.cs +++ b/src/Testcontainers.ActiveMq/ActiveMqConfiguration.cs @@ -9,9 +9,7 @@ public sealed class ActiveMqConfiguration : ContainerConfiguration /// /// The ActiveMq username. /// The ActiveMq password. - public ActiveMqConfiguration( - string username = null, - string password = null) + public ActiveMqConfiguration(string username = null, string password = null) { Username = username; Password = password; @@ -21,7 +19,9 @@ public ActiveMqConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public ActiveMqConfiguration(IResourceConfiguration resourceConfiguration) + public ActiveMqConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -68,4 +68,4 @@ public ActiveMqConfiguration(ActiveMqConfiguration oldValue, ActiveMqConfigurati /// Gets the ActiveMq password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.ActiveMq/ArtemisBuilder.cs b/src/Testcontainers.ActiveMq/ArtemisBuilder.cs index afaa7e82f..2483b13c6 100644 --- a/src/Testcontainers.ActiveMq/ArtemisBuilder.cs +++ b/src/Testcontainers.ActiveMq/ArtemisBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.ActiveMq; /// [PublicAPI] -public sealed class ArtemisBuilder : ContainerBuilder +public sealed class ArtemisBuilder + : ContainerBuilder { public const string ArtemisImage = "apache/activemq-artemis:2.31.2"; @@ -82,17 +83,27 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Username, nameof(DockerResourceConfiguration.Username)) + _ = Guard + .Argument( + DockerResourceConfiguration.Username, + nameof(DockerResourceConfiguration.Username) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override ArtemisBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override ArtemisBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new ActiveMqConfiguration(resourceConfiguration)); } @@ -104,8 +115,11 @@ protected override ArtemisBuilder Clone(IContainerConfiguration resourceConfigur } /// - protected override ArtemisBuilder Merge(ActiveMqConfiguration oldValue, ActiveMqConfiguration newValue) + protected override ArtemisBuilder Merge( + ActiveMqConfiguration oldValue, + ActiveMqConfiguration newValue + ) { return new ArtemisBuilder(new ActiveMqConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.ActiveMq/ArtemisContainer.cs b/src/Testcontainers.ActiveMq/ArtemisContainer.cs index 29e96ac8b..ed1831375 100644 --- a/src/Testcontainers.ActiveMq/ArtemisContainer.cs +++ b/src/Testcontainers.ActiveMq/ArtemisContainer.cs @@ -22,9 +22,13 @@ public ArtemisContainer(ActiveMqConfiguration configuration) /// The ActiveMq broker address. public string GetBrokerAddress() { - var endpoint = new UriBuilder("tcp", Hostname, GetMappedPublicPort(ArtemisBuilder.ArtemisMainPort)); + var endpoint = new UriBuilder( + "tcp", + Hostname, + GetMappedPublicPort(ArtemisBuilder.ArtemisMainPort) + ); endpoint.UserName = Uri.EscapeDataString(_configuration.Username); endpoint.Password = Uri.EscapeDataString(_configuration.Password); return endpoint.ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.ActiveMq/Testcontainers.ActiveMq.csproj b/src/Testcontainers.ActiveMq/Testcontainers.ActiveMq.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.ActiveMq/Testcontainers.ActiveMq.csproj +++ b/src/Testcontainers.ActiveMq/Testcontainers.ActiveMq.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.ActiveMq/Usings.cs b/src/Testcontainers.ActiveMq/Usings.cs index 8e5c20fd5..f89f0c94d 100644 --- a/src/Testcontainers.ActiveMq/Usings.cs +++ b/src/Testcontainers.ActiveMq/Usings.cs @@ -4,4 +4,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.ArangoDb/ArangoDbBuilder.cs b/src/Testcontainers.ArangoDb/ArangoDbBuilder.cs index 4ca7b499a..c4a3a008d 100644 --- a/src/Testcontainers.ArangoDb/ArangoDbBuilder.cs +++ b/src/Testcontainers.ArangoDb/ArangoDbBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.ArangoDb; /// [PublicAPI] -public sealed class ArangoDbBuilder : ContainerBuilder +public sealed class ArangoDbBuilder + : ContainerBuilder { public const string ArangoDbImage = "arangodb:3.11.5"; @@ -67,13 +68,19 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override ArangoDbBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override ArangoDbBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new ArangoDbConfiguration(resourceConfiguration)); } @@ -85,8 +92,11 @@ protected override ArangoDbBuilder Clone(IContainerConfiguration resourceConfigu } /// - protected override ArangoDbBuilder Merge(ArangoDbConfiguration oldValue, ArangoDbConfiguration newValue) + protected override ArangoDbBuilder Merge( + ArangoDbConfiguration oldValue, + ArangoDbConfiguration newValue + ) { return new ArangoDbBuilder(new ArangoDbConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.ArangoDb/ArangoDbConfiguration.cs b/src/Testcontainers.ArangoDb/ArangoDbConfiguration.cs index aa71236e9..545809b9d 100644 --- a/src/Testcontainers.ArangoDb/ArangoDbConfiguration.cs +++ b/src/Testcontainers.ArangoDb/ArangoDbConfiguration.cs @@ -8,8 +8,7 @@ public sealed class ArangoDbConfiguration : ContainerConfiguration /// Initializes a new instance of the class. /// /// The ArangoDb password. - public ArangoDbConfiguration( - string password = null) + public ArangoDbConfiguration(string password = null) { Password = password; } @@ -18,7 +17,9 @@ public ArangoDbConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public ArangoDbConfiguration(IResourceConfiguration resourceConfiguration) + public ArangoDbConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -59,4 +60,4 @@ public ArangoDbConfiguration(ArangoDbConfiguration oldValue, ArangoDbConfigurati /// Gets the ArangoDb password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.ArangoDb/ArangoDbContainer.cs b/src/Testcontainers.ArangoDb/ArangoDbContainer.cs index ae7986855..d7acb926c 100644 --- a/src/Testcontainers.ArangoDb/ArangoDbContainer.cs +++ b/src/Testcontainers.ArangoDb/ArangoDbContainer.cs @@ -9,9 +9,7 @@ public sealed class ArangoDbContainer : DockerContainer /// /// The container configuration. public ArangoDbContainer(ArangoDbConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the transport address. @@ -19,6 +17,10 @@ public ArangoDbContainer(ArangoDbConfiguration configuration) /// The transport address. public string GetTransportAddress() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(ArangoDbBuilder.ArangoDbPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(ArangoDbBuilder.ArangoDbPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.ArangoDb/Testcontainers.ArangoDb.csproj b/src/Testcontainers.ArangoDb/Testcontainers.ArangoDb.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.ArangoDb/Testcontainers.ArangoDb.csproj +++ b/src/Testcontainers.ArangoDb/Testcontainers.ArangoDb.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.ArangoDb/Usings.cs b/src/Testcontainers.ArangoDb/Usings.cs index 8e5c20fd5..f89f0c94d 100644 --- a/src/Testcontainers.ArangoDb/Usings.cs +++ b/src/Testcontainers.ArangoDb/Usings.cs @@ -4,4 +4,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Azurite/AzuriteBuilder.cs b/src/Testcontainers.Azurite/AzuriteBuilder.cs index d499791dd..1c79ea58a 100644 --- a/src/Testcontainers.Azurite/AzuriteBuilder.cs +++ b/src/Testcontainers.Azurite/AzuriteBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Azurite; /// [PublicAPI] -public sealed class AzuriteBuilder : ContainerBuilder +public sealed class AzuriteBuilder + : ContainerBuilder { public const string AzuriteImage = "mcr.microsoft.com/azure-storage/azurite:3.28.0"; @@ -14,7 +15,8 @@ public sealed class AzuriteBuilder : ContainerBuilder EnabledServices = new HashSet(); @@ -59,7 +61,11 @@ public AzuriteBuilder WithInMemoryPersistence(float? megabytes = null) { if (megabytes.HasValue) { - return WithCommand("--inMemoryPersistence", "--extentMemoryLimit", megabytes.ToString()); + return WithCommand( + "--inMemoryPersistence", + "--extentMemoryLimit", + megabytes.ToString() + ); } else { @@ -76,20 +82,29 @@ public override AzuriteContainer Build() if (EnabledServices.Contains(AzuriteService.Blob)) { - waitStrategy = waitStrategy.UntilMessageIsLogged("Blob service is successfully listening"); + waitStrategy = waitStrategy.UntilMessageIsLogged( + "Blob service is successfully listening" + ); } if (EnabledServices.Contains(AzuriteService.Queue)) { - waitStrategy = waitStrategy.UntilMessageIsLogged("Queue service is successfully listening"); + waitStrategy = waitStrategy.UntilMessageIsLogged( + "Queue service is successfully listening" + ); } if (EnabledServices.Contains(AzuriteService.Table)) { - waitStrategy = waitStrategy.UntilMessageIsLogged("Table service is successfully listening"); + waitStrategy = waitStrategy.UntilMessageIsLogged( + "Table service is successfully listening" + ); } - var azuriteBuilder = DockerResourceConfiguration.WaitStrategies.Count() > 1 ? this : WithWaitStrategy(waitStrategy); + var azuriteBuilder = + DockerResourceConfiguration.WaitStrategies.Count() > 1 + ? this + : WithWaitStrategy(waitStrategy); return new AzuriteContainer(azuriteBuilder.DockerResourceConfiguration); } @@ -102,11 +117,20 @@ protected override AzuriteBuilder Init() .WithPortBinding(QueuePort, true) .WithPortBinding(TablePort, true) .WithEntrypoint("azurite") - .WithCommand("--blobHost", "0.0.0.0", "--queueHost", "0.0.0.0", "--tableHost", "0.0.0.0"); + .WithCommand( + "--blobHost", + "0.0.0.0", + "--queueHost", + "0.0.0.0", + "--tableHost", + "0.0.0.0" + ); } /// - protected override AzuriteBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override AzuriteBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new AzuriteConfiguration(resourceConfiguration)); } @@ -118,8 +142,11 @@ protected override AzuriteBuilder Clone(IContainerConfiguration resourceConfigur } /// - protected override AzuriteBuilder Merge(AzuriteConfiguration oldValue, AzuriteConfiguration newValue) + protected override AzuriteBuilder Merge( + AzuriteConfiguration oldValue, + AzuriteConfiguration newValue + ) { return new AzuriteBuilder(new AzuriteConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Azurite/AzuriteConfiguration.cs b/src/Testcontainers.Azurite/AzuriteConfiguration.cs index 168adde2c..91cfec956 100644 --- a/src/Testcontainers.Azurite/AzuriteConfiguration.cs +++ b/src/Testcontainers.Azurite/AzuriteConfiguration.cs @@ -7,15 +7,15 @@ public sealed class AzuriteConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public AzuriteConfiguration() - { - } + public AzuriteConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public AzuriteConfiguration(IResourceConfiguration resourceConfiguration) + public AzuriteConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public AzuriteConfiguration(AzuriteConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public AzuriteConfiguration(AzuriteConfiguration oldValue, AzuriteConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Azurite/AzuriteContainer.cs b/src/Testcontainers.Azurite/AzuriteContainer.cs index b7b1023b7..eadfa5f4c 100644 --- a/src/Testcontainers.Azurite/AzuriteContainer.cs +++ b/src/Testcontainers.Azurite/AzuriteContainer.cs @@ -9,9 +9,7 @@ public sealed class AzuriteContainer : DockerContainer /// /// The container configuration. public AzuriteContainer(AzuriteConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Azurite connection string. @@ -26,7 +24,10 @@ public string GetConnectionString() properties.Add("BlobEndpoint", GetBlobEndpoint()); properties.Add("QueueEndpoint", GetQueueEndpoint()); properties.Add("TableEndpoint", GetTableEndpoint()); - return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value))); + return string.Join( + ";", + properties.Select(property => string.Join("=", property.Key, property.Value)) + ); } /// @@ -35,7 +36,12 @@ public string GetConnectionString() /// The Azurite blob endpoint public string GetBlobEndpoint() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(AzuriteBuilder.BlobPort), AzuriteBuilder.AccountName).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(AzuriteBuilder.BlobPort), + AzuriteBuilder.AccountName + ).ToString(); } /// @@ -44,7 +50,12 @@ public string GetBlobEndpoint() /// The Azurite queue endpoint public string GetQueueEndpoint() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(AzuriteBuilder.QueuePort), AzuriteBuilder.AccountName).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(AzuriteBuilder.QueuePort), + AzuriteBuilder.AccountName + ).ToString(); } /// @@ -53,6 +64,11 @@ public string GetQueueEndpoint() /// The Azurite table endpoint public string GetTableEndpoint() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(AzuriteBuilder.TablePort), AzuriteBuilder.AccountName).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(AzuriteBuilder.TablePort), + AzuriteBuilder.AccountName + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Azurite/AzuriteService.cs b/src/Testcontainers.Azurite/AzuriteService.cs index 79867eac8..3796204c9 100644 --- a/src/Testcontainers.Azurite/AzuriteService.cs +++ b/src/Testcontainers.Azurite/AzuriteService.cs @@ -28,4 +28,4 @@ private AzuriteService(string identifier) { _ = identifier; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Azurite/Testcontainers.Azurite.csproj b/src/Testcontainers.Azurite/Testcontainers.Azurite.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Azurite/Testcontainers.Azurite.csproj +++ b/src/Testcontainers.Azurite/Testcontainers.Azurite.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Azurite/Usings.cs b/src/Testcontainers.Azurite/Usings.cs index 2607026ed..15431f43b 100644 --- a/src/Testcontainers.Azurite/Usings.cs +++ b/src/Testcontainers.Azurite/Usings.cs @@ -5,4 +5,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.BigQuery/BigQueryBuilder.cs b/src/Testcontainers.BigQuery/BigQueryBuilder.cs index 985dcf639..099865237 100644 --- a/src/Testcontainers.BigQuery/BigQueryBuilder.cs +++ b/src/Testcontainers.BigQuery/BigQueryBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.BigQuery; /// [PublicAPI] -public sealed class BigQueryBuilder : ContainerBuilder +public sealed class BigQueryBuilder + : ContainerBuilder { public const string BigQueryImage = "ghcr.io/goccy/bigquery-emulator:0.4"; @@ -33,7 +34,7 @@ private BigQueryBuilder(BigQueryConfiguration resourceConfiguration) protected override BigQueryConfiguration DockerResourceConfiguration { get; } /// - /// + /// /// /// /// @@ -60,7 +61,9 @@ protected override BigQueryBuilder Init() } /// - protected override BigQueryBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override BigQueryBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new BigQueryConfiguration(resourceConfiguration)); } @@ -72,8 +75,11 @@ protected override BigQueryBuilder Clone(IContainerConfiguration resourceConfigu } /// - protected override BigQueryBuilder Merge(BigQueryConfiguration oldValue, BigQueryConfiguration newValue) + protected override BigQueryBuilder Merge( + BigQueryConfiguration oldValue, + BigQueryConfiguration newValue + ) { return new BigQueryBuilder(new BigQueryConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.BigQuery/BigQueryConfiguration.cs b/src/Testcontainers.BigQuery/BigQueryConfiguration.cs index 0e705d945..f18ac0c4f 100644 --- a/src/Testcontainers.BigQuery/BigQueryConfiguration.cs +++ b/src/Testcontainers.BigQuery/BigQueryConfiguration.cs @@ -7,15 +7,15 @@ public sealed class BigQueryConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public BigQueryConfiguration() - { - } + public BigQueryConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public BigQueryConfiguration(IResourceConfiguration resourceConfiguration) + public BigQueryConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public BigQueryConfiguration(BigQueryConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public BigQueryConfiguration(BigQueryConfiguration oldValue, BigQueryConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.BigQuery/BigQueryContainer.cs b/src/Testcontainers.BigQuery/BigQueryContainer.cs index 9c2a70e51..22cec42f7 100644 --- a/src/Testcontainers.BigQuery/BigQueryContainer.cs +++ b/src/Testcontainers.BigQuery/BigQueryContainer.cs @@ -9,9 +9,7 @@ public sealed class BigQueryContainer : DockerContainer /// /// The container configuration. public BigQueryContainer(BigQueryConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the BigQuery emulator endpoint. @@ -19,6 +17,10 @@ public BigQueryContainer(BigQueryConfiguration configuration) /// The BigQuery emulator endpoint. public string GetEmulatorEndpoint() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(BigQueryBuilder.BigQueryPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(BigQueryBuilder.BigQueryPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.BigQuery/Testcontainers.BigQuery.csproj b/src/Testcontainers.BigQuery/Testcontainers.BigQuery.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.BigQuery/Testcontainers.BigQuery.csproj +++ b/src/Testcontainers.BigQuery/Testcontainers.BigQuery.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.BigQuery/Usings.cs b/src/Testcontainers.BigQuery/Usings.cs index 79fd3af9b..b31708db0 100644 --- a/src/Testcontainers.BigQuery/Usings.cs +++ b/src/Testcontainers.BigQuery/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Bigtable/BigtableBuilder.cs b/src/Testcontainers.Bigtable/BigtableBuilder.cs index 867487f68..36b4e6376 100644 --- a/src/Testcontainers.Bigtable/BigtableBuilder.cs +++ b/src/Testcontainers.Bigtable/BigtableBuilder.cs @@ -2,9 +2,11 @@ namespace Testcontainers.Bigtable; /// [PublicAPI] -public sealed class BigtableBuilder : ContainerBuilder +public sealed class BigtableBuilder + : ContainerBuilder { - public const string GoogleCloudCliImage = "gcr.io/google.com/cloudsdktool/google-cloud-cli:446.0.1-emulators"; + public const string GoogleCloudCliImage = + "gcr.io/google.com/cloudsdktool/google-cloud-cli:446.0.1-emulators"; public const ushort BigtablePort = 9000; @@ -44,12 +46,21 @@ protected override BigtableBuilder Init() .WithImage(GoogleCloudCliImage) .WithPortBinding(BigtablePort, true) .WithEntrypoint("gcloud") - .WithCommand("beta", "emulators", "bigtable", "start", "--host-port", "0.0.0.0:" + BigtablePort) + .WithCommand( + "beta", + "emulators", + "bigtable", + "start", + "--host-port", + "0.0.0.0:" + BigtablePort + ) .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("(?s).*running.*$")); } /// - protected override BigtableBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override BigtableBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new BigtableConfiguration(resourceConfiguration)); } @@ -61,8 +72,11 @@ protected override BigtableBuilder Clone(IContainerConfiguration resourceConfigu } /// - protected override BigtableBuilder Merge(BigtableConfiguration oldValue, BigtableConfiguration newValue) + protected override BigtableBuilder Merge( + BigtableConfiguration oldValue, + BigtableConfiguration newValue + ) { return new BigtableBuilder(new BigtableConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Bigtable/BigtableConfiguration.cs b/src/Testcontainers.Bigtable/BigtableConfiguration.cs index bf936ef60..d9d79e889 100644 --- a/src/Testcontainers.Bigtable/BigtableConfiguration.cs +++ b/src/Testcontainers.Bigtable/BigtableConfiguration.cs @@ -7,15 +7,15 @@ public sealed class BigtableConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public BigtableConfiguration() - { - } + public BigtableConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public BigtableConfiguration(IResourceConfiguration resourceConfiguration) + public BigtableConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public BigtableConfiguration(BigtableConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public BigtableConfiguration(BigtableConfiguration oldValue, BigtableConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Bigtable/BigtableContainer.cs b/src/Testcontainers.Bigtable/BigtableContainer.cs index f9f402aa4..2feb469ce 100644 --- a/src/Testcontainers.Bigtable/BigtableContainer.cs +++ b/src/Testcontainers.Bigtable/BigtableContainer.cs @@ -9,9 +9,7 @@ public sealed class BigtableContainer : DockerContainer /// /// The container configuration. public BigtableContainer(IContainerConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Bigtable emulator endpoint. @@ -19,6 +17,10 @@ public BigtableContainer(IContainerConfiguration configuration) /// The Bigtable emulator endpoint. public string GetEmulatorEndpoint() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(BigtableBuilder.BigtablePort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(BigtableBuilder.BigtablePort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Bigtable/Testcontainers.Bigtable.csproj b/src/Testcontainers.Bigtable/Testcontainers.Bigtable.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Bigtable/Testcontainers.Bigtable.csproj +++ b/src/Testcontainers.Bigtable/Testcontainers.Bigtable.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Bigtable/Usings.cs b/src/Testcontainers.Bigtable/Usings.cs index 79fd3af9b..b31708db0 100644 --- a/src/Testcontainers.Bigtable/Usings.cs +++ b/src/Testcontainers.Bigtable/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Cassandra/CassandraBuilder.cs b/src/Testcontainers.Cassandra/CassandraBuilder.cs index 9a8590736..b7b1c1259 100644 --- a/src/Testcontainers.Cassandra/CassandraBuilder.cs +++ b/src/Testcontainers.Cassandra/CassandraBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Cassandra; /// [PublicAPI] -public sealed class CassandraBuilder : ContainerBuilder +public sealed class CassandraBuilder + : ContainerBuilder { public const string CassandraImage = "cassandra:5.0"; @@ -45,7 +46,10 @@ protected override CassandraBuilder Init() return base.Init() .WithImage(CassandraImage) .WithPortBinding(CqlPort, true) - .WithEnvironment("JVM_OPTS", "-Dcassandra.skip_wait_for_gossip_to_settle=0 -Dcassandra.initial_token=0") + .WithEnvironment( + "JVM_OPTS", + "-Dcassandra.skip_wait_for_gossip_to_settle=0 -Dcassandra.initial_token=0" + ) .WithEnvironment("HEAP_NEWSIZE", "128M") .WithEnvironment("MAX_HEAP_SIZE", "1024M") .WithEnvironment("CASSANDRA_SNITCH", "GossipingPropertyFileSnitch") @@ -55,20 +59,31 @@ protected override CassandraBuilder Init() } /// - protected override CassandraBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override CassandraBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new CassandraConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new CassandraConfiguration(resourceConfiguration) + ); } /// protected override CassandraBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new CassandraConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new CassandraConfiguration(resourceConfiguration) + ); } /// - protected override CassandraBuilder Merge(CassandraConfiguration oldValue, CassandraConfiguration newValue) + protected override CassandraBuilder Merge( + CassandraConfiguration oldValue, + CassandraConfiguration newValue + ) { return new CassandraBuilder(new CassandraConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Cassandra/CassandraConfiguration.cs b/src/Testcontainers.Cassandra/CassandraConfiguration.cs index 2aade26d3..61039d6ce 100644 --- a/src/Testcontainers.Cassandra/CassandraConfiguration.cs +++ b/src/Testcontainers.Cassandra/CassandraConfiguration.cs @@ -7,15 +7,15 @@ public sealed class CassandraConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public CassandraConfiguration() - { - } + public CassandraConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public CassandraConfiguration(IResourceConfiguration resourceConfiguration) + public CassandraConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public CassandraConfiguration(CassandraConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public CassandraConfiguration(CassandraConfiguration oldValue, CassandraConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Cassandra/CassandraContainer.cs b/src/Testcontainers.Cassandra/CassandraContainer.cs index 819148014..00e2712ed 100644 --- a/src/Testcontainers.Cassandra/CassandraContainer.cs +++ b/src/Testcontainers.Cassandra/CassandraContainer.cs @@ -6,9 +6,7 @@ public sealed class CassandraContainer : DockerContainer, IDatabaseContainer { /// public CassandraContainer(CassandraConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Cassandra connection string. @@ -22,7 +20,10 @@ public string GetConnectionString() properties.Add("Contact Points", Hostname); properties.Add("Port", publicPort); properties.Add("Cluster Name", $"{Hostname}:{publicPort}"); - return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value))); + return string.Join( + ";", + properties.Select(property => string.Join("=", property.Key, property.Value)) + ); } /// @@ -31,14 +32,28 @@ public string GetConnectionString() /// The content of the CQL script to execute. /// Cancellation token. /// Task that completes when the CQL script has been executed. - public async Task ExecScriptAsync(string scriptContent, CancellationToken ct = default) + public async Task ExecScriptAsync( + string scriptContent, + CancellationToken ct = default + ) { - var scriptFilePath = string.Join("/", string.Empty, "tmp", Guid.NewGuid().ToString("D"), Path.GetRandomFileName()); + var scriptFilePath = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid().ToString("D"), + Path.GetRandomFileName() + ); - await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.FileMode644, ct) + await CopyAsync( + Encoding.Default.GetBytes(scriptContent), + scriptFilePath, + Unix.FileMode644, + ct + ) .ConfigureAwait(false); return await ExecAsync(new[] { "cqlsh", "--file", scriptFilePath }, ct) .ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Cassandra/Testcontainers.Cassandra.csproj b/src/Testcontainers.Cassandra/Testcontainers.Cassandra.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Cassandra/Testcontainers.Cassandra.csproj +++ b/src/Testcontainers.Cassandra/Testcontainers.Cassandra.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Cassandra/Usings.cs b/src/Testcontainers.Cassandra/Usings.cs index 191eb3bce..5c4354ec7 100644 --- a/src/Testcontainers.Cassandra/Usings.cs +++ b/src/Testcontainers.Cassandra/Usings.cs @@ -1,12 +1,12 @@ global using System; +global using System.Collections.Generic; global using System.IO; -global using System.Text; global using System.Linq; +global using System.Text; global using System.Threading; global using System.Threading.Tasks; -global using System.Collections.Generic; global using Docker.DotNet.Models; global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.ClickHouse/ClickHouseBuilder.cs b/src/Testcontainers.ClickHouse/ClickHouseBuilder.cs index 4c48dba80..abe390134 100644 --- a/src/Testcontainers.ClickHouse/ClickHouseBuilder.cs +++ b/src/Testcontainers.ClickHouse/ClickHouseBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.ClickHouse; /// [PublicAPI] -public sealed class ClickHouseBuilder : ContainerBuilder +public sealed class ClickHouseBuilder + : ContainerBuilder { public const string ClickHouseImage = "clickhouse/clickhouse-server:23.6-alpine"; @@ -88,8 +89,12 @@ protected override ClickHouseBuilder Init() .WithDatabase(DefaultDatabase) .WithUsername(DefaultUsername) .WithPassword(DefaultPassword) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPort(HttpPort).ForResponseMessageMatching(IsNodeReadyAsync))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request.ForPort(HttpPort).ForResponseMessageMatching(IsNodeReadyAsync) + ) + ); } /// @@ -97,34 +102,48 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override ClickHouseBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override ClickHouseBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new ClickHouseConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new ClickHouseConfiguration(resourceConfiguration) + ); } /// protected override ClickHouseBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new ClickHouseConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new ClickHouseConfiguration(resourceConfiguration) + ); } /// - protected override ClickHouseBuilder Merge(ClickHouseConfiguration oldValue, ClickHouseConfiguration newValue) + protected override ClickHouseBuilder Merge( + ClickHouseConfiguration oldValue, + ClickHouseConfiguration newValue + ) { return new ClickHouseBuilder(new ClickHouseConfiguration(oldValue, newValue)); } private static async Task IsNodeReadyAsync(HttpResponseMessage response) { - var content = await response.Content.ReadAsStringAsync() - .ConfigureAwait(false); + var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return "Ok.\n".Equals(content, StringComparison.OrdinalIgnoreCase); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.ClickHouse/ClickHouseConfiguration.cs b/src/Testcontainers.ClickHouse/ClickHouseConfiguration.cs index f65b3c2ad..3d41f8776 100644 --- a/src/Testcontainers.ClickHouse/ClickHouseConfiguration.cs +++ b/src/Testcontainers.ClickHouse/ClickHouseConfiguration.cs @@ -13,7 +13,8 @@ public sealed class ClickHouseConfiguration : ContainerConfiguration public ClickHouseConfiguration( string database = null, string username = null, - string password = null) + string password = null + ) { Database = database; Username = username; @@ -24,7 +25,9 @@ public ClickHouseConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public ClickHouseConfiguration(IResourceConfiguration resourceConfiguration) + public ClickHouseConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -55,7 +58,10 @@ public ClickHouseConfiguration(ClickHouseConfiguration resourceConfiguration) /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public ClickHouseConfiguration(ClickHouseConfiguration oldValue, ClickHouseConfiguration newValue) + public ClickHouseConfiguration( + ClickHouseConfiguration oldValue, + ClickHouseConfiguration newValue + ) : base(oldValue, newValue) { Database = BuildConfiguration.Combine(oldValue.Database, newValue.Database); @@ -77,4 +83,4 @@ public ClickHouseConfiguration(ClickHouseConfiguration oldValue, ClickHouseConfi /// Gets the ClickHouse password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.ClickHouse/ClickHouseContainer.cs b/src/Testcontainers.ClickHouse/ClickHouseContainer.cs index a52a749f2..70aadde32 100644 --- a/src/Testcontainers.ClickHouse/ClickHouseContainer.cs +++ b/src/Testcontainers.ClickHouse/ClickHouseContainer.cs @@ -28,7 +28,10 @@ public string GetConnectionString() properties.Add("Database", _configuration.Database); properties.Add("Username", _configuration.Username); properties.Add("Password", _configuration.Password); - return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value))); + return string.Join( + ";", + properties.Select(property => string.Join("=", property.Key, property.Value)) + ); } /// @@ -37,14 +40,38 @@ public string GetConnectionString() /// The content of the SQL script to execute. /// Cancellation token. /// Task that completes when the SQL script has been executed. - public async Task ExecScriptAsync(string scriptContent, CancellationToken ct = default) + public async Task ExecScriptAsync( + string scriptContent, + CancellationToken ct = default + ) { - var scriptFilePath = string.Join("/", string.Empty, "tmp", Guid.NewGuid().ToString("D"), Path.GetRandomFileName()); + var scriptFilePath = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid().ToString("D"), + Path.GetRandomFileName() + ); - await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.FileMode644, ct) + await CopyAsync( + Encoding.Default.GetBytes(scriptContent), + scriptFilePath, + Unix.FileMode644, + ct + ) .ConfigureAwait(false); - return await ExecAsync(new[] { "clickhouse-client", "--database", _configuration.Database, "--queries-file", scriptFilePath }, ct) + return await ExecAsync( + new[] + { + "clickhouse-client", + "--database", + _configuration.Database, + "--queries-file", + scriptFilePath, + }, + ct + ) .ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.ClickHouse/Testcontainers.ClickHouse.csproj b/src/Testcontainers.ClickHouse/Testcontainers.ClickHouse.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.ClickHouse/Testcontainers.ClickHouse.csproj +++ b/src/Testcontainers.ClickHouse/Testcontainers.ClickHouse.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.ClickHouse/Usings.cs b/src/Testcontainers.ClickHouse/Usings.cs index ee2e98dbe..55a66774b 100644 --- a/src/Testcontainers.ClickHouse/Usings.cs +++ b/src/Testcontainers.ClickHouse/Usings.cs @@ -11,4 +11,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.CockroachDb/CockroachDbBuilder.cs b/src/Testcontainers.CockroachDb/CockroachDbBuilder.cs index eea0cda4d..73ed3c2e5 100644 --- a/src/Testcontainers.CockroachDb/CockroachDbBuilder.cs +++ b/src/Testcontainers.CockroachDb/CockroachDbBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.CockroachDb; /// [PublicAPI] -public sealed class CockroachDbBuilder : ContainerBuilder +public sealed class CockroachDbBuilder + : ContainerBuilder { public const string CockroachDbImage = "cockroachdb/cockroach:latest-v23.1"; @@ -90,8 +91,12 @@ protected override CockroachDbBuilder Init() .WithPassword(DefaultPassword) .WithCommand("start-single-node") .WithCommand("--insecure") - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPort(CockroachDbRestPort).ForPath("/health"))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request.ForPort(CockroachDbRestPort).ForPath("/health") + ) + ); } /// @@ -99,25 +104,40 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull(); } /// - protected override CockroachDbBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override CockroachDbBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new CockroachDbConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new CockroachDbConfiguration(resourceConfiguration) + ); } /// protected override CockroachDbBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new CockroachDbConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new CockroachDbConfiguration(resourceConfiguration) + ); } /// - protected override CockroachDbBuilder Merge(CockroachDbConfiguration oldValue, CockroachDbConfiguration newValue) + protected override CockroachDbBuilder Merge( + CockroachDbConfiguration oldValue, + CockroachDbConfiguration newValue + ) { return new CockroachDbBuilder(new CockroachDbConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.CockroachDb/CockroachDbConfiguration.cs b/src/Testcontainers.CockroachDb/CockroachDbConfiguration.cs index 4ef034b9d..ed8582428 100644 --- a/src/Testcontainers.CockroachDb/CockroachDbConfiguration.cs +++ b/src/Testcontainers.CockroachDb/CockroachDbConfiguration.cs @@ -13,7 +13,8 @@ public sealed class CockroachDbConfiguration : ContainerConfiguration public CockroachDbConfiguration( string database = null, string username = null, - string password = null) + string password = null + ) { Database = database; Username = username; @@ -24,7 +25,9 @@ public CockroachDbConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public CockroachDbConfiguration(IResourceConfiguration resourceConfiguration) + public CockroachDbConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -55,7 +58,10 @@ public CockroachDbConfiguration(CockroachDbConfiguration resourceConfiguration) /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public CockroachDbConfiguration(CockroachDbConfiguration oldValue, CockroachDbConfiguration newValue) + public CockroachDbConfiguration( + CockroachDbConfiguration oldValue, + CockroachDbConfiguration newValue + ) : base(oldValue, newValue) { Database = BuildConfiguration.Combine(oldValue.Database, newValue.Database); @@ -77,4 +83,4 @@ public CockroachDbConfiguration(CockroachDbConfiguration oldValue, CockroachDbCo /// Gets the CockroachDb password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.CockroachDb/CockroachDbContainer.cs b/src/Testcontainers.CockroachDb/CockroachDbContainer.cs index f13c98ea7..668558437 100644 --- a/src/Testcontainers.CockroachDb/CockroachDbContainer.cs +++ b/src/Testcontainers.CockroachDb/CockroachDbContainer.cs @@ -28,7 +28,10 @@ public string GetConnectionString() properties.Add("Database", _configuration.Database); properties.Add("Username", _configuration.Username); properties.Add("Password", _configuration.Password); - return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value))); + return string.Join( + ";", + properties.Select(property => string.Join("=", property.Key, property.Value)) + ); } /// @@ -37,14 +40,31 @@ public string GetConnectionString() /// The content of the SQL script to execute. /// Cancellation token. /// Task that completes when the SQL script has been executed. - public async Task ExecScriptAsync(string scriptContent, CancellationToken ct = default) + public async Task ExecScriptAsync( + string scriptContent, + CancellationToken ct = default + ) { - var scriptFilePath = string.Join("/", string.Empty, "tmp", Guid.NewGuid().ToString("D"), Path.GetRandomFileName()); + var scriptFilePath = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid().ToString("D"), + Path.GetRandomFileName() + ); - await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.FileMode644, ct) + await CopyAsync( + Encoding.Default.GetBytes(scriptContent), + scriptFilePath, + Unix.FileMode644, + ct + ) .ConfigureAwait(false); - return await ExecAsync(new[] { "cockroach", "sql", "--insecure", "--file", scriptFilePath }, ct) + return await ExecAsync( + new[] { "cockroach", "sql", "--insecure", "--file", scriptFilePath }, + ct + ) .ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.CockroachDb/Testcontainers.CockroachDb.csproj b/src/Testcontainers.CockroachDb/Testcontainers.CockroachDb.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.CockroachDb/Testcontainers.CockroachDb.csproj +++ b/src/Testcontainers.CockroachDb/Testcontainers.CockroachDb.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.CockroachDb/Usings.cs b/src/Testcontainers.CockroachDb/Usings.cs index e2b02a51e..3481268bc 100644 --- a/src/Testcontainers.CockroachDb/Usings.cs +++ b/src/Testcontainers.CockroachDb/Usings.cs @@ -10,4 +10,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Consul/ConsulBuilder.cs b/src/Testcontainers.Consul/ConsulBuilder.cs index 902f10e8e..acc71b4f2 100644 --- a/src/Testcontainers.Consul/ConsulBuilder.cs +++ b/src/Testcontainers.Consul/ConsulBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Consul; /// [PublicAPI] -public sealed class ConsulBuilder : ContainerBuilder +public sealed class ConsulBuilder + : ContainerBuilder { public const string ConsulImage = "consul:1.15"; @@ -48,12 +49,18 @@ protected override ConsulBuilder Init() .WithPortBinding(ConsulGrpcPort, true) .WithCommand("agent", "-dev", "-client", "0.0.0.0") .WithCreateParameterModifier(cmd => cmd.HostConfig.CapAdd = new[] { "IPC_LOCK" }) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPath("/v1/status/leader").ForPort(ConsulHttpPort))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request.ForPath("/v1/status/leader").ForPort(ConsulHttpPort) + ) + ); } /// - protected override ConsulBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override ConsulBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new ConsulConfiguration(resourceConfiguration)); } @@ -65,8 +72,11 @@ protected override ConsulBuilder Clone(IContainerConfiguration resourceConfigura } /// - protected override ConsulBuilder Merge(ConsulConfiguration oldValue, ConsulConfiguration newValue) + protected override ConsulBuilder Merge( + ConsulConfiguration oldValue, + ConsulConfiguration newValue + ) { return new ConsulBuilder(new ConsulConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Consul/ConsulConfiguration.cs b/src/Testcontainers.Consul/ConsulConfiguration.cs index d67d88d22..b3c916ec6 100644 --- a/src/Testcontainers.Consul/ConsulConfiguration.cs +++ b/src/Testcontainers.Consul/ConsulConfiguration.cs @@ -7,15 +7,15 @@ public sealed class ConsulConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public ConsulConfiguration() - { - } + public ConsulConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public ConsulConfiguration(IResourceConfiguration resourceConfiguration) + public ConsulConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public ConsulConfiguration(ConsulConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public ConsulConfiguration(ConsulConfiguration oldValue, ConsulConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Consul/ConsulContainer.cs b/src/Testcontainers.Consul/ConsulContainer.cs index 9d431865b..533af3f2f 100644 --- a/src/Testcontainers.Consul/ConsulContainer.cs +++ b/src/Testcontainers.Consul/ConsulContainer.cs @@ -9,9 +9,7 @@ public sealed class ConsulContainer : DockerContainer /// /// The container configuration. public ConsulContainer(ConsulConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Consul base address. @@ -19,6 +17,10 @@ public ConsulContainer(ConsulConfiguration configuration) /// The Consul base address. public string GetBaseAddress() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(ConsulBuilder.ConsulHttpPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(ConsulBuilder.ConsulHttpPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Consul/Testcontainers.Consul.csproj b/src/Testcontainers.Consul/Testcontainers.Consul.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Consul/Testcontainers.Consul.csproj +++ b/src/Testcontainers.Consul/Testcontainers.Consul.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Consul/Usings.cs b/src/Testcontainers.Consul/Usings.cs index 79fd3af9b..b31708db0 100644 --- a/src/Testcontainers.Consul/Usings.cs +++ b/src/Testcontainers.Consul/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.CosmosDb/CosmosDbBuilder.cs b/src/Testcontainers.CosmosDb/CosmosDbBuilder.cs index bde981f22..ef2fcbe2b 100644 --- a/src/Testcontainers.CosmosDb/CosmosDbBuilder.cs +++ b/src/Testcontainers.CosmosDb/CosmosDbBuilder.cs @@ -2,13 +2,16 @@ namespace Testcontainers.CosmosDb; /// [PublicAPI] -public sealed class CosmosDbBuilder : ContainerBuilder +public sealed class CosmosDbBuilder + : ContainerBuilder { - public const string CosmosDbImage = "mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest"; + public const string CosmosDbImage = + "mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest"; public const ushort CosmosDbPort = 8081; - public const string DefaultAccountKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="; + public const string DefaultAccountKey = + "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="; /// /// Initializes a new instance of the class. @@ -49,7 +52,9 @@ protected override CosmosDbBuilder Init() } /// - protected override CosmosDbBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override CosmosDbBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new CosmosDbConfiguration(resourceConfiguration)); } @@ -61,7 +66,10 @@ protected override CosmosDbBuilder Clone(IContainerConfiguration resourceConfigu } /// - protected override CosmosDbBuilder Merge(CosmosDbConfiguration oldValue, CosmosDbConfiguration newValue) + protected override CosmosDbBuilder Merge( + CosmosDbConfiguration oldValue, + CosmosDbConfiguration newValue + ) { return new CosmosDbBuilder(new CosmosDbConfiguration(oldValue, newValue)); } @@ -79,7 +87,8 @@ public async Task UntilAsync(IContainer container) try { - using var httpResponse = await httpClient.GetAsync(requestUri) + using var httpResponse = await httpClient + .GetAsync(requestUri) .ConfigureAwait(false); return httpResponse.IsSuccessStatusCode; @@ -94,4 +103,4 @@ public async Task UntilAsync(IContainer container) } } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.CosmosDb/CosmosDbConfiguration.cs b/src/Testcontainers.CosmosDb/CosmosDbConfiguration.cs index c623b6aef..cae5d02d6 100644 --- a/src/Testcontainers.CosmosDb/CosmosDbConfiguration.cs +++ b/src/Testcontainers.CosmosDb/CosmosDbConfiguration.cs @@ -7,15 +7,15 @@ public sealed class CosmosDbConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public CosmosDbConfiguration() - { - } + public CosmosDbConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public CosmosDbConfiguration(IResourceConfiguration resourceConfiguration) + public CosmosDbConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public CosmosDbConfiguration(CosmosDbConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public CosmosDbConfiguration(CosmosDbConfiguration oldValue, CosmosDbConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.CosmosDb/CosmosDbContainer.cs b/src/Testcontainers.CosmosDb/CosmosDbContainer.cs index b7b0a57d7..b6ceb970e 100644 --- a/src/Testcontainers.CosmosDb/CosmosDbContainer.cs +++ b/src/Testcontainers.CosmosDb/CosmosDbContainer.cs @@ -9,9 +9,7 @@ public sealed class CosmosDbContainer : DockerContainer /// /// The container configuration. public CosmosDbContainer(CosmosDbConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the CosmosDb connection string. @@ -20,15 +18,26 @@ public CosmosDbContainer(CosmosDbConfiguration configuration) public string GetConnectionString() { var properties = new Dictionary(); - properties.Add("AccountEndpoint", new UriBuilder(Uri.UriSchemeHttps, Hostname, GetMappedPublicPort(CosmosDbBuilder.CosmosDbPort)).ToString()); + properties.Add( + "AccountEndpoint", + new UriBuilder( + Uri.UriSchemeHttps, + Hostname, + GetMappedPublicPort(CosmosDbBuilder.CosmosDbPort) + ).ToString() + ); properties.Add("AccountKey", CosmosDbBuilder.DefaultAccountKey); - return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value))); + return string.Join( + ";", + properties.Select(property => string.Join("=", property.Key, property.Value)) + ); } /// /// Gets a configured HTTP message handler that automatically trusts the CosmosDb Emulator's certificate. /// - public HttpMessageHandler HttpMessageHandler => new UriRewriter(Hostname, GetMappedPublicPort(CosmosDbBuilder.CosmosDbPort)); + public HttpMessageHandler HttpMessageHandler => + new UriRewriter(Hostname, GetMappedPublicPort(CosmosDbBuilder.CosmosDbPort)); /// /// Gets a configured HTTP client that automatically trusts the CosmosDb Emulator's certificate. @@ -50,17 +59,30 @@ private sealed class UriRewriter : DelegatingHandler /// The target hostname. /// The target port. public UriRewriter(string hostname, ushort port) - : base(new HttpClientHandler { ServerCertificateCustomValidationCallback = (_, _, _, _) => true }) + : base( + new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (_, _, _, _) => true, + } + ) { _hostname = hostname; _port = port; } /// - protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken + ) { - request.RequestUri = new UriBuilder(Uri.UriSchemeHttps, _hostname, _port, request.RequestUri.PathAndQuery).Uri; + request.RequestUri = new UriBuilder( + Uri.UriSchemeHttps, + _hostname, + _port, + request.RequestUri.PathAndQuery + ).Uri; return base.SendAsync(request, cancellationToken); } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.CosmosDb/Testcontainers.CosmosDb.csproj b/src/Testcontainers.CosmosDb/Testcontainers.CosmosDb.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.CosmosDb/Testcontainers.CosmosDb.csproj +++ b/src/Testcontainers.CosmosDb/Testcontainers.CosmosDb.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.CosmosDb/Usings.cs b/src/Testcontainers.CosmosDb/Usings.cs index 8642a70f5..698de4d36 100644 --- a/src/Testcontainers.CosmosDb/Usings.cs +++ b/src/Testcontainers.CosmosDb/Usings.cs @@ -8,4 +8,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.CouchDb/CouchDbBuilder.cs b/src/Testcontainers.CouchDb/CouchDbBuilder.cs index bae17e902..98873971f 100644 --- a/src/Testcontainers.CouchDb/CouchDbBuilder.cs +++ b/src/Testcontainers.CouchDb/CouchDbBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.CouchDb; /// [PublicAPI] -public sealed class CouchDbBuilder : ContainerBuilder +public sealed class CouchDbBuilder + : ContainerBuilder { public const string CouchDbImage = "couchdb:3.3"; @@ -71,8 +72,12 @@ protected override CouchDbBuilder Init() .WithPortBinding(CouchDbPort, true) .WithUsername(DefaultUsername) .WithPassword(DefaultPassword) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPath("/").ForPort(CouchDbPort))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request.ForPath("/").ForPort(CouchDbPort) + ) + ); } /// @@ -80,17 +85,27 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Username, nameof(DockerResourceConfiguration.Username)) + _ = Guard + .Argument( + DockerResourceConfiguration.Username, + nameof(DockerResourceConfiguration.Username) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override CouchDbBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override CouchDbBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new CouchDbConfiguration(resourceConfiguration)); } @@ -102,8 +117,11 @@ protected override CouchDbBuilder Clone(IContainerConfiguration resourceConfigur } /// - protected override CouchDbBuilder Merge(CouchDbConfiguration oldValue, CouchDbConfiguration newValue) + protected override CouchDbBuilder Merge( + CouchDbConfiguration oldValue, + CouchDbConfiguration newValue + ) { return new CouchDbBuilder(new CouchDbConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.CouchDb/CouchDbConfiguration.cs b/src/Testcontainers.CouchDb/CouchDbConfiguration.cs index fc76e153e..e0904db10 100644 --- a/src/Testcontainers.CouchDb/CouchDbConfiguration.cs +++ b/src/Testcontainers.CouchDb/CouchDbConfiguration.cs @@ -9,9 +9,7 @@ public sealed class CouchDbConfiguration : ContainerConfiguration /// /// The CouchDb username. /// The CouchDb password. - public CouchDbConfiguration( - string username = null, - string password = null) + public CouchDbConfiguration(string username = null, string password = null) { Username = username; Password = password; @@ -21,7 +19,9 @@ public CouchDbConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public CouchDbConfiguration(IResourceConfiguration resourceConfiguration) + public CouchDbConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -68,4 +68,4 @@ public CouchDbConfiguration(CouchDbConfiguration oldValue, CouchDbConfiguration /// Gets the CouchDb password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.CouchDb/CouchDbContainer.cs b/src/Testcontainers.CouchDb/CouchDbContainer.cs index e75b000e8..0ebccc201 100644 --- a/src/Testcontainers.CouchDb/CouchDbContainer.cs +++ b/src/Testcontainers.CouchDb/CouchDbContainer.cs @@ -22,9 +22,13 @@ public CouchDbContainer(CouchDbConfiguration configuration) /// The CouchDb connection string. public string GetConnectionString() { - var endpoint = new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(CouchDbBuilder.CouchDbPort)); + var endpoint = new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(CouchDbBuilder.CouchDbPort) + ); endpoint.UserName = Uri.EscapeDataString(_configuration.Username); endpoint.Password = Uri.EscapeDataString(_configuration.Password); return endpoint.ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.CouchDb/Testcontainers.CouchDb.csproj b/src/Testcontainers.CouchDb/Testcontainers.CouchDb.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.CouchDb/Testcontainers.CouchDb.csproj +++ b/src/Testcontainers.CouchDb/Testcontainers.CouchDb.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.CouchDb/Usings.cs b/src/Testcontainers.CouchDb/Usings.cs index 8e5c20fd5..f89f0c94d 100644 --- a/src/Testcontainers.CouchDb/Usings.cs +++ b/src/Testcontainers.CouchDb/Usings.cs @@ -4,4 +4,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Couchbase/CouchbaseBucket.cs b/src/Testcontainers.Couchbase/CouchbaseBucket.cs index 04d8ab472..efcf0e6aa 100644 --- a/src/Testcontainers.Couchbase/CouchbaseBucket.cs +++ b/src/Testcontainers.Couchbase/CouchbaseBucket.cs @@ -9,7 +9,9 @@ public sealed class CouchbaseBucket /// /// Gets the default bucket. /// - public static readonly CouchbaseBucket Default = new CouchbaseBucket(Guid.NewGuid().ToString("D")); + public static readonly CouchbaseBucket Default = new CouchbaseBucket( + Guid.NewGuid().ToString("D") + ); /// /// Initializes a new instance of the struct. @@ -24,7 +26,8 @@ private CouchbaseBucket( bool flushEnabled = false, bool primaryIndexEnabled = true, ushort quotaMiB = 100, - ushort replicaNumber = 0) + ushort replicaNumber = 0 + ) { Name = name; FlushEnabled = flushEnabled; @@ -57,4 +60,4 @@ private CouchbaseBucket( /// Gets the replica number. /// public ushort ReplicaNumber { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Couchbase/CouchbaseBuilder.cs b/src/Testcontainers.Couchbase/CouchbaseBuilder.cs index 710f14647..29d196169 100644 --- a/src/Testcontainers.Couchbase/CouchbaseBuilder.cs +++ b/src/Testcontainers.Couchbase/CouchbaseBuilder.cs @@ -5,7 +5,8 @@ namespace Testcontainers.Couchbase; /// The Couchbase module runs the following services: Data, Index, Query, Search and creates the bucket during the start. /// [PublicAPI] -public sealed class CouchbaseBuilder : ContainerBuilder +public sealed class CouchbaseBuilder + : ContainerBuilder { public const string CouchbaseImage = "couchbase:community-7.0.2"; @@ -41,11 +42,23 @@ public sealed class CouchbaseBuilder : ContainerBuilder BasicAuthenticationHeader = new KeyValuePair("Authorization", "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Join(":", DefaultUsername, DefaultPassword)))); + private static readonly KeyValuePair BasicAuthenticationHeader = + new KeyValuePair( + "Authorization", + "Basic " + + Convert.ToBase64String( + Encoding + .GetEncoding("ISO-8859-1") + .GetBytes(string.Join(":", DefaultUsername, DefaultPassword)) + ) + ); - private static readonly IWaitUntil WaitUntilNodeIsReady = new HttpWaitStrategy().ForPath("/pools").ForPort(MgmtPort); + private static readonly IWaitUntil WaitUntilNodeIsReady = new HttpWaitStrategy() + .ForPath("/pools") + .ForPort(MgmtPort); - private static readonly ISet EnabledServices = new HashSet(); + private static readonly ISet EnabledServices = + new HashSet(); static CouchbaseBuilder() { @@ -86,42 +99,49 @@ public override CouchbaseContainer Build() if (EnabledServices.Any()) { - waitStrategy = waitStrategy.UntilHttpRequestIsSucceeded(request - => request + waitStrategy = waitStrategy.UntilHttpRequestIsSucceeded(request => + request .ForPath("/pools/default") .ForPort(MgmtPort) .ForResponseMessageMatching(IsNodeHealthyAsync) - .WithHeader(BasicAuthenticationHeader.Key, BasicAuthenticationHeader.Value)); + .WithHeader(BasicAuthenticationHeader.Key, BasicAuthenticationHeader.Value) + ); } if (EnabledServices.Contains(CouchbaseService.Query)) { - waitStrategy = waitStrategy.UntilHttpRequestIsSucceeded(request - => request + waitStrategy = waitStrategy.UntilHttpRequestIsSucceeded(request => + request .ForPath("/admin/ping") .ForPort(QueryPort) - .WithHeader(BasicAuthenticationHeader.Key, BasicAuthenticationHeader.Value)); + .WithHeader(BasicAuthenticationHeader.Key, BasicAuthenticationHeader.Value) + ); } if (EnabledServices.Contains(CouchbaseService.Analytics)) { - waitStrategy = waitStrategy.UntilHttpRequestIsSucceeded(request - => request + waitStrategy = waitStrategy.UntilHttpRequestIsSucceeded(request => + request .ForPath("/admin/ping") .ForPort(AnalyticsPort) - .WithHeader(BasicAuthenticationHeader.Key, BasicAuthenticationHeader.Value)); + .WithHeader(BasicAuthenticationHeader.Key, BasicAuthenticationHeader.Value) + ); } if (EnabledServices.Contains(CouchbaseService.Eventing)) { - waitStrategy = waitStrategy.UntilHttpRequestIsSucceeded(request - => request + waitStrategy = waitStrategy.UntilHttpRequestIsSucceeded(request => + request .ForPath("/api/v1/config") .ForPort(EventingPort) - .WithHeader(BasicAuthenticationHeader.Key, BasicAuthenticationHeader.Value)); + .WithHeader(BasicAuthenticationHeader.Key, BasicAuthenticationHeader.Value) + ); } - var couchbaseBuilder = DockerResourceConfiguration.WaitStrategies.Count() > 1 ? this : WithWaitStrategy(waitStrategy); + var couchbaseBuilder = + DockerResourceConfiguration.WaitStrategies.Count() > 1 + ? this + : WithWaitStrategy(waitStrategy); return new CouchbaseContainer(couchbaseBuilder.DockerResourceConfiguration); } @@ -149,19 +169,30 @@ protected override CouchbaseBuilder Init() } /// - protected override CouchbaseBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override CouchbaseBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new CouchbaseConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new CouchbaseConfiguration(resourceConfiguration) + ); } /// protected override CouchbaseBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new CouchbaseConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new CouchbaseConfiguration(resourceConfiguration) + ); } /// - protected override CouchbaseBuilder Merge(CouchbaseConfiguration oldValue, CouchbaseConfiguration newValue) + protected override CouchbaseBuilder Merge( + CouchbaseConfiguration oldValue, + CouchbaseConfiguration newValue + ) { return new CouchbaseBuilder(new CouchbaseConfiguration(oldValue, newValue)); } @@ -183,50 +214,58 @@ private CouchbaseBuilder WithBucket(params CouchbaseBucket[] bucket) /// Cancellation token. private async Task ConfigureCouchbaseAsync(IContainer container, CancellationToken ct = default) { - await WaitStrategy.WaitUntilAsync(() => WaitUntilNodeIsReady.UntilAsync(container), TimeSpan.FromSeconds(2), TimeSpan.FromMinutes(5), -1, ct) + await WaitStrategy + .WaitUntilAsync( + () => WaitUntilNodeIsReady.UntilAsync(container), + TimeSpan.FromSeconds(2), + TimeSpan.FromMinutes(5), + -1, + ct + ) .ConfigureAwait(false); using (var httpClient = new HttpClient(new RetryHandler())) { - httpClient.BaseAddress = new UriBuilder(Uri.UriSchemeHttp, container.Hostname, container.GetMappedPublicPort(MgmtPort)).Uri; + httpClient.BaseAddress = new UriBuilder( + Uri.UriSchemeHttp, + container.Hostname, + container.GetMappedPublicPort(MgmtPort) + ).Uri; using (var request = new RenameNodeRequest(container)) { - using (var response = await httpClient.SendAsync(request, ct) - .ConfigureAwait(false)) + using (var response = await httpClient.SendAsync(request, ct).ConfigureAwait(false)) { - await EnsureSuccessStatusCodeAsync(response) - .ConfigureAwait(false); + await EnsureSuccessStatusCodeAsync(response).ConfigureAwait(false); } } using (var request = new SetupNodeServicesRequest(EnabledServices.ToArray())) { - using (var response = await httpClient.SendAsync(request, ct) - .ConfigureAwait(false)) + using (var response = await httpClient.SendAsync(request, ct).ConfigureAwait(false)) { - await EnsureSuccessStatusCodeAsync(response) - .ConfigureAwait(false); + await EnsureSuccessStatusCodeAsync(response).ConfigureAwait(false); } } using (var request = new SetupMemoryQuotasRequest(EnabledServices.ToArray())) { - using (var response = await httpClient.SendAsync(request, ct) - .ConfigureAwait(false)) + using (var response = await httpClient.SendAsync(request, ct).ConfigureAwait(false)) { - await EnsureSuccessStatusCodeAsync(response) - .ConfigureAwait(false); + await EnsureSuccessStatusCodeAsync(response).ConfigureAwait(false); } } - using (var request = new ConfigureExternalAddressesRequest(container, EnabledServices.ToArray())) + using ( + var request = new ConfigureExternalAddressesRequest( + container, + EnabledServices.ToArray() + ) + ) { - using (var response = await httpClient.SendAsync(request, ct) - .ConfigureAwait(false)) + using (var response = await httpClient.SendAsync(request, ct).ConfigureAwait(false)) { - await EnsureSuccessStatusCodeAsync(response) - .ConfigureAwait(false); + await EnsureSuccessStatusCodeAsync(response).ConfigureAwait(false); } } @@ -234,11 +273,11 @@ await EnsureSuccessStatusCodeAsync(response) { using (var request = new CreateBucketRequest(bucket)) { - using (var response = await httpClient.SendAsync(request, ct) - .ConfigureAwait(false)) + using ( + var response = await httpClient.SendAsync(request, ct).ConfigureAwait(false) + ) { - await EnsureSuccessStatusCodeAsync(response) - .ConfigureAwait(false); + await EnsureSuccessStatusCodeAsync(response).ConfigureAwait(false); } } } @@ -249,27 +288,40 @@ await EnsureSuccessStatusCodeAsync(response) // We got frequently: System.IO.IOException The response ended prematurely. using (var request = new SetupCredentialsRequest()) { - using (var response = await httpClient.SendAsync(request, ct) - .ConfigureAwait(false)) + using (var response = await httpClient.SendAsync(request, ct).ConfigureAwait(false)) { - await EnsureSuccessStatusCodeAsync(response) - .ConfigureAwait(false); + await EnsureSuccessStatusCodeAsync(response).ConfigureAwait(false); } } } // As long as we do not expose the bucket API, we do not need to iterate over all of them. - var waitUntilBucketIsCreated = DockerResourceConfiguration.Buckets.Aggregate(Wait.ForUnixContainer(), (waitStrategy, bucket) - => waitStrategy.UntilHttpRequestIsSucceeded(request - => request - .ForPath("/pools/default/buckets/" + bucket.Name) - .ForPort(MgmtPort) - .ForResponseMessageMatching(AllServicesEnabledAsync) - .WithHeader(BasicAuthenticationHeader.Key, BasicAuthenticationHeader.Value))) + var waitUntilBucketIsCreated = DockerResourceConfiguration + .Buckets.Aggregate( + Wait.ForUnixContainer(), + (waitStrategy, bucket) => + waitStrategy.UntilHttpRequestIsSucceeded(request => + request + .ForPath("/pools/default/buckets/" + bucket.Name) + .ForPort(MgmtPort) + .ForResponseMessageMatching(AllServicesEnabledAsync) + .WithHeader( + BasicAuthenticationHeader.Key, + BasicAuthenticationHeader.Value + ) + ) + ) .Build() .Last(); - await WaitStrategy.WaitUntilAsync(() => waitUntilBucketIsCreated.UntilAsync(container, ct), TimeSpan.FromSeconds(2), TimeSpan.FromMinutes(5), -1, ct) + await WaitStrategy + .WaitUntilAsync( + () => waitUntilBucketIsCreated.UntilAsync(container, ct), + TimeSpan.FromSeconds(2), + TimeSpan.FromMinutes(5), + -1, + ct + ) .ConfigureAwait(false); } @@ -283,14 +335,13 @@ await WaitStrategy.WaitUntilAsync(() => waitUntilBucketIsCreated.UntilAsync(cont /// A value indicating whether the single-node is healthy or not. private static async Task IsNodeHealthyAsync(HttpResponseMessage response) { - var jsonString = await response.Content.ReadAsStringAsync() - .ConfigureAwait(false); + var jsonString = await response.Content.ReadAsStringAsync().ConfigureAwait(false); try { - var status = JsonDocument.Parse(jsonString) - .RootElement - .GetProperty("nodes") + var status = JsonDocument + .Parse(jsonString) + .RootElement.GetProperty("nodes") .EnumerateArray() .ElementAt(0) .GetProperty("status") @@ -314,14 +365,13 @@ private static async Task IsNodeHealthyAsync(HttpResponseMessage response) /// A value indicating whether all services are enabled for a bucket or not. private static async Task AllServicesEnabledAsync(HttpResponseMessage response) { - var jsonString = await response.Content.ReadAsStringAsync() - .ConfigureAwait(false); + var jsonString = await response.Content.ReadAsStringAsync().ConfigureAwait(false); try { - var services = JsonDocument.Parse(jsonString) - .RootElement - .GetProperty("nodes") + var services = JsonDocument + .Parse(jsonString) + .RootElement.GetProperty("nodes") .EnumerateArray() .ElementAt(0) .GetProperty("services") @@ -329,7 +379,9 @@ private static async Task AllServicesEnabledAsync(HttpResponseMessage resp .Select(service => service.GetString()) .Where(service => service != null); - return EnabledServices.All(enabledService => services.Any(service => service.StartsWith(enabledService.Identifier))); + return EnabledServices.All(enabledService => + services.Any(service => service.StartsWith(enabledService.Identifier)) + ); } catch { @@ -350,8 +402,7 @@ private static async Task EnsureSuccessStatusCodeAsync(HttpResponseMessage respo } catch (Exception e) { - var content = await response.Content.ReadAsStringAsync() - .ConfigureAwait(false); + var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); throw new InvalidOperationException(content, e); } @@ -394,7 +445,13 @@ public SetupNodeServicesRequest(params CouchbaseService[] enabledServices) : base(HttpMethod.Post, "/node/controller/setupServices") { IDictionary content = new Dictionary(); - content.Add("services", string.Join(",", enabledServices.Select(enabledService => enabledService.Identifier))); + content.Add( + "services", + string.Join( + ",", + enabledServices.Select(enabledService => enabledService.Identifier) + ) + ); Content = new FormUrlEncodedContent(content); } } @@ -429,7 +486,10 @@ public SetupMemoryQuotasRequest(params CouchbaseService[] enabledServices) } else { - content.Add(enabledService.Identifier + "MemoryQuota", enabledService.MinimumQuotaMb.ToString()); + content.Add( + enabledService.Identifier + "MemoryQuota", + enabledService.MinimumQuotaMb.ToString() + ); } } @@ -450,7 +510,10 @@ private sealed class ConfigureExternalAddressesRequest : HttpRequestMessage /// /// The Couchbase container. /// The enabled Couchbase node services. - public ConfigureExternalAddressesRequest(IContainer container, params CouchbaseService[] enabledServices) + public ConfigureExternalAddressesRequest( + IContainer container, + params CouchbaseService[] enabledServices + ) : base(HttpMethod.Put, "/node/controller/setupAlternateAddresses/external") { IDictionary content = new Dictionary(); @@ -487,8 +550,14 @@ public ConfigureExternalAddressesRequest(IContainer container, params CouchbaseS if (enabledServices.Contains(CouchbaseService.Eventing)) { - content.Add("eventingAdminPort", container.GetMappedPublicPort(EventingPort).ToString()); - content.Add("eventingSSL", container.GetMappedPublicPort(EventingSslPort).ToString()); + content.Add( + "eventingAdminPort", + container.GetMappedPublicPort(EventingPort).ToString() + ); + content.Add( + "eventingSSL", + container.GetMappedPublicPort(EventingSslPort).ToString() + ); } Content = new FormUrlEncodedContent(content); @@ -559,19 +628,19 @@ private sealed class RetryHandler : DelegatingHandler /// Initializes a new instance of the class. /// public RetryHandler() - : base(new HttpClientHandler()) - { - } + : base(new HttpClientHandler()) { } /// - protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + protected override async Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken + ) { for (var _ = 0; _ < MaxRetries; _++) { try { - return await base.SendAsync(request, cancellationToken) - .ConfigureAwait(false); + return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); } catch (HttpRequestException) { @@ -580,7 +649,9 @@ await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken) } } - throw new HttpRequestException($"Unable to configure Couchbase. The HTTP request '{request.RequestUri}' did not complete successfully."); + throw new HttpRequestException( + $"Unable to configure Couchbase. The HTTP request '{request.RequestUri}' did not complete successfully." + ); } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Couchbase/CouchbaseConfiguration.cs b/src/Testcontainers.Couchbase/CouchbaseConfiguration.cs index 92c69f866..835548a26 100644 --- a/src/Testcontainers.Couchbase/CouchbaseConfiguration.cs +++ b/src/Testcontainers.Couchbase/CouchbaseConfiguration.cs @@ -17,7 +17,9 @@ public CouchbaseConfiguration(IEnumerable buckets = null) /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public CouchbaseConfiguration(IResourceConfiguration resourceConfiguration) + public CouchbaseConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -58,4 +60,4 @@ public CouchbaseConfiguration(CouchbaseConfiguration oldValue, CouchbaseConfigur /// Gets a list of Couchbase buckets. /// public IEnumerable Buckets { get; } = Array.Empty(); -} \ No newline at end of file +} diff --git a/src/Testcontainers.Couchbase/CouchbaseContainer.cs b/src/Testcontainers.Couchbase/CouchbaseContainer.cs index 64bdbe8b9..926cde50a 100644 --- a/src/Testcontainers.Couchbase/CouchbaseContainer.cs +++ b/src/Testcontainers.Couchbase/CouchbaseContainer.cs @@ -14,8 +14,17 @@ public CouchbaseContainer(CouchbaseConfiguration configuration) : base(configuration) { _configuration = configuration; - Starting += (_, _) => Logger.LogInformation("Couchbase container is starting, performing configuration."); - Started += (_, _) => Logger.LogInformation("Couchbase container is ready! UI available at {Url}.", new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(CouchbaseBuilder.MgmtPort))); + Starting += (_, _) => + Logger.LogInformation("Couchbase container is starting, performing configuration."); + Started += (_, _) => + Logger.LogInformation( + "Couchbase container is ready! UI available at {Url}.", + new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(CouchbaseBuilder.MgmtPort) + ) + ); } /// @@ -29,6 +38,8 @@ public CouchbaseContainer(CouchbaseConfiguration configuration) /// The Couchbase connection string. public string GetConnectionString() { - return new UriBuilder("couchbase", Hostname, GetMappedPublicPort(CouchbaseBuilder.KvPort)).Uri.Authority; + return new UriBuilder("couchbase", Hostname, GetMappedPublicPort(CouchbaseBuilder.KvPort)) + .Uri + .Authority; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Couchbase/CouchbaseService.cs b/src/Testcontainers.Couchbase/CouchbaseService.cs index a90f38789..f984153b0 100644 --- a/src/Testcontainers.Couchbase/CouchbaseService.cs +++ b/src/Testcontainers.Couchbase/CouchbaseService.cs @@ -60,4 +60,4 @@ private CouchbaseService(string identifier, ushort minimumQuotaMb) /// Gets a value indicating whether the service has a minimum quota or not. /// public bool HasQuota => MinimumQuotaMb > 0; -} \ No newline at end of file +} diff --git a/src/Testcontainers.Couchbase/Testcontainers.Couchbase.csproj b/src/Testcontainers.Couchbase/Testcontainers.Couchbase.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Couchbase/Testcontainers.Couchbase.csproj +++ b/src/Testcontainers.Couchbase/Testcontainers.Couchbase.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Couchbase/Usings.cs b/src/Testcontainers.Couchbase/Usings.cs index c4eeb83d8..94ef04b7c 100644 --- a/src/Testcontainers.Couchbase/Usings.cs +++ b/src/Testcontainers.Couchbase/Usings.cs @@ -11,4 +11,4 @@ global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; global using JetBrains.Annotations; -global using Microsoft.Extensions.Logging; \ No newline at end of file +global using Microsoft.Extensions.Logging; diff --git a/src/Testcontainers.Db2/Db2Builder.cs b/src/Testcontainers.Db2/Db2Builder.cs index 4731c9005..0ba86c1a0 100644 --- a/src/Testcontainers.Db2/Db2Builder.cs +++ b/src/Testcontainers.Db2/Db2Builder.cs @@ -55,7 +55,9 @@ private Db2Builder(Db2Configuration resourceConfiguration) /// A configured instance of . public override Db2Builder WithAcceptLicenseAgreement(bool acceptLicenseAgreement) { - var licenseAgreement = acceptLicenseAgreement ? AcceptLicenseAgreement : DeclineLicenseAgreement; + var licenseAgreement = acceptLicenseAgreement + ? AcceptLicenseAgreement + : DeclineLicenseAgreement; return WithEnvironment(AcceptLicenseAgreementEnvVar, licenseAgreement); } @@ -102,31 +104,42 @@ public override Db2Container Build() } /// - protected override Db2Builder Init() => base.Init() - .WithImage(Db2Image) - .WithPortBinding(Db2Port, true) - .WithDatabase(DefaultDatabase) - .WithUsername(DefaultUsername) - .WithPassword(DefaultPassword) - .WithPrivileged(true) - .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("Setup has completed.")); + protected override Db2Builder Init() => + base.Init() + .WithImage(Db2Image) + .WithPortBinding(Db2Port, true) + .WithDatabase(DefaultDatabase) + .WithUsername(DefaultUsername) + .WithPassword(DefaultPassword) + .WithPrivileged(true) + .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("Setup has completed.")); /// protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Username, nameof(DockerResourceConfiguration.Username)) + _ = Guard + .Argument( + DockerResourceConfiguration.Username, + nameof(DockerResourceConfiguration.Username) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override Db2Builder Clone(IResourceConfiguration resourceConfiguration) + protected override Db2Builder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new Db2Configuration(resourceConfiguration)); } @@ -142,4 +155,4 @@ protected override Db2Builder Merge(Db2Configuration oldValue, Db2Configuration { return new Db2Builder(new Db2Configuration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Db2/Db2Configuration.cs b/src/Testcontainers.Db2/Db2Configuration.cs index 97208985b..634eaeb16 100644 --- a/src/Testcontainers.Db2/Db2Configuration.cs +++ b/src/Testcontainers.Db2/Db2Configuration.cs @@ -10,10 +10,7 @@ public sealed class Db2Configuration : ContainerConfiguration /// The Db2 database. /// The Db2 username. /// The Db2 password. - public Db2Configuration( - string database = null, - string username = null, - string password = null) + public Db2Configuration(string database = null, string username = null, string password = null) { Database = database; Username = username; @@ -77,4 +74,4 @@ public Db2Configuration(Db2Configuration oldValue, Db2Configuration newValue) /// Gets the Db2 password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Db2/Db2Container.cs b/src/Testcontainers.Db2/Db2Container.cs index 660a388d1..fb871864f 100644 --- a/src/Testcontainers.Db2/Db2Container.cs +++ b/src/Testcontainers.Db2/Db2Container.cs @@ -6,7 +6,8 @@ public sealed class Db2Container : DockerContainer, IDatabaseContainer { private readonly Db2Configuration _configuration; - public Db2Container(Db2Configuration configuration) : base(configuration) + public Db2Container(Db2Configuration configuration) + : base(configuration) { _configuration = configuration; } @@ -22,7 +23,10 @@ public string GetConnectionString() properties.Add("Database", _configuration.Database); properties.Add("UID", _configuration.Username); properties.Add("PWD", _configuration.Password); - return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value))); + return string.Join( + ";", + properties.Select(property => string.Join("=", property.Key, property.Value)) + ); } /// @@ -31,18 +35,37 @@ public string GetConnectionString() /// The content of the SQL script to execute. /// Cancellation token. /// Task that completes when the SQL script has been executed. - public async Task ExecScriptAsync(string scriptContent, CancellationToken ct = default) + public async Task ExecScriptAsync( + string scriptContent, + CancellationToken ct = default + ) { const string db2ShellCommandFormat = "su - {1} -c \"db2 connect to {0} && db2 -tvf '{2}'\""; - var scriptFilePath = string.Join("/", string.Empty, "tmp", Guid.NewGuid().ToString("D"), Path.GetRandomFileName()); + var scriptFilePath = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid().ToString("D"), + Path.GetRandomFileName() + ); - var db2ShellCommand = string.Format(db2ShellCommandFormat, _configuration.Database, _configuration.Username, scriptFilePath); + var db2ShellCommand = string.Format( + db2ShellCommandFormat, + _configuration.Database, + _configuration.Username, + scriptFilePath + ); - await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.FileMode644, ct) + await CopyAsync( + Encoding.Default.GetBytes(scriptContent), + scriptFilePath, + Unix.FileMode644, + ct + ) .ConfigureAwait(false); - return await ExecAsync(new[] { "/bin/sh", "-c", db2ShellCommand}, ct) + return await ExecAsync(new[] { "/bin/sh", "-c", db2ShellCommand }, ct) .ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Db2/Testcontainers.Db2.csproj b/src/Testcontainers.Db2/Testcontainers.Db2.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Db2/Testcontainers.Db2.csproj +++ b/src/Testcontainers.Db2/Testcontainers.Db2.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Db2/Usings.cs b/src/Testcontainers.Db2/Usings.cs index e2b02a51e..3481268bc 100644 --- a/src/Testcontainers.Db2/Usings.cs +++ b/src/Testcontainers.Db2/Usings.cs @@ -10,4 +10,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.DynamoDb/DynamoDbBuilder.cs b/src/Testcontainers.DynamoDb/DynamoDbBuilder.cs index cfd22579f..7e5c29d9e 100644 --- a/src/Testcontainers.DynamoDb/DynamoDbBuilder.cs +++ b/src/Testcontainers.DynamoDb/DynamoDbBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.DynamoDb; /// [PublicAPI] -public sealed class DynamoDbBuilder : ContainerBuilder +public sealed class DynamoDbBuilder + : ContainerBuilder { public const string DynamoDbImage = "amazon/dynamodb-local:1.21.0"; @@ -43,12 +44,21 @@ protected override DynamoDbBuilder Init() return base.Init() .WithImage(DynamoDbImage) .WithPortBinding(DynamoDbPort, true) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPath("/").ForPort(DynamoDbPort).ForStatusCode(HttpStatusCode.BadRequest))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request + .ForPath("/") + .ForPort(DynamoDbPort) + .ForStatusCode(HttpStatusCode.BadRequest) + ) + ); } /// - protected override DynamoDbBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override DynamoDbBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new DynamoDbConfiguration(resourceConfiguration)); } @@ -60,8 +70,11 @@ protected override DynamoDbBuilder Clone(IContainerConfiguration resourceConfigu } /// - protected override DynamoDbBuilder Merge(DynamoDbConfiguration oldValue, DynamoDbConfiguration newValue) + protected override DynamoDbBuilder Merge( + DynamoDbConfiguration oldValue, + DynamoDbConfiguration newValue + ) { return new DynamoDbBuilder(new DynamoDbConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.DynamoDb/DynamoDbConfiguration.cs b/src/Testcontainers.DynamoDb/DynamoDbConfiguration.cs index ecd7e0aa9..ca3b35cd7 100644 --- a/src/Testcontainers.DynamoDb/DynamoDbConfiguration.cs +++ b/src/Testcontainers.DynamoDb/DynamoDbConfiguration.cs @@ -7,15 +7,15 @@ public sealed class DynamoDbConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public DynamoDbConfiguration() - { - } + public DynamoDbConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public DynamoDbConfiguration(IResourceConfiguration resourceConfiguration) + public DynamoDbConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public DynamoDbConfiguration(DynamoDbConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public DynamoDbConfiguration(DynamoDbConfiguration oldValue, DynamoDbConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.DynamoDb/DynamoDbContainer.cs b/src/Testcontainers.DynamoDb/DynamoDbContainer.cs index dfd8c4b83..0d16421e0 100644 --- a/src/Testcontainers.DynamoDb/DynamoDbContainer.cs +++ b/src/Testcontainers.DynamoDb/DynamoDbContainer.cs @@ -9,9 +9,7 @@ public sealed class DynamoDbContainer : DockerContainer /// /// The container configuration. public DynamoDbContainer(DynamoDbConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the DynamoDb connection string. @@ -19,6 +17,10 @@ public DynamoDbContainer(DynamoDbConfiguration configuration) /// The DynamoDb connection string. public string GetConnectionString() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(DynamoDbBuilder.DynamoDbPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(DynamoDbBuilder.DynamoDbPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.DynamoDb/Testcontainers.DynamoDb.csproj b/src/Testcontainers.DynamoDb/Testcontainers.DynamoDb.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.DynamoDb/Testcontainers.DynamoDb.csproj +++ b/src/Testcontainers.DynamoDb/Testcontainers.DynamoDb.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.DynamoDb/Usings.cs b/src/Testcontainers.DynamoDb/Usings.cs index 418bc08bd..b82970902 100644 --- a/src/Testcontainers.DynamoDb/Usings.cs +++ b/src/Testcontainers.DynamoDb/Usings.cs @@ -4,4 +4,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Elasticsearch/ElasticsearchBuilder.cs b/src/Testcontainers.Elasticsearch/ElasticsearchBuilder.cs index 39c78bf50..23d6eff89 100644 --- a/src/Testcontainers.Elasticsearch/ElasticsearchBuilder.cs +++ b/src/Testcontainers.Elasticsearch/ElasticsearchBuilder.cs @@ -2,13 +2,17 @@ namespace Testcontainers.Elasticsearch; /// [PublicAPI] -public sealed class ElasticsearchBuilder : ContainerBuilder +public sealed class ElasticsearchBuilder + : ContainerBuilder { - public const string ElasticsearchVmOptionsDirectoryPath = "/usr/share/elasticsearch/config/jvm.options.d/"; + public const string ElasticsearchVmOptionsDirectoryPath = + "/usr/share/elasticsearch/config/jvm.options.d/"; - public const string ElasticsearchDefaultMemoryVmOptionFileName = "elasticsearch-default-memory-vm.options"; + public const string ElasticsearchDefaultMemoryVmOptionFileName = + "elasticsearch-default-memory-vm.options"; - public const string ElasticsearchDefaultMemoryVmOptionFilePath = ElasticsearchVmOptionsDirectoryPath + ElasticsearchDefaultMemoryVmOptionFileName; + public const string ElasticsearchDefaultMemoryVmOptionFilePath = + ElasticsearchVmOptionsDirectoryPath + ElasticsearchDefaultMemoryVmOptionFileName; public const string ElasticsearchImage = "elasticsearch:8.6.1"; @@ -20,7 +24,9 @@ public sealed class ElasticsearchBuilder : ContainerBuilder /// Initializes a new instance of the class. @@ -51,7 +57,10 @@ private ElasticsearchBuilder(ElasticsearchConfiguration resourceConfiguration) /// A configured instance of . public ElasticsearchBuilder WithPassword(string password) { - return Merge(DockerResourceConfiguration, new ElasticsearchConfiguration(password: password)) + return Merge( + DockerResourceConfiguration, + new ElasticsearchConfiguration(password: password) + ) .WithEnvironment("ELASTIC_PASSWORD", password); } @@ -82,25 +91,40 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override ElasticsearchBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override ElasticsearchBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new ElasticsearchConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new ElasticsearchConfiguration(resourceConfiguration) + ); } /// protected override ElasticsearchBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new ElasticsearchConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new ElasticsearchConfiguration(resourceConfiguration) + ); } /// - protected override ElasticsearchBuilder Merge(ElasticsearchConfiguration oldValue, ElasticsearchConfiguration newValue) + protected override ElasticsearchBuilder Merge( + ElasticsearchConfiguration oldValue, + ElasticsearchConfiguration newValue + ) { return new ElasticsearchBuilder(new ElasticsearchConfiguration(oldValue, newValue)); } @@ -115,21 +139,29 @@ protected override ElasticsearchBuilder Merge(ElasticsearchConfiguration oldValu /// A configured instance of . private ElasticsearchBuilder WithUsername(string username) { - return Merge(DockerResourceConfiguration, new ElasticsearchConfiguration(username: username)); + return Merge( + DockerResourceConfiguration, + new ElasticsearchConfiguration(username: username) + ); } /// private sealed class WaitUntil : IWaitUntil { - private static readonly IEnumerable Pattern = new[] { "\"message\":\"started", "\"message\": \"started\"" }; + private static readonly IEnumerable Pattern = new[] + { + "\"message\":\"started", + "\"message\": \"started\"", + }; /// public async Task UntilAsync(IContainer container) { - var (stdout, _) = await container.GetLogsAsync(since: container.StoppedTime, timestampsEnabled: false) + var (stdout, _) = await container + .GetLogsAsync(since: container.StoppedTime, timestampsEnabled: false) .ConfigureAwait(false); return Pattern.Any(stdout.Contains); } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Elasticsearch/ElasticsearchConfiguration.cs b/src/Testcontainers.Elasticsearch/ElasticsearchConfiguration.cs index 9330ddebd..ae2a12375 100644 --- a/src/Testcontainers.Elasticsearch/ElasticsearchConfiguration.cs +++ b/src/Testcontainers.Elasticsearch/ElasticsearchConfiguration.cs @@ -9,9 +9,7 @@ public sealed class ElasticsearchConfiguration : ContainerConfiguration /// /// The Elasticsearch username. /// The Elasticsearch password. - public ElasticsearchConfiguration( - string username = null, - string password = null) + public ElasticsearchConfiguration(string username = null, string password = null) { Username = username; Password = password; @@ -21,7 +19,9 @@ public ElasticsearchConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public ElasticsearchConfiguration(IResourceConfiguration resourceConfiguration) + public ElasticsearchConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -52,7 +52,10 @@ public ElasticsearchConfiguration(ElasticsearchConfiguration resourceConfigurati /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public ElasticsearchConfiguration(ElasticsearchConfiguration oldValue, ElasticsearchConfiguration newValue) + public ElasticsearchConfiguration( + ElasticsearchConfiguration oldValue, + ElasticsearchConfiguration newValue + ) : base(oldValue, newValue) { Username = BuildConfiguration.Combine(oldValue.Username, newValue.Username); @@ -68,4 +71,4 @@ public ElasticsearchConfiguration(ElasticsearchConfiguration oldValue, Elasticse /// Gets the Elasticsearch password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Elasticsearch/ElasticsearchContainer.cs b/src/Testcontainers.Elasticsearch/ElasticsearchContainer.cs index d924b1866..538ff2170 100644 --- a/src/Testcontainers.Elasticsearch/ElasticsearchContainer.cs +++ b/src/Testcontainers.Elasticsearch/ElasticsearchContainer.cs @@ -28,23 +28,31 @@ public ElasticsearchContainer(ElasticsearchConfiguration configuration) /// The Elasticsearch connection string. public string GetConnectionString() { - var hasSecurityEnabled = _configuration.Environments - .TryGetValue("xpack.security.enabled", out var securityEnabled); + var hasSecurityEnabled = _configuration.Environments.TryGetValue( + "xpack.security.enabled", + out var securityEnabled + ); - var hasHttpSslEnabled = _configuration.Environments - .TryGetValue("xpack.security.http.ssl.enabled", out var httpSslEnabled); + var hasHttpSslEnabled = _configuration.Environments.TryGetValue( + "xpack.security.http.ssl.enabled", + out var httpSslEnabled + ); var httpsDisabled = - hasSecurityEnabled && - hasHttpSslEnabled && - "false".Equals(securityEnabled, StringComparison.OrdinalIgnoreCase) && - "false".Equals(httpSslEnabled, StringComparison.OrdinalIgnoreCase); + hasSecurityEnabled + && hasHttpSslEnabled + && "false".Equals(securityEnabled, StringComparison.OrdinalIgnoreCase) + && "false".Equals(httpSslEnabled, StringComparison.OrdinalIgnoreCase); var scheme = httpsDisabled ? Uri.UriSchemeHttp : Uri.UriSchemeHttps; - var endpoint = new UriBuilder(scheme, Hostname, GetMappedPublicPort(ElasticsearchBuilder.ElasticsearchHttpsPort)); + var endpoint = new UriBuilder( + scheme, + Hostname, + GetMappedPublicPort(ElasticsearchBuilder.ElasticsearchHttpsPort) + ); endpoint.UserName = _configuration.Username; endpoint.Password = _configuration.Password; return endpoint.ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Elasticsearch/Testcontainers.Elasticsearch.csproj b/src/Testcontainers.Elasticsearch/Testcontainers.Elasticsearch.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Elasticsearch/Testcontainers.Elasticsearch.csproj +++ b/src/Testcontainers.Elasticsearch/Testcontainers.Elasticsearch.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Elasticsearch/Usings.cs b/src/Testcontainers.Elasticsearch/Usings.cs index 292302742..79361176a 100644 --- a/src/Testcontainers.Elasticsearch/Usings.cs +++ b/src/Testcontainers.Elasticsearch/Usings.cs @@ -8,4 +8,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.EventHubs/EventHubsBuilder.cs b/src/Testcontainers.EventHubs/EventHubsBuilder.cs index 87b207531..3a05655e1 100644 --- a/src/Testcontainers.EventHubs/EventHubsBuilder.cs +++ b/src/Testcontainers.EventHubs/EventHubsBuilder.cs @@ -2,13 +2,15 @@ namespace Testcontainers.EventHubs; /// [PublicAPI] -public sealed class EventHubsBuilder : ContainerBuilder +public sealed class EventHubsBuilder + : ContainerBuilder { public const string EventHubsNetworkAlias = "eventhubs-container"; public const string AzuriteNetworkAlias = "azurite-container"; - public const string EventHubsImage = "mcr.microsoft.com/azure-messaging/eventhubs-emulator:latest"; + public const string EventHubsImage = + "mcr.microsoft.com/azure-messaging/eventhubs-emulator:latest"; public const ushort EventHubsPort = 5672; @@ -55,7 +57,9 @@ private EventHubsBuilder(EventHubsConfiguration resourceConfiguration) /// A configured instance of . public override EventHubsBuilder WithAcceptLicenseAgreement(bool acceptLicenseAgreement) { - var licenseAgreement = acceptLicenseAgreement ? AcceptLicenseAgreement : DeclineLicenseAgreement; + var licenseAgreement = acceptLicenseAgreement + ? AcceptLicenseAgreement + : DeclineLicenseAgreement; return WithEnvironment(AcceptLicenseAgreementEnvVar, licenseAgreement); } @@ -74,9 +78,13 @@ public override EventHubsBuilder WithAcceptLicenseAgreement(bool acceptLicenseAg public EventHubsBuilder WithAzuriteContainer( INetwork network, AzuriteContainer container, - string networkAlias) + string networkAlias + ) { - return Merge(DockerResourceConfiguration, new EventHubsConfiguration(azuriteContainer: container)) + return Merge( + DockerResourceConfiguration, + new EventHubsConfiguration(azuriteContainer: container) + ) .DependsOn(container) .WithNetwork(network) .WithNetworkAliases(EventHubsNetworkAlias) @@ -89,10 +97,15 @@ public EventHubsBuilder WithAzuriteContainer( /// /// The service configuration. /// A configured instance of . - public EventHubsBuilder WithConfigurationBuilder(EventHubsServiceConfiguration serviceConfiguration) + public EventHubsBuilder WithConfigurationBuilder( + EventHubsServiceConfiguration serviceConfiguration + ) { var resourceContent = Encoding.Default.GetBytes(serviceConfiguration.Build()); - return Merge(DockerResourceConfiguration, new EventHubsConfiguration(serviceConfiguration: serviceConfiguration)) + return Merge( + DockerResourceConfiguration, + new EventHubsConfiguration(serviceConfiguration: serviceConfiguration) + ) .WithResourceMapping(resourceContent, "Eventhubs_Emulator/ConfigFiles/Config.json"); } @@ -109,8 +122,7 @@ public override EventHubsContainer Build() // If the user has not provided an existing Azurite container instance, // we configure one. - var network = new NetworkBuilder() - .Build(); + var network = new NetworkBuilder().Build(); var container = new AzuriteBuilder() .WithNetwork(network) @@ -126,9 +138,19 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.ServiceConfiguration, nameof(DockerResourceConfiguration.ServiceConfiguration)) + _ = Guard + .Argument( + DockerResourceConfiguration.ServiceConfiguration, + nameof(DockerResourceConfiguration.ServiceConfiguration) + ) .NotNull() - .ThrowIf(argument => !argument.Value.Validate(), _ => throw new ArgumentException("The service configuration of the Azure Event Hubs Emulator is invalid.")); + .ThrowIf( + argument => !argument.Value.Validate(), + _ => + throw new ArgumentException( + "The service configuration of the Azure Event Hubs Emulator is invalid." + ) + ); } /// @@ -138,25 +160,40 @@ protected override EventHubsBuilder Init() .WithImage(EventHubsImage) .WithPortBinding(EventHubsPort, true) .WithPortBinding(EventHubsHttpPort, true) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPort(EventHubsHttpPort).ForPath("/health"))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request.ForPort(EventHubsHttpPort).ForPath("/health") + ) + ); } /// - protected override EventHubsBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override EventHubsBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new EventHubsConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new EventHubsConfiguration(resourceConfiguration) + ); } /// protected override EventHubsBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new EventHubsConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new EventHubsConfiguration(resourceConfiguration) + ); } /// - protected override EventHubsBuilder Merge(EventHubsConfiguration oldValue, EventHubsConfiguration newValue) + protected override EventHubsBuilder Merge( + EventHubsConfiguration oldValue, + EventHubsConfiguration newValue + ) { return new EventHubsBuilder(new EventHubsConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.EventHubs/EventHubsConfiguration.cs b/src/Testcontainers.EventHubs/EventHubsConfiguration.cs index 76c57ecbb..0ecf861dc 100644 --- a/src/Testcontainers.EventHubs/EventHubsConfiguration.cs +++ b/src/Testcontainers.EventHubs/EventHubsConfiguration.cs @@ -9,8 +9,10 @@ public sealed class EventHubsConfiguration : ContainerConfiguration /// /// The Azurite container. /// The service configuration. - public EventHubsConfiguration(AzuriteContainer azuriteContainer = null, - EventHubsServiceConfiguration serviceConfiguration = null) + public EventHubsConfiguration( + AzuriteContainer azuriteContainer = null, + EventHubsServiceConfiguration serviceConfiguration = null + ) { AzuriteContainer = azuriteContainer; ServiceConfiguration = serviceConfiguration; @@ -20,7 +22,9 @@ public EventHubsConfiguration(AzuriteContainer azuriteContainer = null, /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public EventHubsConfiguration(IResourceConfiguration resourceConfiguration) + public EventHubsConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -54,8 +58,14 @@ public EventHubsConfiguration(EventHubsConfiguration resourceConfiguration) public EventHubsConfiguration(EventHubsConfiguration oldValue, EventHubsConfiguration newValue) : base(oldValue, newValue) { - AzuriteContainer = BuildConfiguration.Combine(oldValue.AzuriteContainer, newValue.AzuriteContainer); - ServiceConfiguration = BuildConfiguration.Combine(oldValue.ServiceConfiguration, newValue.ServiceConfiguration); + AzuriteContainer = BuildConfiguration.Combine( + oldValue.AzuriteContainer, + newValue.AzuriteContainer + ); + ServiceConfiguration = BuildConfiguration.Combine( + oldValue.ServiceConfiguration, + newValue.ServiceConfiguration + ); } /// @@ -67,4 +77,4 @@ public EventHubsConfiguration(EventHubsConfiguration oldValue, EventHubsConfigur /// Gets the service configuration. /// public EventHubsServiceConfiguration ServiceConfiguration { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.EventHubs/EventHubsContainer.cs b/src/Testcontainers.EventHubs/EventHubsContainer.cs index 9b7259d73..9100cde46 100644 --- a/src/Testcontainers.EventHubs/EventHubsContainer.cs +++ b/src/Testcontainers.EventHubs/EventHubsContainer.cs @@ -9,9 +9,7 @@ public sealed class EventHubsContainer : DockerContainer /// /// The container configuration. public EventHubsContainer(EventHubsConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Event Hubs connection string. @@ -20,11 +18,21 @@ public EventHubsContainer(EventHubsConfiguration configuration) public string GetConnectionString() { var properties = new Dictionary(); - properties.Add("Endpoint", new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(EventHubsBuilder.EventHubsPort)).ToString()); + properties.Add( + "Endpoint", + new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(EventHubsBuilder.EventHubsPort) + ).ToString() + ); properties.Add("DefaultEndpointsProtocol", Uri.UriSchemeHttp); 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))); + return string.Join( + ";", + properties.Select(property => string.Join("=", property.Key, property.Value)) + ); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.EventHubs/EventHubsServiceConfiguration.cs b/src/Testcontainers.EventHubs/EventHubsServiceConfiguration.cs index 1a499f25d..20a27be66 100644 --- a/src/Testcontainers.EventHubs/EventHubsServiceConfiguration.cs +++ b/src/Testcontainers.EventHubs/EventHubsServiceConfiguration.cs @@ -7,7 +7,10 @@ public record RootConfiguration(UserConfig UserConfig) } [PublicAPI] -public record UserConfig(IReadOnlyCollection NamespaceConfig, LoggingConfig LoggingConfig) +public record UserConfig( + IReadOnlyCollection NamespaceConfig, + LoggingConfig LoggingConfig +) { public IReadOnlyCollection NamespaceConfig { get; } = NamespaceConfig; @@ -25,7 +28,11 @@ public record NamespaceConfig(string Type, string Name, IReadOnlyCollection ConsumerGroups) +public record Entity( + string Name, + int PartitionCount, + IReadOnlyCollection ConsumerGroups +) { public string Name { get; } = Name; @@ -62,33 +69,64 @@ public static EventHubsServiceConfiguration Create() return new EventHubsServiceConfiguration(namespaceConfig); } - public EventHubsServiceConfiguration WithEntity(string name, int partitionCount, params string[] consumerGroupNames) + public EventHubsServiceConfiguration WithEntity( + string name, + int partitionCount, + params string[] consumerGroupNames + ) { // Filter out the consumer group name `$default` because the `$default` group // is created automatically by the container image. - var validConsumerGroupNames = consumerGroupNames.Where(consumerGroupName => !"$Default".Equals(consumerGroupName, StringComparison.OrdinalIgnoreCase)).ToList(); - return WithEntity(name, partitionCount, new ReadOnlyCollection(validConsumerGroupNames)); + var validConsumerGroupNames = consumerGroupNames + .Where(consumerGroupName => + !"$Default".Equals(consumerGroupName, StringComparison.OrdinalIgnoreCase) + ) + .ToList(); + return WithEntity( + name, + partitionCount, + new ReadOnlyCollection(validConsumerGroupNames) + ); } - public EventHubsServiceConfiguration WithEntity(string name, int partitionCount, IEnumerable consumerGroupNames) + public EventHubsServiceConfiguration WithEntity( + string name, + int partitionCount, + IEnumerable consumerGroupNames + ) { - var consumerGroups = new ReadOnlyCollection(consumerGroupNames.Select(consumerGroupName => new ConsumerGroup(consumerGroupName)).ToList()); + var consumerGroups = new ReadOnlyCollection( + consumerGroupNames + .Select(consumerGroupName => new ConsumerGroup(consumerGroupName)) + .ToList() + ); var entity = new Entity(name, partitionCount, consumerGroups); - var entities = new ReadOnlyCollection(_namespaceConfig.Entities.Append(entity).ToList()); - return new EventHubsServiceConfiguration(new NamespaceConfig(_namespaceConfig.Type, _namespaceConfig.Name, entities)); + var entities = new ReadOnlyCollection( + _namespaceConfig.Entities.Append(entity).ToList() + ); + return new EventHubsServiceConfiguration( + new NamespaceConfig(_namespaceConfig.Type, _namespaceConfig.Name, entities) + ); } public bool Validate() { // The emulator provides the usage quotas as described at: // https://learn.microsoft.com/en-us/azure/event-hubs/overview-emulator#usage-quotas. - Predicate isValidEntity = entity => entity.PartitionCount > 0 && entity.PartitionCount <= 32 && entity.ConsumerGroups.Count <= 20; - return _namespaceConfig.Entities.Count > 0 && _namespaceConfig.Entities.Count <= 10 && _namespaceConfig.Entities.All(entity => isValidEntity(entity)); + Predicate isValidEntity = entity => + entity.PartitionCount > 0 + && entity.PartitionCount <= 32 + && entity.ConsumerGroups.Count <= 20; + return _namespaceConfig.Entities.Count > 0 + && _namespaceConfig.Entities.Count <= 10 + && _namespaceConfig.Entities.All(entity => isValidEntity(entity)); } public string Build() { - var rootConfiguration = new RootConfiguration(new UserConfig([_namespaceConfig], new LoggingConfig("file"))); + var rootConfiguration = new RootConfiguration( + new UserConfig([_namespaceConfig], new LoggingConfig("file")) + ); return JsonSerializer.Serialize(rootConfiguration); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.EventHubs/Testcontainers.EventHubs.csproj b/src/Testcontainers.EventHubs/Testcontainers.EventHubs.csproj index 643fdade3..355bd57b2 100644 --- a/src/Testcontainers.EventHubs/Testcontainers.EventHubs.csproj +++ b/src/Testcontainers.EventHubs/Testcontainers.EventHubs.csproj @@ -1,13 +1,17 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + + diff --git a/src/Testcontainers.EventHubs/Usings.cs b/src/Testcontainers.EventHubs/Usings.cs index aac442571..1d2b6d437 100644 --- a/src/Testcontainers.EventHubs/Usings.cs +++ b/src/Testcontainers.EventHubs/Usings.cs @@ -11,4 +11,4 @@ global using DotNet.Testcontainers.Containers; global using DotNet.Testcontainers.Networks; global using JetBrains.Annotations; -global using Testcontainers.Azurite; \ No newline at end of file +global using Testcontainers.Azurite; diff --git a/src/Testcontainers.EventStoreDb/EventStoreDbBuilder.cs b/src/Testcontainers.EventStoreDb/EventStoreDbBuilder.cs index 6e73a3886..f876a8564 100644 --- a/src/Testcontainers.EventStoreDb/EventStoreDbBuilder.cs +++ b/src/Testcontainers.EventStoreDb/EventStoreDbBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.EventStoreDb; /// [PublicAPI] -public sealed class EventStoreDbBuilder : ContainerBuilder +public sealed class EventStoreDbBuilder + : ContainerBuilder { public const string EventStoreDbImage = "eventstore/eventstore:22.10.1-buster-slim"; @@ -50,20 +51,31 @@ protected override EventStoreDbBuilder Init() } /// - protected override EventStoreDbBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override EventStoreDbBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new EventStoreDbConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new EventStoreDbConfiguration(resourceConfiguration) + ); } /// protected override EventStoreDbBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new EventStoreDbConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new EventStoreDbConfiguration(resourceConfiguration) + ); } /// - protected override EventStoreDbBuilder Merge(EventStoreDbConfiguration oldValue, EventStoreDbConfiguration newValue) + protected override EventStoreDbBuilder Merge( + EventStoreDbConfiguration oldValue, + EventStoreDbConfiguration newValue + ) { return new EventStoreDbBuilder(new EventStoreDbConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.EventStoreDb/EventStoreDbConfiguration.cs b/src/Testcontainers.EventStoreDb/EventStoreDbConfiguration.cs index c19cd06ba..3dd2e357c 100644 --- a/src/Testcontainers.EventStoreDb/EventStoreDbConfiguration.cs +++ b/src/Testcontainers.EventStoreDb/EventStoreDbConfiguration.cs @@ -7,15 +7,15 @@ public sealed class EventStoreDbConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public EventStoreDbConfiguration() - { - } + public EventStoreDbConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public EventStoreDbConfiguration(IResourceConfiguration resourceConfiguration) + public EventStoreDbConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -46,8 +46,9 @@ public EventStoreDbConfiguration(EventStoreDbConfiguration resourceConfiguration /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public EventStoreDbConfiguration(EventStoreDbConfiguration oldValue, EventStoreDbConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + public EventStoreDbConfiguration( + EventStoreDbConfiguration oldValue, + EventStoreDbConfiguration newValue + ) + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.EventStoreDb/EventStoreDbContainer.cs b/src/Testcontainers.EventStoreDb/EventStoreDbContainer.cs index 6d0ddc347..1ddaa7b92 100644 --- a/src/Testcontainers.EventStoreDb/EventStoreDbContainer.cs +++ b/src/Testcontainers.EventStoreDb/EventStoreDbContainer.cs @@ -9,9 +9,7 @@ public sealed class EventStoreDbContainer : DockerContainer /// /// The container configuration. public EventStoreDbContainer(EventStoreDbConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the EventStoreDb connection string. @@ -19,8 +17,12 @@ public EventStoreDbContainer(EventStoreDbConfiguration configuration) /// The EventStoreDb connection string. public string GetConnectionString() { - var endpoint = new UriBuilder("esdb", Hostname, GetMappedPublicPort(EventStoreDbBuilder.EventStoreDbPort)); + var endpoint = new UriBuilder( + "esdb", + Hostname, + GetMappedPublicPort(EventStoreDbBuilder.EventStoreDbPort) + ); endpoint.Query = "tls=false"; return endpoint.ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.EventStoreDb/Testcontainers.EventStoreDb.csproj b/src/Testcontainers.EventStoreDb/Testcontainers.EventStoreDb.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.EventStoreDb/Testcontainers.EventStoreDb.csproj +++ b/src/Testcontainers.EventStoreDb/Testcontainers.EventStoreDb.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.EventStoreDb/Usings.cs b/src/Testcontainers.EventStoreDb/Usings.cs index 79fd3af9b..b31708db0 100644 --- a/src/Testcontainers.EventStoreDb/Usings.cs +++ b/src/Testcontainers.EventStoreDb/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.FakeGcsServer/FakeGcsServerBuilder.cs b/src/Testcontainers.FakeGcsServer/FakeGcsServerBuilder.cs index d253da5fa..1707ec82a 100644 --- a/src/Testcontainers.FakeGcsServer/FakeGcsServerBuilder.cs +++ b/src/Testcontainers.FakeGcsServer/FakeGcsServerBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.FakeGcsServer; /// [PublicAPI] -public sealed class FakeGcsServerBuilder : ContainerBuilder +public sealed class FakeGcsServerBuilder + : ContainerBuilder { public const string FakeGcsServerImage = "fsouza/fake-gcs-server:1.47"; @@ -46,40 +47,72 @@ protected override FakeGcsServerBuilder Init() .WithImage(FakeGcsServerImage) .WithPortBinding(FakeGcsServerPort, true) .WithEntrypoint("/bin/sh", "-c") - .WithCommand("while [ ! -f " + StartupScriptFilePath + " ]; do sleep 0.1; done; " + StartupScriptFilePath) + .WithCommand( + "while [ ! -f " + + StartupScriptFilePath + + " ]; do sleep 0.1; done; " + + StartupScriptFilePath + ) .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("server started")) - .WithStartupCallback((container, ct) => - { - const char lf = '\n'; - var startupScript = new StringBuilder(); - startupScript.Append("#!/bin/sh"); - startupScript.Append(lf); - startupScript.Append("fake-gcs-server "); - startupScript.Append("-backend memory "); - startupScript.Append("-scheme http "); - // If we do not remove the trailing slash, uploading an object will result in an - // error: HttpStatusCode.NotFound. The HTTP request appears incorrect. The - // container logs indicate the presence of an extra slash: `PUT //upload/storage/v1`. - startupScript.Append("-external-url " + new UriBuilder(Uri.UriSchemeHttp, container.Hostname, container.GetMappedPublicPort(FakeGcsServerPort)).ToString().Trim('/')); - return container.CopyAsync(Encoding.Default.GetBytes(startupScript.ToString()), StartupScriptFilePath, Unix.FileMode755, ct); - }); + .WithStartupCallback( + (container, ct) => + { + const char lf = '\n'; + var startupScript = new StringBuilder(); + startupScript.Append("#!/bin/sh"); + startupScript.Append(lf); + startupScript.Append("fake-gcs-server "); + startupScript.Append("-backend memory "); + startupScript.Append("-scheme http "); + // If we do not remove the trailing slash, uploading an object will result in an + // error: HttpStatusCode.NotFound. The HTTP request appears incorrect. The + // container logs indicate the presence of an extra slash: `PUT //upload/storage/v1`. + startupScript.Append( + "-external-url " + + new UriBuilder( + Uri.UriSchemeHttp, + container.Hostname, + container.GetMappedPublicPort(FakeGcsServerPort) + ) + .ToString() + .Trim('/') + ); + return container.CopyAsync( + Encoding.Default.GetBytes(startupScript.ToString()), + StartupScriptFilePath, + Unix.FileMode755, + ct + ); + } + ); } /// - protected override FakeGcsServerBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override FakeGcsServerBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new FakeGcsServerConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new FakeGcsServerConfiguration(resourceConfiguration) + ); } /// protected override FakeGcsServerBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new FakeGcsServerConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new FakeGcsServerConfiguration(resourceConfiguration) + ); } /// - protected override FakeGcsServerBuilder Merge(FakeGcsServerConfiguration oldValue, FakeGcsServerConfiguration newValue) + protected override FakeGcsServerBuilder Merge( + FakeGcsServerConfiguration oldValue, + FakeGcsServerConfiguration newValue + ) { return new FakeGcsServerBuilder(new FakeGcsServerConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.FakeGcsServer/FakeGcsServerConfiguration.cs b/src/Testcontainers.FakeGcsServer/FakeGcsServerConfiguration.cs index b9c4ffe16..718e48ec6 100644 --- a/src/Testcontainers.FakeGcsServer/FakeGcsServerConfiguration.cs +++ b/src/Testcontainers.FakeGcsServer/FakeGcsServerConfiguration.cs @@ -7,15 +7,15 @@ public sealed class FakeGcsServerConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public FakeGcsServerConfiguration() - { - } + public FakeGcsServerConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public FakeGcsServerConfiguration(IResourceConfiguration resourceConfiguration) + public FakeGcsServerConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -46,8 +46,9 @@ public FakeGcsServerConfiguration(FakeGcsServerConfiguration resourceConfigurati /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public FakeGcsServerConfiguration(FakeGcsServerConfiguration oldValue, FakeGcsServerConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + public FakeGcsServerConfiguration( + FakeGcsServerConfiguration oldValue, + FakeGcsServerConfiguration newValue + ) + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.FakeGcsServer/FakeGcsServerContainer.cs b/src/Testcontainers.FakeGcsServer/FakeGcsServerContainer.cs index 8eb31f3ca..b3c9e0c79 100644 --- a/src/Testcontainers.FakeGcsServer/FakeGcsServerContainer.cs +++ b/src/Testcontainers.FakeGcsServer/FakeGcsServerContainer.cs @@ -9,9 +9,7 @@ public sealed class FakeGcsServerContainer : DockerContainer /// /// The container configuration. public FakeGcsServerContainer(FakeGcsServerConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the FakeGcsServer connection string. @@ -19,6 +17,11 @@ public FakeGcsServerContainer(FakeGcsServerConfiguration configuration) /// The FakeGcsServer connection string. public string GetConnectionString() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(FakeGcsServerBuilder.FakeGcsServerPort), "/storage/v1/").ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(FakeGcsServerBuilder.FakeGcsServerPort), + "/storage/v1/" + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.FakeGcsServer/Testcontainers.FakeGcsServer.csproj b/src/Testcontainers.FakeGcsServer/Testcontainers.FakeGcsServer.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.FakeGcsServer/Testcontainers.FakeGcsServer.csproj +++ b/src/Testcontainers.FakeGcsServer/Testcontainers.FakeGcsServer.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.FakeGcsServer/Usings.cs b/src/Testcontainers.FakeGcsServer/Usings.cs index 4ee39f0be..1734e5e13 100644 --- a/src/Testcontainers.FakeGcsServer/Usings.cs +++ b/src/Testcontainers.FakeGcsServer/Usings.cs @@ -4,4 +4,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.FirebirdSql/FirebirdSqlBuilder.cs b/src/Testcontainers.FirebirdSql/FirebirdSqlBuilder.cs index fb1f42795..945dd9cb2 100644 --- a/src/Testcontainers.FirebirdSql/FirebirdSqlBuilder.cs +++ b/src/Testcontainers.FirebirdSql/FirebirdSqlBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.FirebirdSql; /// [PublicAPI] -public sealed class FirebirdSqlBuilder : ContainerBuilder +public sealed class FirebirdSqlBuilder + : ContainerBuilder { public const string FirebirdSqlImage = "jacobalberty/firebird:v4.0"; @@ -59,7 +60,12 @@ public FirebirdSqlBuilder WithDatabase(string database) public FirebirdSqlBuilder WithUsername(string username) { return Merge(DockerResourceConfiguration, new FirebirdSqlConfiguration(username: username)) - .WithEnvironment("FIREBIRD_USER", "sysdba".Equals(username, StringComparison.OrdinalIgnoreCase) ? string.Empty : username); + .WithEnvironment( + "FIREBIRD_USER", + "sysdba".Equals(username, StringComparison.OrdinalIgnoreCase) + ? string.Empty + : username + ); } /// @@ -90,7 +96,10 @@ protected override FirebirdSqlBuilder Init() .WithDatabase(DefaultDatabase) .WithUsername(DefaultUsername) .WithPassword(DefaultPassword) - .WithResourceMapping(Encoding.Default.GetBytes(TestQueryString), "/home/firebird_check.sql") + .WithResourceMapping( + Encoding.Default.GetBytes(TestQueryString), + "/home/firebird_check.sql" + ) .WithWaitStrategy(Wait.ForUnixContainer().UntilContainerIsHealthy()); } @@ -99,26 +108,41 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override FirebirdSqlBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override FirebirdSqlBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new FirebirdSqlConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new FirebirdSqlConfiguration(resourceConfiguration) + ); } /// protected override FirebirdSqlBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new FirebirdSqlConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new FirebirdSqlConfiguration(resourceConfiguration) + ); } /// - protected override FirebirdSqlBuilder Merge(FirebirdSqlConfiguration oldValue, FirebirdSqlConfiguration newValue) + protected override FirebirdSqlBuilder Merge( + FirebirdSqlConfiguration oldValue, + FirebirdSqlConfiguration newValue + ) { return new FirebirdSqlBuilder(new FirebirdSqlConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.FirebirdSql/FirebirdSqlConfiguration.cs b/src/Testcontainers.FirebirdSql/FirebirdSqlConfiguration.cs index c01064efc..ddfad7726 100644 --- a/src/Testcontainers.FirebirdSql/FirebirdSqlConfiguration.cs +++ b/src/Testcontainers.FirebirdSql/FirebirdSqlConfiguration.cs @@ -15,7 +15,8 @@ public sealed class FirebirdSqlConfiguration : ContainerConfiguration public FirebirdSqlConfiguration( string database = null, string username = null, - string password = null) + string password = null + ) { _database = database; Username = username; @@ -26,7 +27,9 @@ public FirebirdSqlConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public FirebirdSqlConfiguration(IResourceConfiguration resourceConfiguration) + public FirebirdSqlConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -57,7 +60,10 @@ public FirebirdSqlConfiguration(FirebirdSqlConfiguration resourceConfiguration) /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public FirebirdSqlConfiguration(FirebirdSqlConfiguration oldValue, FirebirdSqlConfiguration newValue) + public FirebirdSqlConfiguration( + FirebirdSqlConfiguration oldValue, + FirebirdSqlConfiguration newValue + ) : base(oldValue, newValue) { _database = BuildConfiguration.Combine(oldValue._database, newValue._database); @@ -68,7 +74,10 @@ public FirebirdSqlConfiguration(FirebirdSqlConfiguration oldValue, FirebirdSqlCo /// /// Gets the FirebirdSql database. /// - public string Database => Image.Tag != null && (Image.Tag.StartsWith("2.5") || Image.Tag.StartsWith("v2.5")) ? string.Join("/", "/firebird/data", _database) : _database; + public string Database => + Image.Tag != null && (Image.Tag.StartsWith("2.5") || Image.Tag.StartsWith("v2.5")) + ? string.Join("/", "/firebird/data", _database) + : _database; /// /// Gets the FirebirdSql username. @@ -79,4 +88,4 @@ public FirebirdSqlConfiguration(FirebirdSqlConfiguration oldValue, FirebirdSqlCo /// Gets the FirebirdSql password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.FirebirdSql/FirebirdSqlContainer.cs b/src/Testcontainers.FirebirdSql/FirebirdSqlContainer.cs index 0c5538fe0..781804206 100644 --- a/src/Testcontainers.FirebirdSql/FirebirdSqlContainer.cs +++ b/src/Testcontainers.FirebirdSql/FirebirdSqlContainer.cs @@ -28,7 +28,10 @@ public string GetConnectionString() properties.Add("Database", _configuration.Database); properties.Add("User", _configuration.Username); properties.Add("Password", _configuration.Password); - return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value))); + return string.Join( + ";", + properties.Select(property => string.Join("=", property.Key, property.Value)) + ); } /// @@ -37,14 +40,41 @@ public string GetConnectionString() /// The content of the SQL script to execute. /// Cancellation token. /// Task that completes when the SQL script has been executed. - public async Task ExecScriptAsync(string scriptContent, CancellationToken ct = default) + public async Task ExecScriptAsync( + string scriptContent, + CancellationToken ct = default + ) { - var scriptFilePath = string.Join("/", string.Empty, "tmp", Guid.NewGuid().ToString("D"), Path.GetRandomFileName()); + var scriptFilePath = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid().ToString("D"), + Path.GetRandomFileName() + ); - await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.FileMode644, ct) + await CopyAsync( + Encoding.Default.GetBytes(scriptContent), + scriptFilePath, + Unix.FileMode644, + ct + ) .ConfigureAwait(false); - return await ExecAsync(new[] { "/usr/local/firebird/bin/isql", "-i", scriptFilePath, "-user", _configuration.Username, "-pass", _configuration.Password, _configuration.Database }, ct) + return await ExecAsync( + new[] + { + "/usr/local/firebird/bin/isql", + "-i", + scriptFilePath, + "-user", + _configuration.Username, + "-pass", + _configuration.Password, + _configuration.Database, + }, + ct + ) .ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.FirebirdSql/Testcontainers.FirebirdSql.csproj b/src/Testcontainers.FirebirdSql/Testcontainers.FirebirdSql.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.FirebirdSql/Testcontainers.FirebirdSql.csproj +++ b/src/Testcontainers.FirebirdSql/Testcontainers.FirebirdSql.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.FirebirdSql/Usings.cs b/src/Testcontainers.FirebirdSql/Usings.cs index e2b02a51e..3481268bc 100644 --- a/src/Testcontainers.FirebirdSql/Usings.cs +++ b/src/Testcontainers.FirebirdSql/Usings.cs @@ -10,4 +10,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Firestore/FirestoreBuilder.cs b/src/Testcontainers.Firestore/FirestoreBuilder.cs index 74ff2e38d..abdcd102f 100644 --- a/src/Testcontainers.Firestore/FirestoreBuilder.cs +++ b/src/Testcontainers.Firestore/FirestoreBuilder.cs @@ -2,9 +2,11 @@ namespace Testcontainers.Firestore; /// [PublicAPI] -public sealed class FirestoreBuilder : ContainerBuilder +public sealed class FirestoreBuilder + : ContainerBuilder { - public const string GoogleCloudCliImage = "gcr.io/google.com/cloudsdktool/google-cloud-cli:446.0.1-emulators"; + public const string GoogleCloudCliImage = + "gcr.io/google.com/cloudsdktool/google-cloud-cli:446.0.1-emulators"; public const ushort FirestorePort = 8080; @@ -44,25 +46,43 @@ protected override FirestoreBuilder Init() .WithImage(GoogleCloudCliImage) .WithPortBinding(FirestorePort, true) .WithEntrypoint("gcloud") - .WithCommand("beta", "emulators", "firestore", "start", "--host-port", "0.0.0.0:" + FirestorePort) + .WithCommand( + "beta", + "emulators", + "firestore", + "start", + "--host-port", + "0.0.0.0:" + FirestorePort + ) .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("(?s).*running.*$")); } /// - protected override FirestoreBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override FirestoreBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new FirestoreConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new FirestoreConfiguration(resourceConfiguration) + ); } /// protected override FirestoreBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new FirestoreConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new FirestoreConfiguration(resourceConfiguration) + ); } /// - protected override FirestoreBuilder Merge(FirestoreConfiguration oldValue, FirestoreConfiguration newValue) + protected override FirestoreBuilder Merge( + FirestoreConfiguration oldValue, + FirestoreConfiguration newValue + ) { return new FirestoreBuilder(new FirestoreConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Firestore/FirestoreConfiguration.cs b/src/Testcontainers.Firestore/FirestoreConfiguration.cs index 91fbd7836..e91fcc07a 100644 --- a/src/Testcontainers.Firestore/FirestoreConfiguration.cs +++ b/src/Testcontainers.Firestore/FirestoreConfiguration.cs @@ -7,15 +7,15 @@ public sealed class FirestoreConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public FirestoreConfiguration() - { - } + public FirestoreConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public FirestoreConfiguration(IResourceConfiguration resourceConfiguration) + public FirestoreConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public FirestoreConfiguration(FirestoreConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public FirestoreConfiguration(FirestoreConfiguration oldValue, FirestoreConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Firestore/FirestoreContainer.cs b/src/Testcontainers.Firestore/FirestoreContainer.cs index 2c90e42e5..ee0e4e415 100644 --- a/src/Testcontainers.Firestore/FirestoreContainer.cs +++ b/src/Testcontainers.Firestore/FirestoreContainer.cs @@ -9,9 +9,7 @@ public sealed class FirestoreContainer : DockerContainer /// /// The container configuration. public FirestoreContainer(FirestoreConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Firestore emulator endpoint. @@ -19,6 +17,10 @@ public FirestoreContainer(FirestoreConfiguration configuration) /// The Firestore emulator endpoint. public string GetEmulatorEndpoint() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(FirestoreBuilder.FirestorePort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(FirestoreBuilder.FirestorePort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Firestore/Testcontainers.Firestore.csproj b/src/Testcontainers.Firestore/Testcontainers.Firestore.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Firestore/Testcontainers.Firestore.csproj +++ b/src/Testcontainers.Firestore/Testcontainers.Firestore.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Firestore/Usings.cs b/src/Testcontainers.Firestore/Usings.cs index 79fd3af9b..b31708db0 100644 --- a/src/Testcontainers.Firestore/Usings.cs +++ b/src/Testcontainers.Firestore/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.GCloud/Testcontainers.GCloud.csproj b/src/Testcontainers.GCloud/Testcontainers.GCloud.csproj index 2c527d992..3c6f0ca97 100644 --- a/src/Testcontainers.GCloud/Testcontainers.GCloud.csproj +++ b/src/Testcontainers.GCloud/Testcontainers.GCloud.csproj @@ -1,12 +1,12 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.InfluxDb/InfluxDbBuilder.cs b/src/Testcontainers.InfluxDb/InfluxDbBuilder.cs index de01dbabd..999c50cee 100644 --- a/src/Testcontainers.InfluxDb/InfluxDbBuilder.cs +++ b/src/Testcontainers.InfluxDb/InfluxDbBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.InfluxDb; /// [PublicAPI] -public sealed class InfluxDbBuilder : ContainerBuilder +public sealed class InfluxDbBuilder + : ContainerBuilder { public const string InfluxDbImage = "influxdb:2.7"; @@ -67,7 +68,10 @@ public InfluxDbBuilder WithPassword(string password) /// A configured instance of . public InfluxDbBuilder WithOrganization(string organization) { - return Merge(DockerResourceConfiguration, new InfluxDbConfiguration(organization: organization)) + return Merge( + DockerResourceConfiguration, + new InfluxDbConfiguration(organization: organization) + ) .WithEnvironment("DOCKER_INFLUXDB_INIT_ORG", organization); } @@ -122,8 +126,15 @@ protected override InfluxDbBuilder Init() .WithPassword(DefaultPassword) .WithOrganization(DefaultOrganization) .WithBucket(DefaultBucket) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPort(InfluxDbPort).ForPath("/ping").ForStatusCode(HttpStatusCode.NoContent))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request + .ForPort(InfluxDbPort) + .ForPath("/ping") + .ForStatusCode(HttpStatusCode.NoContent) + ) + ); } /// @@ -131,25 +142,43 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Username, nameof(DockerResourceConfiguration.Username)) + _ = Guard + .Argument( + DockerResourceConfiguration.Username, + nameof(DockerResourceConfiguration.Username) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Organization, nameof(DockerResourceConfiguration.Organization)) + _ = Guard + .Argument( + DockerResourceConfiguration.Organization, + nameof(DockerResourceConfiguration.Organization) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Bucket, nameof(DockerResourceConfiguration.Bucket)) + _ = Guard + .Argument( + DockerResourceConfiguration.Bucket, + nameof(DockerResourceConfiguration.Bucket) + ) .NotNull() .NotEmpty(); } /// - protected override InfluxDbBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override InfluxDbBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new InfluxDbConfiguration(resourceConfiguration)); } @@ -161,8 +190,11 @@ protected override InfluxDbBuilder Clone(IContainerConfiguration resourceConfigu } /// - protected override InfluxDbBuilder Merge(InfluxDbConfiguration oldValue, InfluxDbConfiguration newValue) + protected override InfluxDbBuilder Merge( + InfluxDbConfiguration oldValue, + InfluxDbConfiguration newValue + ) { return new InfluxDbBuilder(new InfluxDbConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.InfluxDb/InfluxDbConfiguration.cs b/src/Testcontainers.InfluxDb/InfluxDbConfiguration.cs index 68eb29dc4..8725f0d2f 100644 --- a/src/Testcontainers.InfluxDb/InfluxDbConfiguration.cs +++ b/src/Testcontainers.InfluxDb/InfluxDbConfiguration.cs @@ -19,7 +19,8 @@ public InfluxDbConfiguration( string organization = null, string bucket = null, string adminToken = null, - string retention = null) + string retention = null + ) { Username = username; Password = password; @@ -33,7 +34,9 @@ public InfluxDbConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public InfluxDbConfiguration(IResourceConfiguration resourceConfiguration) + public InfluxDbConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -104,4 +107,4 @@ public InfluxDbConfiguration(InfluxDbConfiguration oldValue, InfluxDbConfigurati /// Gets the InfluxDb retention. /// public string Retention { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.InfluxDb/InfluxDbContainer.cs b/src/Testcontainers.InfluxDb/InfluxDbContainer.cs index 29f9efe44..4466f1ec6 100644 --- a/src/Testcontainers.InfluxDb/InfluxDbContainer.cs +++ b/src/Testcontainers.InfluxDb/InfluxDbContainer.cs @@ -9,9 +9,7 @@ public sealed class InfluxDbContainer : DockerContainer /// /// The container configuration. public InfluxDbContainer(InfluxDbConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the InfluxDb address. @@ -19,6 +17,10 @@ public InfluxDbContainer(InfluxDbConfiguration configuration) /// The InfluxDb address. public string GetAddress() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(InfluxDbBuilder.InfluxDbPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(InfluxDbBuilder.InfluxDbPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.InfluxDb/Testcontainers.InfluxDb.csproj b/src/Testcontainers.InfluxDb/Testcontainers.InfluxDb.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.InfluxDb/Testcontainers.InfluxDb.csproj +++ b/src/Testcontainers.InfluxDb/Testcontainers.InfluxDb.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.InfluxDb/Usings.cs b/src/Testcontainers.InfluxDb/Usings.cs index 40b1c789a..46ae7f45e 100644 --- a/src/Testcontainers.InfluxDb/Usings.cs +++ b/src/Testcontainers.InfluxDb/Usings.cs @@ -5,4 +5,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.JanusGraph/JanusGraphBuilder.cs b/src/Testcontainers.JanusGraph/JanusGraphBuilder.cs index 2b30f7f45..42cfaa84a 100644 --- a/src/Testcontainers.JanusGraph/JanusGraphBuilder.cs +++ b/src/Testcontainers.JanusGraph/JanusGraphBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.JanusGraph; /// [PublicAPI] -public sealed class JanusGraphBuilder : ContainerBuilder +public sealed class JanusGraphBuilder + : ContainerBuilder { public const string JanusGraphImage = "janusgraph/janusgraph:1.0.0"; @@ -44,24 +45,37 @@ protected override JanusGraphBuilder Init() .WithImage(JanusGraphImage) .WithPortBinding(JanusGraphPort, true) .WithEnvironment("janusgraph.storage.backend", "inmemory") - .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("Channel started at port")); + .WithWaitStrategy( + Wait.ForUnixContainer().UntilMessageIsLogged("Channel started at port") + ); } /// - protected override JanusGraphBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override JanusGraphBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new JanusGraphConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new JanusGraphConfiguration(resourceConfiguration) + ); } /// protected override JanusGraphBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new JanusGraphConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new JanusGraphConfiguration(resourceConfiguration) + ); } /// - protected override JanusGraphBuilder Merge(JanusGraphConfiguration oldValue, JanusGraphConfiguration newValue) + protected override JanusGraphBuilder Merge( + JanusGraphConfiguration oldValue, + JanusGraphConfiguration newValue + ) { return new JanusGraphBuilder(new JanusGraphConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.JanusGraph/JanusGraphConfiguration.cs b/src/Testcontainers.JanusGraph/JanusGraphConfiguration.cs index d5cd60f82..98839e741 100644 --- a/src/Testcontainers.JanusGraph/JanusGraphConfiguration.cs +++ b/src/Testcontainers.JanusGraph/JanusGraphConfiguration.cs @@ -7,15 +7,15 @@ public sealed class JanusGraphConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public JanusGraphConfiguration() - { - } + public JanusGraphConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public JanusGraphConfiguration(IResourceConfiguration resourceConfiguration) + public JanusGraphConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -46,8 +46,9 @@ public JanusGraphConfiguration(JanusGraphConfiguration resourceConfiguration) /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public JanusGraphConfiguration(JanusGraphConfiguration oldValue, JanusGraphConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + public JanusGraphConfiguration( + JanusGraphConfiguration oldValue, + JanusGraphConfiguration newValue + ) + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.JanusGraph/JanusGraphContainer.cs b/src/Testcontainers.JanusGraph/JanusGraphContainer.cs index 0896ba0fc..191edad24 100644 --- a/src/Testcontainers.JanusGraph/JanusGraphContainer.cs +++ b/src/Testcontainers.JanusGraph/JanusGraphContainer.cs @@ -9,7 +9,5 @@ public sealed class JanusGraphContainer : DockerContainer /// /// The container configuration. public JanusGraphContainer(JanusGraphConfiguration configuration) - : base(configuration) - { - } -} \ No newline at end of file + : base(configuration) { } +} diff --git a/src/Testcontainers.JanusGraph/Testcontainers.JanusGraph.csproj b/src/Testcontainers.JanusGraph/Testcontainers.JanusGraph.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.JanusGraph/Testcontainers.JanusGraph.csproj +++ b/src/Testcontainers.JanusGraph/Testcontainers.JanusGraph.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.JanusGraph/Usings.cs b/src/Testcontainers.JanusGraph/Usings.cs index a2faed446..2ceda0595 100644 --- a/src/Testcontainers.JanusGraph/Usings.cs +++ b/src/Testcontainers.JanusGraph/Usings.cs @@ -2,4 +2,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.K3s/K3sBuilder.cs b/src/Testcontainers.K3s/K3sBuilder.cs index 6734ebb2c..7799734a1 100644 --- a/src/Testcontainers.K3s/K3sBuilder.cs +++ b/src/Testcontainers.K3s/K3sBuilder.cs @@ -51,12 +51,18 @@ protected override K3sBuilder Init() .WithTmpfsMount("/run") .WithTmpfsMount("/var/run") .WithCommand("server", "--disable=traefik") - .WithCreateParameterModifier(parameterModifier => parameterModifier.HostConfig.CgroupnsMode = "host") - .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("Node controller sync successful")); + .WithCreateParameterModifier(parameterModifier => + parameterModifier.HostConfig.CgroupnsMode = "host" + ) + .WithWaitStrategy( + Wait.ForUnixContainer().UntilMessageIsLogged("Node controller sync successful") + ); } /// - protected override K3sBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override K3sBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new K3sConfiguration(resourceConfiguration)); } @@ -72,4 +78,4 @@ protected override K3sBuilder Merge(K3sConfiguration oldValue, K3sConfiguration { return new K3sBuilder(new K3sConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.K3s/K3sConfiguration.cs b/src/Testcontainers.K3s/K3sConfiguration.cs index 4c50d1123..6ae472b5f 100644 --- a/src/Testcontainers.K3s/K3sConfiguration.cs +++ b/src/Testcontainers.K3s/K3sConfiguration.cs @@ -7,9 +7,7 @@ public sealed class K3sConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public K3sConfiguration() - { - } + public K3sConfiguration() { } /// /// Initializes a new instance of the class. @@ -47,7 +45,5 @@ public K3sConfiguration(K3sConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public K3sConfiguration(K3sConfiguration oldValue, K3sConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.K3s/K3sContainer.cs b/src/Testcontainers.K3s/K3sContainer.cs index aac1ea798..c8ab48938 100644 --- a/src/Testcontainers.K3s/K3sContainer.cs +++ b/src/Testcontainers.K3s/K3sContainer.cs @@ -9,9 +9,7 @@ public sealed class K3sContainer : DockerContainer /// /// The container configuration. public K3sContainer(K3sConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Kubeconfig. @@ -24,8 +22,18 @@ public async Task GetKubeconfigAsync() var kubeconfig = Encoding.Default.GetString(kubeconfigBytes); - var server = new UriBuilder(Uri.UriSchemeHttps, Hostname, GetMappedPublicPort(K3sBuilder.KubeSecurePort)).ToString(); + var server = new UriBuilder( + Uri.UriSchemeHttps, + Hostname, + GetMappedPublicPort(K3sBuilder.KubeSecurePort) + ).ToString(); - return Regex.Replace(kubeconfig, "server:\\s?[:/\\.\\d\\w]+", "server: " + server, RegexOptions.None, TimeSpan.FromSeconds(1)); + return Regex.Replace( + kubeconfig, + "server:\\s?[:/\\.\\d\\w]+", + "server: " + server, + RegexOptions.None, + TimeSpan.FromSeconds(1) + ); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.K3s/Testcontainers.K3s.csproj b/src/Testcontainers.K3s/Testcontainers.K3s.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.K3s/Testcontainers.K3s.csproj +++ b/src/Testcontainers.K3s/Testcontainers.K3s.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.K3s/Usings.cs b/src/Testcontainers.K3s/Usings.cs index 633a735fb..bb0267fac 100644 --- a/src/Testcontainers.K3s/Usings.cs +++ b/src/Testcontainers.K3s/Usings.cs @@ -6,4 +6,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Kafka/ApacheConfiguration.cs b/src/Testcontainers.Kafka/ApacheConfiguration.cs index 3e8d68868..ab422653c 100644 --- a/src/Testcontainers.Kafka/ApacheConfiguration.cs +++ b/src/Testcontainers.Kafka/ApacheConfiguration.cs @@ -3,30 +3,23 @@ namespace Testcontainers.Kafka; /// internal sealed class ApacheConfiguration : IKafkaVendorConfiguration { - static ApacheConfiguration() - { - } + static ApacheConfiguration() { } /// /// Initializes a new instance of the class. /// - private ApacheConfiguration() - { - } + private ApacheConfiguration() { } /// /// Gets the singleton instance of the Apache vendor configuration. /// - public static IKafkaVendorConfiguration Instance { get; } - = new ApacheConfiguration(); + public static IKafkaVendorConfiguration Instance { get; } = new ApacheConfiguration(); /// - public KafkaVendor Vendor - => KafkaVendor.ApacheSoftwareFoundation; + public KafkaVendor Vendor => KafkaVendor.ApacheSoftwareFoundation; /// - public ConsensusProtocol ConsensusProtocol - => ConsensusProtocol.KRaft; + public ConsensusProtocol ConsensusProtocol => ConsensusProtocol.KRaft; /// public bool IsImageFromVendor(IImage image) @@ -37,26 +30,55 @@ public bool IsImageFromVendor(IImage image) /// public void Validate(KafkaConfiguration resourceConfiguration) { - const string message = "Local ZooKeeper is not supported for Apache Kafka images. Configure an external ZooKeeper."; + const string message = + "Local ZooKeeper is not supported for Apache Kafka images. Configure an external ZooKeeper."; - var isZooKeeperConsensus = resourceConfiguration.ConsensusProtocol == ConsensusProtocol.ZooKeeper; + var isZooKeeperConsensus = + resourceConfiguration.ConsensusProtocol == ConsensusProtocol.ZooKeeper; - var hasLocalZooKeeper = isZooKeeperConsensus && resourceConfiguration.Environments.TryGetValue("KAFKA_ZOOKEEPER_CONNECT", out var connectionString) && connectionString.StartsWith("localhost"); + var hasLocalZooKeeper = + isZooKeeperConsensus + && resourceConfiguration.Environments.TryGetValue( + "KAFKA_ZOOKEEPER_CONNECT", + out var connectionString + ) + && connectionString.StartsWith("localhost"); - _ = Guard.Argument(resourceConfiguration, nameof(IContainerConfiguration.Image)) - .ThrowIf(_ => hasLocalZooKeeper, argument => new ArgumentException(message, argument.Name)); + _ = Guard + .Argument(resourceConfiguration, nameof(IContainerConfiguration.Image)) + .ThrowIf( + _ => hasLocalZooKeeper, + argument => new ArgumentException(message, argument.Name) + ); } /// - public string CreateStartupScript(KafkaConfiguration resourceConfiguration, KafkaContainer container) + public string CreateStartupScript( + KafkaConfiguration resourceConfiguration, + KafkaContainer container + ) { - var additionalAdvertisedListeners = string.Join(",", container.AdvertisedListeners ?? Array.Empty()); + var additionalAdvertisedListeners = string.Join( + ",", + container.AdvertisedListeners ?? Array.Empty() + ); var startupScript = new StringWriter(); startupScript.NewLine = "\n"; startupScript.WriteLine("#!/bin/bash"); - startupScript.WriteLine("export KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://" + container.Hostname + ":" + container.GetMappedPublicPort(KafkaBuilder.KafkaPort) + ",BROKER://" + container.IpAddress + ":" + KafkaBuilder.BrokerPort + "," + additionalAdvertisedListeners); + startupScript.WriteLine( + "export KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://" + + container.Hostname + + ":" + + container.GetMappedPublicPort(KafkaBuilder.KafkaPort) + + ",BROKER://" + + container.IpAddress + + ":" + + KafkaBuilder.BrokerPort + + "," + + additionalAdvertisedListeners + ); startupScript.WriteLine("exec /etc/kafka/docker/run"); return startupScript.ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Kafka/ConfluentConfiguration.cs b/src/Testcontainers.Kafka/ConfluentConfiguration.cs index f2e584710..757adb5f3 100644 --- a/src/Testcontainers.Kafka/ConfluentConfiguration.cs +++ b/src/Testcontainers.Kafka/ConfluentConfiguration.cs @@ -3,30 +3,23 @@ namespace Testcontainers.Kafka; /// internal sealed class ConfluentConfiguration : IKafkaVendorConfiguration { - static ConfluentConfiguration() - { - } + static ConfluentConfiguration() { } /// /// Initializes a new instance of the class. /// - private ConfluentConfiguration() - { - } + private ConfluentConfiguration() { } /// /// Gets the singleton instance of the Confluent vendor configuration. /// - public static IKafkaVendorConfiguration Instance { get; } - = new ConfluentConfiguration(); + public static IKafkaVendorConfiguration Instance { get; } = new ConfluentConfiguration(); /// - public KafkaVendor Vendor - => KafkaVendor.Confluent; + public KafkaVendor Vendor => KafkaVendor.Confluent; /// - public ConsensusProtocol ConsensusProtocol - => ConsensusProtocol.ZooKeeper; + public ConsensusProtocol ConsensusProtocol => ConsensusProtocol.ZooKeeper; /// public bool IsImageFromVendor(IImage image) @@ -37,23 +30,43 @@ public bool IsImageFromVendor(IImage image) /// public void Validate(KafkaConfiguration resourceConfiguration) { - const string message = "KRaft is not supported for Confluent Platform images with versions earlier than 7.0.0."; + const string message = + "KRaft is not supported for Confluent Platform images with versions earlier than 7.0.0."; - Predicate isUnsupportedImage = value => value.ConsensusProtocol == ConsensusProtocol.KRaft - && IsImageFromVendor(value.Image) && value.Image.MatchVersion(v => v.Major < 7); + Predicate isUnsupportedImage = value => + value.ConsensusProtocol == ConsensusProtocol.KRaft + && IsImageFromVendor(value.Image) + && value.Image.MatchVersion(v => v.Major < 7); - _ = Guard.Argument(resourceConfiguration, nameof(IContainerConfiguration.Image)) - .ThrowIf(argument => isUnsupportedImage(argument.Value), argument => new ArgumentException(message, argument.Name)); + _ = Guard + .Argument(resourceConfiguration, nameof(IContainerConfiguration.Image)) + .ThrowIf( + argument => isUnsupportedImage(argument.Value), + argument => new ArgumentException(message, argument.Name) + ); } /// - public string CreateStartupScript(KafkaConfiguration resourceConfiguration, KafkaContainer container) + public string CreateStartupScript( + KafkaConfiguration resourceConfiguration, + KafkaContainer container + ) { - var additionalAdvertisedListeners = string.Join(",", container.AdvertisedListeners ?? Array.Empty()); + var additionalAdvertisedListeners = string.Join( + ",", + container.AdvertisedListeners ?? Array.Empty() + ); - var isZooKeeperConsensus = resourceConfiguration.ConsensusProtocol == ConsensusProtocol.ZooKeeper; + var isZooKeeperConsensus = + resourceConfiguration.ConsensusProtocol == ConsensusProtocol.ZooKeeper; - var hasLocalZooKeeper = isZooKeeperConsensus && resourceConfiguration.Environments.TryGetValue("KAFKA_ZOOKEEPER_CONNECT", out var connectionString) && connectionString.StartsWith("localhost"); + var hasLocalZooKeeper = + isZooKeeperConsensus + && resourceConfiguration.Environments.TryGetValue( + "KAFKA_ZOOKEEPER_CONNECT", + out var connectionString + ) + && connectionString.StartsWith("localhost"); var startupScript = new StringWriter(); startupScript.NewLine = "\n"; @@ -62,14 +75,31 @@ public string CreateStartupScript(KafkaConfiguration resourceConfiguration, Kafk if (isZooKeeperConsensus && hasLocalZooKeeper) { startupScript.WriteLine("echo '' > /etc/confluent/docker/ensure"); - startupScript.WriteLine("echo 'clientPort=" + KafkaBuilder.ZooKeeperPort + "' > zookeeper.properties"); - startupScript.WriteLine("echo 'dataDir=/var/lib/zookeeper/data' >> zookeeper.properties"); - startupScript.WriteLine("echo 'dataLogDir=/var/lib/zookeeper/log' >> zookeeper.properties"); + startupScript.WriteLine( + "echo 'clientPort=" + KafkaBuilder.ZooKeeperPort + "' > zookeeper.properties" + ); + startupScript.WriteLine( + "echo 'dataDir=/var/lib/zookeeper/data' >> zookeeper.properties" + ); + startupScript.WriteLine( + "echo 'dataLogDir=/var/lib/zookeeper/log' >> zookeeper.properties" + ); startupScript.WriteLine("zookeeper-server-start zookeeper.properties &"); } - startupScript.WriteLine("export KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://" + container.Hostname + ":" + container.GetMappedPublicPort(KafkaBuilder.KafkaPort) + ",BROKER://" + container.IpAddress + ":" + KafkaBuilder.BrokerPort + "," + additionalAdvertisedListeners); + startupScript.WriteLine( + "export KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://" + + container.Hostname + + ":" + + container.GetMappedPublicPort(KafkaBuilder.KafkaPort) + + ",BROKER://" + + container.IpAddress + + ":" + + KafkaBuilder.BrokerPort + + "," + + additionalAdvertisedListeners + ); startupScript.WriteLine("exec /etc/confluent/docker/run"); return startupScript.ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Kafka/IKafkaVendorConfiguration.cs b/src/Testcontainers.Kafka/IKafkaVendorConfiguration.cs index 533915760..8011914c6 100644 --- a/src/Testcontainers.Kafka/IKafkaVendorConfiguration.cs +++ b/src/Testcontainers.Kafka/IKafkaVendorConfiguration.cs @@ -34,5 +34,8 @@ internal interface IKafkaVendorConfiguration /// The resource configuration. /// The Kafka container. /// The startup script as a string. - public string CreateStartupScript(KafkaConfiguration resourceConfiguration, KafkaContainer container); -} \ No newline at end of file + public string CreateStartupScript( + KafkaConfiguration resourceConfiguration, + KafkaContainer container + ); +} diff --git a/src/Testcontainers.Kafka/KafkaBuilder.cs b/src/Testcontainers.Kafka/KafkaBuilder.cs index 5b3b2fb12..5f079ca71 100644 --- a/src/Testcontainers.Kafka/KafkaBuilder.cs +++ b/src/Testcontainers.Kafka/KafkaBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Kafka; /// [PublicAPI] -public sealed class KafkaBuilder : ContainerBuilder +public sealed class KafkaBuilder + : ContainerBuilder { public const string KafkaImage = "confluentinc/cp-kafka:7.5.9"; @@ -22,7 +23,11 @@ public sealed class KafkaBuilder : ContainerBuilder /// Initializes a new instance of the class. @@ -88,7 +93,10 @@ private KafkaBuilder(KafkaConfiguration resourceConfiguration) /// A configured instance of . public KafkaBuilder WithListener(string kafka) { - var index = DockerResourceConfiguration.Listeners == null ? 0 : DockerResourceConfiguration.Listeners.Count(); + var index = + DockerResourceConfiguration.Listeners == null + ? 0 + : DockerResourceConfiguration.Listeners.Count(); var protocol = $"{ProtocolPrefix}-{index}"; var listener = $"{protocol}://{kafka}"; var listenerSecurityProtocolMap = $"{protocol}:PLAINTEXT"; @@ -98,17 +106,25 @@ public KafkaBuilder WithListener(string kafka) var host = kafka.Split(':')[0]; - var updatedListeners = DockerResourceConfiguration.Environments["KAFKA_LISTENERS"] + var updatedListeners = DockerResourceConfiguration + .Environments["KAFKA_LISTENERS"] .Split(',') .Concat(listeners); - var updatedListenersSecurityProtocolMap = DockerResourceConfiguration.Environments["KAFKA_LISTENER_SECURITY_PROTOCOL_MAP"] + var updatedListenersSecurityProtocolMap = DockerResourceConfiguration + .Environments["KAFKA_LISTENER_SECURITY_PROTOCOL_MAP"] .Split(',') .Concat(listenersSecurityProtocolMap); - return Merge(DockerResourceConfiguration, new KafkaConfiguration(listeners: listeners, advertisedListeners: listeners)) + return Merge( + DockerResourceConfiguration, + new KafkaConfiguration(listeners: listeners, advertisedListeners: listeners) + ) .WithEnvironment("KAFKA_LISTENERS", string.Join(",", updatedListeners)) - .WithEnvironment("KAFKA_LISTENER_SECURITY_PROTOCOL_MAP", string.Join(",", updatedListenersSecurityProtocolMap)) + .WithEnvironment( + "KAFKA_LISTENER_SECURITY_PROTOCOL_MAP", + string.Join(",", updatedListenersSecurityProtocolMap) + ) .WithNetworkAliases(host); } @@ -119,7 +135,10 @@ public KafkaBuilder WithListener(string kafka) /// A configured instance of . private KafkaBuilder WithConsensusProtocol(ConsensusProtocol consensusProtocol) { - return Merge(DockerResourceConfiguration, new KafkaConfiguration(consensusProtocol: consensusProtocol)); + return Merge( + DockerResourceConfiguration, + new KafkaConfiguration(consensusProtocol: consensusProtocol) + ); } /// @@ -131,7 +150,10 @@ public KafkaBuilder WithKRaft() return WithConsensusProtocol(ConsensusProtocol.KRaft) .WithEnvironment("KAFKA_CONTROLLER_LISTENER_NAMES", "CONTROLLER") .WithEnvironment("KAFKA_PROCESS_ROLES", "broker,controller") - .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged(".*Transitioning from RECOVERY to RUNNING.*")); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilMessageIsLogged(".*Transitioning from RECOVERY to RUNNING.*") + ); } /// @@ -143,8 +165,13 @@ public KafkaBuilder WithZooKeeper(string connectionString = null) { return WithConsensusProtocol(ConsensusProtocol.ZooKeeper) .WithPortBinding(ZooKeeperPort, connectionString == null) - .WithEnvironment("KAFKA_ZOOKEEPER_CONNECT", connectionString ?? $"localhost:{ZooKeeperPort}") - .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("\\[KafkaServer id=\\d+\\] started")); + .WithEnvironment( + "KAFKA_ZOOKEEPER_CONNECT", + connectionString ?? $"localhost:{ZooKeeperPort}" + ) + .WithWaitStrategy( + Wait.ForUnixContainer().UntilMessageIsLogged("\\[KafkaServer id=\\d+\\] started") + ); } /// @@ -181,7 +208,10 @@ public override KafkaContainer Build() KafkaBuilder kafkaBuilder; // Instead of this approach, should we consider using a builder for each vendor? - var vendorConfiguration = VendorConfigurations.Single(v => v.Vendor.Equals(DockerResourceConfiguration.Vendor) || v.IsImageFromVendor(DockerResourceConfiguration.Image)); + var vendorConfiguration = VendorConfigurations.Single(v => + v.Vendor.Equals(DockerResourceConfiguration.Vendor) + || v.IsImageFromVendor(DockerResourceConfiguration.Image) + ); // If the user hasn't set a consensus protocol, use the vendor's default configuration. if (DockerResourceConfiguration.ConsensusProtocol.HasValue) @@ -198,17 +228,29 @@ public override KafkaContainer Build() } else { - throw new ArgumentException($"No default configuration available for vendor '{vendorConfiguration.Vendor}'."); + throw new ArgumentException( + $"No default configuration available for vendor '{vendorConfiguration.Vendor}'." + ); } // Validate that the configuration is compatible with the vendor's image. vendorConfiguration.Validate(DockerResourceConfiguration); - var startupKafkaBuilder = kafkaBuilder.WithStartupCallback((container, ct) => - { - var startupScript = vendorConfiguration.CreateStartupScript(kafkaBuilder.DockerResourceConfiguration, container); - return container.CopyAsync(Encoding.Default.GetBytes(startupScript), StartupScriptFilePath, Unix.FileMode755, ct); - }); + var startupKafkaBuilder = kafkaBuilder.WithStartupCallback( + (container, ct) => + { + var startupScript = vendorConfiguration.CreateStartupScript( + kafkaBuilder.DockerResourceConfiguration, + container + ); + return container.CopyAsync( + Encoding.Default.GetBytes(startupScript), + StartupScriptFilePath, + Unix.FileMode755, + ct + ); + } + ); return new KafkaContainer(startupKafkaBuilder.DockerResourceConfiguration); } @@ -220,12 +262,21 @@ protected override KafkaBuilder Init() .WithImage(KafkaImage) .WithPortBinding(KafkaPort, true) .WithPortBinding(BrokerPort, true) - .WithEnvironment("KAFKA_LISTENERS", $"PLAINTEXT://:{KafkaPort},BROKER://:{BrokerPort},CONTROLLER://:{ControllerPort}") - .WithEnvironment("KAFKA_LISTENER_SECURITY_PROTOCOL_MAP", "BROKER:PLAINTEXT,CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT") + .WithEnvironment( + "KAFKA_LISTENERS", + $"PLAINTEXT://:{KafkaPort},BROKER://:{BrokerPort},CONTROLLER://:{ControllerPort}" + ) + .WithEnvironment( + "KAFKA_LISTENER_SECURITY_PROTOCOL_MAP", + "BROKER:PLAINTEXT,CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT" + ) .WithEnvironment("KAFKA_INTER_BROKER_LISTENER_NAME", "BROKER") .WithEnvironment("KAFKA_BROKER_ID", "1") .WithEnvironment("KAFKA_NODE_ID", NodeId) - .WithEnvironment("KAFKA_CONTROLLER_QUORUM_VOTERS", $"{NodeId}@localhost:{ControllerPort}") + .WithEnvironment( + "KAFKA_CONTROLLER_QUORUM_VOTERS", + $"{NodeId}@localhost:{ControllerPort}" + ) .WithEnvironment("KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR", "1") .WithEnvironment("KAFKA_OFFSETS_TOPIC_NUM_PARTITIONS", "1") .WithEnvironment("KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR", "1") @@ -234,7 +285,9 @@ protected override KafkaBuilder Init() .WithEnvironment("KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS", "0") .WithEnvironment("CLUSTER_ID", ClusterId) .WithEntrypoint("/bin/sh", "-c") - .WithCommand($"while [ ! -f {StartupScriptFilePath} ]; do sleep 0.1; done; {StartupScriptFilePath}"); + .WithCommand( + $"while [ ! -f {StartupScriptFilePath} ]; do sleep 0.1; done; {StartupScriptFilePath}" + ); } /// @@ -244,14 +297,27 @@ protected override void Validate() base.Validate(); - Predicate vendorNotFound = value => value == null && !VendorConfigurations.Any(v => v.IsImageFromVendor(DockerResourceConfiguration.Image)); - - _ = Guard.Argument(DockerResourceConfiguration.Vendor, nameof(DockerResourceConfiguration.Vendor)) - .ThrowIf(argument => vendorNotFound(argument.Value), argument => new ArgumentException(message, argument.Name)); + Predicate vendorNotFound = value => + value == null + && !VendorConfigurations.Any(v => + v.IsImageFromVendor(DockerResourceConfiguration.Image) + ); + + _ = Guard + .Argument( + DockerResourceConfiguration.Vendor, + nameof(DockerResourceConfiguration.Vendor) + ) + .ThrowIf( + argument => vendorNotFound(argument.Value), + argument => new ArgumentException(message, argument.Name) + ); } /// - protected override KafkaBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override KafkaBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new KafkaConfiguration(resourceConfiguration)); } @@ -267,4 +333,4 @@ protected override KafkaBuilder Merge(KafkaConfiguration oldValue, KafkaConfigur { return new KafkaBuilder(new KafkaConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Kafka/KafkaConfiguration.cs b/src/Testcontainers.Kafka/KafkaConfiguration.cs index a643b2f1d..8945cdd8b 100644 --- a/src/Testcontainers.Kafka/KafkaConfiguration.cs +++ b/src/Testcontainers.Kafka/KafkaConfiguration.cs @@ -15,7 +15,8 @@ public KafkaConfiguration( KafkaVendor? vendor = null, ConsensusProtocol? consensusProtocol = null, IEnumerable listeners = null, - IEnumerable advertisedListeners = null) + IEnumerable advertisedListeners = null + ) { Vendor = vendor; ConsensusProtocol = consensusProtocol; @@ -27,7 +28,9 @@ public KafkaConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public KafkaConfiguration(IResourceConfiguration resourceConfiguration) + public KafkaConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -62,9 +65,15 @@ public KafkaConfiguration(KafkaConfiguration oldValue, KafkaConfiguration newVal : base(oldValue, newValue) { Vendor = BuildConfiguration.Combine(oldValue.Vendor, newValue.Vendor); - ConsensusProtocol = BuildConfiguration.Combine(oldValue.ConsensusProtocol, newValue.ConsensusProtocol); + ConsensusProtocol = BuildConfiguration.Combine( + oldValue.ConsensusProtocol, + newValue.ConsensusProtocol + ); Listeners = BuildConfiguration.Combine(oldValue.Listeners, newValue.Listeners); - AdvertisedListeners = BuildConfiguration.Combine(oldValue.AdvertisedListeners, newValue.AdvertisedListeners); + AdvertisedListeners = BuildConfiguration.Combine( + oldValue.AdvertisedListeners, + newValue.AdvertisedListeners + ); } /// @@ -86,4 +95,4 @@ public KafkaConfiguration(KafkaConfiguration oldValue, KafkaConfiguration newVal /// Gets a list of advertised listeners. /// public IEnumerable AdvertisedListeners { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Kafka/KafkaConsensusProtocol.cs b/src/Testcontainers.Kafka/KafkaConsensusProtocol.cs index 8ed4ff522..9b5490a8b 100644 --- a/src/Testcontainers.Kafka/KafkaConsensusProtocol.cs +++ b/src/Testcontainers.Kafka/KafkaConsensusProtocol.cs @@ -14,4 +14,4 @@ public enum ConsensusProtocol /// Represents the ZooKeeper-based consensus protocol. /// ZooKeeper, -} \ No newline at end of file +} diff --git a/src/Testcontainers.Kafka/KafkaContainer.cs b/src/Testcontainers.Kafka/KafkaContainer.cs index 89a20db5b..c34c4f749 100644 --- a/src/Testcontainers.Kafka/KafkaContainer.cs +++ b/src/Testcontainers.Kafka/KafkaContainer.cs @@ -22,7 +22,11 @@ public KafkaContainer(KafkaConfiguration configuration) /// The broker address. public string GetBootstrapAddress() { - return new UriBuilder("PLAINTEXT", Hostname, GetMappedPublicPort(KafkaBuilder.KafkaPort)).ToString(); + return new UriBuilder( + "PLAINTEXT", + Hostname, + GetMappedPublicPort(KafkaBuilder.KafkaPort) + ).ToString(); } /// @@ -30,9 +34,6 @@ public string GetBootstrapAddress() /// public IEnumerable AdvertisedListeners { - get - { - return _configuration.AdvertisedListeners; - } + get { return _configuration.AdvertisedListeners; } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Kafka/KafkaVendor.cs b/src/Testcontainers.Kafka/KafkaVendor.cs index 43bba99ed..b42a51611 100644 --- a/src/Testcontainers.Kafka/KafkaVendor.cs +++ b/src/Testcontainers.Kafka/KafkaVendor.cs @@ -16,4 +16,4 @@ public enum KafkaVendor /// extra features. /// Confluent, -} \ No newline at end of file +} diff --git a/src/Testcontainers.Kafka/Testcontainers.Kafka.csproj b/src/Testcontainers.Kafka/Testcontainers.Kafka.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Kafka/Testcontainers.Kafka.csproj +++ b/src/Testcontainers.Kafka/Testcontainers.Kafka.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Kafka/Usings.cs b/src/Testcontainers.Kafka/Usings.cs index cb20b6cdd..a826d02aa 100644 --- a/src/Testcontainers.Kafka/Usings.cs +++ b/src/Testcontainers.Kafka/Usings.cs @@ -9,4 +9,4 @@ global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; global using DotNet.Testcontainers.Images; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Keycloak/KeycloakBuilder.cs b/src/Testcontainers.Keycloak/KeycloakBuilder.cs index d3d406dc3..d02cac603 100644 --- a/src/Testcontainers.Keycloak/KeycloakBuilder.cs +++ b/src/Testcontainers.Keycloak/KeycloakBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Keycloak; /// [PublicAPI] -public sealed class KeycloakBuilder : ContainerBuilder +public sealed class KeycloakBuilder + : ContainerBuilder { public const string KeycloakImage = "quay.io/keycloak/keycloak:21.1"; @@ -70,13 +71,20 @@ public override KeycloakContainer Build() var image = DockerResourceConfiguration.Image; // https://www.keycloak.org/docs/latest/release_notes/index.html#management-port-for-metrics-and-health-endpoints. - var isMajorVersionGreaterOrEqual25 = image.MatchLatestOrNightly() || image.MatchVersion(predicate); + var isMajorVersionGreaterOrEqual25 = + image.MatchLatestOrNightly() || image.MatchVersion(predicate); var waitStrategy = Wait.ForUnixContainer() .UntilHttpRequestIsSucceeded(request => - request.ForPath("/health/ready").ForPort(isMajorVersionGreaterOrEqual25 ? KeycloakHealthPort : KeycloakPort)); - - var keycloakBuilder = DockerResourceConfiguration.WaitStrategies.Count() > 1 ? this : WithWaitStrategy(waitStrategy); + request + .ForPath("/health/ready") + .ForPort(isMajorVersionGreaterOrEqual25 ? KeycloakHealthPort : KeycloakPort) + ); + + var keycloakBuilder = + DockerResourceConfiguration.WaitStrategies.Count() > 1 + ? this + : WithWaitStrategy(waitStrategy); return new KeycloakContainer(keycloakBuilder.DockerResourceConfiguration); } @@ -98,17 +106,27 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Username, nameof(DockerResourceConfiguration.Username)) + _ = Guard + .Argument( + DockerResourceConfiguration.Username, + nameof(DockerResourceConfiguration.Username) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override KeycloakBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override KeycloakBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new KeycloakConfiguration(resourceConfiguration)); } @@ -120,8 +138,11 @@ protected override KeycloakBuilder Clone(IContainerConfiguration resourceConfigu } /// - protected override KeycloakBuilder Merge(KeycloakConfiguration oldValue, KeycloakConfiguration newValue) + protected override KeycloakBuilder Merge( + KeycloakConfiguration oldValue, + KeycloakConfiguration newValue + ) { return new KeycloakBuilder(new KeycloakConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Keycloak/KeycloakConfiguration.cs b/src/Testcontainers.Keycloak/KeycloakConfiguration.cs index b1b2937e8..54d239949 100644 --- a/src/Testcontainers.Keycloak/KeycloakConfiguration.cs +++ b/src/Testcontainers.Keycloak/KeycloakConfiguration.cs @@ -19,7 +19,9 @@ public KeycloakConfiguration(string username = null, string password = null) /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public KeycloakConfiguration(IResourceConfiguration resourceConfiguration) + public KeycloakConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -66,4 +68,4 @@ public KeycloakConfiguration(KeycloakConfiguration oldValue, KeycloakConfigurati /// Gets the admin password. /// public string Password { get; } = null!; -} \ No newline at end of file +} diff --git a/src/Testcontainers.Keycloak/KeycloakContainer.cs b/src/Testcontainers.Keycloak/KeycloakContainer.cs index 526aec6a1..4aff00093 100644 --- a/src/Testcontainers.Keycloak/KeycloakContainer.cs +++ b/src/Testcontainers.Keycloak/KeycloakContainer.cs @@ -9,9 +9,7 @@ public sealed class KeycloakContainer : DockerContainer /// /// The container configuration. public KeycloakContainer(KeycloakConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Keycloak base address. @@ -19,6 +17,10 @@ public KeycloakContainer(KeycloakConfiguration configuration) /// The Keycloak base address. public string GetBaseAddress() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(KeycloakBuilder.KeycloakPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(KeycloakBuilder.KeycloakPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Keycloak/Testcontainers.Keycloak.csproj b/src/Testcontainers.Keycloak/Testcontainers.Keycloak.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Keycloak/Testcontainers.Keycloak.csproj +++ b/src/Testcontainers.Keycloak/Testcontainers.Keycloak.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Keycloak/Usings.cs b/src/Testcontainers.Keycloak/Usings.cs index f82c6873d..e8535f53b 100644 --- a/src/Testcontainers.Keycloak/Usings.cs +++ b/src/Testcontainers.Keycloak/Usings.cs @@ -5,4 +5,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Kusto/KustoBuilder.cs b/src/Testcontainers.Kusto/KustoBuilder.cs index a946ecde1..ae612a6f5 100644 --- a/src/Testcontainers.Kusto/KustoBuilder.cs +++ b/src/Testcontainers.Kusto/KustoBuilder.cs @@ -6,7 +6,8 @@ namespace Testcontainers.Kusto; /// https://learn.microsoft.com/azure/data-explorer/kusto-emulator-overview. /// [PublicAPI] -public sealed class KustoBuilder : ContainerBuilder +public sealed class KustoBuilder + : ContainerBuilder { public const string KustoImage = "mcr.microsoft.com/azuredataexplorer/kustainer-linux:latest"; @@ -48,15 +49,28 @@ protected override KustoBuilder Init() .WithImage(KustoImage) .WithPortBinding(KustoPort, true) .WithEnvironment("ACCEPT_EULA", "Y") - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => request - .WithMethod(HttpMethod.Post) - .ForPort(KustoPort) - .ForPath("/v1/rest/mgmt") - .WithContent(() => new StringContent("{\"csl\":\".show cluster\"}", Encoding.Default, "application/json")))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request + .WithMethod(HttpMethod.Post) + .ForPort(KustoPort) + .ForPath("/v1/rest/mgmt") + .WithContent(() => + new StringContent( + "{\"csl\":\".show cluster\"}", + Encoding.Default, + "application/json" + ) + ) + ) + ); } /// - protected override KustoBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override KustoBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new KustoConfiguration(resourceConfiguration)); } @@ -72,4 +86,4 @@ protected override KustoBuilder Merge(KustoConfiguration oldValue, KustoConfigur { return new KustoBuilder(new KustoConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Kusto/KustoConfiguration.cs b/src/Testcontainers.Kusto/KustoConfiguration.cs index ef49aab0d..d6bc3f10f 100644 --- a/src/Testcontainers.Kusto/KustoConfiguration.cs +++ b/src/Testcontainers.Kusto/KustoConfiguration.cs @@ -7,15 +7,15 @@ public sealed class KustoConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public KustoConfiguration() - { - } + public KustoConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public KustoConfiguration(IResourceConfiguration resourceConfiguration) + public KustoConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public KustoConfiguration(KustoConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public KustoConfiguration(KustoConfiguration oldValue, KustoConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Kusto/KustoContainer.cs b/src/Testcontainers.Kusto/KustoContainer.cs index 05599e180..b8a93938a 100644 --- a/src/Testcontainers.Kusto/KustoContainer.cs +++ b/src/Testcontainers.Kusto/KustoContainer.cs @@ -9,9 +9,7 @@ public sealed class KustoContainer : DockerContainer /// /// The container configuration. public KustoContainer(KustoConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Kusto connection string. @@ -19,6 +17,10 @@ public KustoContainer(KustoConfiguration configuration) /// The Kusto connection string. public string GetConnectionString() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(KustoBuilder.KustoPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(KustoBuilder.KustoPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Kusto/Testcontainers.Kusto.csproj b/src/Testcontainers.Kusto/Testcontainers.Kusto.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Kusto/Testcontainers.Kusto.csproj +++ b/src/Testcontainers.Kusto/Testcontainers.Kusto.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Kusto/Usings.cs b/src/Testcontainers.Kusto/Usings.cs index 1ea451a51..6bb9bef19 100644 --- a/src/Testcontainers.Kusto/Usings.cs +++ b/src/Testcontainers.Kusto/Usings.cs @@ -5,4 +5,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.LocalStack/LocalStackBuilder.cs b/src/Testcontainers.LocalStack/LocalStackBuilder.cs index 3bfdca00c..7b68b7ae2 100644 --- a/src/Testcontainers.LocalStack/LocalStackBuilder.cs +++ b/src/Testcontainers.LocalStack/LocalStackBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.LocalStack; /// [PublicAPI] -public sealed class LocalStackBuilder : ContainerBuilder +public sealed class LocalStackBuilder + : ContainerBuilder { public const string LocalStackImage = "localstack/localstack:2.0"; @@ -43,25 +44,40 @@ protected override LocalStackBuilder Init() return base.Init() .WithImage(LocalStackImage) .WithPortBinding(LocalStackPort, true) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPath("/_localstack/health").ForPort(LocalStackPort))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request.ForPath("/_localstack/health").ForPort(LocalStackPort) + ) + ); } /// - protected override LocalStackBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override LocalStackBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new LocalStackConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new LocalStackConfiguration(resourceConfiguration) + ); } /// protected override LocalStackBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new LocalStackConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new LocalStackConfiguration(resourceConfiguration) + ); } /// - protected override LocalStackBuilder Merge(LocalStackConfiguration oldValue, LocalStackConfiguration newValue) + protected override LocalStackBuilder Merge( + LocalStackConfiguration oldValue, + LocalStackConfiguration newValue + ) { return new LocalStackBuilder(new LocalStackConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.LocalStack/LocalStackConfiguration.cs b/src/Testcontainers.LocalStack/LocalStackConfiguration.cs index 2e53b55fc..bcc24f12f 100644 --- a/src/Testcontainers.LocalStack/LocalStackConfiguration.cs +++ b/src/Testcontainers.LocalStack/LocalStackConfiguration.cs @@ -7,15 +7,15 @@ public sealed class LocalStackConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public LocalStackConfiguration() - { - } + public LocalStackConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public LocalStackConfiguration(IResourceConfiguration resourceConfiguration) + public LocalStackConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -46,8 +46,9 @@ public LocalStackConfiguration(LocalStackConfiguration resourceConfiguration) /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public LocalStackConfiguration(LocalStackConfiguration oldValue, LocalStackConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + public LocalStackConfiguration( + LocalStackConfiguration oldValue, + LocalStackConfiguration newValue + ) + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.LocalStack/LocalStackContainer.cs b/src/Testcontainers.LocalStack/LocalStackContainer.cs index a65f776ea..39246c437 100644 --- a/src/Testcontainers.LocalStack/LocalStackContainer.cs +++ b/src/Testcontainers.LocalStack/LocalStackContainer.cs @@ -9,9 +9,7 @@ public sealed class LocalStackContainer : DockerContainer /// /// The container configuration. public LocalStackContainer(LocalStackConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the LocalStack connection string. @@ -19,6 +17,10 @@ public LocalStackContainer(LocalStackConfiguration configuration) /// The LocalStack connection string. public string GetConnectionString() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(LocalStackBuilder.LocalStackPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(LocalStackBuilder.LocalStackPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.LocalStack/Testcontainers.LocalStack.csproj b/src/Testcontainers.LocalStack/Testcontainers.LocalStack.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.LocalStack/Testcontainers.LocalStack.csproj +++ b/src/Testcontainers.LocalStack/Testcontainers.LocalStack.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.LocalStack/Usings.cs b/src/Testcontainers.LocalStack/Usings.cs index 79fd3af9b..b31708db0 100644 --- a/src/Testcontainers.LocalStack/Usings.cs +++ b/src/Testcontainers.LocalStack/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.LowkeyVault/LowkeyVaultBuilder.cs b/src/Testcontainers.LowkeyVault/LowkeyVaultBuilder.cs index 2294a9a86..beac99bce 100644 --- a/src/Testcontainers.LowkeyVault/LowkeyVaultBuilder.cs +++ b/src/Testcontainers.LowkeyVault/LowkeyVaultBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.LowkeyVault; /// [PublicAPI] -public sealed class LowkeyVaultBuilder : ContainerBuilder +public sealed class LowkeyVaultBuilder + : ContainerBuilder { public const string LowkeyVaultImage = "nagyesta/lowkey-vault:2.7.1-ubi9-minimal"; @@ -43,7 +44,10 @@ private LowkeyVaultBuilder(LowkeyVaultConfiguration dockerResourceConfiguration) /// A configured instance of . public LowkeyVaultBuilder WithArguments(IEnumerable arguments) { - return Merge(DockerResourceConfiguration, new LowkeyVaultConfiguration(arguments: arguments)); + return Merge( + DockerResourceConfiguration, + new LowkeyVaultConfiguration(arguments: arguments) + ); } /// @@ -51,7 +55,10 @@ public override LowkeyVaultContainer Build() { Validate(); - var lowkeyVaultBusBuilder = WithEnvironment("LOWKEY_ARGS", string.Join(" ", DockerResourceConfiguration.Arguments)); + var lowkeyVaultBusBuilder = WithEnvironment( + "LOWKEY_ARGS", + string.Join(" ", DockerResourceConfiguration.Arguments) + ); return new LowkeyVaultContainer(lowkeyVaultBusBuilder.DockerResourceConfiguration); } @@ -63,24 +70,37 @@ protected override LowkeyVaultBuilder Init() .WithPortBinding(LowkeyVaultPort, true) .WithPortBinding(LowkeyVaultTokenPort, true) .WithArguments(new[] { "--LOWKEY_VAULT_RELAXED_PORTS=true" }) - .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("(?s).*Started LowkeyVaultApp.*$")); + .WithWaitStrategy( + Wait.ForUnixContainer().UntilMessageIsLogged("(?s).*Started LowkeyVaultApp.*$") + ); } /// - protected override LowkeyVaultBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override LowkeyVaultBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new LowkeyVaultConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new LowkeyVaultConfiguration(resourceConfiguration) + ); } /// protected override LowkeyVaultBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new LowkeyVaultConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new LowkeyVaultConfiguration(resourceConfiguration) + ); } /// - protected override LowkeyVaultBuilder Merge(LowkeyVaultConfiguration oldValue, LowkeyVaultConfiguration newValue) + protected override LowkeyVaultBuilder Merge( + LowkeyVaultConfiguration oldValue, + LowkeyVaultConfiguration newValue + ) { return new LowkeyVaultBuilder(new LowkeyVaultConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.LowkeyVault/LowkeyVaultConfiguration.cs b/src/Testcontainers.LowkeyVault/LowkeyVaultConfiguration.cs index 69a72550d..2f63ab978 100644 --- a/src/Testcontainers.LowkeyVault/LowkeyVaultConfiguration.cs +++ b/src/Testcontainers.LowkeyVault/LowkeyVaultConfiguration.cs @@ -17,7 +17,9 @@ public LowkeyVaultConfiguration(IEnumerable arguments = null) /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public LowkeyVaultConfiguration(IResourceConfiguration resourceConfiguration) + public LowkeyVaultConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -48,7 +50,10 @@ public LowkeyVaultConfiguration(LowkeyVaultConfiguration resourceConfiguration) /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public LowkeyVaultConfiguration(LowkeyVaultConfiguration oldValue, LowkeyVaultConfiguration newValue) + public LowkeyVaultConfiguration( + LowkeyVaultConfiguration oldValue, + LowkeyVaultConfiguration newValue + ) : base(oldValue, newValue) { Arguments = BuildConfiguration.Combine(oldValue.Arguments, newValue.Arguments); @@ -58,4 +63,4 @@ public LowkeyVaultConfiguration(LowkeyVaultConfiguration oldValue, LowkeyVaultCo /// Gets the arguments that are added to the LOWKEY_ARGS environment variable. /// public IEnumerable Arguments { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.LowkeyVault/LowkeyVaultContainer.cs b/src/Testcontainers.LowkeyVault/LowkeyVaultContainer.cs index 9d53942dd..43c07354e 100644 --- a/src/Testcontainers.LowkeyVault/LowkeyVaultContainer.cs +++ b/src/Testcontainers.LowkeyVault/LowkeyVaultContainer.cs @@ -9,9 +9,7 @@ public sealed class LowkeyVaultContainer : DockerContainer /// /// The container configuration. public LowkeyVaultContainer(LowkeyVaultConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the base HTTPS address for the Lowkey Vault service. @@ -19,7 +17,11 @@ public LowkeyVaultContainer(LowkeyVaultConfiguration configuration) /// The base address URL. public string GetBaseAddress() { - return new UriBuilder(Uri.UriSchemeHttps, Hostname, GetMappedPublicPort(LowkeyVaultBuilder.LowkeyVaultPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttps, + Hostname, + GetMappedPublicPort(LowkeyVaultBuilder.LowkeyVaultPort) + ).ToString(); } /// @@ -29,7 +31,12 @@ public string GetBaseAddress() public string GetAuthTokenUrl() { const string identityAuthTokenUriPath = "/metadata/identity/oauth2/token"; - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(LowkeyVaultBuilder.LowkeyVaultTokenPort), identityAuthTokenUriPath).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(LowkeyVaultBuilder.LowkeyVaultTokenPort), + identityAuthTokenUriPath + ).ToString(); } /// @@ -40,22 +47,28 @@ public async Task GetCertificateAsync() { const string defaultCertFilePathUriPath = "/metadata/default-cert/lowkey-vault.p12"; - var requestUri = new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(LowkeyVaultBuilder.LowkeyVaultTokenPort), defaultCertFilePathUriPath).Uri; + var requestUri = new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(LowkeyVaultBuilder.LowkeyVaultTokenPort), + defaultCertFilePathUriPath + ).Uri; using var httpClient = new HttpClient(); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); - using var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage) + using var httpResponseMessage = await httpClient + .SendAsync(httpRequestMessage) .ConfigureAwait(false); httpResponseMessage.EnsureSuccessStatusCode(); - var certificateBytes = await httpResponseMessage.Content.ReadAsByteArrayAsync() + var certificateBytes = await httpResponseMessage + .Content.ReadAsByteArrayAsync() .ConfigureAwait(false); - var certificatePassword = await GetCertificatePasswordAsync() - .ConfigureAwait(false); + var certificatePassword = await GetCertificatePasswordAsync().ConfigureAwait(false); #if NET9_0_OR_GREATER return X509CertificateLoader.LoadPkcs12Collection(certificateBytes, certificatePassword); @@ -73,18 +86,23 @@ public async Task GetCertificatePasswordAsync() { const string defaultCertPasswordUriPath = "/metadata/default-cert/password"; - var requestUri = new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(LowkeyVaultBuilder.LowkeyVaultTokenPort), defaultCertPasswordUriPath).Uri; + var requestUri = new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(LowkeyVaultBuilder.LowkeyVaultTokenPort), + defaultCertPasswordUriPath + ).Uri; using var httpClient = new HttpClient(); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); - using var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage) + using var httpResponseMessage = await httpClient + .SendAsync(httpRequestMessage) .ConfigureAwait(false); httpResponseMessage.EnsureSuccessStatusCode(); - return await httpResponseMessage.Content.ReadAsStringAsync() - .ConfigureAwait(false); + return await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.LowkeyVault/Testcontainers.LowkeyVault.csproj b/src/Testcontainers.LowkeyVault/Testcontainers.LowkeyVault.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.LowkeyVault/Testcontainers.LowkeyVault.csproj +++ b/src/Testcontainers.LowkeyVault/Testcontainers.LowkeyVault.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.LowkeyVault/Usings.cs b/src/Testcontainers.LowkeyVault/Usings.cs index 74dd2925d..7b9b51176 100644 --- a/src/Testcontainers.LowkeyVault/Usings.cs +++ b/src/Testcontainers.LowkeyVault/Usings.cs @@ -7,4 +7,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.MariaDb/MariaDbBuilder.cs b/src/Testcontainers.MariaDb/MariaDbBuilder.cs index 98c067bc2..f6443b25a 100644 --- a/src/Testcontainers.MariaDb/MariaDbBuilder.cs +++ b/src/Testcontainers.MariaDb/MariaDbBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.MariaDb; /// [PublicAPI] -public sealed class MariaDbBuilder : ContainerBuilder +public sealed class MariaDbBuilder + : ContainerBuilder { public const string MariaDbImage = "mariadb:10.10"; @@ -55,7 +56,12 @@ public MariaDbBuilder WithDatabase(string database) public MariaDbBuilder WithUsername(string username) { return Merge(DockerResourceConfiguration, new MariaDbConfiguration(username: username)) - .WithEnvironment("MARIADB_USER", "root".Equals(username, StringComparison.OrdinalIgnoreCase) ? string.Empty : username); + .WithEnvironment( + "MARIADB_USER", + "root".Equals(username, StringComparison.OrdinalIgnoreCase) + ? string.Empty + : username + ); } /// @@ -77,7 +83,13 @@ public override MariaDbContainer Build() // By default, the base builder waits until the container is running. However, for MariaDb, a more advanced waiting strategy is necessary that requires access to the configured database, username and password. // If the user does not provide a custom waiting strategy, append the default MariaDb waiting strategy. - var mariaDbBuilder = DockerResourceConfiguration.WaitStrategies.Count() > 1 ? this : WithWaitStrategy(Wait.ForUnixContainer().AddCustomWaitStrategy(new WaitUntil(DockerResourceConfiguration))); + var mariaDbBuilder = + DockerResourceConfiguration.WaitStrategies.Count() > 1 + ? this + : WithWaitStrategy( + Wait.ForUnixContainer() + .AddCustomWaitStrategy(new WaitUntil(DockerResourceConfiguration)) + ); return new MariaDbContainer(mariaDbBuilder.DockerResourceConfiguration); } @@ -98,17 +110,27 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Username, nameof(DockerResourceConfiguration.Username)) + _ = Guard + .Argument( + DockerResourceConfiguration.Username, + nameof(DockerResourceConfiguration.Username) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override MariaDbBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override MariaDbBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new MariaDbConfiguration(resourceConfiguration)); } @@ -120,7 +142,10 @@ protected override MariaDbBuilder Clone(IContainerConfiguration resourceConfigur } /// - protected override MariaDbBuilder Merge(MariaDbConfiguration oldValue, MariaDbConfiguration newValue) + protected override MariaDbBuilder Merge( + MariaDbConfiguration oldValue, + MariaDbConfiguration newValue + ) { return new MariaDbBuilder(new MariaDbConfiguration(oldValue, newValue)); } @@ -136,16 +161,22 @@ private sealed class WaitUntil : IWaitUntil /// The container configuration. public WaitUntil(MariaDbConfiguration configuration) { - _command = new List { "mariadb", configuration.Database, "--wait", "--silent", "--execute=SELECT 1;" }; + _command = new List + { + "mariadb", + configuration.Database, + "--wait", + "--silent", + "--execute=SELECT 1;", + }; } /// public async Task UntilAsync(IContainer container) { - var execResult = await container.ExecAsync(_command) - .ConfigureAwait(false); + var execResult = await container.ExecAsync(_command).ConfigureAwait(false); return 0L.Equals(execResult.ExitCode); } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.MariaDb/MariaDbConfiguration.cs b/src/Testcontainers.MariaDb/MariaDbConfiguration.cs index 8b41ef7b8..b6d5795c1 100644 --- a/src/Testcontainers.MariaDb/MariaDbConfiguration.cs +++ b/src/Testcontainers.MariaDb/MariaDbConfiguration.cs @@ -13,7 +13,8 @@ public sealed class MariaDbConfiguration : ContainerConfiguration public MariaDbConfiguration( string database = null, string username = null, - string password = null) + string password = null + ) { Database = database; Username = username; @@ -24,7 +25,9 @@ public MariaDbConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public MariaDbConfiguration(IResourceConfiguration resourceConfiguration) + public MariaDbConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -77,4 +80,4 @@ public MariaDbConfiguration(MariaDbConfiguration oldValue, MariaDbConfiguration /// Gets the MariaDb password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.MariaDb/MariaDbContainer.cs b/src/Testcontainers.MariaDb/MariaDbContainer.cs index a1bb69eb4..68b6a1bc3 100644 --- a/src/Testcontainers.MariaDb/MariaDbContainer.cs +++ b/src/Testcontainers.MariaDb/MariaDbContainer.cs @@ -28,7 +28,10 @@ public string GetConnectionString() properties.Add("Database", _configuration.Database); properties.Add("Uid", _configuration.Username); properties.Add("Pwd", _configuration.Password); - return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value))); + return string.Join( + ";", + properties.Select(property => string.Join("=", property.Key, property.Value)) + ); } /// @@ -37,14 +40,31 @@ public string GetConnectionString() /// The content of the SQL script to execute. /// Cancellation token. /// Task that completes when the SQL script has been executed. - public async Task ExecScriptAsync(string scriptContent, CancellationToken ct = default) + public async Task ExecScriptAsync( + string scriptContent, + CancellationToken ct = default + ) { - var scriptFilePath = string.Join("/", string.Empty, "tmp", Guid.NewGuid().ToString("D"), Path.GetRandomFileName()); + var scriptFilePath = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid().ToString("D"), + Path.GetRandomFileName() + ); - await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.FileMode644, ct) + await CopyAsync( + Encoding.Default.GetBytes(scriptContent), + scriptFilePath, + Unix.FileMode644, + ct + ) .ConfigureAwait(false); - return await ExecAsync(new[] { "mariadb", _configuration.Database, $"--execute=source {scriptFilePath};" }, ct) + return await ExecAsync( + new[] { "mariadb", _configuration.Database, $"--execute=source {scriptFilePath};" }, + ct + ) .ConfigureAwait(false); } @@ -63,6 +83,11 @@ internal Task WriteConfigurationFileAsync(CancellationToken ct = default) config.WriteLine("protocol=TCP"); config.WriteLine($"user={_configuration.Username}"); config.WriteLine($"password={_configuration.Password}"); - return CopyAsync(Encoding.Default.GetBytes(config.ToString()), "/etc/mysql/my.cnf", UnixFileModes.UserRead | UnixFileModes.UserWrite, ct); + return CopyAsync( + Encoding.Default.GetBytes(config.ToString()), + "/etc/mysql/my.cnf", + UnixFileModes.UserRead | UnixFileModes.UserWrite, + ct + ); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.MariaDb/Testcontainers.MariaDb.csproj b/src/Testcontainers.MariaDb/Testcontainers.MariaDb.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.MariaDb/Testcontainers.MariaDb.csproj +++ b/src/Testcontainers.MariaDb/Testcontainers.MariaDb.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.MariaDb/Usings.cs b/src/Testcontainers.MariaDb/Usings.cs index e2b02a51e..3481268bc 100644 --- a/src/Testcontainers.MariaDb/Usings.cs +++ b/src/Testcontainers.MariaDb/Usings.cs @@ -10,4 +10,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Milvus/MilvusBuilder.cs b/src/Testcontainers.Milvus/MilvusBuilder.cs index 44c2d8a60..9b7047dfc 100644 --- a/src/Testcontainers.Milvus/MilvusBuilder.cs +++ b/src/Testcontainers.Milvus/MilvusBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Milvus; /// [PublicAPI] -public sealed class MilvusBuilder : ContainerBuilder +public sealed class MilvusBuilder + : ContainerBuilder { public const string MilvusEtcdConfigFilePath = "/milvus/configs/embedEtcd.yaml"; @@ -12,7 +13,13 @@ public sealed class MilvusBuilder : ContainerBuilder /// Initializes a new instance of the class. @@ -70,12 +77,18 @@ protected override MilvusBuilder Init() .WithEnvironment("ETCD_CONFIG_PATH", MilvusEtcdConfigFilePath) .WithEnvironment("ETCD_DATA_DIR", "/var/lib/milvus/etcd") .WithResourceMapping(EtcdConfig, MilvusEtcdConfigFilePath) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPort(MilvusManagementPort).ForPath("/healthz"))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request.ForPort(MilvusManagementPort).ForPath("/healthz") + ) + ); } /// - protected override MilvusBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override MilvusBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new MilvusConfiguration(resourceConfiguration)); } @@ -87,8 +100,11 @@ protected override MilvusBuilder Clone(IContainerConfiguration resourceConfigura } /// - protected override MilvusBuilder Merge(MilvusConfiguration oldValue, MilvusConfiguration newValue) + protected override MilvusBuilder Merge( + MilvusConfiguration oldValue, + MilvusConfiguration newValue + ) { return new MilvusBuilder(new MilvusConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Milvus/MilvusConfiguration.cs b/src/Testcontainers.Milvus/MilvusConfiguration.cs index 32b7dba70..4ca9a055c 100644 --- a/src/Testcontainers.Milvus/MilvusConfiguration.cs +++ b/src/Testcontainers.Milvus/MilvusConfiguration.cs @@ -7,15 +7,15 @@ public sealed class MilvusConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public MilvusConfiguration() - { - } + public MilvusConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public MilvusConfiguration(IResourceConfiguration resourceConfiguration) + public MilvusConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public MilvusConfiguration(MilvusConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public MilvusConfiguration(MilvusConfiguration oldValue, MilvusConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Milvus/MilvusContainer.cs b/src/Testcontainers.Milvus/MilvusContainer.cs index a856ad421..cf0297206 100644 --- a/src/Testcontainers.Milvus/MilvusContainer.cs +++ b/src/Testcontainers.Milvus/MilvusContainer.cs @@ -9,9 +9,7 @@ public sealed class MilvusContainer : DockerContainer /// /// The container configuration. public MilvusContainer(MilvusConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Milvus endpoint. @@ -19,6 +17,10 @@ public MilvusContainer(MilvusConfiguration configuration) /// The Milvus endpoint. public Uri GetEndpoint() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(MilvusBuilder.MilvusGrpcPort)).Uri; + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(MilvusBuilder.MilvusGrpcPort) + ).Uri; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Milvus/Testcontainers.Milvus.csproj b/src/Testcontainers.Milvus/Testcontainers.Milvus.csproj index cbff16956..fab0ac0d5 100644 --- a/src/Testcontainers.Milvus/Testcontainers.Milvus.csproj +++ b/src/Testcontainers.Milvus/Testcontainers.Milvus.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1;net462 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1;net462 + latest + + + + + + + + diff --git a/src/Testcontainers.Milvus/Usings.cs b/src/Testcontainers.Milvus/Usings.cs index 4ee39f0be..1734e5e13 100644 --- a/src/Testcontainers.Milvus/Usings.cs +++ b/src/Testcontainers.Milvus/Usings.cs @@ -4,4 +4,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Minio/MinioBuilder.cs b/src/Testcontainers.Minio/MinioBuilder.cs index 5373864ea..8a7cc909d 100644 --- a/src/Testcontainers.Minio/MinioBuilder.cs +++ b/src/Testcontainers.Minio/MinioBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Minio; /// [PublicAPI] -public sealed class MinioBuilder : ContainerBuilder +public sealed class MinioBuilder + : ContainerBuilder { public const string MinioImage = "minio/minio:RELEASE.2023-01-31T02-24-19Z"; @@ -72,8 +73,12 @@ protected override MinioBuilder Init() .WithCommand("server", "/data") .WithUsername(DefaultUsername) .WithPassword(DefaultPassword) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPath("/minio/health/ready").ForPort(MinioPort))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request.ForPath("/minio/health/ready").ForPort(MinioPort) + ) + ); } /// @@ -81,17 +86,27 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Username, nameof(DockerResourceConfiguration.Username)) + _ = Guard + .Argument( + DockerResourceConfiguration.Username, + nameof(DockerResourceConfiguration.Username) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override MinioBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override MinioBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new MinioConfiguration(resourceConfiguration)); } @@ -107,4 +122,4 @@ protected override MinioBuilder Merge(MinioConfiguration oldValue, MinioConfigur { return new MinioBuilder(new MinioConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Minio/MinioConfiguration.cs b/src/Testcontainers.Minio/MinioConfiguration.cs index fa2c8d5ce..5d4f5521b 100644 --- a/src/Testcontainers.Minio/MinioConfiguration.cs +++ b/src/Testcontainers.Minio/MinioConfiguration.cs @@ -9,9 +9,7 @@ public sealed class MinioConfiguration : ContainerConfiguration /// /// The Minio database. /// The Minio username. - public MinioConfiguration( - string username = null, - string password = null) + public MinioConfiguration(string username = null, string password = null) { Username = username; Password = password; @@ -21,7 +19,9 @@ public MinioConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public MinioConfiguration(IResourceConfiguration resourceConfiguration) + public MinioConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -68,4 +68,4 @@ public MinioConfiguration(MinioConfiguration oldValue, MinioConfiguration newVal /// Gets the Minio password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Minio/MinioContainer.cs b/src/Testcontainers.Minio/MinioContainer.cs index 656d577a9..ea8f26c6b 100644 --- a/src/Testcontainers.Minio/MinioContainer.cs +++ b/src/Testcontainers.Minio/MinioContainer.cs @@ -40,6 +40,10 @@ public string GetSecretKey() /// The Minio connection string. public string GetConnectionString() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(MinioBuilder.MinioPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(MinioBuilder.MinioPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Minio/Testcontainers.Minio.csproj b/src/Testcontainers.Minio/Testcontainers.Minio.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Minio/Testcontainers.Minio.csproj +++ b/src/Testcontainers.Minio/Testcontainers.Minio.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Minio/Usings.cs b/src/Testcontainers.Minio/Usings.cs index 8e5c20fd5..f89f0c94d 100644 --- a/src/Testcontainers.Minio/Usings.cs +++ b/src/Testcontainers.Minio/Usings.cs @@ -4,4 +4,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.MongoDb/MongoDbBuilder.cs b/src/Testcontainers.MongoDb/MongoDbBuilder.cs index 786c401cd..2177754ef 100644 --- a/src/Testcontainers.MongoDb/MongoDbBuilder.cs +++ b/src/Testcontainers.MongoDb/MongoDbBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.MongoDb; /// [PublicAPI] -public sealed class MongoDbBuilder : ContainerBuilder +public sealed class MongoDbBuilder + : ContainerBuilder { public const string MongoDbImage = "mongo:6.0"; @@ -12,7 +13,8 @@ public sealed class MongoDbBuilder : ContainerBuilder \"" + KeyFileFilePath + "\""); initKeyFileScript.WriteLine("chmod 600 \"" + KeyFileFilePath + "\""); - return Merge(DockerResourceConfiguration, new MongoDbConfiguration(replicaSetName: replicaSetName)) + return Merge( + DockerResourceConfiguration, + new MongoDbConfiguration(replicaSetName: replicaSetName) + ) .WithCommand("--replSet", replicaSetName, "--keyFile", KeyFileFilePath, "--bind_ip_all") - .WithResourceMapping(Encoding.Default.GetBytes(initKeyFileScript.ToString()), InitKeyFileScriptFilePath, Unix.FileMode755); + .WithResourceMapping( + Encoding.Default.GetBytes(initKeyFileScript.ToString()), + InitKeyFileScriptFilePath, + Unix.FileMode755 + ); } /// @@ -101,7 +116,10 @@ public override MongoDbContainer Build() } // If the user does not provide a custom waiting strategy, append the default MongoDb waiting strategy. - var mongoDbBuilder = DockerResourceConfiguration.WaitStrategies.Count() > 1 ? this : WithWaitStrategy(Wait.ForUnixContainer().AddCustomWaitStrategy(waitUntil)); + var mongoDbBuilder = + DockerResourceConfiguration.WaitStrategies.Count() > 1 + ? this + : WithWaitStrategy(Wait.ForUnixContainer().AddCustomWaitStrategy(waitUntil)); return new MongoDbContainer(mongoDbBuilder.DockerResourceConfiguration); } @@ -118,22 +136,42 @@ protected override MongoDbBuilder Init() /// protected override void Validate() { - const string message = "Missing username or password. Both must be specified for a user to be created."; + const string message = + "Missing username or password. Both must be specified for a user to be created."; base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Username, nameof(DockerResourceConfiguration.Username)) + _ = Guard + .Argument( + DockerResourceConfiguration.Username, + nameof(DockerResourceConfiguration.Username) + ) .NotNull(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull(); - _ = Guard.Argument(DockerResourceConfiguration, "Credentials") - .ThrowIf(argument => 1.Equals(new[] { argument.Value.Username, argument.Value.Password }.Count(string.IsNullOrWhiteSpace)), argument => new ArgumentException(message, argument.Name)); + _ = Guard + .Argument(DockerResourceConfiguration, "Credentials") + .ThrowIf( + argument => + 1.Equals( + new[] { argument.Value.Username, argument.Value.Password }.Count( + string.IsNullOrWhiteSpace + ) + ), + argument => new ArgumentException(message, argument.Name) + ); } /// - protected override MongoDbBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override MongoDbBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new MongoDbConfiguration(resourceConfiguration)); } @@ -145,7 +183,10 @@ protected override MongoDbBuilder Clone(IContainerConfiguration resourceConfigur } /// - protected override MongoDbBuilder Merge(MongoDbConfiguration oldValue, MongoDbConfiguration newValue) + protected override MongoDbBuilder Merge( + MongoDbConfiguration oldValue, + MongoDbConfiguration newValue + ) { return new MongoDbBuilder(new MongoDbConfiguration(oldValue, newValue)); } @@ -163,19 +204,27 @@ private sealed class WaitIndicateReadiness : IWaitUntil /// The container configuration. public WaitIndicateReadiness(MongoDbConfiguration configuration) { - _count = string.IsNullOrEmpty(configuration.Username) && string.IsNullOrEmpty(configuration.Password) ? 1 : 2; + _count = + string.IsNullOrEmpty(configuration.Username) + && string.IsNullOrEmpty(configuration.Password) + ? 1 + : 2; } /// public async Task UntilAsync(IContainer container) { - var (stdout, stderr) = await container.GetLogsAsync(since: container.StoppedTime, timestampsEnabled: false) + var (stdout, stderr) = await container + .GetLogsAsync(since: container.StoppedTime, timestampsEnabled: false) .ConfigureAwait(false); - return _count.Equals(Array.Empty() - .Concat(stdout.Split(LineEndings, StringSplitOptions.RemoveEmptyEntries)) - .Concat(stderr.Split(LineEndings, StringSplitOptions.RemoveEmptyEntries)) - .Count(line => line.Contains("Waiting for connections"))); + return _count.Equals( + Array + .Empty() + .Concat(stdout.Split(LineEndings, StringSplitOptions.RemoveEmptyEntries)) + .Concat(stderr.Split(LineEndings, StringSplitOptions.RemoveEmptyEntries)) + .Count(line => line.Contains("Waiting for connections")) + ); } } @@ -190,7 +239,8 @@ private sealed class WaitInitiateReplicaSet : IWaitUntil /// The container configuration. public WaitInitiateReplicaSet(MongoDbConfiguration configuration) { - _scriptContent = $"try{{rs.status()}}catch(e){{rs.initiate({{_id:'{configuration.ReplicaSetName}',members:[{{_id:0,host:'127.0.0.1:27017'}}]}});throw e;}}"; + _scriptContent = + $"try{{rs.status()}}catch(e){{rs.initiate({{_id:'{configuration.ReplicaSetName}',members:[{{_id:0,host:'127.0.0.1:27017'}}]}});throw e;}}"; } /// @@ -202,10 +252,9 @@ public Task UntilAsync(IContainer container) /// private async Task UntilAsync(MongoDbContainer container) { - var execResult = await container.ExecScriptAsync(_scriptContent) - .ConfigureAwait(false); + var execResult = await container.ExecScriptAsync(_scriptContent).ConfigureAwait(false); return 0L.Equals(execResult.ExitCode); } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.MongoDb/MongoDbConfiguration.cs b/src/Testcontainers.MongoDb/MongoDbConfiguration.cs index b069b2959..7845c2c7d 100644 --- a/src/Testcontainers.MongoDb/MongoDbConfiguration.cs +++ b/src/Testcontainers.MongoDb/MongoDbConfiguration.cs @@ -13,7 +13,8 @@ public sealed class MongoDbConfiguration : ContainerConfiguration public MongoDbConfiguration( string username = null, string password = null, - string replicaSetName = null) + string replicaSetName = null + ) { Username = username; Password = password; @@ -24,7 +25,9 @@ public MongoDbConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public MongoDbConfiguration(IResourceConfiguration resourceConfiguration) + public MongoDbConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -60,7 +63,10 @@ public MongoDbConfiguration(MongoDbConfiguration oldValue, MongoDbConfiguration { Username = BuildConfiguration.Combine(oldValue.Username, newValue.Username); Password = BuildConfiguration.Combine(oldValue.Password, newValue.Password); - ReplicaSetName = BuildConfiguration.Combine(oldValue.ReplicaSetName, newValue.ReplicaSetName); + ReplicaSetName = BuildConfiguration.Combine( + oldValue.ReplicaSetName, + newValue.ReplicaSetName + ); } /// @@ -80,4 +86,4 @@ public MongoDbConfiguration(MongoDbConfiguration oldValue, MongoDbConfiguration /// If specified, the container will be started as a single-node replica set. /// public string ReplicaSetName { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.MongoDb/MongoDbContainer.cs b/src/Testcontainers.MongoDb/MongoDbContainer.cs index 10404d62c..05108326c 100644 --- a/src/Testcontainers.MongoDb/MongoDbContainer.cs +++ b/src/Testcontainers.MongoDb/MongoDbContainer.cs @@ -23,7 +23,11 @@ public MongoDbContainer(MongoDbConfiguration configuration) public string GetConnectionString() { // The MongoDb documentation recommends to use percent-encoding for username and password: https://www.mongodb.com/docs/manual/reference/connection-string/. - var endpoint = new UriBuilder("mongodb", Hostname, GetMappedPublicPort(MongoDbBuilder.MongoDbPort)); + var endpoint = new UriBuilder( + "mongodb", + Hostname, + GetMappedPublicPort(MongoDbBuilder.MongoDbPort) + ); endpoint.UserName = Uri.EscapeDataString(_configuration.Username); endpoint.Password = Uri.EscapeDataString(_configuration.Password); endpoint.Query = "?directConnection=true"; @@ -36,11 +40,25 @@ public string GetConnectionString() /// The content of the JavaScript script to execute. /// Cancellation token. /// Task that completes when the JavaScript script has been executed. - public async Task ExecScriptAsync(string scriptContent, CancellationToken ct = default) + public async Task ExecScriptAsync( + string scriptContent, + CancellationToken ct = default + ) { - var scriptFilePath = string.Join("/", string.Empty, "tmp", Guid.NewGuid().ToString("D"), Path.GetRandomFileName()); + var scriptFilePath = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid().ToString("D"), + Path.GetRandomFileName() + ); - await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.FileMode644, ct) + await CopyAsync( + Encoding.Default.GetBytes(scriptContent), + scriptFilePath, + Unix.FileMode644, + ct + ) .ConfigureAwait(false); var whichMongoDbShell = await ExecAsync(new[] { "which", "mongosh" }, ct) @@ -49,14 +67,15 @@ await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.F var command = new[] { whichMongoDbShell.ExitCode == 0 ? "mongosh" : "mongo", - "--username", _configuration.Username, - "--password", _configuration.Password, + "--username", + _configuration.Username, + "--password", + _configuration.Password, "--quiet", "--eval", $"load('{scriptFilePath}')", }; - return await ExecAsync(command, ct) - .ConfigureAwait(false); + return await ExecAsync(command, ct).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.MongoDb/Testcontainers.MongoDb.csproj b/src/Testcontainers.MongoDb/Testcontainers.MongoDb.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.MongoDb/Testcontainers.MongoDb.csproj +++ b/src/Testcontainers.MongoDb/Testcontainers.MongoDb.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.MongoDb/Usings.cs b/src/Testcontainers.MongoDb/Usings.cs index 16243387a..e446cb013 100644 --- a/src/Testcontainers.MongoDb/Usings.cs +++ b/src/Testcontainers.MongoDb/Usings.cs @@ -9,4 +9,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.MsSql/MsSqlBuilder.cs b/src/Testcontainers.MsSql/MsSqlBuilder.cs index 7a5481f6b..99451149d 100644 --- a/src/Testcontainers.MsSql/MsSqlBuilder.cs +++ b/src/Testcontainers.MsSql/MsSqlBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.MsSql; /// [PublicAPI] -public sealed class MsSqlBuilder : ContainerBuilder +public sealed class MsSqlBuilder + : ContainerBuilder { public const string MsSqlImage = "mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04"; @@ -73,13 +74,19 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override MsSqlBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override MsSqlBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new MsSqlConfiguration(resourceConfiguration)); } @@ -140,13 +147,13 @@ public Task UntilAsync(IContainer container) /// private static async Task UntilAsync(MsSqlContainer container) { - var sqlCmdFilePath = await container.GetSqlCmdFilePathAsync() - .ConfigureAwait(false); + var sqlCmdFilePath = await container.GetSqlCmdFilePathAsync().ConfigureAwait(false); - var execResult = await container.ExecAsync(new[] { sqlCmdFilePath, "-C", "-Q", "SELECT 1;" }) + var execResult = await container + .ExecAsync(new[] { sqlCmdFilePath, "-C", "-Q", "SELECT 1;" }) .ConfigureAwait(false); return 0L.Equals(execResult.ExitCode); } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.MsSql/MsSqlConfiguration.cs b/src/Testcontainers.MsSql/MsSqlConfiguration.cs index 0e5e2a486..a1ae55ae5 100644 --- a/src/Testcontainers.MsSql/MsSqlConfiguration.cs +++ b/src/Testcontainers.MsSql/MsSqlConfiguration.cs @@ -13,7 +13,8 @@ public sealed class MsSqlConfiguration : ContainerConfiguration public MsSqlConfiguration( string database = null, string username = null, - string password = null) + string password = null + ) { Database = database; Username = username; @@ -24,7 +25,9 @@ public MsSqlConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public MsSqlConfiguration(IResourceConfiguration resourceConfiguration) + public MsSqlConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -77,4 +80,4 @@ public MsSqlConfiguration(MsSqlConfiguration oldValue, MsSqlConfiguration newVal /// Gets the MsSql password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.MsSql/MsSqlContainer.cs b/src/Testcontainers.MsSql/MsSqlContainer.cs index 6f3b13f1e..364c59b9a 100644 --- a/src/Testcontainers.MsSql/MsSqlContainer.cs +++ b/src/Testcontainers.MsSql/MsSqlContainer.cs @@ -4,7 +4,12 @@ namespace Testcontainers.MsSql; [PublicAPI] public sealed class MsSqlContainer : DockerContainer, IDatabaseContainer { - private static readonly string[] FindSqlCmdFilePath = { "/bin/sh", "-c", "find /opt/mssql-tools*/bin/sqlcmd -type f -print -quit" }; + private static readonly string[] FindSqlCmdFilePath = + { + "/bin/sh", + "-c", + "find /opt/mssql-tools*/bin/sqlcmd -type f -print -quit", + }; private readonly Lazy> _lazySqlCmdFilePath; @@ -33,7 +38,10 @@ public string GetConnectionString() properties.Add("User Id", _configuration.Username); properties.Add("Password", _configuration.Password); properties.Add("TrustServerCertificate", bool.TrueString); - return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value))); + return string.Join( + ";", + properties.Select(property => string.Join("=", property.Key, property.Value)) + ); } /// @@ -55,17 +63,46 @@ public Task GetSqlCmdFilePathAsync(CancellationToken ct = default) /// The content of the SQL script to execute. /// Cancellation token. /// Task that completes when the SQL script has been executed. - public async Task ExecScriptAsync(string scriptContent, CancellationToken ct = default) + public async Task ExecScriptAsync( + string scriptContent, + CancellationToken ct = default + ) { - var scriptFilePath = string.Join("/", string.Empty, "tmp", Guid.NewGuid().ToString("D"), Path.GetRandomFileName()); + var scriptFilePath = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid().ToString("D"), + Path.GetRandomFileName() + ); - var sqlCmdFilePath = await GetSqlCmdFilePathAsync(ct) - .ConfigureAwait(false); + var sqlCmdFilePath = await GetSqlCmdFilePathAsync(ct).ConfigureAwait(false); - await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.FileMode644, ct) + await CopyAsync( + Encoding.Default.GetBytes(scriptContent), + scriptFilePath, + Unix.FileMode644, + ct + ) .ConfigureAwait(false); - return await ExecAsync(new[] { sqlCmdFilePath, "-C", "-b", "-r", "1", "-U", _configuration.Username, "-P", _configuration.Password, "-i", scriptFilePath }, ct) + return await ExecAsync( + new[] + { + sqlCmdFilePath, + "-C", + "-b", + "-r", + "1", + "-U", + _configuration.Username, + "-P", + _configuration.Password, + "-i", + scriptFilePath, + }, + ct + ) .ConfigureAwait(false); } @@ -81,4 +118,4 @@ private async Task FindSqlCmdFilePathAsync() throw new NotSupportedException("The sqlcmd binary could not be found."); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.MsSql/Testcontainers.MsSql.csproj b/src/Testcontainers.MsSql/Testcontainers.MsSql.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.MsSql/Testcontainers.MsSql.csproj +++ b/src/Testcontainers.MsSql/Testcontainers.MsSql.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.MsSql/Usings.cs b/src/Testcontainers.MsSql/Usings.cs index e2b02a51e..3481268bc 100644 --- a/src/Testcontainers.MsSql/Usings.cs +++ b/src/Testcontainers.MsSql/Usings.cs @@ -10,4 +10,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.MySql/MySqlBuilder.cs b/src/Testcontainers.MySql/MySqlBuilder.cs index 91bfc5a9c..7618cdd90 100644 --- a/src/Testcontainers.MySql/MySqlBuilder.cs +++ b/src/Testcontainers.MySql/MySqlBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.MySql; /// [PublicAPI] -public sealed class MySqlBuilder : ContainerBuilder +public sealed class MySqlBuilder + : ContainerBuilder { public const string MySqlImage = "mysql:8.0"; @@ -55,7 +56,12 @@ public MySqlBuilder WithDatabase(string database) public MySqlBuilder WithUsername(string username) { return Merge(DockerResourceConfiguration, new MySqlConfiguration(username: username)) - .WithEnvironment("MYSQL_USER", "root".Equals(username, StringComparison.OrdinalIgnoreCase) ? string.Empty : username); + .WithEnvironment( + "MYSQL_USER", + "root".Equals(username, StringComparison.OrdinalIgnoreCase) + ? string.Empty + : username + ); } /// @@ -77,7 +83,13 @@ public override MySqlContainer Build() // By default, the base builder waits until the container is running. However, for MySql, a more advanced waiting strategy is necessary that requires access to the configured database, username and password. // If the user does not provide a custom waiting strategy, append the default MySql waiting strategy. - var mySqlBuilder = DockerResourceConfiguration.WaitStrategies.Count() > 1 ? this : WithWaitStrategy(Wait.ForUnixContainer().AddCustomWaitStrategy(new WaitUntil(DockerResourceConfiguration))); + var mySqlBuilder = + DockerResourceConfiguration.WaitStrategies.Count() > 1 + ? this + : WithWaitStrategy( + Wait.ForUnixContainer() + .AddCustomWaitStrategy(new WaitUntil(DockerResourceConfiguration)) + ); return new MySqlContainer(mySqlBuilder.DockerResourceConfiguration); } @@ -90,7 +102,13 @@ protected override MySqlBuilder Init() .WithDatabase(DefaultDatabase) .WithUsername(DefaultUsername) .WithPassword(DefaultPassword) - .WithStartupCallback((container, ct) => Task.WhenAll(container.CreateMySqlFilesDirectoryAsync(ct), container.WriteConfigurationFileAsync(ct))); + .WithStartupCallback( + (container, ct) => + Task.WhenAll( + container.CreateMySqlFilesDirectoryAsync(ct), + container.WriteConfigurationFileAsync(ct) + ) + ); } /// @@ -98,17 +116,27 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Username, nameof(DockerResourceConfiguration.Username)) + _ = Guard + .Argument( + DockerResourceConfiguration.Username, + nameof(DockerResourceConfiguration.Username) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override MySqlBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override MySqlBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new MySqlConfiguration(resourceConfiguration)); } @@ -136,16 +164,22 @@ private sealed class WaitUntil : IWaitUntil /// The container configuration. public WaitUntil(MySqlConfiguration configuration) { - _command = new List { "mysql", configuration.Database, "--wait", "--silent", "--execute=SELECT 1;" }; + _command = new List + { + "mysql", + configuration.Database, + "--wait", + "--silent", + "--execute=SELECT 1;", + }; } /// public async Task UntilAsync(IContainer container) { - var execResult = await container.ExecAsync(_command) - .ConfigureAwait(false); + var execResult = await container.ExecAsync(_command).ConfigureAwait(false); return 0L.Equals(execResult.ExitCode); } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.MySql/MySqlConfiguration.cs b/src/Testcontainers.MySql/MySqlConfiguration.cs index b97f020ea..a8c60ea60 100644 --- a/src/Testcontainers.MySql/MySqlConfiguration.cs +++ b/src/Testcontainers.MySql/MySqlConfiguration.cs @@ -13,7 +13,8 @@ public sealed class MySqlConfiguration : ContainerConfiguration public MySqlConfiguration( string database = null, string username = null, - string password = null) + string password = null + ) { Database = database; Username = username; @@ -24,7 +25,9 @@ public MySqlConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public MySqlConfiguration(IResourceConfiguration resourceConfiguration) + public MySqlConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -77,4 +80,4 @@ public MySqlConfiguration(MySqlConfiguration oldValue, MySqlConfiguration newVal /// Gets the MySql password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.MySql/MySqlContainer.cs b/src/Testcontainers.MySql/MySqlContainer.cs index 209625cda..945080404 100644 --- a/src/Testcontainers.MySql/MySqlContainer.cs +++ b/src/Testcontainers.MySql/MySqlContainer.cs @@ -28,7 +28,10 @@ public string GetConnectionString() properties.Add("Database", _configuration.Database); properties.Add("Uid", _configuration.Username); properties.Add("Pwd", _configuration.Password); - return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value))); + return string.Join( + ";", + properties.Select(property => string.Join("=", property.Key, property.Value)) + ); } /// @@ -37,14 +40,31 @@ public string GetConnectionString() /// The content of the SQL script to execute. /// Cancellation token. /// Task that completes when the SQL script has been executed. - public async Task ExecScriptAsync(string scriptContent, CancellationToken ct = default) + public async Task ExecScriptAsync( + string scriptContent, + CancellationToken ct = default + ) { - var scriptFilePath = string.Join("/", string.Empty, "tmp", Guid.NewGuid().ToString("D"), Path.GetRandomFileName()); + var scriptFilePath = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid().ToString("D"), + Path.GetRandomFileName() + ); - await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.FileMode644, ct) + await CopyAsync( + Encoding.Default.GetBytes(scriptContent), + scriptFilePath, + Unix.FileMode644, + ct + ) .ConfigureAwait(false); - return await ExecAsync(new[] { "mysql", _configuration.Database, $"--execute=source {scriptFilePath};" }, ct) + return await ExecAsync( + new[] { "mysql", _configuration.Database, $"--execute=source {scriptFilePath};" }, + ct + ) .ConfigureAwait(false); } @@ -77,6 +97,11 @@ internal Task WriteConfigurationFileAsync(CancellationToken ct = default) config.WriteLine("protocol=TCP"); config.WriteLine($"user={_configuration.Username}"); config.WriteLine($"password={_configuration.Password}"); - return CopyAsync(Encoding.Default.GetBytes(config.ToString()), "/etc/mysql/my.cnf", UnixFileModes.UserRead | UnixFileModes.UserWrite, ct); + return CopyAsync( + Encoding.Default.GetBytes(config.ToString()), + "/etc/mysql/my.cnf", + UnixFileModes.UserRead | UnixFileModes.UserWrite, + ct + ); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.MySql/Testcontainers.MySql.csproj b/src/Testcontainers.MySql/Testcontainers.MySql.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.MySql/Testcontainers.MySql.csproj +++ b/src/Testcontainers.MySql/Testcontainers.MySql.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.MySql/Usings.cs b/src/Testcontainers.MySql/Usings.cs index e2b02a51e..3481268bc 100644 --- a/src/Testcontainers.MySql/Usings.cs +++ b/src/Testcontainers.MySql/Usings.cs @@ -10,4 +10,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Nats/NatsBuilder.cs b/src/Testcontainers.Nats/NatsBuilder.cs index eaea58cca..365fa6083 100644 --- a/src/Testcontainers.Nats/NatsBuilder.cs +++ b/src/Testcontainers.Nats/NatsBuilder.cs @@ -87,18 +87,37 @@ protected override void Validate() base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Username, nameof(DockerResourceConfiguration.Username)) + _ = Guard + .Argument( + DockerResourceConfiguration.Username, + nameof(DockerResourceConfiguration.Username) + ) .NotNull(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull(); - _ = Guard.Argument(DockerResourceConfiguration, "Credentials") - .ThrowIf(argument => 1.Equals(new[] { argument.Value.Username, argument.Value.Password }.Count(string.IsNullOrWhiteSpace)), argument => new ArgumentException(message, argument.Name)); + _ = Guard + .Argument(DockerResourceConfiguration, "Credentials") + .ThrowIf( + argument => + 1.Equals( + new[] { argument.Value.Username, argument.Value.Password }.Count( + string.IsNullOrWhiteSpace + ) + ), + argument => new ArgumentException(message, argument.Name) + ); } /// - protected override NatsBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override NatsBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new NatsConfiguration(resourceConfiguration)); } @@ -114,4 +133,4 @@ protected override NatsBuilder Merge(NatsConfiguration oldValue, NatsConfigurati { return new NatsBuilder(new NatsConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Nats/NatsConfiguration.cs b/src/Testcontainers.Nats/NatsConfiguration.cs index 4c410b773..05362f0a8 100644 --- a/src/Testcontainers.Nats/NatsConfiguration.cs +++ b/src/Testcontainers.Nats/NatsConfiguration.cs @@ -9,9 +9,7 @@ public sealed class NatsConfiguration : ContainerConfiguration /// /// The Nats username. /// The Nats password. - public NatsConfiguration( - string username = null, - string password = null) + public NatsConfiguration(string username = null, string password = null) { Username = username; Password = password; @@ -21,7 +19,9 @@ public NatsConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public NatsConfiguration(IResourceConfiguration resourceConfiguration) + public NatsConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -68,4 +68,4 @@ public NatsConfiguration(NatsConfiguration oldValue, NatsConfiguration newValue) /// The Nats password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Nats/NatsContainer.cs b/src/Testcontainers.Nats/NatsContainer.cs index 24f3e80fc..89a14eb59 100644 --- a/src/Testcontainers.Nats/NatsContainer.cs +++ b/src/Testcontainers.Nats/NatsContainer.cs @@ -25,7 +25,11 @@ public NatsContainer(NatsConfiguration configuration) /// A Nats connection string in the format: nats://hostname:port. public string GetConnectionString() { - var endpoint = new UriBuilder("nats", Hostname, GetMappedPublicPort(NatsBuilder.NatsClientPort)); + var endpoint = new UriBuilder( + "nats", + Hostname, + GetMappedPublicPort(NatsBuilder.NatsClientPort) + ); endpoint.UserName = Uri.EscapeDataString(_configuration.Username); endpoint.Password = Uri.EscapeDataString(_configuration.Password); return endpoint.ToString(); @@ -37,6 +41,10 @@ public string GetConnectionString() /// An HTTP address in the format: http://hostname:port. public string GetManagementEndpoint() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(NatsBuilder.NatsHttpManagementPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(NatsBuilder.NatsHttpManagementPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Nats/Testcontainers.Nats.csproj b/src/Testcontainers.Nats/Testcontainers.Nats.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Nats/Testcontainers.Nats.csproj +++ b/src/Testcontainers.Nats/Testcontainers.Nats.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Nats/Usings.cs b/src/Testcontainers.Nats/Usings.cs index f82c6873d..e8535f53b 100644 --- a/src/Testcontainers.Nats/Usings.cs +++ b/src/Testcontainers.Nats/Usings.cs @@ -5,4 +5,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Neo4j/Neo4jBuilder.cs b/src/Testcontainers.Neo4j/Neo4jBuilder.cs index 399076936..f92f658cf 100644 --- a/src/Testcontainers.Neo4j/Neo4jBuilder.cs +++ b/src/Testcontainers.Neo4j/Neo4jBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Neo4j; /// [PublicAPI] -public sealed class Neo4jBuilder : ContainerBuilder +public sealed class Neo4jBuilder + : ContainerBuilder { public const string Neo4jImage = "neo4j:5.4"; @@ -33,7 +34,8 @@ private Neo4jBuilder(Neo4jConfiguration resourceConfiguration) protected override Neo4jConfiguration DockerResourceConfiguration { get; } /// - protected override string AcceptLicenseAgreementEnvVar { get; } = "NEO4J_ACCEPT_LICENSE_AGREEMENT"; + protected override string AcceptLicenseAgreementEnvVar { get; } = + "NEO4J_ACCEPT_LICENSE_AGREEMENT"; /// protected override string AcceptLicenseAgreement { get; } = "yes"; @@ -84,18 +86,32 @@ public Neo4jBuilder WithEnterpriseEdition(bool acceptLicenseAgreement) else if (image.MatchVersion(v => Array.Exists(operatingSystems, v.Contains))) { MatchEvaluator evaluator = match => $"{enterpriseSuffix}-{match.Value}"; - tag = Regex.Replace(image.Tag, string.Join("|", operatingSystems), evaluator, RegexOptions.None, TimeSpan.FromSeconds(1)); + tag = Regex.Replace( + image.Tag, + string.Join("|", operatingSystems), + evaluator, + RegexOptions.None, + TimeSpan.FromSeconds(1) + ); } else { tag = $"{image.Tag}-{enterpriseSuffix}"; } - var enterpriseImage = new DockerImage(image.Repository, image.Registry, tag, tag == null ? image.Digest : null); + var enterpriseImage = new DockerImage( + image.Repository, + image.Registry, + tag, + tag == null ? image.Digest : null + ); - var licenseAgreement = acceptLicenseAgreement ? AcceptLicenseAgreement : DeclineLicenseAgreement; + var licenseAgreement = acceptLicenseAgreement + ? AcceptLicenseAgreement + : DeclineLicenseAgreement; - return WithImage(enterpriseImage).WithEnvironment(AcceptLicenseAgreementEnvVar, licenseAgreement); + return WithImage(enterpriseImage) + .WithEnvironment(AcceptLicenseAgreementEnvVar, licenseAgreement); } /// @@ -112,11 +128,26 @@ protected override void Validate() base.Validate(); - Predicate licenseAgreementNotAccepted = value => value.Image.Tag != null && value.Image.Tag.Contains("enterprise") - && (!value.Environments.TryGetValue(AcceptLicenseAgreementEnvVar, out var licenseAgreementValue) || !AcceptLicenseAgreement.Equals(licenseAgreementValue, StringComparison.Ordinal)); - - _ = Guard.Argument(DockerResourceConfiguration, nameof(DockerResourceConfiguration.Image)) - .ThrowIf(argument => licenseAgreementNotAccepted(argument.Value), argument => throw new ArgumentException(string.Format(message, DockerResourceConfiguration.Image.FullName), argument.Name)); + Predicate licenseAgreementNotAccepted = value => + value.Image.Tag != null + && value.Image.Tag.Contains("enterprise") + && ( + !value.Environments.TryGetValue( + AcceptLicenseAgreementEnvVar, + out var licenseAgreementValue + ) || !AcceptLicenseAgreement.Equals(licenseAgreementValue, StringComparison.Ordinal) + ); + + _ = Guard + .Argument(DockerResourceConfiguration, nameof(DockerResourceConfiguration.Image)) + .ThrowIf( + argument => licenseAgreementNotAccepted(argument.Value), + argument => + throw new ArgumentException( + string.Format(message, DockerResourceConfiguration.Image.FullName), + argument.Name + ) + ); } /// @@ -127,12 +158,18 @@ protected override Neo4jBuilder Init() .WithPortBinding(Neo4jHttpPort, true) .WithPortBinding(Neo4jBoltPort, true) .WithEnvironment("NEO4J_AUTH", "none") - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPath("/").ForPort(Neo4jHttpPort))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request.ForPath("/").ForPort(Neo4jHttpPort) + ) + ); } /// - protected override Neo4jBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override Neo4jBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new Neo4jConfiguration(resourceConfiguration)); } @@ -148,4 +185,4 @@ protected override Neo4jBuilder Merge(Neo4jConfiguration oldValue, Neo4jConfigur { return new Neo4jBuilder(new Neo4jConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Neo4j/Neo4jConfiguration.cs b/src/Testcontainers.Neo4j/Neo4jConfiguration.cs index 422e695ee..15be4e2a1 100644 --- a/src/Testcontainers.Neo4j/Neo4jConfiguration.cs +++ b/src/Testcontainers.Neo4j/Neo4jConfiguration.cs @@ -7,15 +7,15 @@ public sealed class Neo4jConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public Neo4jConfiguration() - { - } + public Neo4jConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public Neo4jConfiguration(IResourceConfiguration resourceConfiguration) + public Neo4jConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public Neo4jConfiguration(Neo4jConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public Neo4jConfiguration(Neo4jConfiguration oldValue, Neo4jConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Neo4j/Neo4jContainer.cs b/src/Testcontainers.Neo4j/Neo4jContainer.cs index cbc5c7e35..fb723701e 100644 --- a/src/Testcontainers.Neo4j/Neo4jContainer.cs +++ b/src/Testcontainers.Neo4j/Neo4jContainer.cs @@ -9,9 +9,7 @@ public sealed class Neo4jContainer : DockerContainer /// /// The container configuration. public Neo4jContainer(Neo4jConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Neo4j connection string. @@ -19,6 +17,10 @@ public Neo4jContainer(Neo4jConfiguration configuration) /// The Neo4j connection string. public string GetConnectionString() { - return new UriBuilder("neo4j", Hostname, GetMappedPublicPort(Neo4jBuilder.Neo4jBoltPort)).ToString(); + return new UriBuilder( + "neo4j", + Hostname, + GetMappedPublicPort(Neo4jBuilder.Neo4jBoltPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Neo4j/Testcontainers.Neo4j.csproj b/src/Testcontainers.Neo4j/Testcontainers.Neo4j.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Neo4j/Testcontainers.Neo4j.csproj +++ b/src/Testcontainers.Neo4j/Testcontainers.Neo4j.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Neo4j/Usings.cs b/src/Testcontainers.Neo4j/Usings.cs index 271ad97d9..7d6803788 100644 --- a/src/Testcontainers.Neo4j/Usings.cs +++ b/src/Testcontainers.Neo4j/Usings.cs @@ -6,4 +6,4 @@ global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; global using DotNet.Testcontainers.Images; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Ollama/OllamaBuilder.cs b/src/Testcontainers.Ollama/OllamaBuilder.cs index 0001de7b8..ca4250b16 100644 --- a/src/Testcontainers.Ollama/OllamaBuilder.cs +++ b/src/Testcontainers.Ollama/OllamaBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Ollama; /// [PublicAPI] -public sealed class OllamaBuilder : ContainerBuilder +public sealed class OllamaBuilder + : ContainerBuilder { public const string OllamaImage = "ollama/ollama:0.6.6"; @@ -43,12 +44,18 @@ protected override OllamaBuilder Init() return base.Init() .WithImage(OllamaImage) .WithPortBinding(OllamaPort, true) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPath("/api/version").ForPort(OllamaPort))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request.ForPath("/api/version").ForPort(OllamaPort) + ) + ); } /// - protected override OllamaBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override OllamaBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new OllamaConfiguration(resourceConfiguration)); } @@ -60,8 +67,11 @@ protected override OllamaBuilder Clone(IContainerConfiguration resourceConfigura } /// - protected override OllamaBuilder Merge(OllamaConfiguration oldValue, OllamaConfiguration newValue) + protected override OllamaBuilder Merge( + OllamaConfiguration oldValue, + OllamaConfiguration newValue + ) { return new OllamaBuilder(new OllamaConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Ollama/OllamaConfiguration.cs b/src/Testcontainers.Ollama/OllamaConfiguration.cs index c520558e4..c4912dfb0 100644 --- a/src/Testcontainers.Ollama/OllamaConfiguration.cs +++ b/src/Testcontainers.Ollama/OllamaConfiguration.cs @@ -7,15 +7,15 @@ public sealed class OllamaConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public OllamaConfiguration() - { - } + public OllamaConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public OllamaConfiguration(IResourceConfiguration resourceConfiguration) + public OllamaConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public OllamaConfiguration(OllamaConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public OllamaConfiguration(OllamaConfiguration oldValue, OllamaConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Ollama/OllamaContainer.cs b/src/Testcontainers.Ollama/OllamaContainer.cs index 0effcf125..af35efd7c 100644 --- a/src/Testcontainers.Ollama/OllamaContainer.cs +++ b/src/Testcontainers.Ollama/OllamaContainer.cs @@ -9,9 +9,7 @@ public sealed class OllamaContainer : DockerContainer /// /// The container configuration. public OllamaContainer(OllamaConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Ollama base address. @@ -19,6 +17,10 @@ public OllamaContainer(OllamaConfiguration configuration) /// The Ollama base address. public string GetBaseAddress() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(OllamaBuilder.OllamaPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(OllamaBuilder.OllamaPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Ollama/Testcontainers.Ollama.csproj b/src/Testcontainers.Ollama/Testcontainers.Ollama.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Ollama/Testcontainers.Ollama.csproj +++ b/src/Testcontainers.Ollama/Testcontainers.Ollama.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Ollama/Usings.cs b/src/Testcontainers.Ollama/Usings.cs index 79fd3af9b..b31708db0 100644 --- a/src/Testcontainers.Ollama/Usings.cs +++ b/src/Testcontainers.Ollama/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.OpenSearch/OpenSearchBuilder.cs b/src/Testcontainers.OpenSearch/OpenSearchBuilder.cs index 50f1e4e5a..1e0c3a0fa 100644 --- a/src/Testcontainers.OpenSearch/OpenSearchBuilder.cs +++ b/src/Testcontainers.OpenSearch/OpenSearchBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.OpenSearch; /// [PublicAPI] -public sealed class OpenSearchBuilder : ContainerBuilder +public sealed class OpenSearchBuilder + : ContainerBuilder { public const string OpenSearchImage = "opensearchproject/opensearch:2.12.0"; @@ -70,8 +71,14 @@ public OpenSearchBuilder WithPassword(string password) /// A configured instance of . public OpenSearchBuilder WithSecurityEnabled(bool securityEnabled = true) { - return Merge(DockerResourceConfiguration, new OpenSearchConfiguration(tlsEnabled: securityEnabled)) - .WithEnvironment("plugins.security.disabled", (!securityEnabled).ToString().ToLowerInvariant()); + return Merge( + DockerResourceConfiguration, + new OpenSearchConfiguration(tlsEnabled: securityEnabled) + ) + .WithEnvironment( + "plugins.security.disabled", + (!securityEnabled).ToString().ToLowerInvariant() + ); } /// @@ -98,7 +105,13 @@ public override OpenSearchContainer Build() // By default, the base builder waits until the container is running. However, for OpenSearch, a more advanced waiting strategy is necessary that requires access to the password. // If the user does not provide a custom waiting strategy, append the default OpenSearch waiting strategy. - openSearchBuilder = DockerResourceConfiguration.WaitStrategies.Count() > 1 ? openSearchBuilder : openSearchBuilder.WithWaitStrategy(Wait.ForUnixContainer().AddCustomWaitStrategy(new WaitUntil(DockerResourceConfiguration))); + openSearchBuilder = + DockerResourceConfiguration.WaitStrategies.Count() > 1 + ? openSearchBuilder + : openSearchBuilder.WithWaitStrategy( + Wait.ForUnixContainer() + .AddCustomWaitStrategy(new WaitUntil(DockerResourceConfiguration)) + ); return new OpenSearchContainer(openSearchBuilder.DockerResourceConfiguration); } @@ -121,25 +134,40 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override OpenSearchBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override OpenSearchBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new OpenSearchConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new OpenSearchConfiguration(resourceConfiguration) + ); } /// protected override OpenSearchBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new OpenSearchConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new OpenSearchConfiguration(resourceConfiguration) + ); } /// - protected override OpenSearchBuilder Merge(OpenSearchConfiguration oldValue, OpenSearchConfiguration newValue) + protected override OpenSearchBuilder Merge( + OpenSearchConfiguration oldValue, + OpenSearchConfiguration newValue + ) { return new OpenSearchBuilder(new OpenSearchConfiguration(oldValue, newValue)); } @@ -189,8 +217,7 @@ public async Task UntilAsync(IContainer container) .WithBasicAuthentication(_username, _password) .ForPort(OpenSearchRestApiPort); - return await httpWaitStrategy.UntilAsync(container) - .ConfigureAwait(false); + return await httpWaitStrategy.UntilAsync(container).ConfigureAwait(false); } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.OpenSearch/OpenSearchConfiguration.cs b/src/Testcontainers.OpenSearch/OpenSearchConfiguration.cs index 613b75cb1..ac21644d5 100644 --- a/src/Testcontainers.OpenSearch/OpenSearchConfiguration.cs +++ b/src/Testcontainers.OpenSearch/OpenSearchConfiguration.cs @@ -13,7 +13,8 @@ public sealed class OpenSearchConfiguration : ContainerConfiguration public OpenSearchConfiguration( bool? tlsEnabled = null, string username = null, - string password = null) + string password = null + ) { TlsEnabled = tlsEnabled; Username = username; @@ -24,35 +25,34 @@ public OpenSearchConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public OpenSearchConfiguration(IResourceConfiguration resourceConfiguration) - : base(resourceConfiguration) - { - } + public OpenSearchConfiguration( + IResourceConfiguration resourceConfiguration + ) + : base(resourceConfiguration) { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. public OpenSearchConfiguration(IContainerConfiguration resourceConfiguration) - : base(resourceConfiguration) - { - } + : base(resourceConfiguration) { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. public OpenSearchConfiguration(OpenSearchConfiguration resourceConfiguration) - : this(new OpenSearchConfiguration(), resourceConfiguration) - { - } + : this(new OpenSearchConfiguration(), resourceConfiguration) { } /// /// Initializes a new instance of the class. /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public OpenSearchConfiguration(OpenSearchConfiguration oldValue, OpenSearchConfiguration newValue) + public OpenSearchConfiguration( + OpenSearchConfiguration oldValue, + OpenSearchConfiguration newValue + ) : base(oldValue, newValue) { TlsEnabled = BuildConfiguration.Combine(oldValue.TlsEnabled, newValue.TlsEnabled); @@ -74,4 +74,4 @@ public OpenSearchConfiguration(OpenSearchConfiguration oldValue, OpenSearchConfi /// Gets the OpenSearch password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.OpenSearch/OpenSearchContainer.cs b/src/Testcontainers.OpenSearch/OpenSearchContainer.cs index 49213a424..a8c9abc11 100644 --- a/src/Testcontainers.OpenSearch/OpenSearchContainer.cs +++ b/src/Testcontainers.OpenSearch/OpenSearchContainer.cs @@ -31,7 +31,13 @@ public NetworkCredential GetCredentials() /// The OpenSearch connection string. public string GetConnectionString() { - var schema = _configuration.TlsEnabled.GetValueOrDefault() ? Uri.UriSchemeHttps : Uri.UriSchemeHttp; - return new UriBuilder(schema, Hostname, GetMappedPublicPort(OpenSearchBuilder.OpenSearchRestApiPort)).ToString(); + var schema = _configuration.TlsEnabled.GetValueOrDefault() + ? Uri.UriSchemeHttps + : Uri.UriSchemeHttp; + return new UriBuilder( + schema, + Hostname, + GetMappedPublicPort(OpenSearchBuilder.OpenSearchRestApiPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.OpenSearch/Testcontainers.OpenSearch.csproj b/src/Testcontainers.OpenSearch/Testcontainers.OpenSearch.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.OpenSearch/Testcontainers.OpenSearch.csproj +++ b/src/Testcontainers.OpenSearch/Testcontainers.OpenSearch.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.OpenSearch/Usings.cs b/src/Testcontainers.OpenSearch/Usings.cs index ca1247a6e..55c0c4d26 100644 --- a/src/Testcontainers.OpenSearch/Usings.cs +++ b/src/Testcontainers.OpenSearch/Usings.cs @@ -8,4 +8,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Oracle/OracleBuilder.cs b/src/Testcontainers.Oracle/OracleBuilder.cs index e6c5710b5..ec80d2575 100644 --- a/src/Testcontainers.Oracle/OracleBuilder.cs +++ b/src/Testcontainers.Oracle/OracleBuilder.cs @@ -2,13 +2,16 @@ namespace Testcontainers.Oracle; /// [PublicAPI] -public sealed class OracleBuilder : ContainerBuilder +public sealed class OracleBuilder + : ContainerBuilder { public const string OracleImage = "gvenzl/oracle-xe:21.3.0-slim-faststart"; public const ushort OraclePort = 1521; - [Obsolete("This constant is obsolete and should not be used. It is only applicable for Oracle images between versions 11 and 22.")] + [Obsolete( + "This constant is obsolete and should not be used. It is only applicable for Oracle images between versions 11 and 22." + )] public const string DefaultDatabase = "XEPDB1"; public const string DefaultUsername = "oracle"; @@ -81,12 +84,19 @@ public override OracleContainer Build() var defaultServiceName = GetDefaultServiceName(); if (DockerResourceConfiguration.Database == null) { - return new OracleContainer(WithDatabase(defaultServiceName).DockerResourceConfiguration); + return new OracleContainer( + WithDatabase(defaultServiceName).DockerResourceConfiguration + ); } if (DockerResourceConfiguration.Database != defaultServiceName) { - return new OracleContainer(WithEnvironment("ORACLE_DATABASE", DockerResourceConfiguration.Database).DockerResourceConfiguration); + return new OracleContainer( + WithEnvironment( + "ORACLE_DATABASE", + DockerResourceConfiguration.Database + ).DockerResourceConfiguration + ); } return new OracleContainer(DockerResourceConfiguration); @@ -100,7 +110,9 @@ protected override OracleBuilder Init() .WithPortBinding(OraclePort, true) .WithUsername(DefaultUsername) .WithPassword(DefaultPassword) - .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("DATABASE IS READY TO USE!")); + .WithWaitStrategy( + Wait.ForUnixContainer().UntilMessageIsLogged("DATABASE IS READY TO USE!") + ); } /// @@ -108,25 +120,43 @@ protected override void Validate() { base.Validate(); - const string message = "The image '{0}' does not support configuring the database. It is only supported on Oracle 18 and onwards."; + const string message = + "The image '{0}' does not support configuring the database. It is only supported on Oracle 18 and onwards."; Predicate databaseConfigurationNotSupported = value => value.Database != null && value.Image.MatchVersion(v => v.Major < 18); - _ = Guard.Argument(DockerResourceConfiguration, nameof(DockerResourceConfiguration.Database)) - .ThrowIf(argument => databaseConfigurationNotSupported(argument.Value), _ => throw new NotSupportedException(string.Format(message, DockerResourceConfiguration.Image.FullName))); - - _ = Guard.Argument(DockerResourceConfiguration.Username, nameof(DockerResourceConfiguration.Username)) + _ = Guard + .Argument(DockerResourceConfiguration, nameof(DockerResourceConfiguration.Database)) + .ThrowIf( + argument => databaseConfigurationNotSupported(argument.Value), + _ => + throw new NotSupportedException( + string.Format(message, DockerResourceConfiguration.Image.FullName) + ) + ); + + _ = Guard + .Argument( + DockerResourceConfiguration.Username, + nameof(DockerResourceConfiguration.Username) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override OracleBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override OracleBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new OracleConfiguration(resourceConfiguration)); } @@ -138,7 +168,10 @@ protected override OracleBuilder Clone(IContainerConfiguration resourceConfigura } /// - protected override OracleBuilder Merge(OracleConfiguration oldValue, OracleConfiguration newValue) + protected override OracleBuilder Merge( + OracleConfiguration oldValue, + OracleConfiguration newValue + ) { return new OracleBuilder(new OracleConfiguration(oldValue, newValue)); } @@ -157,4 +190,4 @@ private string GetDefaultServiceName() return "XE"; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Oracle/OracleConfiguration.cs b/src/Testcontainers.Oracle/OracleConfiguration.cs index 815b033f2..bc9484724 100644 --- a/src/Testcontainers.Oracle/OracleConfiguration.cs +++ b/src/Testcontainers.Oracle/OracleConfiguration.cs @@ -13,7 +13,8 @@ public sealed class OracleConfiguration : ContainerConfiguration public OracleConfiguration( string database = null, string username = null, - string password = null) + string password = null + ) { Database = database; Username = username; @@ -24,7 +25,9 @@ public OracleConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public OracleConfiguration(IResourceConfiguration resourceConfiguration) + public OracleConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -77,4 +80,4 @@ public OracleConfiguration(OracleConfiguration oldValue, OracleConfiguration new /// Gets the Oracle password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Oracle/OracleContainer.cs b/src/Testcontainers.Oracle/OracleContainer.cs index 54eac0c72..7bfd64db9 100644 --- a/src/Testcontainers.Oracle/OracleContainer.cs +++ b/src/Testcontainers.Oracle/OracleContainer.cs @@ -22,8 +22,16 @@ public OracleContainer(OracleConfiguration configuration) /// The Oracle connection string. public string GetConnectionString() { - const string dataSource = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1}))(CONNECT_DATA=(SERVICE_NAME={2})));User Id={3};Password={4};"; - return string.Format(dataSource, Hostname, GetMappedPublicPort(OracleBuilder.OraclePort), _configuration.Database, _configuration.Username, _configuration.Password); + const string dataSource = + "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1}))(CONNECT_DATA=(SERVICE_NAME={2})));User Id={3};Password={4};"; + return string.Format( + dataSource, + Hostname, + GetMappedPublicPort(OracleBuilder.OraclePort), + _configuration.Database, + _configuration.Username, + _configuration.Password + ); } /// @@ -32,14 +40,36 @@ public string GetConnectionString() /// The content of the SQL script to execute. /// Cancellation token. /// Task that completes when the SQL script has been executed. - public async Task ExecScriptAsync(string scriptContent, CancellationToken ct = default) + public async Task ExecScriptAsync( + string scriptContent, + CancellationToken ct = default + ) { - var scriptFilePath = string.Join("/", string.Empty, "tmp", Guid.NewGuid().ToString("D"), Path.GetRandomFileName()); + var scriptFilePath = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid().ToString("D"), + Path.GetRandomFileName() + ); - await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.FileMode644, ct) + await CopyAsync( + Encoding.Default.GetBytes(scriptContent), + scriptFilePath, + Unix.FileMode644, + ct + ) .ConfigureAwait(false); - return await ExecAsync(new[] { "/bin/sh", "-c", $"exit | sqlplus -LOGON -SILENT {_configuration.Username}/{_configuration.Password}@localhost:1521/{_configuration.Database} @{scriptFilePath}" }, ct) + return await ExecAsync( + new[] + { + "/bin/sh", + "-c", + $"exit | sqlplus -LOGON -SILENT {_configuration.Username}/{_configuration.Password}@localhost:1521/{_configuration.Database} @{scriptFilePath}", + }, + ct + ) .ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Oracle/Testcontainers.Oracle.csproj b/src/Testcontainers.Oracle/Testcontainers.Oracle.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Oracle/Testcontainers.Oracle.csproj +++ b/src/Testcontainers.Oracle/Testcontainers.Oracle.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Oracle/Usings.cs b/src/Testcontainers.Oracle/Usings.cs index 6fe3559a7..43011e602 100644 --- a/src/Testcontainers.Oracle/Usings.cs +++ b/src/Testcontainers.Oracle/Usings.cs @@ -8,4 +8,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Papercut/PapercutBuilder.cs b/src/Testcontainers.Papercut/PapercutBuilder.cs index 69293818d..690aab7c8 100644 --- a/src/Testcontainers.Papercut/PapercutBuilder.cs +++ b/src/Testcontainers.Papercut/PapercutBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Papercut; /// [PublicAPI] -public sealed class PapercutBuilder : ContainerBuilder +public sealed class PapercutBuilder + : ContainerBuilder { public const string PapercutImage = "changemakerstudiosus/papercut-smtp:latest"; @@ -46,12 +47,21 @@ protected override PapercutBuilder Init() .WithImage(PapercutImage) .WithPortBinding(SmtpPort, true) .WithPortBinding(HttpPort, true) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPath("/health").ForPort(HttpPort).ForResponseMessageMatching(IsInstanceHealthyAsync))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request + .ForPath("/health") + .ForPort(HttpPort) + .ForResponseMessageMatching(IsInstanceHealthyAsync) + ) + ); } /// - protected override PapercutBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override PapercutBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new PapercutConfiguration(resourceConfiguration)); } @@ -63,7 +73,10 @@ protected override PapercutBuilder Clone(IContainerConfiguration resourceConfigu } /// - protected override PapercutBuilder Merge(PapercutConfiguration oldValue, PapercutConfiguration newValue) + protected override PapercutBuilder Merge( + PapercutConfiguration oldValue, + PapercutConfiguration newValue + ) { return new PapercutBuilder(new PapercutConfiguration(oldValue, newValue)); } @@ -75,9 +88,11 @@ protected override PapercutBuilder Merge(PapercutConfiguration oldValue, Papercu /// A value indicating whether the instance is healthy or not. private static async Task IsInstanceHealthyAsync(HttpResponseMessage response) { - var body = await response.Content.ReadAsStringAsync() - .ConfigureAwait(false); + var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - return "Papercut WebUI server started successfully.".Equals(body, StringComparison.OrdinalIgnoreCase); + return "Papercut WebUI server started successfully.".Equals( + body, + StringComparison.OrdinalIgnoreCase + ); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Papercut/PapercutConfiguration.cs b/src/Testcontainers.Papercut/PapercutConfiguration.cs index 6582a0276..aac9809eb 100644 --- a/src/Testcontainers.Papercut/PapercutConfiguration.cs +++ b/src/Testcontainers.Papercut/PapercutConfiguration.cs @@ -7,15 +7,15 @@ public sealed class PapercutConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public PapercutConfiguration() - { - } + public PapercutConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public PapercutConfiguration(IResourceConfiguration resourceConfiguration) + public PapercutConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public PapercutConfiguration(PapercutConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public PapercutConfiguration(PapercutConfiguration oldValue, PapercutConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Papercut/PapercutContainer.cs b/src/Testcontainers.Papercut/PapercutContainer.cs index 2ad934865..4ec077f2d 100644 --- a/src/Testcontainers.Papercut/PapercutContainer.cs +++ b/src/Testcontainers.Papercut/PapercutContainer.cs @@ -9,9 +9,7 @@ public sealed class PapercutContainer : DockerContainer /// /// The container configuration. public PapercutContainer(PapercutConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the SMTP port. @@ -24,6 +22,10 @@ public PapercutContainer(PapercutConfiguration configuration) /// The Papercut base address. public string GetBaseAddress() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(PapercutBuilder.HttpPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(PapercutBuilder.HttpPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Papercut/Testcontainers.Papercut.csproj b/src/Testcontainers.Papercut/Testcontainers.Papercut.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Papercut/Testcontainers.Papercut.csproj +++ b/src/Testcontainers.Papercut/Testcontainers.Papercut.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Papercut/Usings.cs b/src/Testcontainers.Papercut/Usings.cs index 2dfa21a9b..3e36f0c5e 100644 --- a/src/Testcontainers.Papercut/Usings.cs +++ b/src/Testcontainers.Papercut/Usings.cs @@ -5,4 +5,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.PostgreSql/PostgreSqlBuilder.cs b/src/Testcontainers.PostgreSql/PostgreSqlBuilder.cs index 73ec3a317..2757303eb 100644 --- a/src/Testcontainers.PostgreSql/PostgreSqlBuilder.cs +++ b/src/Testcontainers.PostgreSql/PostgreSqlBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.PostgreSql; /// [PublicAPI] -public sealed class PostgreSqlBuilder : ContainerBuilder +public sealed class PostgreSqlBuilder + : ContainerBuilder { public const string PostgreSqlImage = "postgres:15.1"; @@ -76,7 +77,13 @@ public override PostgreSqlContainer Build() // By default, the base builder waits until the container is running. However, for PostgreSql, a more advanced waiting strategy is necessary that requires access to the configured database and username. // If the user does not provide a custom waiting strategy, append the default PostgreSql waiting strategy. - var postgreSqlBuilder = DockerResourceConfiguration.WaitStrategies.Count() > 1 ? this : WithWaitStrategy(Wait.ForUnixContainer().AddCustomWaitStrategy(new WaitUntil(DockerResourceConfiguration))); + var postgreSqlBuilder = + DockerResourceConfiguration.WaitStrategies.Count() > 1 + ? this + : WithWaitStrategy( + Wait.ForUnixContainer() + .AddCustomWaitStrategy(new WaitUntil(DockerResourceConfiguration)) + ); return new PostgreSqlContainer(postgreSqlBuilder.DockerResourceConfiguration); } @@ -100,25 +107,40 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override PostgreSqlBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override PostgreSqlBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new PostgreSqlConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new PostgreSqlConfiguration(resourceConfiguration) + ); } /// protected override PostgreSqlBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new PostgreSqlConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new PostgreSqlConfiguration(resourceConfiguration) + ); } /// - protected override PostgreSqlBuilder Merge(PostgreSqlConfiguration oldValue, PostgreSqlConfiguration newValue) + protected override PostgreSqlBuilder Merge( + PostgreSqlConfiguration oldValue, + PostgreSqlConfiguration newValue + ) { return new PostgreSqlBuilder(new PostgreSqlConfiguration(oldValue, newValue)); } @@ -135,7 +157,16 @@ private sealed class WaitUntil : IWaitUntil public WaitUntil(PostgreSqlConfiguration configuration) { // Explicitly specify the host to ensure readiness only after the initdb scripts have executed, and the server is listening on TCP/IP. - _command = new List { "pg_isready", "--host", "localhost", "--dbname", configuration.Database, "--username", configuration.Username }; + _command = new List + { + "pg_isready", + "--host", + "localhost", + "--dbname", + configuration.Database, + "--username", + configuration.Username, + }; } /// @@ -149,15 +180,16 @@ public WaitUntil(PostgreSqlConfiguration configuration) /// Thrown when the PostgreSql image does not contain pg_isready. public async Task UntilAsync(IContainer container) { - var execResult = await container.ExecAsync(_command) - .ConfigureAwait(false); + var execResult = await container.ExecAsync(_command).ConfigureAwait(false); if (execResult.Stderr.Contains("pg_isready was not found")) { - throw new NotSupportedException($"The '{container.Image.FullName}' image does not contain: pg_isready. Please use 'postgres:9.3' onwards."); + throw new NotSupportedException( + $"The '{container.Image.FullName}' image does not contain: pg_isready. Please use 'postgres:9.3' onwards." + ); } return 0L.Equals(execResult.ExitCode); } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.PostgreSql/PostgreSqlConfiguration.cs b/src/Testcontainers.PostgreSql/PostgreSqlConfiguration.cs index 05873fe8a..f19a8d8aa 100644 --- a/src/Testcontainers.PostgreSql/PostgreSqlConfiguration.cs +++ b/src/Testcontainers.PostgreSql/PostgreSqlConfiguration.cs @@ -13,7 +13,8 @@ public sealed class PostgreSqlConfiguration : ContainerConfiguration public PostgreSqlConfiguration( string database = null, string username = null, - string password = null) + string password = null + ) { Database = database; Username = username; @@ -24,7 +25,9 @@ public PostgreSqlConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public PostgreSqlConfiguration(IResourceConfiguration resourceConfiguration) + public PostgreSqlConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -55,7 +58,10 @@ public PostgreSqlConfiguration(PostgreSqlConfiguration resourceConfiguration) /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public PostgreSqlConfiguration(PostgreSqlConfiguration oldValue, PostgreSqlConfiguration newValue) + public PostgreSqlConfiguration( + PostgreSqlConfiguration oldValue, + PostgreSqlConfiguration newValue + ) : base(oldValue, newValue) { Database = BuildConfiguration.Combine(oldValue.Database, newValue.Database); @@ -77,4 +83,4 @@ public PostgreSqlConfiguration(PostgreSqlConfiguration oldValue, PostgreSqlConfi /// Gets the PostgreSql password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.PostgreSql/PostgreSqlContainer.cs b/src/Testcontainers.PostgreSql/PostgreSqlContainer.cs index b4ebdf8a9..b5bd51304 100644 --- a/src/Testcontainers.PostgreSql/PostgreSqlContainer.cs +++ b/src/Testcontainers.PostgreSql/PostgreSqlContainer.cs @@ -28,7 +28,10 @@ public string GetConnectionString() properties.Add("Database", _configuration.Database); properties.Add("Username", _configuration.Username); properties.Add("Password", _configuration.Password); - return string.Join(";", properties.Select(property => string.Join("=", property.Key, property.Value))); + return string.Join( + ";", + properties.Select(property => string.Join("=", property.Key, property.Value)) + ); } /// @@ -37,14 +40,40 @@ public string GetConnectionString() /// The content of the SQL script to execute. /// Cancellation token. /// Task that completes when the SQL script has been executed. - public async Task ExecScriptAsync(string scriptContent, CancellationToken ct = default) + public async Task ExecScriptAsync( + string scriptContent, + CancellationToken ct = default + ) { - var scriptFilePath = string.Join("/", string.Empty, "tmp", Guid.NewGuid().ToString("D"), Path.GetRandomFileName()); + var scriptFilePath = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid().ToString("D"), + Path.GetRandomFileName() + ); - await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.FileMode644, ct) + await CopyAsync( + Encoding.Default.GetBytes(scriptContent), + scriptFilePath, + Unix.FileMode644, + ct + ) .ConfigureAwait(false); - return await ExecAsync(new[] { "psql", "--username", _configuration.Username, "--dbname", _configuration.Database, "--file", scriptFilePath }, ct) + return await ExecAsync( + new[] + { + "psql", + "--username", + _configuration.Username, + "--dbname", + _configuration.Database, + "--file", + scriptFilePath, + }, + ct + ) .ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.PostgreSql/Testcontainers.PostgreSql.csproj b/src/Testcontainers.PostgreSql/Testcontainers.PostgreSql.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.PostgreSql/Testcontainers.PostgreSql.csproj +++ b/src/Testcontainers.PostgreSql/Testcontainers.PostgreSql.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.PostgreSql/Usings.cs b/src/Testcontainers.PostgreSql/Usings.cs index e2b02a51e..3481268bc 100644 --- a/src/Testcontainers.PostgreSql/Usings.cs +++ b/src/Testcontainers.PostgreSql/Usings.cs @@ -10,4 +10,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.PubSub/PubSubBuilder.cs b/src/Testcontainers.PubSub/PubSubBuilder.cs index 3956e8a13..18dd418a3 100644 --- a/src/Testcontainers.PubSub/PubSubBuilder.cs +++ b/src/Testcontainers.PubSub/PubSubBuilder.cs @@ -2,9 +2,11 @@ namespace Testcontainers.PubSub; /// [PublicAPI] -public sealed class PubSubBuilder : ContainerBuilder +public sealed class PubSubBuilder + : ContainerBuilder { - public const string GoogleCloudCliImage = "gcr.io/google.com/cloudsdktool/google-cloud-cli:446.0.1-emulators"; + public const string GoogleCloudCliImage = + "gcr.io/google.com/cloudsdktool/google-cloud-cli:446.0.1-emulators"; public const ushort PubSubPort = 8085; @@ -44,12 +46,21 @@ protected override PubSubBuilder Init() .WithImage(GoogleCloudCliImage) .WithPortBinding(PubSubPort, true) .WithEntrypoint("gcloud") - .WithCommand("beta", "emulators", "pubsub", "start", "--host-port", "0.0.0.0:" + PubSubPort) + .WithCommand( + "beta", + "emulators", + "pubsub", + "start", + "--host-port", + "0.0.0.0:" + PubSubPort + ) .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("(?s).*started.*$")); } /// - protected override PubSubBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override PubSubBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new PubSubConfiguration(resourceConfiguration)); } @@ -61,8 +72,11 @@ protected override PubSubBuilder Clone(IContainerConfiguration resourceConfigura } /// - protected override PubSubBuilder Merge(PubSubConfiguration oldValue, PubSubConfiguration newValue) + protected override PubSubBuilder Merge( + PubSubConfiguration oldValue, + PubSubConfiguration newValue + ) { return new PubSubBuilder(new PubSubConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.PubSub/PubSubConfiguration.cs b/src/Testcontainers.PubSub/PubSubConfiguration.cs index f093f497b..eae320365 100644 --- a/src/Testcontainers.PubSub/PubSubConfiguration.cs +++ b/src/Testcontainers.PubSub/PubSubConfiguration.cs @@ -7,15 +7,15 @@ public sealed class PubSubConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public PubSubConfiguration() - { - } + public PubSubConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public PubSubConfiguration(IResourceConfiguration resourceConfiguration) + public PubSubConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public PubSubConfiguration(PubSubConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public PubSubConfiguration(PubSubConfiguration oldValue, PubSubConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.PubSub/PubSubContainer.cs b/src/Testcontainers.PubSub/PubSubContainer.cs index b3a8e7ec6..c70aee851 100644 --- a/src/Testcontainers.PubSub/PubSubContainer.cs +++ b/src/Testcontainers.PubSub/PubSubContainer.cs @@ -9,9 +9,7 @@ public sealed class PubSubContainer : DockerContainer /// /// The container configuration. public PubSubContainer(PubSubConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the PubSub emulator endpoint. @@ -19,6 +17,10 @@ public PubSubContainer(PubSubConfiguration configuration) /// The PubSub emulator endpoint. public string GetEmulatorEndpoint() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(PubSubBuilder.PubSubPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(PubSubBuilder.PubSubPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.PubSub/Testcontainers.PubSub.csproj b/src/Testcontainers.PubSub/Testcontainers.PubSub.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.PubSub/Testcontainers.PubSub.csproj +++ b/src/Testcontainers.PubSub/Testcontainers.PubSub.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.PubSub/Usings.cs b/src/Testcontainers.PubSub/Usings.cs index 79fd3af9b..b31708db0 100644 --- a/src/Testcontainers.PubSub/Usings.cs +++ b/src/Testcontainers.PubSub/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Pulsar/PulsarBuilder.cs b/src/Testcontainers.Pulsar/PulsarBuilder.cs index 23218b1ea..6cf7150db 100644 --- a/src/Testcontainers.Pulsar/PulsarBuilder.cs +++ b/src/Testcontainers.Pulsar/PulsarBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Pulsar; /// [PublicAPI] -public sealed class PulsarBuilder : ContainerBuilder +public sealed class PulsarBuilder + : ContainerBuilder { public const string PulsarImage = "apachepulsar/pulsar:3.0.9"; @@ -16,7 +17,8 @@ public sealed class PulsarBuilder : ContainerBuilder AuthenticationEnvVars = InitAuthenticationEnvVars(); + private static readonly IReadOnlyDictionary AuthenticationEnvVars = + InitAuthenticationEnvVars(); /// /// Initializes a new instance of the class. @@ -49,7 +51,10 @@ private PulsarBuilder(PulsarConfiguration resourceConfiguration) /// A configured instance of . public PulsarBuilder WithAuthentication() { - return Merge(DockerResourceConfiguration, new PulsarConfiguration(authenticationEnabled: true)) + return Merge( + DockerResourceConfiguration, + new PulsarConfiguration(authenticationEnabled: true) + ) .WithEnvironment(AuthenticationEnvVars); } @@ -60,7 +65,10 @@ public PulsarBuilder WithAuthentication() /// A configured instance of . public PulsarBuilder WithFunctionsWorker(bool functionsWorkerEnabled = true) { - return Merge(DockerResourceConfiguration, new PulsarConfiguration(functionsWorkerEnabled: functionsWorkerEnabled)); + return Merge( + DockerResourceConfiguration, + new PulsarConfiguration(functionsWorkerEnabled: functionsWorkerEnabled) + ); } /// @@ -80,9 +88,14 @@ public override PulsarContainer Build() waitStrategy = waitStrategy.UntilMessageIsLogged("Function worker service started"); } - waitStrategy = waitStrategy.AddCustomWaitStrategy(new WaitUntil(DockerResourceConfiguration.AuthenticationEnabled.GetValueOrDefault())); + waitStrategy = waitStrategy.AddCustomWaitStrategy( + new WaitUntil(DockerResourceConfiguration.AuthenticationEnabled.GetValueOrDefault()) + ); - var pulsarBuilder = DockerResourceConfiguration.WaitStrategies.Count() > 1 ? this : WithWaitStrategy(waitStrategy); + var pulsarBuilder = + DockerResourceConfiguration.WaitStrategies.Count() > 1 + ? this + : WithWaitStrategy(waitStrategy); return new PulsarContainer(pulsarBuilder.DockerResourceConfiguration); } @@ -95,12 +108,19 @@ protected override PulsarBuilder Init() .WithPortBinding(PulsarWebServicePort, true) .WithFunctionsWorker(false) .WithEntrypoint("/bin/sh", "-c") - .WithCommand("while [ ! -f " + StartupScriptFilePath + " ]; do sleep 0.1; done; " + StartupScriptFilePath) + .WithCommand( + "while [ ! -f " + + StartupScriptFilePath + + " ]; do sleep 0.1; done; " + + StartupScriptFilePath + ) .WithStartupCallback((container, ct) => container.CopyStartupScriptAsync(ct)); } /// - protected override PulsarBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override PulsarBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new PulsarConfiguration(resourceConfiguration)); } @@ -112,19 +132,26 @@ protected override PulsarBuilder Clone(IContainerConfiguration resourceConfigura } /// - protected override PulsarBuilder Merge(PulsarConfiguration oldValue, PulsarConfiguration newValue) + protected override PulsarBuilder Merge( + PulsarConfiguration oldValue, + PulsarConfiguration newValue + ) { return new PulsarBuilder(new PulsarConfiguration(oldValue, newValue)); } private static IReadOnlyDictionary InitAuthenticationEnvVars() { - const string authenticationPlugin = "org.apache.pulsar.client.impl.auth.AuthenticationToken"; + const string authenticationPlugin = + "org.apache.pulsar.client.impl.auth.AuthenticationToken"; var authenticationEnvVars = new Dictionary(); authenticationEnvVars.Add("authenticateOriginalAuthData", "false"); authenticationEnvVars.Add("authenticationEnabled", "true"); authenticationEnvVars.Add("authorizationEnabled", "true"); - authenticationEnvVars.Add("authenticationProviders", "org.apache.pulsar.broker.authentication.AuthenticationProviderToken"); + authenticationEnvVars.Add( + "authenticationProviders", + "org.apache.pulsar.broker.authentication.AuthenticationProviderToken" + ); authenticationEnvVars.Add("brokerClientAuthenticationPlugin", authenticationPlugin); authenticationEnvVars.Add("CLIENT_PREFIX_authPlugin", authenticationPlugin); authenticationEnvVars.Add("PULSAR_PREFIX_authenticationRefreshCheckSeconds", "5"); @@ -167,10 +194,14 @@ private async Task UntilAsync(PulsarContainer container) { try { - _authToken = await container.CreateAuthenticationTokenAsync(TimeSpan.FromHours(1)) + _authToken = await container + .CreateAuthenticationTokenAsync(TimeSpan.FromHours(1)) .ConfigureAwait(false); - _ = _httpWaitStrategy.WithHeader("Authorization", "Bearer " + _authToken.Trim()); + _ = _httpWaitStrategy.WithHeader( + "Authorization", + "Bearer " + _authToken.Trim() + ); } catch { @@ -178,8 +209,7 @@ private async Task UntilAsync(PulsarContainer container) } } - return await _httpWaitStrategy.UntilAsync(container) - .ConfigureAwait(false); + return await _httpWaitStrategy.UntilAsync(container).ConfigureAwait(false); } /// @@ -189,14 +219,13 @@ private async Task UntilAsync(PulsarContainer container) /// A value indicating whether the cluster is healthy or not. private static async Task IsClusterHealthyAsync(HttpResponseMessage response) { - var jsonString = await response.Content.ReadAsStringAsync() - .ConfigureAwait(false); + var jsonString = await response.Content.ReadAsStringAsync().ConfigureAwait(false); try { - var status = JsonDocument.Parse(jsonString) - .RootElement - .EnumerateArray() + var status = JsonDocument + .Parse(jsonString) + .RootElement.EnumerateArray() .ElementAt(0) .GetString(); @@ -208,4 +237,4 @@ private static async Task IsClusterHealthyAsync(HttpResponseMessage respon } } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Pulsar/PulsarConfiguration.cs b/src/Testcontainers.Pulsar/PulsarConfiguration.cs index 9a290878b..1717d738b 100644 --- a/src/Testcontainers.Pulsar/PulsarConfiguration.cs +++ b/src/Testcontainers.Pulsar/PulsarConfiguration.cs @@ -11,7 +11,8 @@ public sealed class PulsarConfiguration : ContainerConfiguration /// A value indicating whether function workers is enabled or not. public PulsarConfiguration( bool? authenticationEnabled = null, - bool? functionsWorkerEnabled = null) + bool? functionsWorkerEnabled = null + ) { AuthenticationEnabled = authenticationEnabled; FunctionsWorkerEnabled = functionsWorkerEnabled; @@ -21,7 +22,9 @@ public PulsarConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public PulsarConfiguration(IResourceConfiguration resourceConfiguration) + public PulsarConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -55,8 +58,12 @@ public PulsarConfiguration(PulsarConfiguration resourceConfiguration) public PulsarConfiguration(PulsarConfiguration oldValue, PulsarConfiguration newValue) : base(oldValue, newValue) { - AuthenticationEnabled = (oldValue.AuthenticationEnabled.HasValue && oldValue.AuthenticationEnabled.Value) || (newValue.AuthenticationEnabled.HasValue && newValue.AuthenticationEnabled.Value); - FunctionsWorkerEnabled = (oldValue.FunctionsWorkerEnabled.HasValue && oldValue.FunctionsWorkerEnabled.Value) || (newValue.FunctionsWorkerEnabled.HasValue && newValue.FunctionsWorkerEnabled.Value); + AuthenticationEnabled = + (oldValue.AuthenticationEnabled.HasValue && oldValue.AuthenticationEnabled.Value) + || (newValue.AuthenticationEnabled.HasValue && newValue.AuthenticationEnabled.Value); + FunctionsWorkerEnabled = + (oldValue.FunctionsWorkerEnabled.HasValue && oldValue.FunctionsWorkerEnabled.Value) + || (newValue.FunctionsWorkerEnabled.HasValue && newValue.FunctionsWorkerEnabled.Value); } /// @@ -68,4 +75,4 @@ public PulsarConfiguration(PulsarConfiguration oldValue, PulsarConfiguration new /// Gets a value indicating whether function workers is enabled or not. /// public bool? FunctionsWorkerEnabled { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Pulsar/PulsarContainer.cs b/src/Testcontainers.Pulsar/PulsarContainer.cs index 290a88bdd..0680fd29a 100644 --- a/src/Testcontainers.Pulsar/PulsarContainer.cs +++ b/src/Testcontainers.Pulsar/PulsarContainer.cs @@ -22,7 +22,11 @@ public PulsarContainer(PulsarConfiguration configuration) /// The Pulsar broker address. public string GetBrokerAddress() { - return new UriBuilder("pulsar", Hostname, GetMappedPublicPort(PulsarBuilder.PulsarBrokerDataPort)).ToString(); + return new UriBuilder( + "pulsar", + Hostname, + GetMappedPublicPort(PulsarBuilder.PulsarBrokerDataPort) + ).ToString(); } /// @@ -31,7 +35,11 @@ public string GetBrokerAddress() /// The Pulsar web service address. public string GetServiceAddress() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(PulsarBuilder.PulsarWebServicePort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(PulsarBuilder.PulsarWebServicePort) + ).ToString(); } /// @@ -41,9 +49,15 @@ public string GetServiceAddress() /// Cancellation token. /// A task that completes when the authentication token has been created. /// - public async Task CreateAuthenticationTokenAsync(TimeSpan expiryTime, CancellationToken ct = default) + public async Task CreateAuthenticationTokenAsync( + TimeSpan expiryTime, + CancellationToken ct = default + ) { - if (_configuration.AuthenticationEnabled.HasValue && !_configuration.AuthenticationEnabled.Value) + if ( + _configuration.AuthenticationEnabled.HasValue + && !_configuration.AuthenticationEnabled.Value + ) { throw new ArgumentException("Failed to create token. Authentication is not enabled."); } @@ -65,7 +79,9 @@ public async Task CreateAuthenticationTokenAsync(TimeSpan expiryTime, Ca if (_configuration.Image.MatchVersion(IsVersionAffectedByGhIssue22811)) { - Logger.LogWarning("The 'apachepulsar/pulsar:3.2.0-3' and '3.3.0' images contains a regression. The expiry time is converted to the wrong unit of time: https://github.com/apache/pulsar/issues/22811."); + Logger.LogWarning( + "The 'apachepulsar/pulsar:3.2.0-3' and '3.3.0' images contains a regression. The expiry time is converted to the wrong unit of time: https://github.com/apache/pulsar/issues/22811." + ); secondsToMilliseconds = 1000; } else @@ -77,12 +93,13 @@ public async Task CreateAuthenticationTokenAsync(TimeSpan expiryTime, Ca command.Add($"{secondsToMilliseconds * expiryTime.TotalSeconds}s"); } - var tokensResult = await ExecAsync(command, ct) - .ConfigureAwait(false); + var tokensResult = await ExecAsync(command, ct).ConfigureAwait(false); if (tokensResult.ExitCode != 0) { - throw new ArgumentException($"Failed to create token. Command returned a non-zero exit code: {tokensResult.Stderr}."); + throw new ArgumentException( + $"Failed to create token. Command returned a non-zero exit code: {tokensResult.Stderr}." + ); } return tokensResult.Stdout; @@ -99,28 +116,51 @@ internal Task CopyStartupScriptAsync(CancellationToken ct = default) startupScript.NewLine = "\n"; startupScript.WriteLine("#!/bin/bash"); - if (_configuration.AuthenticationEnabled.HasValue && _configuration.AuthenticationEnabled.Value) + if ( + _configuration.AuthenticationEnabled.HasValue + && _configuration.AuthenticationEnabled.Value + ) { - startupScript.WriteLine("bin/pulsar tokens create-secret-key --output " + PulsarBuilder.SecretKeyFilePath); - startupScript.WriteLine("export brokerClientAuthenticationParameters=token:$(bin/pulsar tokens create --secret-key $PULSAR_PREFIX_tokenSecretKey --subject $superUserRoles)"); - startupScript.WriteLine("export CLIENT_PREFIX_authParams=$brokerClientAuthenticationParameters"); + startupScript.WriteLine( + "bin/pulsar tokens create-secret-key --output " + PulsarBuilder.SecretKeyFilePath + ); + startupScript.WriteLine( + "export brokerClientAuthenticationParameters=token:$(bin/pulsar tokens create --secret-key $PULSAR_PREFIX_tokenSecretKey --subject $superUserRoles)" + ); + startupScript.WriteLine( + "export CLIENT_PREFIX_authParams=$brokerClientAuthenticationParameters" + ); startupScript.WriteLine("bin/apply-config-from-env.py conf/standalone.conf"); - startupScript.WriteLine("bin/apply-config-from-env.py --prefix CLIENT_PREFIX_ conf/client.conf"); + startupScript.WriteLine( + "bin/apply-config-from-env.py --prefix CLIENT_PREFIX_ conf/client.conf" + ); } startupScript.Write("bin/pulsar standalone"); - if (_configuration.FunctionsWorkerEnabled.HasValue && !_configuration.FunctionsWorkerEnabled.Value) + if ( + _configuration.FunctionsWorkerEnabled.HasValue + && !_configuration.FunctionsWorkerEnabled.Value + ) { startupScript.Write(" --no-functions-worker"); startupScript.Write(" --no-stream-storage"); } - return CopyAsync(Encoding.Default.GetBytes(startupScript.ToString()), PulsarBuilder.StartupScriptFilePath, Unix.FileMode755, ct); + return CopyAsync( + Encoding.Default.GetBytes(startupScript.ToString()), + PulsarBuilder.StartupScriptFilePath, + Unix.FileMode755, + ct + ); } private static bool IsVersionAffectedByGhIssue22811(System.Version version) { - return version.Major == 3 && ((version.Minor == 2 && version.Build is >= 0 and <= 3) || (version.Minor == 3 && version.Build == 0)); + return version.Major == 3 + && ( + (version.Minor == 2 && version.Build is >= 0 and <= 3) + || (version.Minor == 3 && version.Build == 0) + ); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Pulsar/Testcontainers.Pulsar.csproj b/src/Testcontainers.Pulsar/Testcontainers.Pulsar.csproj index a108060b3..22a90c564 100644 --- a/src/Testcontainers.Pulsar/Testcontainers.Pulsar.csproj +++ b/src/Testcontainers.Pulsar/Testcontainers.Pulsar.csproj @@ -1,12 +1,16 @@ - - netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Pulsar/Usings.cs b/src/Testcontainers.Pulsar/Usings.cs index cbed90f27..e00a8360e 100644 --- a/src/Testcontainers.Pulsar/Usings.cs +++ b/src/Testcontainers.Pulsar/Usings.cs @@ -13,4 +13,4 @@ global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; global using JetBrains.Annotations; -global using Microsoft.Extensions.Logging; \ No newline at end of file +global using Microsoft.Extensions.Logging; diff --git a/src/Testcontainers.Qdrant/QdrantBuilder.cs b/src/Testcontainers.Qdrant/QdrantBuilder.cs index 703119346..c76990794 100644 --- a/src/Testcontainers.Qdrant/QdrantBuilder.cs +++ b/src/Testcontainers.Qdrant/QdrantBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Qdrant; /// [PublicAPI] -public sealed class QdrantBuilder : ContainerBuilder +public sealed class QdrantBuilder + : ContainerBuilder { public const string QdrantImage = "qdrant/qdrant:v1.13.4"; @@ -55,7 +56,10 @@ public QdrantBuilder WithApiKey(string apiKey) /// A configured instance of . public QdrantBuilder WithCertificate(string certificate, string certificateKey) { - return Merge(DockerResourceConfiguration, new QdrantConfiguration(certificate: certificate, certificateKey: certificateKey)) + return Merge( + DockerResourceConfiguration, + new QdrantConfiguration(certificate: certificate, certificateKey: certificateKey) + ) .WithEnvironment("QDRANT__SERVICE__ENABLE_TLS", "1") .WithEnvironment("QDRANT__TLS__CERT", CertificateFilePath) .WithEnvironment("QDRANT__TLS__KEY", CertificateKeyFilePath) @@ -70,7 +74,13 @@ public override QdrantContainer Build() // By default, the base builder waits until the container is running. However, for Qdrant, a more advanced waiting strategy is necessary that requires access to the configured certificate. // If the user does not provide a custom waiting strategy, append the default Qdrant waiting strategy. - var qdrantBuilder = DockerResourceConfiguration.WaitStrategies.Count() > 1 ? this : WithWaitStrategy(Wait.ForUnixContainer().AddCustomWaitStrategy(new WaitUntil(DockerResourceConfiguration))); + var qdrantBuilder = + DockerResourceConfiguration.WaitStrategies.Count() > 1 + ? this + : WithWaitStrategy( + Wait.ForUnixContainer() + .AddCustomWaitStrategy(new WaitUntil(DockerResourceConfiguration)) + ); return new QdrantContainer(qdrantBuilder.DockerResourceConfiguration); } @@ -84,7 +94,9 @@ protected override QdrantBuilder Init() } /// - protected override QdrantBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override QdrantBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new QdrantConfiguration(resourceConfiguration)); } @@ -96,7 +108,10 @@ protected override QdrantBuilder Clone(IContainerConfiguration resourceConfigura } /// - protected override QdrantBuilder Merge(QdrantConfiguration oldValue, QdrantConfiguration newValue) + protected override QdrantBuilder Merge( + QdrantConfiguration oldValue, + QdrantConfiguration newValue + ) { return new QdrantBuilder(new QdrantConfiguration(oldValue, newValue)); } @@ -127,8 +142,7 @@ public async Task UntilAsync(IContainer container) .ForPort(QdrantHttpPort) .ForPath("/readyz"); - return await httpWaitStrategy.UntilAsync(container) - .ConfigureAwait(false); + return await httpWaitStrategy.UntilAsync(container).ConfigureAwait(false); } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Qdrant/QdrantConfiguration.cs b/src/Testcontainers.Qdrant/QdrantConfiguration.cs index 99a4288d0..cf1f66bb8 100644 --- a/src/Testcontainers.Qdrant/QdrantConfiguration.cs +++ b/src/Testcontainers.Qdrant/QdrantConfiguration.cs @@ -13,7 +13,8 @@ public sealed class QdrantConfiguration : ContainerConfiguration public QdrantConfiguration( string apiKey = null, string certificate = null, - string certificateKey = null) + string certificateKey = null + ) { ApiKey = apiKey; Certificate = certificate; @@ -24,7 +25,9 @@ public QdrantConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public QdrantConfiguration(IResourceConfiguration resourceConfiguration) + public QdrantConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -60,7 +63,10 @@ public QdrantConfiguration(QdrantConfiguration oldValue, QdrantConfiguration new { ApiKey = BuildConfiguration.Combine(oldValue.ApiKey, newValue.ApiKey); Certificate = BuildConfiguration.Combine(oldValue.Certificate, newValue.Certificate); - CertificateKey = BuildConfiguration.Combine(oldValue.CertificateKey, newValue.CertificateKey); + CertificateKey = BuildConfiguration.Combine( + oldValue.CertificateKey, + newValue.CertificateKey + ); } /// @@ -82,4 +88,4 @@ public QdrantConfiguration(QdrantConfiguration oldValue, QdrantConfiguration new /// Gets the private key associated with the certificate in PEM format. /// public string CertificateKey { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Qdrant/QdrantContainer.cs b/src/Testcontainers.Qdrant/QdrantContainer.cs index f6399ee44..19c30aeba 100644 --- a/src/Testcontainers.Qdrant/QdrantContainer.cs +++ b/src/Testcontainers.Qdrant/QdrantContainer.cs @@ -22,7 +22,11 @@ public QdrantContainer(QdrantConfiguration configuration) public string GetHttpConnectionString() { var scheme = _configuration.TlsEnabled ? Uri.UriSchemeHttps : Uri.UriSchemeHttp; - var endpoint = new UriBuilder(scheme, Hostname, GetMappedPublicPort(QdrantBuilder.QdrantHttpPort)); + var endpoint = new UriBuilder( + scheme, + Hostname, + GetMappedPublicPort(QdrantBuilder.QdrantHttpPort) + ); return endpoint.ToString(); } @@ -32,7 +36,11 @@ public string GetHttpConnectionString() public string GetGrpcConnectionString() { var scheme = _configuration.TlsEnabled ? Uri.UriSchemeHttps : Uri.UriSchemeHttp; - var endpoint = new UriBuilder(scheme, Hostname, GetMappedPublicPort(QdrantBuilder.QdrantGrpcPort)); + var endpoint = new UriBuilder( + scheme, + Hostname, + GetMappedPublicPort(QdrantBuilder.QdrantGrpcPort) + ); return endpoint.ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Qdrant/Testcontainers.Qdrant.csproj b/src/Testcontainers.Qdrant/Testcontainers.Qdrant.csproj index cbff16956..fab0ac0d5 100644 --- a/src/Testcontainers.Qdrant/Testcontainers.Qdrant.csproj +++ b/src/Testcontainers.Qdrant/Testcontainers.Qdrant.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1;net462 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1;net462 + latest + + + + + + + + diff --git a/src/Testcontainers.Qdrant/Usings.cs b/src/Testcontainers.Qdrant/Usings.cs index 9c8bc5fba..235a9a4e9 100644 --- a/src/Testcontainers.Qdrant/Usings.cs +++ b/src/Testcontainers.Qdrant/Usings.cs @@ -7,4 +7,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.RabbitMq/RabbitMqBuilder.cs b/src/Testcontainers.RabbitMq/RabbitMqBuilder.cs index 5b72bbb95..f78a30b7d 100644 --- a/src/Testcontainers.RabbitMq/RabbitMqBuilder.cs +++ b/src/Testcontainers.RabbitMq/RabbitMqBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.RabbitMq; /// [PublicAPI] -public sealed class RabbitMqBuilder : ContainerBuilder +public sealed class RabbitMqBuilder + : ContainerBuilder { public const string RabbitMqImage = "rabbitmq:3.11"; @@ -71,7 +72,9 @@ protected override RabbitMqBuilder Init() .WithPortBinding(RabbitMqPort, true) .WithUsername(DefaultUsername) .WithPassword(DefaultPassword) - .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("Server startup complete")); + .WithWaitStrategy( + Wait.ForUnixContainer().UntilMessageIsLogged("Server startup complete") + ); } /// @@ -79,17 +82,27 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Username, nameof(DockerResourceConfiguration.Username)) + _ = Guard + .Argument( + DockerResourceConfiguration.Username, + nameof(DockerResourceConfiguration.Username) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); } /// - protected override RabbitMqBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override RabbitMqBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new RabbitMqConfiguration(resourceConfiguration)); } @@ -101,8 +114,11 @@ protected override RabbitMqBuilder Clone(IContainerConfiguration resourceConfigu } /// - protected override RabbitMqBuilder Merge(RabbitMqConfiguration oldValue, RabbitMqConfiguration newValue) + protected override RabbitMqBuilder Merge( + RabbitMqConfiguration oldValue, + RabbitMqConfiguration newValue + ) { return new RabbitMqBuilder(new RabbitMqConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.RabbitMq/RabbitMqConfiguration.cs b/src/Testcontainers.RabbitMq/RabbitMqConfiguration.cs index b9248ba62..587109fdd 100644 --- a/src/Testcontainers.RabbitMq/RabbitMqConfiguration.cs +++ b/src/Testcontainers.RabbitMq/RabbitMqConfiguration.cs @@ -9,9 +9,7 @@ public sealed class RabbitMqConfiguration : ContainerConfiguration /// /// The RabbitMq username. /// The RabbitMq password. - public RabbitMqConfiguration( - string username = null, - string password = null) + public RabbitMqConfiguration(string username = null, string password = null) { Username = username; Password = password; @@ -21,7 +19,9 @@ public RabbitMqConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public RabbitMqConfiguration(IResourceConfiguration resourceConfiguration) + public RabbitMqConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -68,4 +68,4 @@ public RabbitMqConfiguration(RabbitMqConfiguration oldValue, RabbitMqConfigurati /// Gets the RabbitMq password. /// public string Password { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.RabbitMq/RabbitMqContainer.cs b/src/Testcontainers.RabbitMq/RabbitMqContainer.cs index d679e9203..b8b4850b1 100644 --- a/src/Testcontainers.RabbitMq/RabbitMqContainer.cs +++ b/src/Testcontainers.RabbitMq/RabbitMqContainer.cs @@ -22,9 +22,13 @@ public RabbitMqContainer(RabbitMqConfiguration configuration) /// The RabbitMq connection string. public string GetConnectionString() { - var endpoint = new UriBuilder("amqp", Hostname, GetMappedPublicPort(RabbitMqBuilder.RabbitMqPort)); + var endpoint = new UriBuilder( + "amqp", + Hostname, + GetMappedPublicPort(RabbitMqBuilder.RabbitMqPort) + ); endpoint.UserName = Uri.EscapeDataString(_configuration.Username); endpoint.Password = Uri.EscapeDataString(_configuration.Password); return endpoint.ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.RabbitMq/Testcontainers.RabbitMq.csproj b/src/Testcontainers.RabbitMq/Testcontainers.RabbitMq.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.RabbitMq/Testcontainers.RabbitMq.csproj +++ b/src/Testcontainers.RabbitMq/Testcontainers.RabbitMq.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.RabbitMq/Usings.cs b/src/Testcontainers.RabbitMq/Usings.cs index 8e5c20fd5..f89f0c94d 100644 --- a/src/Testcontainers.RabbitMq/Usings.cs +++ b/src/Testcontainers.RabbitMq/Usings.cs @@ -4,4 +4,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.RavenDb/RavenDbBuilder.cs b/src/Testcontainers.RavenDb/RavenDbBuilder.cs index 86fc1435f..650c65cab 100644 --- a/src/Testcontainers.RavenDb/RavenDbBuilder.cs +++ b/src/Testcontainers.RavenDb/RavenDbBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.RavenDb; /// [PublicAPI] -public sealed class RavenDbBuilder : ContainerBuilder +public sealed class RavenDbBuilder + : ContainerBuilder { public const string RavenDbImage = "ravendb/ravendb:5.4-ubuntu-latest"; @@ -47,7 +48,9 @@ protected override RavenDbBuilder Init() } /// - protected override RavenDbBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override RavenDbBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new RavenDbConfiguration(resourceConfiguration)); } @@ -59,8 +62,11 @@ protected override RavenDbBuilder Clone(IContainerConfiguration resourceConfigur } /// - protected override RavenDbBuilder Merge(RavenDbConfiguration oldValue, RavenDbConfiguration newValue) + protected override RavenDbBuilder Merge( + RavenDbConfiguration oldValue, + RavenDbConfiguration newValue + ) { return new RavenDbBuilder(new RavenDbConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.RavenDb/RavenDbConfiguration.cs b/src/Testcontainers.RavenDb/RavenDbConfiguration.cs index c36cfc26e..170c4adda 100644 --- a/src/Testcontainers.RavenDb/RavenDbConfiguration.cs +++ b/src/Testcontainers.RavenDb/RavenDbConfiguration.cs @@ -7,15 +7,15 @@ public sealed class RavenDbConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public RavenDbConfiguration() - { - } + public RavenDbConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public RavenDbConfiguration(IResourceConfiguration resourceConfiguration) + public RavenDbConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public RavenDbConfiguration(RavenDbConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public RavenDbConfiguration(RavenDbConfiguration oldValue, RavenDbConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.RavenDb/RavenDbContainer.cs b/src/Testcontainers.RavenDb/RavenDbContainer.cs index 62a5ad872..c025a3831 100644 --- a/src/Testcontainers.RavenDb/RavenDbContainer.cs +++ b/src/Testcontainers.RavenDb/RavenDbContainer.cs @@ -9,9 +9,7 @@ public sealed class RavenDbContainer : DockerContainer /// /// The container configuration. public RavenDbContainer(RavenDbConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the RavenDb connection string. @@ -19,6 +17,10 @@ public RavenDbContainer(RavenDbConfiguration configuration) /// The RavenDb connection string. public string GetConnectionString() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(RavenDbBuilder.RavenDbPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(RavenDbBuilder.RavenDbPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.RavenDb/Testcontainers.RavenDb.csproj b/src/Testcontainers.RavenDb/Testcontainers.RavenDb.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.RavenDb/Testcontainers.RavenDb.csproj +++ b/src/Testcontainers.RavenDb/Testcontainers.RavenDb.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.RavenDb/Usings.cs b/src/Testcontainers.RavenDb/Usings.cs index 79fd3af9b..b31708db0 100644 --- a/src/Testcontainers.RavenDb/Usings.cs +++ b/src/Testcontainers.RavenDb/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Redis/RedisBuilder.cs b/src/Testcontainers.Redis/RedisBuilder.cs index 9c8be98d3..4251fcf96 100644 --- a/src/Testcontainers.Redis/RedisBuilder.cs +++ b/src/Testcontainers.Redis/RedisBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Redis; /// [PublicAPI] -public sealed class RedisBuilder : ContainerBuilder +public sealed class RedisBuilder + : ContainerBuilder { public const string RedisImage = "redis:7.0"; @@ -47,7 +48,9 @@ protected override RedisBuilder Init() } /// - protected override RedisBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override RedisBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new RedisConfiguration(resourceConfiguration)); } @@ -63,4 +66,4 @@ protected override RedisBuilder Merge(RedisConfiguration oldValue, RedisConfigur { return new RedisBuilder(new RedisConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Redis/RedisConfiguration.cs b/src/Testcontainers.Redis/RedisConfiguration.cs index 05d1d911a..81c1aeffe 100644 --- a/src/Testcontainers.Redis/RedisConfiguration.cs +++ b/src/Testcontainers.Redis/RedisConfiguration.cs @@ -7,15 +7,15 @@ public sealed class RedisConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public RedisConfiguration() - { - } + public RedisConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public RedisConfiguration(IResourceConfiguration resourceConfiguration) + public RedisConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public RedisConfiguration(RedisConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public RedisConfiguration(RedisConfiguration oldValue, RedisConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Redis/RedisContainer.cs b/src/Testcontainers.Redis/RedisContainer.cs index 4c30d0917..dc36aecd2 100644 --- a/src/Testcontainers.Redis/RedisContainer.cs +++ b/src/Testcontainers.Redis/RedisContainer.cs @@ -9,9 +9,7 @@ public sealed class RedisContainer : DockerContainer /// /// The container configuration. public RedisContainer(RedisConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Redis connection string. @@ -19,7 +17,9 @@ public RedisContainer(RedisConfiguration configuration) /// The Redis connection string. public string GetConnectionString() { - return new UriBuilder("redis", Hostname, GetMappedPublicPort(RedisBuilder.RedisPort)).Uri.Authority; + return new UriBuilder("redis", Hostname, GetMappedPublicPort(RedisBuilder.RedisPort)) + .Uri + .Authority; } /// @@ -28,14 +28,28 @@ public string GetConnectionString() /// The content of the Lua script to execute. /// Cancellation token. /// Task that completes when the Lua script has been executed. - public async Task ExecScriptAsync(string scriptContent, CancellationToken ct = default) + public async Task ExecScriptAsync( + string scriptContent, + CancellationToken ct = default + ) { - var scriptFilePath = string.Join("/", string.Empty, "tmp", Guid.NewGuid().ToString("D"), Path.GetRandomFileName()); + var scriptFilePath = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid().ToString("D"), + Path.GetRandomFileName() + ); - await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.FileMode644, ct) + await CopyAsync( + Encoding.Default.GetBytes(scriptContent), + scriptFilePath, + Unix.FileMode644, + ct + ) .ConfigureAwait(false); return await ExecAsync(new[] { "redis-cli", "--eval", scriptFilePath, "0" }, ct) .ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Redis/Testcontainers.Redis.csproj b/src/Testcontainers.Redis/Testcontainers.Redis.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Redis/Testcontainers.Redis.csproj +++ b/src/Testcontainers.Redis/Testcontainers.Redis.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Redis/Usings.cs b/src/Testcontainers.Redis/Usings.cs index 3c22a4545..b517ff22f 100644 --- a/src/Testcontainers.Redis/Usings.cs +++ b/src/Testcontainers.Redis/Usings.cs @@ -7,4 +7,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Redpanda/RedpandaBuilder.cs b/src/Testcontainers.Redpanda/RedpandaBuilder.cs index d3116d614..2bb1c94da 100644 --- a/src/Testcontainers.Redpanda/RedpandaBuilder.cs +++ b/src/Testcontainers.Redpanda/RedpandaBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Redpanda; /// [PublicAPI] -public sealed class RedpandaBuilder : ContainerBuilder +public sealed class RedpandaBuilder + : ContainerBuilder { public const string RedpandaImage = "docker.redpanda.com/redpandadata/redpanda:v22.2.1"; @@ -49,26 +50,49 @@ protected override RedpandaBuilder Init() .WithPortBinding(SchemaRegistryPort, true) .WithPortBinding(RedpandaPort, true) .WithEntrypoint("/bin/sh", "-c") - .WithCommand("while [ ! -f " + StartupScriptFilePath + " ]; do sleep 0.1; done; " + StartupScriptFilePath) - .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("Started Kafka API server")) - .WithStartupCallback((container, ct) => - { - const char lf = '\n'; - var startupScript = new StringBuilder(); - startupScript.Append("#!/bin/bash"); - startupScript.Append(lf); - startupScript.Append("/usr/bin/rpk redpanda start "); - startupScript.Append("--mode dev-container "); - startupScript.Append("--smp 1 "); - startupScript.Append("--memory 1G "); - startupScript.Append("--kafka-addr PLAINTEXT://0.0.0.0:29092,OUTSIDE://0.0.0.0:9092 "); - startupScript.Append("--advertise-kafka-addr PLAINTEXT://127.0.0.1:29092,OUTSIDE://" + container.Hostname + ":" + container.GetMappedPublicPort(RedpandaPort)); - return container.CopyAsync(Encoding.Default.GetBytes(startupScript.ToString()), StartupScriptFilePath, Unix.FileMode755, ct); - }); + .WithCommand( + "while [ ! -f " + + StartupScriptFilePath + + " ]; do sleep 0.1; done; " + + StartupScriptFilePath + ) + .WithWaitStrategy( + Wait.ForUnixContainer().UntilMessageIsLogged("Started Kafka API server") + ) + .WithStartupCallback( + (container, ct) => + { + const char lf = '\n'; + var startupScript = new StringBuilder(); + startupScript.Append("#!/bin/bash"); + startupScript.Append(lf); + startupScript.Append("/usr/bin/rpk redpanda start "); + startupScript.Append("--mode dev-container "); + startupScript.Append("--smp 1 "); + startupScript.Append("--memory 1G "); + startupScript.Append( + "--kafka-addr PLAINTEXT://0.0.0.0:29092,OUTSIDE://0.0.0.0:9092 " + ); + startupScript.Append( + "--advertise-kafka-addr PLAINTEXT://127.0.0.1:29092,OUTSIDE://" + + container.Hostname + + ":" + + container.GetMappedPublicPort(RedpandaPort) + ); + return container.CopyAsync( + Encoding.Default.GetBytes(startupScript.ToString()), + StartupScriptFilePath, + Unix.FileMode755, + ct + ); + } + ); } /// - protected override RedpandaBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override RedpandaBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new RedpandaConfiguration(resourceConfiguration)); } @@ -80,8 +104,11 @@ protected override RedpandaBuilder Clone(IContainerConfiguration resourceConfigu } /// - protected override RedpandaBuilder Merge(RedpandaConfiguration oldValue, RedpandaConfiguration newValue) + protected override RedpandaBuilder Merge( + RedpandaConfiguration oldValue, + RedpandaConfiguration newValue + ) { return new RedpandaBuilder(new RedpandaConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Redpanda/RedpandaConfiguration.cs b/src/Testcontainers.Redpanda/RedpandaConfiguration.cs index 5bc672eba..46626fa7b 100644 --- a/src/Testcontainers.Redpanda/RedpandaConfiguration.cs +++ b/src/Testcontainers.Redpanda/RedpandaConfiguration.cs @@ -7,15 +7,15 @@ public sealed class RedpandaConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public RedpandaConfiguration() - { - } + public RedpandaConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public RedpandaConfiguration(IResourceConfiguration resourceConfiguration) + public RedpandaConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public RedpandaConfiguration(RedpandaConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public RedpandaConfiguration(RedpandaConfiguration oldValue, RedpandaConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Redpanda/RedpandaContainer.cs b/src/Testcontainers.Redpanda/RedpandaContainer.cs index 0ac279353..6424bdad5 100644 --- a/src/Testcontainers.Redpanda/RedpandaContainer.cs +++ b/src/Testcontainers.Redpanda/RedpandaContainer.cs @@ -9,9 +9,7 @@ public sealed class RedpandaContainer : DockerContainer /// /// The container configuration. public RedpandaContainer(RedpandaConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Schema Registry address. @@ -19,7 +17,11 @@ public RedpandaContainer(RedpandaConfiguration configuration) /// The Schema Registry address. public string GetSchemaRegistryAddress() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(RedpandaBuilder.SchemaRegistryPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(RedpandaBuilder.SchemaRegistryPort) + ).ToString(); } /// @@ -28,6 +30,10 @@ public string GetSchemaRegistryAddress() /// The bootstrap address. public string GetBootstrapAddress() { - return new UriBuilder("PLAINTEXT", Hostname, GetMappedPublicPort(RedpandaBuilder.RedpandaPort)).ToString(); + return new UriBuilder( + "PLAINTEXT", + Hostname, + GetMappedPublicPort(RedpandaBuilder.RedpandaPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Redpanda/Testcontainers.Redpanda.csproj b/src/Testcontainers.Redpanda/Testcontainers.Redpanda.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Redpanda/Testcontainers.Redpanda.csproj +++ b/src/Testcontainers.Redpanda/Testcontainers.Redpanda.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Redpanda/Usings.cs b/src/Testcontainers.Redpanda/Usings.cs index fd6c6ccbc..1734e5e13 100644 --- a/src/Testcontainers.Redpanda/Usings.cs +++ b/src/Testcontainers.Redpanda/Usings.cs @@ -1,7 +1,7 @@ global using System; -global using Docker.DotNet.Models; global using System.Text; +global using Docker.DotNet.Models; global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.ServiceBus/ServiceBusBuilder.cs b/src/Testcontainers.ServiceBus/ServiceBusBuilder.cs index 0938396dc..82f9d589e 100644 --- a/src/Testcontainers.ServiceBus/ServiceBusBuilder.cs +++ b/src/Testcontainers.ServiceBus/ServiceBusBuilder.cs @@ -2,13 +2,15 @@ namespace Testcontainers.ServiceBus; /// [PublicAPI] -public sealed class ServiceBusBuilder : ContainerBuilder +public sealed class ServiceBusBuilder + : ContainerBuilder { public const string ServiceBusNetworkAlias = "servicebus-container"; public const string DatabaseNetworkAlias = "database-container"; - public const string ServiceBusImage = "mcr.microsoft.com/azure-messaging/servicebus-emulator:latest"; + public const string ServiceBusImage = + "mcr.microsoft.com/azure-messaging/servicebus-emulator:latest"; public const ushort ServiceBusPort = 5672; @@ -55,7 +57,9 @@ private ServiceBusBuilder(ServiceBusConfiguration resourceConfiguration) /// A configured instance of . public override ServiceBusBuilder WithAcceptLicenseAgreement(bool acceptLicenseAgreement) { - var licenseAgreement = acceptLicenseAgreement ? AcceptLicenseAgreement : DeclineLicenseAgreement; + var licenseAgreement = acceptLicenseAgreement + ? AcceptLicenseAgreement + : DeclineLicenseAgreement; return WithEnvironment(AcceptLicenseAgreementEnvVar, licenseAgreement); } @@ -76,9 +80,13 @@ public ServiceBusBuilder WithMsSqlContainer( INetwork network, MsSqlContainer container, string networkAlias, - string password = MsSqlBuilder.DefaultPassword) + string password = MsSqlBuilder.DefaultPassword + ) { - return Merge(DockerResourceConfiguration, new ServiceBusConfiguration(databaseContainer: container)) + return Merge( + DockerResourceConfiguration, + new ServiceBusConfiguration(databaseContainer: container) + ) .DependsOn(container) .WithNetwork(network) .WithNetworkAliases(ServiceBusNetworkAlias) @@ -96,7 +104,10 @@ public ServiceBusBuilder WithMsSqlContainer( /// A configured instance of . public ServiceBusBuilder WithConfig(string configFilePath) { - return WithResourceMapping(new FileInfo(configFilePath), new FileInfo("/ServiceBus_Emulator/ConfigFiles/Config.json")); + return WithResourceMapping( + new FileInfo(configFilePath), + new FileInfo("/ServiceBus_Emulator/ConfigFiles/Config.json") + ); } /// @@ -112,8 +123,7 @@ public override ServiceBusContainer Build() // If the user has not provided an existing MSSQL container instance, // we configure one. - var network = new NetworkBuilder() - .Build(); + var network = new NetworkBuilder().Build(); var container = new MsSqlBuilder() .WithNetwork(network) @@ -132,25 +142,40 @@ protected override ServiceBusBuilder Init() .WithPortBinding(ServiceBusPort, true) .WithPortBinding(ServiceBusHttpPort, true) .WithEnvironment("SQL_WAIT_INTERVAL", "0") - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPort(ServiceBusHttpPort).ForPath("/health"))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request.ForPort(ServiceBusHttpPort).ForPath("/health") + ) + ); } /// - protected override ServiceBusBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override ServiceBusBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new ServiceBusConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new ServiceBusConfiguration(resourceConfiguration) + ); } /// protected override ServiceBusBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new ServiceBusConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new ServiceBusConfiguration(resourceConfiguration) + ); } /// - protected override ServiceBusBuilder Merge(ServiceBusConfiguration oldValue, ServiceBusConfiguration newValue) + protected override ServiceBusBuilder Merge( + ServiceBusConfiguration oldValue, + ServiceBusConfiguration newValue + ) { return new ServiceBusBuilder(new ServiceBusConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.ServiceBus/ServiceBusConfiguration.cs b/src/Testcontainers.ServiceBus/ServiceBusConfiguration.cs index d12b8ac71..689cc4c59 100644 --- a/src/Testcontainers.ServiceBus/ServiceBusConfiguration.cs +++ b/src/Testcontainers.ServiceBus/ServiceBusConfiguration.cs @@ -17,7 +17,9 @@ public ServiceBusConfiguration(IDatabaseContainer databaseContainer = null) /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public ServiceBusConfiguration(IResourceConfiguration resourceConfiguration) + public ServiceBusConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -48,14 +50,20 @@ public ServiceBusConfiguration(ServiceBusConfiguration resourceConfiguration) /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public ServiceBusConfiguration(ServiceBusConfiguration oldValue, ServiceBusConfiguration newValue) + public ServiceBusConfiguration( + ServiceBusConfiguration oldValue, + ServiceBusConfiguration newValue + ) : base(oldValue, newValue) { - DatabaseContainer = BuildConfiguration.Combine(oldValue.DatabaseContainer, newValue.DatabaseContainer); + DatabaseContainer = BuildConfiguration.Combine( + oldValue.DatabaseContainer, + newValue.DatabaseContainer + ); } /// /// Gets the database container. /// public IDatabaseContainer DatabaseContainer { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.ServiceBus/ServiceBusContainer.cs b/src/Testcontainers.ServiceBus/ServiceBusContainer.cs index 32c35d3e7..74781a640 100644 --- a/src/Testcontainers.ServiceBus/ServiceBusContainer.cs +++ b/src/Testcontainers.ServiceBus/ServiceBusContainer.cs @@ -9,9 +9,7 @@ public sealed class ServiceBusContainer : DockerContainer /// /// The container configuration. public ServiceBusContainer(ServiceBusConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Service Bus connection string. @@ -20,10 +18,20 @@ public ServiceBusContainer(ServiceBusConfiguration configuration) public string GetConnectionString() { var properties = new Dictionary(); - properties.Add("Endpoint", new UriBuilder("amqp", Hostname, GetMappedPublicPort(ServiceBusBuilder.ServiceBusPort)).ToString()); + 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))); + return string.Join( + ";", + properties.Select(property => string.Join("=", property.Key, property.Value)) + ); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.ServiceBus/Testcontainers.ServiceBus.csproj b/src/Testcontainers.ServiceBus/Testcontainers.ServiceBus.csproj index f24f1b880..98bc56ba1 100644 --- a/src/Testcontainers.ServiceBus/Testcontainers.ServiceBus.csproj +++ b/src/Testcontainers.ServiceBus/Testcontainers.ServiceBus.csproj @@ -1,13 +1,17 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + + diff --git a/src/Testcontainers.ServiceBus/Usings.cs b/src/Testcontainers.ServiceBus/Usings.cs index b8e2cde7e..1beb1dfaa 100644 --- a/src/Testcontainers.ServiceBus/Usings.cs +++ b/src/Testcontainers.ServiceBus/Usings.cs @@ -8,4 +8,4 @@ global using DotNet.Testcontainers.Containers; global using DotNet.Testcontainers.Networks; global using JetBrains.Annotations; -global using Testcontainers.MsSql; \ No newline at end of file +global using Testcontainers.MsSql; diff --git a/src/Testcontainers.Sftp/SftpBuilder.cs b/src/Testcontainers.Sftp/SftpBuilder.cs index d37b7c460..45a102fbc 100644 --- a/src/Testcontainers.Sftp/SftpBuilder.cs +++ b/src/Testcontainers.Sftp/SftpBuilder.cs @@ -63,7 +63,10 @@ public SftpBuilder WithPassword(string password) /// A configured instance of . public SftpBuilder WithUploadDirectory(string uploadDirectory) { - return Merge(DockerResourceConfiguration, new SftpConfiguration(uploadDirectory: uploadDirectory)); + return Merge( + DockerResourceConfiguration, + new SftpConfiguration(uploadDirectory: uploadDirectory) + ); } /// @@ -71,13 +74,16 @@ public override SftpContainer Build() { Validate(); - var sftpBuilder = WithCommand(string.Join( - ":", - DockerResourceConfiguration.Username, - DockerResourceConfiguration.Password, - string.Empty, - string.Empty, - DockerResourceConfiguration.UploadDirectory)); + var sftpBuilder = WithCommand( + string.Join( + ":", + DockerResourceConfiguration.Username, + DockerResourceConfiguration.Password, + string.Empty, + string.Empty, + DockerResourceConfiguration.UploadDirectory + ) + ); return new SftpContainer(sftpBuilder.DockerResourceConfiguration); } @@ -91,7 +97,9 @@ protected override SftpBuilder Init() .WithUsername(DefaultUsername) .WithPassword(DefaultPassword) .WithUploadDirectory(DefaultUploadDirectory) - .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("Server listening on .+")); + .WithWaitStrategy( + Wait.ForUnixContainer().UntilMessageIsLogged("Server listening on .+") + ); } /// @@ -99,21 +107,35 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Username, nameof(DockerResourceConfiguration.Username)) + _ = Guard + .Argument( + DockerResourceConfiguration.Username, + nameof(DockerResourceConfiguration.Username) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Password, nameof(DockerResourceConfiguration.Password)) + _ = Guard + .Argument( + DockerResourceConfiguration.Password, + nameof(DockerResourceConfiguration.Password) + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.UploadDirectory, nameof(DockerResourceConfiguration.UploadDirectory)) + _ = Guard + .Argument( + DockerResourceConfiguration.UploadDirectory, + nameof(DockerResourceConfiguration.UploadDirectory) + ) .NotNull() .NotEmpty(); } /// - protected override SftpBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override SftpBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new SftpConfiguration(resourceConfiguration)); } @@ -129,4 +151,4 @@ protected override SftpBuilder Merge(SftpConfiguration oldValue, SftpConfigurati { return new SftpBuilder(new SftpConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Sftp/SftpConfiguration.cs b/src/Testcontainers.Sftp/SftpConfiguration.cs index 9dfb00c44..2a616500b 100644 --- a/src/Testcontainers.Sftp/SftpConfiguration.cs +++ b/src/Testcontainers.Sftp/SftpConfiguration.cs @@ -13,7 +13,8 @@ public sealed class SftpConfiguration : ContainerConfiguration public SftpConfiguration( string username = null, string password = null, - string uploadDirectory = null) + string uploadDirectory = null + ) { Username = username; Password = password; @@ -24,7 +25,9 @@ public SftpConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public SftpConfiguration(IResourceConfiguration resourceConfiguration) + public SftpConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -60,7 +63,10 @@ public SftpConfiguration(SftpConfiguration oldValue, SftpConfiguration newValue) { Username = BuildConfiguration.Combine(oldValue.Username, newValue.Username); Password = BuildConfiguration.Combine(oldValue.Password, newValue.Password); - UploadDirectory = BuildConfiguration.Combine(oldValue.UploadDirectory, newValue.UploadDirectory); + UploadDirectory = BuildConfiguration.Combine( + oldValue.UploadDirectory, + newValue.UploadDirectory + ); } /// @@ -77,4 +83,4 @@ public SftpConfiguration(SftpConfiguration oldValue, SftpConfiguration newValue) /// Gets the directory to which files are uploaded. /// public string UploadDirectory { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Sftp/SftpContainer.cs b/src/Testcontainers.Sftp/SftpContainer.cs index d93956f73..207908e13 100644 --- a/src/Testcontainers.Sftp/SftpContainer.cs +++ b/src/Testcontainers.Sftp/SftpContainer.cs @@ -9,7 +9,5 @@ public sealed class SftpContainer : DockerContainer /// /// The container configuration. public SftpContainer(SftpConfiguration configuration) - : base(configuration) - { - } -} \ No newline at end of file + : base(configuration) { } +} diff --git a/src/Testcontainers.Sftp/Testcontainers.Sftp.csproj b/src/Testcontainers.Sftp/Testcontainers.Sftp.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Sftp/Testcontainers.Sftp.csproj +++ b/src/Testcontainers.Sftp/Testcontainers.Sftp.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Sftp/Usings.cs b/src/Testcontainers.Sftp/Usings.cs index fa3a104a1..9add3e4ce 100644 --- a/src/Testcontainers.Sftp/Usings.cs +++ b/src/Testcontainers.Sftp/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Typesense/Testcontainers.Typesense.csproj b/src/Testcontainers.Typesense/Testcontainers.Typesense.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Typesense/Testcontainers.Typesense.csproj +++ b/src/Testcontainers.Typesense/Testcontainers.Typesense.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Typesense/TypesenseBuilder.cs b/src/Testcontainers.Typesense/TypesenseBuilder.cs index c7f926f3f..90f9aa81c 100644 --- a/src/Testcontainers.Typesense/TypesenseBuilder.cs +++ b/src/Testcontainers.Typesense/TypesenseBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Typesense; /// [PublicAPI] -public sealed class TypesenseBuilder : ContainerBuilder +public sealed class TypesenseBuilder + : ContainerBuilder { public const string TypesenseImage = "typesense/typesense:28.0"; @@ -69,8 +70,15 @@ protected override TypesenseBuilder Init() .WithPortBinding(TypesensePort, true) .WithDataDirectory(DefaultDataDirectory) .WithApiKey(DefaultApiKey) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPort(TypesensePort).ForPath("/health").ForResponseMessageMatching(IsNodeReadyAsync))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request + .ForPort(TypesensePort) + .ForPath("/health") + .ForResponseMessageMatching(IsNodeReadyAsync) + ) + ); } /// @@ -78,38 +86,53 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Environments["TYPESENSE_DATA_DIR"], "DataDirectory") + _ = Guard + .Argument( + DockerResourceConfiguration.Environments["TYPESENSE_DATA_DIR"], + "DataDirectory" + ) .NotNull() .NotEmpty(); - _ = Guard.Argument(DockerResourceConfiguration.Environments["TYPESENSE_API_KEY"], "ApiKey") + _ = Guard + .Argument(DockerResourceConfiguration.Environments["TYPESENSE_API_KEY"], "ApiKey") .NotNull() .NotEmpty(); } /// - protected override TypesenseBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override TypesenseBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new TypesenseConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new TypesenseConfiguration(resourceConfiguration) + ); } /// protected override TypesenseBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new TypesenseConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new TypesenseConfiguration(resourceConfiguration) + ); } /// - protected override TypesenseBuilder Merge(TypesenseConfiguration oldValue, TypesenseConfiguration newValue) + protected override TypesenseBuilder Merge( + TypesenseConfiguration oldValue, + TypesenseConfiguration newValue + ) { return new TypesenseBuilder(new TypesenseConfiguration(oldValue, newValue)); } private static async Task IsNodeReadyAsync(HttpResponseMessage response) { - var content = await response.Content.ReadAsStringAsync() - .ConfigureAwait(false); + var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return "{\"ok\":true}".Equals(content, StringComparison.OrdinalIgnoreCase); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Typesense/TypesenseConfiguration.cs b/src/Testcontainers.Typesense/TypesenseConfiguration.cs index aaa5a4b50..eef997bbc 100644 --- a/src/Testcontainers.Typesense/TypesenseConfiguration.cs +++ b/src/Testcontainers.Typesense/TypesenseConfiguration.cs @@ -7,15 +7,15 @@ public sealed class TypesenseConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public TypesenseConfiguration() - { - } + public TypesenseConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public TypesenseConfiguration(IResourceConfiguration resourceConfiguration) + public TypesenseConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public TypesenseConfiguration(TypesenseConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public TypesenseConfiguration(TypesenseConfiguration oldValue, TypesenseConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Typesense/TypesenseContainer.cs b/src/Testcontainers.Typesense/TypesenseContainer.cs index d94a63aee..073e83b33 100644 --- a/src/Testcontainers.Typesense/TypesenseContainer.cs +++ b/src/Testcontainers.Typesense/TypesenseContainer.cs @@ -9,9 +9,7 @@ public sealed class TypesenseContainer : DockerContainer /// /// The container configuration. public TypesenseContainer(TypesenseConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } /// /// Gets the Typesense base address. @@ -19,6 +17,10 @@ public TypesenseContainer(TypesenseConfiguration configuration) /// The Typesense base address. public string GetBaseAddress() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(TypesenseBuilder.TypesensePort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(TypesenseBuilder.TypesensePort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Typesense/Usings.cs b/src/Testcontainers.Typesense/Usings.cs index cafc6c2ef..30575e05d 100644 --- a/src/Testcontainers.Typesense/Usings.cs +++ b/src/Testcontainers.Typesense/Usings.cs @@ -6,4 +6,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Weaviate/Testcontainers.Weaviate.csproj b/src/Testcontainers.Weaviate/Testcontainers.Weaviate.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.Weaviate/Testcontainers.Weaviate.csproj +++ b/src/Testcontainers.Weaviate/Testcontainers.Weaviate.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.Weaviate/Usings.cs b/src/Testcontainers.Weaviate/Usings.cs index 79fd3af9b..b31708db0 100644 --- a/src/Testcontainers.Weaviate/Usings.cs +++ b/src/Testcontainers.Weaviate/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Configurations; global using DotNet.Testcontainers.Containers; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/src/Testcontainers.Weaviate/WeaviateBuilder.cs b/src/Testcontainers.Weaviate/WeaviateBuilder.cs index 92d56dcaa..e562d5dec 100644 --- a/src/Testcontainers.Weaviate/WeaviateBuilder.cs +++ b/src/Testcontainers.Weaviate/WeaviateBuilder.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Weaviate; /// [PublicAPI] -public sealed class WeaviateBuilder : ContainerBuilder +public sealed class WeaviateBuilder + : ContainerBuilder { public const string WeaviateImage = "semitechnologies/weaviate:1.26.14"; @@ -13,15 +14,16 @@ public sealed class WeaviateBuilder : ContainerBuilder /// Initializes a new instance of the class. /// - public WeaviateBuilder() : this(new WeaviateConfiguration()) - => DockerResourceConfiguration = Init().DockerResourceConfiguration; + public WeaviateBuilder() + : this(new WeaviateConfiguration()) => + DockerResourceConfiguration = Init().DockerResourceConfiguration; /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - private WeaviateBuilder(WeaviateConfiguration resourceConfiguration) : base(resourceConfiguration) - => DockerResourceConfiguration = resourceConfiguration; + private WeaviateBuilder(WeaviateConfiguration resourceConfiguration) + : base(resourceConfiguration) => DockerResourceConfiguration = resourceConfiguration; /// protected override WeaviateConfiguration DockerResourceConfiguration { get; } @@ -34,28 +36,34 @@ public override WeaviateContainer Build() } /// - protected override WeaviateBuilder Init() - => base.Init() + protected override WeaviateBuilder Init() => + base.Init() .WithImage(WeaviateImage) .WithPortBinding(WeaviateHttpPort, true) .WithPortBinding(WeaviateGrpcPort, true) .WithEnvironment("AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED", "true") .WithEnvironment("PERSISTENCE_DATA_PATH", "/var/lib/weaviate") - .WithWaitStrategy(Wait.ForUnixContainer() - .UntilPortIsAvailable(WeaviateHttpPort) - .UntilPortIsAvailable(WeaviateGrpcPort) - .UntilHttpRequestIsSucceeded(request => - request.ForPath("/v1/.well-known/ready").ForPort(WeaviateHttpPort))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilPortIsAvailable(WeaviateHttpPort) + .UntilPortIsAvailable(WeaviateGrpcPort) + .UntilHttpRequestIsSucceeded(request => + request.ForPath("/v1/.well-known/ready").ForPort(WeaviateHttpPort) + ) + ); /// - protected override WeaviateBuilder Clone(IResourceConfiguration resourceConfiguration) - => Merge(DockerResourceConfiguration, new WeaviateConfiguration(resourceConfiguration)); + protected override WeaviateBuilder Clone( + IResourceConfiguration resourceConfiguration + ) => Merge(DockerResourceConfiguration, new WeaviateConfiguration(resourceConfiguration)); /// - protected override WeaviateBuilder Clone(IContainerConfiguration resourceConfiguration) - => Merge(DockerResourceConfiguration, new WeaviateConfiguration(resourceConfiguration)); + protected override WeaviateBuilder Clone(IContainerConfiguration resourceConfiguration) => + Merge(DockerResourceConfiguration, new WeaviateConfiguration(resourceConfiguration)); /// - protected override WeaviateBuilder Merge(WeaviateConfiguration oldValue, WeaviateConfiguration newValue) - => new(new WeaviateConfiguration(oldValue, newValue)); -} \ No newline at end of file + protected override WeaviateBuilder Merge( + WeaviateConfiguration oldValue, + WeaviateConfiguration newValue + ) => new(new WeaviateConfiguration(oldValue, newValue)); +} diff --git a/src/Testcontainers.Weaviate/WeaviateConfiguration.cs b/src/Testcontainers.Weaviate/WeaviateConfiguration.cs index 87d42c016..fa683affa 100644 --- a/src/Testcontainers.Weaviate/WeaviateConfiguration.cs +++ b/src/Testcontainers.Weaviate/WeaviateConfiguration.cs @@ -7,15 +7,15 @@ public sealed class WeaviateConfiguration : ContainerConfiguration /// /// Initializes a new instance of the class. /// - public WeaviateConfiguration() - { - } + public WeaviateConfiguration() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public WeaviateConfiguration(IResourceConfiguration resourceConfiguration) + public WeaviateConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -47,7 +47,5 @@ public WeaviateConfiguration(WeaviateConfiguration resourceConfiguration) /// The old Docker resource configuration. /// The new Docker resource configuration. public WeaviateConfiguration(WeaviateConfiguration oldValue, WeaviateConfiguration newValue) - : base(oldValue, newValue) - { - } -} \ No newline at end of file + : base(oldValue, newValue) { } +} diff --git a/src/Testcontainers.Weaviate/WeaviateContainer.cs b/src/Testcontainers.Weaviate/WeaviateContainer.cs index 6eba03c0d..f5f25a068 100644 --- a/src/Testcontainers.Weaviate/WeaviateContainer.cs +++ b/src/Testcontainers.Weaviate/WeaviateContainer.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Weaviate; /// [PublicAPI] -public sealed class WeaviateContainer(WeaviateConfiguration configuration) : DockerContainer(configuration) +public sealed class WeaviateContainer(WeaviateConfiguration configuration) + : DockerContainer(configuration) { /// /// Gets the Weaviate base address. @@ -10,6 +11,10 @@ public sealed class WeaviateContainer(WeaviateConfiguration configuration) : Doc /// The Weaviate base address. public string GetBaseAddress() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(WeaviateBuilder.WeaviateHttpPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(WeaviateBuilder.WeaviateHttpPort) + ).ToString(); } -} \ No newline at end of file +} diff --git a/src/Testcontainers.WebDriver/Testcontainers.WebDriver.csproj b/src/Testcontainers.WebDriver/Testcontainers.WebDriver.csproj index 9a25b9c4d..fd9c3fe09 100644 --- a/src/Testcontainers.WebDriver/Testcontainers.WebDriver.csproj +++ b/src/Testcontainers.WebDriver/Testcontainers.WebDriver.csproj @@ -1,12 +1,16 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + diff --git a/src/Testcontainers.WebDriver/Usings.cs b/src/Testcontainers.WebDriver/Usings.cs index 00e88cf71..e4b6354ae 100644 --- a/src/Testcontainers.WebDriver/Usings.cs +++ b/src/Testcontainers.WebDriver/Usings.cs @@ -13,4 +13,4 @@ global using DotNet.Testcontainers.Images; global using DotNet.Testcontainers.Networks; global using JetBrains.Annotations; -global using Microsoft.Extensions.Logging.Abstractions; \ No newline at end of file +global using Microsoft.Extensions.Logging.Abstractions; diff --git a/src/Testcontainers.WebDriver/WebDriverBrowser.cs b/src/Testcontainers.WebDriver/WebDriverBrowser.cs index 5e04f32c4..80ad92892 100644 --- a/src/Testcontainers.WebDriver/WebDriverBrowser.cs +++ b/src/Testcontainers.WebDriver/WebDriverBrowser.cs @@ -9,26 +9,30 @@ public readonly struct WebDriverBrowser /// /// Gets the Selenium standalone Chrome configuration. /// - public static readonly WebDriverBrowser Chrome = new WebDriverBrowser("selenium/standalone-chrome:110.0"); + public static readonly WebDriverBrowser Chrome = new WebDriverBrowser( + "selenium/standalone-chrome:110.0" + ); /// /// Gets the Selenium standalone Firefox configuration. /// - public static readonly WebDriverBrowser Firefox = new WebDriverBrowser("selenium/standalone-firefox:110.0"); + public static readonly WebDriverBrowser Firefox = new WebDriverBrowser( + "selenium/standalone-firefox:110.0" + ); /// /// Gets the Selenium standalone Edge configuration. /// - public static readonly WebDriverBrowser Edge = new WebDriverBrowser("selenium/standalone-edge:110.0"); + public static readonly WebDriverBrowser Edge = new WebDriverBrowser( + "selenium/standalone-edge:110.0" + ); /// /// Initializes a new instance of the struct. /// /// The Selenium standalone Docker image. public WebDriverBrowser(string image) - : this(new DockerImage(image)) - { - } + : this(new DockerImage(image)) { } /// /// Initializes a new instance of the struct. @@ -44,4 +48,4 @@ public WebDriverBrowser(IImage image) /// [NotNull] public IImage Image { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.WebDriver/WebDriverBuilder.cs b/src/Testcontainers.WebDriver/WebDriverBuilder.cs index 4ec108ecc..7c1cb77cf 100644 --- a/src/Testcontainers.WebDriver/WebDriverBuilder.cs +++ b/src/Testcontainers.WebDriver/WebDriverBuilder.cs @@ -5,7 +5,8 @@ namespace Testcontainers.WebDriver; /// Find further information about the Selenium Grid image, including its configurations, here: https://github.com/SeleniumHQ/docker-selenium. /// [PublicAPI] -public sealed class WebDriverBuilder : ContainerBuilder +public sealed class WebDriverBuilder + : ContainerBuilder { public const string WebDriverNetworkAlias = "standalone-container"; @@ -17,7 +18,12 @@ public sealed class WebDriverBuilder : ContainerBuilder /// Initializes a new instance of the class. @@ -64,7 +70,10 @@ public WebDriverBuilder WithBrowser(WebDriverBrowser webDriverBrowser) /// A configured instance of . public WebDriverBuilder WithConfigurationFromTomlFile(string configTomlFilePath) { - return WithResourceMapping(new FileInfo(configTomlFilePath), new FileInfo("/opt/bin/config.toml")); + return WithResourceMapping( + new FileInfo(configTomlFilePath), + new FileInfo("/opt/bin/config.toml") + ); } /// @@ -81,7 +90,10 @@ public WebDriverBuilder WithRecording() .WithEnvironment("DISPLAY_CONTAINER_NAME", WebDriverNetworkAlias) .Build(); - return Merge(DockerResourceConfiguration, new WebDriverConfiguration(ffmpegContainer: ffmpegContainer)); + return Merge( + DockerResourceConfiguration, + new WebDriverConfiguration(ffmpegContainer: ffmpegContainer) + ); } /// @@ -100,24 +112,42 @@ protected override WebDriverBuilder Init() .WithNetworkAliases(WebDriverNetworkAlias) .WithPortBinding(WebDriverPort, true) .WithPortBinding(VncServerPort, true) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPath("/wd/hub/status").ForPort(WebDriverPort).ForResponseMessageMatching(IsGridReadyAsync))); + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request + .ForPath("/wd/hub/status") + .ForPort(WebDriverPort) + .ForResponseMessageMatching(IsGridReadyAsync) + ) + ); } /// - protected override WebDriverBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override WebDriverBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new WebDriverConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new WebDriverConfiguration(resourceConfiguration) + ); } /// protected override WebDriverBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new WebDriverConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new WebDriverConfiguration(resourceConfiguration) + ); } /// - protected override WebDriverBuilder Merge(WebDriverConfiguration oldValue, WebDriverConfiguration newValue) + protected override WebDriverBuilder Merge( + WebDriverConfiguration oldValue, + WebDriverConfiguration newValue + ) { return new WebDriverBuilder(new WebDriverConfiguration(oldValue, newValue)); } @@ -132,14 +162,13 @@ protected override WebDriverBuilder Merge(WebDriverConfiguration oldValue, WebDr /// A value indicating whether the Selenium Grid is ready. private static async Task IsGridReadyAsync(HttpResponseMessage response) { - var jsonString = await response.Content.ReadAsStringAsync() - .ConfigureAwait(false); + var jsonString = await response.Content.ReadAsStringAsync().ConfigureAwait(false); try { - return JsonDocument.Parse(jsonString) - .RootElement - .GetProperty("value") + return JsonDocument + .Parse(jsonString) + .RootElement.GetProperty("value") .GetProperty("ready") .GetBoolean(); } @@ -148,4 +177,4 @@ private static async Task IsGridReadyAsync(HttpResponseMessage response) return false; } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.WebDriver/WebDriverConfiguration.cs b/src/Testcontainers.WebDriver/WebDriverConfiguration.cs index cd5f2fc01..ed111c9eb 100644 --- a/src/Testcontainers.WebDriver/WebDriverConfiguration.cs +++ b/src/Testcontainers.WebDriver/WebDriverConfiguration.cs @@ -17,7 +17,9 @@ public WebDriverConfiguration(IContainer ffmpegContainer = null) /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public WebDriverConfiguration(IResourceConfiguration resourceConfiguration) + public WebDriverConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -51,11 +53,14 @@ public WebDriverConfiguration(WebDriverConfiguration resourceConfiguration) public WebDriverConfiguration(WebDriverConfiguration oldValue, WebDriverConfiguration newValue) : base(oldValue, newValue) { - FFmpegContainer = BuildConfiguration.Combine(oldValue.FFmpegContainer, newValue.FFmpegContainer); + FFmpegContainer = BuildConfiguration.Combine( + oldValue.FFmpegContainer, + newValue.FFmpegContainer + ); } /// /// Gets the FFmpeg container. /// public IContainer FFmpegContainer { get; } -} \ No newline at end of file +} diff --git a/src/Testcontainers.WebDriver/WebDriverContainer.cs b/src/Testcontainers.WebDriver/WebDriverContainer.cs index 4797d6e0d..f6a003578 100644 --- a/src/Testcontainers.WebDriver/WebDriverContainer.cs +++ b/src/Testcontainers.WebDriver/WebDriverContainer.cs @@ -25,7 +25,11 @@ public WebDriverContainer(WebDriverConfiguration configuration) /// The Selenium Grid connection string. public string GetConnectionString() { - return new UriBuilder(Uri.UriSchemeHttp, Hostname, GetMappedPublicPort(WebDriverBuilder.WebDriverPort)).ToString(); + return new UriBuilder( + Uri.UriSchemeHttp, + Hostname, + GetMappedPublicPort(WebDriverBuilder.WebDriverPort) + ).ToString(); } /// @@ -48,18 +52,30 @@ public INetwork GetNetwork() /// The video recording is either not enabled or the container has not been stopped. public async Task ExportVideoAsync(string target, CancellationToken ct = default) { - Guard.Argument(_ffmpegContainer.State, nameof(_ffmpegContainer.State)) - .ThrowIf(argument => TestcontainersStates.Undefined.Equals(argument.Value), _ => new InvalidOperationException("Could not export video. Please enable the video recording first.")); - - Guard.Argument(_ffmpegContainer.State, nameof(_ffmpegContainer.State)) - .ThrowIf(argument => !TestcontainersStates.Exited.Equals(argument.Value), _ => new InvalidOperationException("Could not export video. Please stop the WebDriver container first.")); - - var bytes = await _ffmpegContainer.ReadFileAsync(WebDriverBuilder.VideoFilePath, ct) + Guard + .Argument(_ffmpegContainer.State, nameof(_ffmpegContainer.State)) + .ThrowIf( + argument => TestcontainersStates.Undefined.Equals(argument.Value), + _ => new InvalidOperationException( + "Could not export video. Please enable the video recording first." + ) + ); + + Guard + .Argument(_ffmpegContainer.State, nameof(_ffmpegContainer.State)) + .ThrowIf( + argument => !TestcontainersStates.Exited.Equals(argument.Value), + _ => new InvalidOperationException( + "Could not export video. Please stop the WebDriver container first." + ) + ); + + var bytes = await _ffmpegContainer + .ReadFileAsync(WebDriverBuilder.VideoFilePath, ct) .ConfigureAwait(false); #if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER - await File.WriteAllBytesAsync(target, bytes, ct) - .ConfigureAwait(false); + await File.WriteAllBytesAsync(target, bytes, ct).ConfigureAwait(false); #else File.WriteAllBytes(target, bytes); #endif @@ -68,11 +84,9 @@ await File.WriteAllBytesAsync(target, bytes, ct) /// protected override async Task UnsafeCreateAsync(CancellationToken ct = default) { - await _configuration.Networks.Single().CreateAsync(ct) - .ConfigureAwait(false); + await _configuration.Networks.Single().CreateAsync(ct).ConfigureAwait(false); - await base.UnsafeCreateAsync(ct) - .ConfigureAwait(false); + await base.UnsafeCreateAsync(ct).ConfigureAwait(false); } /// @@ -84,21 +98,17 @@ protected override Task UnsafeDeleteAsync(CancellationToken ct = default) /// protected override async Task UnsafeStartAsync(CancellationToken ct = default) { - await base.UnsafeStartAsync(ct) - .ConfigureAwait(false); + await base.UnsafeStartAsync(ct).ConfigureAwait(false); - await _ffmpegContainer.StartAsync(ct) - .ConfigureAwait(false); + await _ffmpegContainer.StartAsync(ct).ConfigureAwait(false); } /// protected override async Task UnsafeStopAsync(CancellationToken ct = default) { - await _ffmpegContainer.StopAsync(ct) - .ConfigureAwait(false); + await _ffmpegContainer.StopAsync(ct).ConfigureAwait(false); - await base.UnsafeStopAsync(ct) - .ConfigureAwait(false); + await base.UnsafeStopAsync(ct).ConfigureAwait(false); } /// @@ -106,23 +116,28 @@ await base.UnsafeStopAsync(ct) /// private sealed class FFmpegContainer : DockerContainer { - static FFmpegContainer() - { - } + static FFmpegContainer() { } /// /// Initializes a new instance of the class. /// private FFmpegContainer() - : base(new ContainerConfiguration(new ResourceConfiguration(new DockerEndpointAuthenticationConfiguration(new Uri("tcp://ffmpeg")), null, null, false, NullLogger.Instance))) - { - } + : base( + new ContainerConfiguration( + new ResourceConfiguration( + new DockerEndpointAuthenticationConfiguration(new Uri("tcp://ffmpeg")), + null, + null, + false, + NullLogger.Instance + ) + ) + ) { } /// /// Gets the instance. /// - public static IContainer Instance { get; } - = new FFmpegContainer(); + public static IContainer Instance { get; } = new FFmpegContainer(); /// public override Task StartAsync(CancellationToken ct = default) @@ -136,4 +151,4 @@ public override Task StopAsync(CancellationToken ct = default) return Task.CompletedTask; } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Xunit/ContainerFixture.cs b/src/Testcontainers.Xunit/ContainerFixture.cs index d368e46cf..360e31bd1 100644 --- a/src/Testcontainers.Xunit/ContainerFixture.cs +++ b/src/Testcontainers.Xunit/ContainerFixture.cs @@ -12,4 +12,4 @@ namespace Testcontainers.Xunit; public class ContainerFixture(IMessageSink messageSink) : ContainerLifetime(new MessageSinkLogger(messageSink)) where TBuilderEntity : IContainerBuilder, new() - where TContainerEntity : IContainer; \ No newline at end of file + where TContainerEntity : IContainer; diff --git a/src/Testcontainers.Xunit/ContainerLifetime.cs b/src/Testcontainers.Xunit/ContainerLifetime.cs index 3b07842f7..d6cbc844d 100644 --- a/src/Testcontainers.Xunit/ContainerLifetime.cs +++ b/src/Testcontainers.Xunit/ContainerLifetime.cs @@ -16,7 +16,9 @@ public abstract class ContainerLifetime : IAsy protected ContainerLifetime(ILogger logger) { - _container = new Lazy(() => Configure(new TBuilderEntity().WithLogger(logger)).Build()); + _container = new Lazy(() => + Configure(new TBuilderEntity().WithLogger(logger)).Build() + ); } /// @@ -41,8 +43,7 @@ public TContainerEntity Container /// async LifetimeTask IAsyncDisposable.DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -81,7 +82,7 @@ await Container.StartAsync(TestContext.Current.CancellationToken) #else await Container.StartAsync() #endif - .ConfigureAwait(false); + .ConfigureAwait(false); } catch (Exception e) { @@ -91,15 +92,14 @@ await Container.StartAsync() #if XUNIT_V3 /// -#else - /// +#else + /// #endif protected virtual async LifetimeTask DisposeAsyncCore() { if (_exception == null) { - await Container.DisposeAsync() - .ConfigureAwait(false); + await Container.DisposeAsync().ConfigureAwait(false); } } -} \ No newline at end of file +} diff --git a/src/Testcontainers.Xunit/ContainerTest.cs b/src/Testcontainers.Xunit/ContainerTest.cs index 50130830e..311136bc4 100644 --- a/src/Testcontainers.Xunit/ContainerTest.cs +++ b/src/Testcontainers.Xunit/ContainerTest.cs @@ -9,10 +9,13 @@ namespace Testcontainers.Xunit; /// The builder entity. /// The container entity. [PublicAPI] -public abstract class ContainerTest(ITestOutputHelper testOutputHelper, Func configure = null) - : ContainerLifetime(new TestOutputLogger(testOutputHelper)) +public abstract class ContainerTest( + ITestOutputHelper testOutputHelper, + Func configure = null +) : ContainerLifetime(new TestOutputLogger(testOutputHelper)) where TBuilderEntity : IContainerBuilder, new() where TContainerEntity : IContainer { - protected override TBuilderEntity Configure(TBuilderEntity builder) => configure != null ? configure(builder) : builder; -} \ No newline at end of file + protected override TBuilderEntity Configure(TBuilderEntity builder) => + configure != null ? configure(builder) : builder; +} diff --git a/src/Testcontainers.Xunit/DbContainerFixture.cs b/src/Testcontainers.Xunit/DbContainerFixture.cs index f533f06ed..8d64a1dc1 100644 --- a/src/Testcontainers.Xunit/DbContainerFixture.cs +++ b/src/Testcontainers.Xunit/DbContainerFixture.cs @@ -9,7 +9,8 @@ namespace Testcontainers.Xunit; /// The container entity. [PublicAPI] public abstract class DbContainerFixture(IMessageSink messageSink) - : ContainerFixture(messageSink), IDbContainerTestMethods + : ContainerFixture(messageSink), + IDbContainerTestMethods where TBuilderEntity : IContainerBuilder, new() where TContainerEntity : IContainer, IDatabaseContainer { @@ -18,10 +19,12 @@ public abstract class DbContainerFixture(IMess /// protected override async LifetimeTask InitializeAsync() { - await base.InitializeAsync() - .ConfigureAwait(false); + await base.InitializeAsync().ConfigureAwait(false); - _testMethods = new DbContainerTestMethods(DbProviderFactory, new Lazy(() => ConnectionString)); + _testMethods = new DbContainerTestMethods( + DbProviderFactory, + new Lazy(() => ConnectionString) + ); } /// @@ -29,12 +32,10 @@ protected override async LifetimeTask DisposeAsyncCore() { if (_testMethods != null) { - await _testMethods.DisposeAsync() - .ConfigureAwait(true); + await _testMethods.DisposeAsync().ConfigureAwait(true); } - await base.DisposeAsyncCore() - .ConfigureAwait(true); + await base.DisposeAsyncCore().ConfigureAwait(true); } /// @@ -55,12 +56,15 @@ await base.DisposeAsyncCore() public DbConnection OpenConnection() => _testMethods.OpenConnection(); /// - public ValueTask OpenConnectionAsync(CancellationToken cancellationToken = default) => _testMethods.OpenConnectionAsync(cancellationToken); + public ValueTask OpenConnectionAsync( + CancellationToken cancellationToken = default + ) => _testMethods.OpenConnectionAsync(cancellationToken); /// - public DbCommand CreateCommand(string commandText = null) => _testMethods.CreateCommand(commandText); + public DbCommand CreateCommand(string commandText = null) => + _testMethods.CreateCommand(commandText); /// public DbBatch CreateBatch() => _testMethods.CreateBatch(); #endif -} \ No newline at end of file +} diff --git a/src/Testcontainers.Xunit/DbContainerTest.cs b/src/Testcontainers.Xunit/DbContainerTest.cs index ae5b29bfc..457f1b885 100644 --- a/src/Testcontainers.Xunit/DbContainerTest.cs +++ b/src/Testcontainers.Xunit/DbContainerTest.cs @@ -7,8 +7,12 @@ namespace Testcontainers.Xunit; /// The builder entity. /// The container entity. [PublicAPI] -public abstract class DbContainerTest(ITestOutputHelper testOutputHelper, Func configure = null) - : ContainerTest(testOutputHelper, configure), IDbContainerTestMethods +public abstract class DbContainerTest( + ITestOutputHelper testOutputHelper, + Func configure = null +) + : ContainerTest(testOutputHelper, configure), + IDbContainerTestMethods where TBuilderEntity : IContainerBuilder, new() where TContainerEntity : IContainer, IDatabaseContainer { @@ -17,10 +21,12 @@ public abstract class DbContainerTest(ITestOut /// protected override async LifetimeTask InitializeAsync() { - await base.InitializeAsync() - .ConfigureAwait(false); + await base.InitializeAsync().ConfigureAwait(false); - _testMethods = new DbContainerTestMethods(DbProviderFactory, new Lazy(() => ConnectionString)); + _testMethods = new DbContainerTestMethods( + DbProviderFactory, + new Lazy(() => ConnectionString) + ); } /// @@ -28,12 +34,10 @@ protected override async LifetimeTask DisposeAsyncCore() { if (_testMethods != null) { - await _testMethods.DisposeAsync() - .ConfigureAwait(true); + await _testMethods.DisposeAsync().ConfigureAwait(true); } - await base.DisposeAsyncCore() - .ConfigureAwait(true); + await base.DisposeAsyncCore().ConfigureAwait(true); } /// @@ -54,12 +58,15 @@ await base.DisposeAsyncCore() public DbConnection OpenConnection() => _testMethods.OpenConnection(); /// - public ValueTask OpenConnectionAsync(CancellationToken cancellationToken = default) => _testMethods.OpenConnectionAsync(cancellationToken); + public ValueTask OpenConnectionAsync( + CancellationToken cancellationToken = default + ) => _testMethods.OpenConnectionAsync(cancellationToken); /// - public DbCommand CreateCommand(string commandText = null) => _testMethods.CreateCommand(commandText); + public DbCommand CreateCommand(string commandText = null) => + _testMethods.CreateCommand(commandText); /// public DbBatch CreateBatch() => _testMethods.CreateBatch(); #endif -} \ No newline at end of file +} diff --git a/src/Testcontainers.Xunit/DbContainerTestMethods.cs b/src/Testcontainers.Xunit/DbContainerTestMethods.cs index ec798553b..710de2e37 100644 --- a/src/Testcontainers.Xunit/DbContainerTestMethods.cs +++ b/src/Testcontainers.Xunit/DbContainerTestMethods.cs @@ -1,9 +1,14 @@ namespace Testcontainers.Xunit; -internal sealed class DbContainerTestMethods(DbProviderFactory dbProviderFactory, Lazy connectionString) : IDbContainerTestMethods, IAsyncDisposable +internal sealed class DbContainerTestMethods( + DbProviderFactory dbProviderFactory, + Lazy connectionString +) : IDbContainerTestMethods, IAsyncDisposable { - private readonly DbProviderFactory _dbProviderFactory = dbProviderFactory ?? throw new ArgumentNullException(nameof(dbProviderFactory)); - private readonly Lazy _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); + private readonly DbProviderFactory _dbProviderFactory = + dbProviderFactory ?? throw new ArgumentNullException(nameof(dbProviderFactory)); + private readonly Lazy _connectionString = + connectionString ?? throw new ArgumentNullException(nameof(connectionString)); #if NET8_0_OR_GREATER [CanBeNull] @@ -21,9 +26,12 @@ private DbDataSource DbDataSource public DbConnection OpenConnection() => DbDataSource.OpenConnection(); - public ValueTask OpenConnectionAsync(CancellationToken cancellationToken = default) => DbDataSource.OpenConnectionAsync(cancellationToken); + public ValueTask OpenConnectionAsync( + CancellationToken cancellationToken = default + ) => DbDataSource.OpenConnectionAsync(cancellationToken); - public DbCommand CreateCommand(string commandText = null) => DbDataSource.CreateCommand(commandText); + public DbCommand CreateCommand(string commandText = null) => + DbDataSource.CreateCommand(commandText); public DbBatch CreateBatch() => DbDataSource.CreateBatch(); @@ -31,11 +39,15 @@ private DbDataSource DbDataSource #else public DbConnection CreateConnection() { - var connection = _dbProviderFactory.CreateConnection() ?? throw new InvalidOperationException($"DbProviderFactory.CreateConnection() returned null for {_dbProviderFactory}"); + var connection = + _dbProviderFactory.CreateConnection() + ?? throw new InvalidOperationException( + $"DbProviderFactory.CreateConnection() returned null for {_dbProviderFactory}" + ); connection.ConnectionString = _connectionString.Value; return connection; } public ValueTask DisposeAsync() => default; #endif -} \ No newline at end of file +} diff --git a/src/Testcontainers.Xunit/IDbContainerTestMethods.cs b/src/Testcontainers.Xunit/IDbContainerTestMethods.cs index a45e032c2..35e95aead 100644 --- a/src/Testcontainers.Xunit/IDbContainerTestMethods.cs +++ b/src/Testcontainers.Xunit/IDbContainerTestMethods.cs @@ -60,4 +60,4 @@ internal interface IDbContainerTestMethods /// A that's ready for execution against the database. DbBatch CreateBatch(); #endif -} \ No newline at end of file +} diff --git a/src/Testcontainers.Xunit/Logger.cs b/src/Testcontainers.Xunit/Logger.cs index e3d8e5b53..cca6ebd1e 100644 --- a/src/Testcontainers.Xunit/Logger.cs +++ b/src/Testcontainers.Xunit/Logger.cs @@ -2,14 +2,30 @@ namespace Testcontainers.Xunit; internal abstract class Logger : ILogger { - protected static string GetMessage(TState state, Exception exception, Func formatter) + protected static string GetMessage( + TState state, + Exception exception, + Func formatter + ) { - return exception == null ? formatter(state, null) : $"{formatter(state, exception)}{Environment.NewLine}{exception}"; + return exception == null + ? formatter(state, null) + : $"{formatter(state, exception)}{Environment.NewLine}{exception}"; } - protected abstract void Log(TState state, Exception exception, Func formatter); + protected abstract void Log( + TState state, + Exception exception, + Func formatter + ); - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception exception, + Func formatter + ) { Log(state, exception, formatter); } @@ -17,4 +33,4 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None; public IDisposable BeginScope(TState state) => new NullScope(); -} \ No newline at end of file +} diff --git a/src/Testcontainers.Xunit/MessageSinkLogger.cs b/src/Testcontainers.Xunit/MessageSinkLogger.cs index 29a53d166..0a850705c 100644 --- a/src/Testcontainers.Xunit/MessageSinkLogger.cs +++ b/src/Testcontainers.Xunit/MessageSinkLogger.cs @@ -4,7 +4,11 @@ internal sealed class MessageSinkLogger(IMessageSink messageSink) : Logger { private readonly IMessageSink _messageSink = messageSink; - protected override void Log(TState state, Exception exception, Func formatter) + protected override void Log( + TState state, + Exception exception, + Func formatter + ) { if (_messageSink == null) { @@ -35,4 +39,4 @@ public override bool Equals(object obj) /// logs the runtime information once per Docker Engine API client and logger. /// public override int GetHashCode() => _messageSink?.GetHashCode() ?? 0; -} \ No newline at end of file +} diff --git a/src/Testcontainers.Xunit/NullScope.cs b/src/Testcontainers.Xunit/NullScope.cs index 16c6393dc..37e54646f 100644 --- a/src/Testcontainers.Xunit/NullScope.cs +++ b/src/Testcontainers.Xunit/NullScope.cs @@ -2,7 +2,5 @@ namespace Testcontainers.Xunit; internal sealed class NullScope : IDisposable { - public void Dispose() - { - } -} \ No newline at end of file + public void Dispose() { } +} diff --git a/src/Testcontainers.Xunit/TestOutputLogger.cs b/src/Testcontainers.Xunit/TestOutputLogger.cs index e4e856ee2..6454afb1c 100644 --- a/src/Testcontainers.Xunit/TestOutputLogger.cs +++ b/src/Testcontainers.Xunit/TestOutputLogger.cs @@ -4,7 +4,11 @@ internal sealed class TestOutputLogger(ITestOutputHelper testOutputHelper) : Log { private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); - protected override void Log(TState state, Exception exception, Func formatter) + protected override void Log( + TState state, + Exception exception, + Func formatter + ) { if (testOutputHelper == null) { @@ -12,6 +16,8 @@ protected override void Log(TState state, Exception exception, Func - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - - - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + + + + + + + + + + diff --git a/src/Testcontainers.Xunit/Usings.cs b/src/Testcontainers.Xunit/Usings.cs index 90d314624..861615c69 100644 --- a/src/Testcontainers.Xunit/Usings.cs +++ b/src/Testcontainers.Xunit/Usings.cs @@ -16,4 +16,4 @@ #else global using Xunit.Abstractions; global using LifetimeTask = System.Threading.Tasks.Task; -#endif \ No newline at end of file +#endif diff --git a/src/Testcontainers.XunitV3/Testcontainers.XunitV3.csproj b/src/Testcontainers.XunitV3/Testcontainers.XunitV3.csproj index a59b84b03..c99dac385 100644 --- a/src/Testcontainers.XunitV3/Testcontainers.XunitV3.csproj +++ b/src/Testcontainers.XunitV3/Testcontainers.XunitV3.csproj @@ -1,18 +1,22 @@ - - net8.0;net9.0;netstandard2.0;netstandard2.1 - latest - $(DefineConstants);XUNIT_V3 - - - - - - - - - - - - - \ No newline at end of file + + net8.0;net9.0;netstandard2.0;netstandard2.1 + latest + $(DefineConstants);XUNIT_V3 + + + + + + + + + + + + + diff --git a/src/Testcontainers/Builders/AbstractBuilder`4.cs b/src/Testcontainers/Builders/AbstractBuilder`4.cs index 5b7c0d857..e8369d395 100644 --- a/src/Testcontainers/Builders/AbstractBuilder`4.cs +++ b/src/Testcontainers/Builders/AbstractBuilder`4.cs @@ -18,7 +18,12 @@ namespace DotNet.Testcontainers.Builders /// The underlying Docker.DotNet resource entity. /// The configuration entity. [PublicAPI] - public abstract class AbstractBuilder : IAbstractBuilder + public abstract class AbstractBuilder< + TBuilderEntity, + TResourceEntity, + TCreateResourceEntity, + TConfigurationEntity + > : IAbstractBuilder where TBuilderEntity : IAbstractBuilder where TConfigurationEntity : IResourceConfiguration { @@ -26,9 +31,7 @@ public abstract class AbstractBuilder class. /// /// The Docker resource configuration. - protected AbstractBuilder(TConfigurationEntity dockerResourceConfiguration) - { - } + protected AbstractBuilder(TConfigurationEntity dockerResourceConfiguration) { } /// /// Gets the Docker resource configuration. @@ -48,21 +51,32 @@ public TBuilderEntity WithDockerEndpoint(Uri endpoint) } /// - public TBuilderEntity WithDockerEndpoint(IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig) + public TBuilderEntity WithDockerEndpoint( + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig + ) { - return Clone(new ResourceConfiguration(dockerEndpointAuthenticationConfiguration: dockerEndpointAuthConfig)); + return Clone( + new ResourceConfiguration( + dockerEndpointAuthenticationConfiguration: dockerEndpointAuthConfig + ) + ); } /// public TBuilderEntity WithCleanUp(bool cleanUp) { - return WithResourceReaperSessionId(TestcontainersSettings.ResourceReaperEnabled && cleanUp ? ResourceReaper.DefaultSessionId : Guid.Empty); + return WithResourceReaperSessionId( + TestcontainersSettings.ResourceReaperEnabled && cleanUp + ? ResourceReaper.DefaultSessionId + : Guid.Empty + ); } /// public TBuilderEntity WithReuse(bool reuse) { - return Clone(new ResourceConfiguration(reuse: reuse)).WithCleanUp(!reuse); + return Clone(new ResourceConfiguration(reuse: reuse)) + .WithCleanUp(!reuse); } /// @@ -78,10 +92,14 @@ public TBuilderEntity WithLabel(IReadOnlyDictionary labels) } /// - public TBuilderEntity WithCreateParameterModifier(Action parameterModifier) + public TBuilderEntity WithCreateParameterModifier( + Action parameterModifier + ) { var parameterModifiers = new[] { parameterModifier }; - return Clone(new ResourceConfiguration(parameterModifiers: parameterModifiers)); + return Clone( + new ResourceConfiguration(parameterModifiers: parameterModifiers) + ); } /// @@ -100,7 +118,10 @@ public TBuilderEntity WithLogger(ILogger logger) /// A configured instance of . protected TBuilderEntity WithResourceReaperSessionId(Guid resourceReaperSessionId) { - return WithLabel(ResourceReaper.ResourceReaperSessionLabel, resourceReaperSessionId.ToString("D")); + return WithLabel( + ResourceReaper.ResourceReaperSessionLabel, + resourceReaperSessionId.ToString("D") + ); } /// @@ -131,7 +152,9 @@ protected TBuilderEntity WithResourceReaperSessionId(Guid resourceReaperSessionI /// A configured instance of . protected virtual TBuilderEntity Init() { - return WithDockerEndpoint(TestcontainersSettings.OS.DockerEndpointAuthConfig).WithLabel(DefaultLabels.Instance).WithLogger(ConsoleLogger.Instance); + return WithDockerEndpoint(TestcontainersSettings.OS.DockerEndpointAuthConfig) + .WithLabel(DefaultLabels.Instance) + .WithLogger(ConsoleLogger.Instance); } /// @@ -140,15 +163,34 @@ protected virtual TBuilderEntity Init() /// Thrown when a mandatory Docker resource configuration is not set. protected virtual void Validate() { - _ = Guard.Argument(DockerResourceConfiguration.Logger, nameof(IResourceConfiguration.Logger)) + _ = Guard + .Argument( + DockerResourceConfiguration.Logger, + nameof(IResourceConfiguration.Logger) + ) .NotNull(); - _ = Guard.Argument(DockerResourceConfiguration.DockerEndpointAuthConfig, nameof(IResourceConfiguration.DockerEndpointAuthConfig)) + _ = Guard + .Argument( + DockerResourceConfiguration.DockerEndpointAuthConfig, + nameof(IResourceConfiguration.DockerEndpointAuthConfig) + ) .ThrowIf(argument => argument.Value == null, CreateDockerUnavailableException); - const string reuseNotSupported = "Reuse cannot be used in conjunction with WithCleanUp(true)."; - _ = Guard.Argument(DockerResourceConfiguration, nameof(IResourceConfiguration.Reuse)) - .ThrowIf(argument => argument.Value.Reuse.HasValue && argument.Value.Reuse.Value && !Guid.Empty.Equals(argument.Value.SessionId), argument => new ArgumentException(reuseNotSupported, argument.Name)); + const string reuseNotSupported = + "Reuse cannot be used in conjunction with WithCleanUp(true)."; + _ = Guard + .Argument( + DockerResourceConfiguration, + nameof(IResourceConfiguration.Reuse) + ) + .ThrowIf( + argument => + argument.Value.Reuse.HasValue + && argument.Value.Reuse.Value + && !Guid.Empty.Equals(argument.Value.SessionId), + argument => new ArgumentException(reuseNotSupported, argument.Name) + ); } /// @@ -156,7 +198,9 @@ protected virtual void Validate() /// /// The Docker resource configuration. /// A configured instance of . - protected abstract TBuilderEntity Clone(IResourceConfiguration resourceConfiguration); + protected abstract TBuilderEntity Clone( + IResourceConfiguration resourceConfiguration + ); /// /// Merges the Docker resource builder configuration. @@ -164,22 +208,35 @@ protected virtual void Validate() /// The old Docker resource configuration. /// The new Docker resource configuration. /// A configured instance of . - protected abstract TBuilderEntity Merge(TConfigurationEntity oldValue, TConfigurationEntity newValue); - - private static Exception CreateDockerUnavailableException(Guard.ArgumentInfo argument) + protected abstract TBuilderEntity Merge( + TConfigurationEntity oldValue, + TConfigurationEntity newValue + ); + + private static Exception CreateDockerUnavailableException( + Guard.ArgumentInfo argument + ) { - var unavailableExceptions = TestcontainersSettings.DockerEndpointAuthProviders - .Select(authProvider => authProvider.LastException) + var unavailableExceptions = TestcontainersSettings + .DockerEndpointAuthProviders.Select(authProvider => authProvider.LastException) .Where(exception => exception != null); var exception = new AggregateException(unavailableExceptions); var exceptionInfo = new StringBuilder(512); - exceptionInfo.AppendLine("Docker is either not running or misconfigured. Please ensure that Docker is running and that the endpoint is properly configured."); - exceptionInfo.AppendLine("You can customize your configuration using either the environment variables or the ~/.testcontainers.properties file."); - exceptionInfo.AppendLine("For more information, visit: https://dotnet.testcontainers.org/custom_configuration/."); + exceptionInfo.AppendLine( + "Docker is either not running or misconfigured. Please ensure that Docker is running and that the endpoint is properly configured." + ); + exceptionInfo.AppendLine( + "You can customize your configuration using either the environment variables or the ~/.testcontainers.properties file." + ); + exceptionInfo.AppendLine( + "For more information, visit: https://dotnet.testcontainers.org/custom_configuration/." + ); exceptionInfo.AppendLine(" Details: "); - exceptionInfo.Append(string.Join(Environment.NewLine, exception.InnerExceptions.Select(e => " " + e.Message))); + exceptionInfo.Append( + string.Join(Environment.NewLine, exception.InnerExceptions.Select(e => " " + e.Message)) + ); return new DockerUnavailableException(exceptionInfo.ToString(), exception); } diff --git a/src/Testcontainers/Builders/Base64Provider.cs b/src/Testcontainers/Builders/Base64Provider.cs index 465477792..2baeec621 100644 --- a/src/Testcontainers/Builders/Base64Provider.cs +++ b/src/Testcontainers/Builders/Base64Provider.cs @@ -22,9 +22,7 @@ internal sealed class Base64Provider : IDockerRegistryAuthenticationProvider /// The logger. [PublicAPI] public Base64Provider(JsonDocument jsonDocument, ILogger logger) - : this(jsonDocument.RootElement, logger) - { - } + : this(jsonDocument.RootElement, logger) { } /// /// Initializes a new instance of the class. @@ -59,9 +57,16 @@ public static bool HasDockerRegistryName(JsonProperty property, string registryH return true; } - if (TryGetHost(propertyName, out var propertyNameNormalized) && TryGetHost(registryHost, out var registryHostNormalized)) + if ( + TryGetHost(propertyName, out var propertyNameNormalized) + && TryGetHost(registryHost, out var registryHostNormalized) + ) { - return string.Equals(propertyNameNormalized, registryHostNormalized, StringComparison.OrdinalIgnoreCase); + return string.Equals( + propertyNameNormalized, + registryHostNormalized, + StringComparison.OrdinalIgnoreCase + ); } else { @@ -72,7 +77,11 @@ public static bool HasDockerRegistryName(JsonProperty property, string registryH /// public bool IsApplicable(string hostname) { - return !JsonValueKind.Undefined.Equals(_rootElement.ValueKind) && !JsonValueKind.Null.Equals(_rootElement.ValueKind) && _rootElement.EnumerateObject().Any(property => HasDockerRegistryName(property, hostname)); + return !JsonValueKind.Undefined.Equals(_rootElement.ValueKind) + && !JsonValueKind.Null.Equals(_rootElement.ValueKind) + && _rootElement + .EnumerateObject() + .Any(property => HasDockerRegistryName(property, hostname)); } /// @@ -85,21 +94,31 @@ public IDockerRegistryAuthenticationConfiguration GetAuthConfig(string hostname) return null; } - var authProperty = _rootElement.EnumerateObject().LastOrDefault(property => HasDockerRegistryName(property, hostname)); + var authProperty = _rootElement + .EnumerateObject() + .LastOrDefault(property => HasDockerRegistryName(property, hostname)); if (JsonValueKind.Undefined.Equals(authProperty.Value.ValueKind)) { return null; } - if (authProperty.Value.TryGetProperty("identitytoken", out var identityToken) && JsonValueKind.String.Equals(identityToken.ValueKind)) + if ( + authProperty.Value.TryGetProperty("identitytoken", out var identityToken) + && JsonValueKind.String.Equals(identityToken.ValueKind) + ) { var identityTokenValue = identityToken.GetString(); if (!string.IsNullOrEmpty(identityTokenValue)) { _logger.DockerRegistryCredentialFound(hostname); - return new DockerRegistryAuthenticationConfiguration(authProperty.Name, null, null, identityTokenValue); + return new DockerRegistryAuthenticationConfiguration( + authProperty.Name, + null, + null, + identityTokenValue + ); } } @@ -108,7 +127,9 @@ public IDockerRegistryAuthenticationConfiguration GetAuthConfig(string hostname) return null; } - if (!JsonValueKind.String.Equals(auth.ValueKind) && !JsonValueKind.Null.Equals(auth.ValueKind)) + if ( + !JsonValueKind.String.Equals(auth.ValueKind) && !JsonValueKind.Null.Equals(auth.ValueKind) + ) { _logger.DockerRegistryAuthPropertyValueKindInvalid(hostname, auth.ValueKind); return null; @@ -143,7 +164,11 @@ public IDockerRegistryAuthenticationConfiguration GetAuthConfig(string hostname) } _logger.DockerRegistryCredentialFound(hostname); - return new DockerRegistryAuthenticationConfiguration(authProperty.Name, credential[0], credential[1]); + return new DockerRegistryAuthenticationConfiguration( + authProperty.Name, + credential[0], + credential[1] + ); } /// diff --git a/src/Testcontainers/Builders/BuildConfiguration.cs b/src/Testcontainers/Builders/BuildConfiguration.cs index a4dcec675..71adbd361 100644 --- a/src/Testcontainers/Builders/BuildConfiguration.cs +++ b/src/Testcontainers/Builders/BuildConfiguration.cs @@ -33,9 +33,7 @@ public static T Combine(T oldValue, T newValue) /// The new configuration. /// The type of elements in the collection. /// An updated configuration. - public static IEnumerable Combine( - IEnumerable oldValue, - IEnumerable newValue) + public static IEnumerable Combine(IEnumerable oldValue, IEnumerable newValue) { if (newValue == null && oldValue == null) { @@ -59,9 +57,7 @@ public static IEnumerable Combine( /// The new configuration. /// The type of elements in the collection. /// An updated configuration. - public static IReadOnlyList Combine( - IReadOnlyList oldValue, - IReadOnlyList newValue) + public static IReadOnlyList Combine(IReadOnlyList oldValue, IReadOnlyList newValue) { if (newValue == null && oldValue == null) { @@ -91,7 +87,8 @@ public static IReadOnlyList Combine( /// An updated configuration. public static ComposableEnumerable Combine( ComposableEnumerable oldValue, - ComposableEnumerable newValue) + ComposableEnumerable newValue + ) { // Creating a new container configuration before merging will follow this branch // and return the default value. If we use the overwrite implementation, @@ -121,7 +118,8 @@ public static ComposableEnumerable Combine( /// An updated configuration. public static IReadOnlyDictionary Combine( IReadOnlyDictionary oldValue, - IReadOnlyDictionary newValue) + IReadOnlyDictionary newValue + ) { if (newValue == null && oldValue == null) { diff --git a/src/Testcontainers/Builders/CommonDirectoryPath.cs b/src/Testcontainers/Builders/CommonDirectoryPath.cs index 3e8912e1f..64b2a68f9 100644 --- a/src/Testcontainers/Builders/CommonDirectoryPath.cs +++ b/src/Testcontainers/Builders/CommonDirectoryPath.cs @@ -38,14 +38,18 @@ public CommonDirectoryPath(string directoryPath) [PublicAPI] public static CommonDirectoryPath GetBinDirectory() { - var indexOfBinDirectory = WorkingDirectoryPath.LastIndexOf("bin", StringComparison.OrdinalIgnoreCase); + var indexOfBinDirectory = WorkingDirectoryPath.LastIndexOf( + "bin", + StringComparison.OrdinalIgnoreCase + ); if (indexOfBinDirectory > -1) { return new CommonDirectoryPath(WorkingDirectoryPath.Substring(0, indexOfBinDirectory)); } - const string message = "Cannot find 'bin' and resolve the base directory in the directory tree."; + const string message = + "Cannot find 'bin' and resolve the base directory in the directory tree."; throw new DirectoryNotFoundException(message); } @@ -59,7 +63,9 @@ public static CommonDirectoryPath GetBinDirectory() /// The first Git directory upwards the directory tree. /// Thrown when the Git directory was not found upwards the directory tree. [PublicAPI] - public static CommonDirectoryPath GetGitDirectory([CallerFilePath, NotNull] string filePath = "") + public static CommonDirectoryPath GetGitDirectory( + [CallerFilePath, NotNull] string filePath = "" + ) { return new CommonDirectoryPath(GetDirectoryPath(Path.GetDirectoryName(filePath), ".git")); } @@ -74,9 +80,13 @@ public static CommonDirectoryPath GetGitDirectory([CallerFilePath, NotNull] stri /// The first Visual Studio solution file upwards the directory tree. /// Thrown when the Visual Studio solution file was not found upwards the directory tree. [PublicAPI] - public static CommonDirectoryPath GetSolutionDirectory([CallerFilePath, NotNull] string filePath = "") + public static CommonDirectoryPath GetSolutionDirectory( + [CallerFilePath, NotNull] string filePath = "" + ) { - return new CommonDirectoryPath(GetDirectoryPath(Path.GetDirectoryName(filePath), "*.sln", "*.slnx")); + return new CommonDirectoryPath( + GetDirectoryPath(Path.GetDirectoryName(filePath), "*.sln", "*.slnx") + ); } /// @@ -89,9 +99,13 @@ public static CommonDirectoryPath GetSolutionDirectory([CallerFilePath, NotNull] /// The first CSharp, FSharp or Visual Basic project file upwards the directory tree. /// Thrown when no CSharp, FSharp or Visual Basic project file was found upwards the directory tree. [PublicAPI] - public static CommonDirectoryPath GetProjectDirectory([CallerFilePath, NotNull] string filePath = "") + public static CommonDirectoryPath GetProjectDirectory( + [CallerFilePath, NotNull] string filePath = "" + ) { - return new CommonDirectoryPath(GetDirectoryPath(Path.GetDirectoryName(filePath), "*.csproj", "*.fsproj", "*.vbproj")); + return new CommonDirectoryPath( + GetDirectoryPath(Path.GetDirectoryName(filePath), "*.csproj", "*.fsproj", "*.vbproj") + ); } /// @@ -100,25 +114,35 @@ public static CommonDirectoryPath GetProjectDirectory([CallerFilePath, NotNull] /// The caller file path. /// The caller file path directory. [PublicAPI] - public static CommonDirectoryPath GetCallerFileDirectory([CallerFilePath, NotNull] string filePath = "") + public static CommonDirectoryPath GetCallerFileDirectory( + [CallerFilePath, NotNull] string filePath = "" + ) { return new CommonDirectoryPath(Path.GetDirectoryName(filePath)); } private static string GetDirectoryPath(string path, params string[] searchPatterns) { - return GetDirectoryPath(Directory.Exists(path) ? new DirectoryInfo(path) : null, searchPatterns); + return GetDirectoryPath( + Directory.Exists(path) ? new DirectoryInfo(path) : null, + searchPatterns + ); } private static string GetDirectoryPath(DirectoryInfo path, params string[] searchPatterns) { if (path != null) { - var paths = searchPatterns.SelectMany(searchPattern => path.EnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly)).Any(); + var paths = searchPatterns + .SelectMany(searchPattern => + path.EnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly) + ) + .Any(); return paths ? path.FullName : GetDirectoryPath(path.Parent, searchPatterns); } - var message = $"Cannot find '{string.Join(", ", searchPatterns)}' and resolve the base directory in the directory tree."; + var message = + $"Cannot find '{string.Join(", ", searchPatterns)}' and resolve the base directory in the directory tree."; throw new DirectoryNotFoundException(message); } } diff --git a/src/Testcontainers/Builders/ContainerBuilder.cs b/src/Testcontainers/Builders/ContainerBuilder.cs index 416640f48..1e744b875 100644 --- a/src/Testcontainers/Builders/ContainerBuilder.cs +++ b/src/Testcontainers/Builders/ContainerBuilder.cs @@ -26,7 +26,8 @@ namespace DotNet.Testcontainers.Builders /// /// [PublicAPI] - public class ContainerBuilder : ContainerBuilder + public class ContainerBuilder + : ContainerBuilder { /// /// Initializes a new instance of the class. @@ -64,7 +65,9 @@ protected sealed override ContainerBuilder Init() } /// - protected override ContainerBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override ContainerBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new ContainerConfiguration(resourceConfiguration)); } @@ -76,7 +79,10 @@ protected override ContainerBuilder Clone(IContainerConfiguration resourceConfig } /// - protected override ContainerBuilder Merge(IContainerConfiguration oldValue, IContainerConfiguration newValue) + protected override ContainerBuilder Merge( + IContainerConfiguration oldValue, + IContainerConfiguration newValue + ) { return new ContainerBuilder(new ContainerConfiguration(oldValue, newValue)); } diff --git a/src/Testcontainers/Builders/ContainerBuilder`3.cs b/src/Testcontainers/Builders/ContainerBuilder`3.cs index f508e7b51..5b635c97d 100644 --- a/src/Testcontainers/Builders/ContainerBuilder`3.cs +++ b/src/Testcontainers/Builders/ContainerBuilder`3.cs @@ -22,7 +22,14 @@ namespace DotNet.Testcontainers.Builders /// The resource entity. /// The configuration entity. [PublicAPI] - public abstract class ContainerBuilder : AbstractBuilder, IContainerBuilder + public abstract class ContainerBuilder + : AbstractBuilder< + TBuilderEntity, + TContainerEntity, + CreateContainerParameters, + TConfigurationEntity + >, + IContainerBuilder where TBuilderEntity : ContainerBuilder where TContainerEntity : IContainer where TConfigurationEntity : IContainerConfiguration @@ -32,9 +39,7 @@ public abstract class ContainerBuilder /// The Docker resource configuration. protected ContainerBuilder(TConfigurationEntity dockerResourceConfiguration) - : base(dockerResourceConfiguration) - { - } + : base(dockerResourceConfiguration) { } /// /// Gets the name of the environment variable that must be set to accept the image license agreement. @@ -54,7 +59,8 @@ protected ContainerBuilder(TConfigurationEntity dockerResourceConfiguration) /// public virtual TBuilderEntity WithAcceptLicenseAgreement(bool acceptLicenseAgreement) { - const string licenseAgreementNotRequired = "The module does not require you to accept a license agreement."; + const string licenseAgreementNotRequired = + "The module does not require you to accept a license agreement."; throw new InvalidOperationException(licenseAgreementNotRequired); } @@ -179,7 +185,10 @@ public TBuilderEntity WithPortBinding(int port, bool assignRandomHostPort = fals /// public TBuilderEntity WithPortBinding(int hostPort, int containerPort) { - return WithPortBinding(hostPort.ToString(CultureInfo.InvariantCulture), containerPort.ToString(CultureInfo.InvariantCulture)); + return WithPortBinding( + hostPort.ToString(CultureInfo.InvariantCulture), + containerPort.ToString(CultureInfo.InvariantCulture) + ); } /// @@ -197,7 +206,8 @@ public TBuilderEntity WithPortBinding(string hostPort, string containerPort) hostPort = "0".Equals(hostPort, StringComparison.OrdinalIgnoreCase) ? string.Empty : hostPort; var portBindings = new Dictionary { { containerPort, hostPort } }; - return Clone(new ContainerConfiguration(portBindings: portBindings)).WithExposedPort(containerPort); + return Clone(new ContainerConfiguration(portBindings: portBindings)) + .WithExposedPort(containerPort); } /// @@ -208,15 +218,27 @@ public TBuilderEntity WithResourceMapping(IResourceMapping resourceMapping) } /// - public TBuilderEntity WithResourceMapping(byte[] resourceContent, string filePath, UnixFileModes fileMode = Unix.FileMode644) + public TBuilderEntity WithResourceMapping( + byte[] resourceContent, + string filePath, + UnixFileModes fileMode = Unix.FileMode644 + ) { return WithResourceMapping(new BinaryResourceMapping(resourceContent, filePath, fileMode)); } /// - public TBuilderEntity WithResourceMapping(string source, string target, UnixFileModes fileMode = Unix.FileMode644) + public TBuilderEntity WithResourceMapping( + string source, + string target, + UnixFileModes fileMode = Unix.FileMode644 + ) { - if (Uri.IsWellFormedUriString(source, UriKind.Absolute) && Uri.TryCreate(source, UriKind.Absolute, out var uri) && new[] { Uri.UriSchemeHttp, Uri.UriSchemeHttps, Uri.UriSchemeFile }.Contains(uri.Scheme)) + if ( + Uri.IsWellFormedUriString(source, UriKind.Absolute) + && Uri.TryCreate(source, UriKind.Absolute, out var uri) + && new[] { Uri.UriSchemeHttp, Uri.UriSchemeHttps, Uri.UriSchemeFile }.Contains(uri.Scheme) + ) { return WithResourceMapping(uri, target, fileMode); } @@ -234,19 +256,31 @@ public TBuilderEntity WithResourceMapping(string source, string target, UnixFile } /// - public TBuilderEntity WithResourceMapping(DirectoryInfo source, string target, UnixFileModes fileMode = Unix.FileMode644) + public TBuilderEntity WithResourceMapping( + DirectoryInfo source, + string target, + UnixFileModes fileMode = Unix.FileMode644 + ) { return WithResourceMapping(new FileResourceMapping(source.FullName, target, fileMode)); } /// - public TBuilderEntity WithResourceMapping(FileInfo source, string target, UnixFileModes fileMode = Unix.FileMode644) + public TBuilderEntity WithResourceMapping( + FileInfo source, + string target, + UnixFileModes fileMode = Unix.FileMode644 + ) { return WithResourceMapping(new FileResourceMapping(source.FullName, target, fileMode)); } /// - public TBuilderEntity WithResourceMapping(FileInfo source, FileInfo target, UnixFileModes fileMode = Unix.FileMode644) + public TBuilderEntity WithResourceMapping( + FileInfo source, + FileInfo target, + UnixFileModes fileMode = Unix.FileMode644 + ) { using (var fileStream = source.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { @@ -259,7 +293,11 @@ public TBuilderEntity WithResourceMapping(FileInfo source, FileInfo target, Unix } /// - public TBuilderEntity WithResourceMapping(Uri source, string target, UnixFileModes fileMode = Unix.FileMode644) + public TBuilderEntity WithResourceMapping( + Uri source, + string target, + UnixFileModes fileMode = Unix.FileMode644 + ) { if (source.IsFile) { @@ -385,15 +423,26 @@ public TBuilderEntity WithWaitStrategy(IWaitForContainerOS waitStrategy) } /// - public TBuilderEntity WithStartupCallback(Func startupCallback) + public TBuilderEntity WithStartupCallback( + Func startupCallback + ) { - return Clone(new ContainerConfiguration(startupCallback: (container, ct) => startupCallback((TContainerEntity)container, ct))); + return Clone( + new ContainerConfiguration( + startupCallback: (container, ct) => startupCallback((TContainerEntity)container, ct) + ) + ); } /// protected override TBuilderEntity Init() { - return base.Init().WithImagePullPolicy(PullPolicy.Missing).WithPortForwarding().WithOutputConsumer(Consume.DoNotConsumeStdoutAndStderr()).WithWaitStrategy(Wait.ForUnixContainer()).WithStartupCallback((_, _) => Task.CompletedTask); + return base.Init() + .WithImagePullPolicy(PullPolicy.Missing) + .WithPortForwarding() + .WithOutputConsumer(Consume.DoNotConsumeStdoutAndStderr()) + .WithWaitStrategy(Wait.ForUnixContainer()) + .WithStartupCallback((_, _) => Task.CompletedTask); } /// @@ -401,11 +450,21 @@ protected override void Validate() { base.Validate(); - const string reuseNotSupported = "Reuse cannot be used in conjunction with WithAutoRemove(true)."; - _ = Guard.Argument(DockerResourceConfiguration, nameof(IContainerConfiguration.Reuse)) - .ThrowIf(argument => argument.Value.Reuse.HasValue && argument.Value.Reuse.Value && argument.Value.AutoRemove.HasValue && argument.Value.AutoRemove.Value, argument => new ArgumentException(reuseNotSupported, argument.Name)); - - _ = Guard.Argument(DockerResourceConfiguration.Image, nameof(IContainerConfiguration.Image)) + const string reuseNotSupported = + "Reuse cannot be used in conjunction with WithAutoRemove(true)."; + _ = Guard + .Argument(DockerResourceConfiguration, nameof(IContainerConfiguration.Reuse)) + .ThrowIf( + argument => + argument.Value.Reuse.HasValue + && argument.Value.Reuse.Value + && argument.Value.AutoRemove.HasValue + && argument.Value.AutoRemove.Value, + argument => new ArgumentException(reuseNotSupported, argument.Name) + ); + + _ = Guard + .Argument(DockerResourceConfiguration.Image, nameof(IContainerConfiguration.Image)) .NotNull(); } @@ -418,10 +477,19 @@ protected virtual void ValidateLicenseAgreement() const string message = "The image '{0}' requires you to accept a license agreement."; Predicate licenseAgreementNotAccepted = value => - !value.Environments.TryGetValue(AcceptLicenseAgreementEnvVar, out var licenseAgreementValue) || !AcceptLicenseAgreement.Equals(licenseAgreementValue, StringComparison.Ordinal); + !value.Environments.TryGetValue(AcceptLicenseAgreementEnvVar, out var licenseAgreementValue) + || !AcceptLicenseAgreement.Equals(licenseAgreementValue, StringComparison.Ordinal); - _ = Guard.Argument(DockerResourceConfiguration, nameof(DockerResourceConfiguration.Image)) - .ThrowIf(argument => licenseAgreementNotAccepted(argument.Value), argument => throw new ArgumentException(string.Format(message, DockerResourceConfiguration.Image.FullName), argument.Name)); + _ = Guard + .Argument(DockerResourceConfiguration, nameof(DockerResourceConfiguration.Image)) + .ThrowIf( + argument => licenseAgreementNotAccepted(argument.Value), + argument => + throw new ArgumentException( + string.Format(message, DockerResourceConfiguration.Image.FullName), + argument.Name + ) + ); } /// @@ -434,7 +502,11 @@ protected virtual void ValidateLicenseAgreement() private TBuilderEntity WithPortForwarding() { const string hostname = "host.testcontainers.internal"; - return PortForwardingContainer.Instance != null && TestcontainersStates.Running.Equals(PortForwardingContainer.Instance.State) ? WithExtraHost(hostname, PortForwardingContainer.Instance.IpAddress) : Clone(new ContainerConfiguration()); + return + PortForwardingContainer.Instance != null + && TestcontainersStates.Running.Equals(PortForwardingContainer.Instance.State) + ? WithExtraHost(hostname, PortForwardingContainer.Instance.IpAddress) + : Clone(new ContainerConfiguration()); } /// @@ -443,18 +515,14 @@ private sealed class FromExistingNetwork : NetworkBuilder /// /// Initializes a new instance of the class. /// - public FromExistingNetwork() - { - } + public FromExistingNetwork() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. public FromExistingNetwork(INetworkConfiguration dockerResourceConfiguration) - : base(dockerResourceConfiguration) - { - } + : base(dockerResourceConfiguration) { } /// public override INetwork Build() @@ -463,7 +531,10 @@ public override INetwork Build() } /// - protected override NetworkBuilder Merge(INetworkConfiguration oldValue, INetworkConfiguration newValue) + protected override NetworkBuilder Merge( + INetworkConfiguration oldValue, + INetworkConfiguration newValue + ) { return new FromExistingNetwork(new NetworkConfiguration(oldValue, newValue)); } @@ -509,18 +580,14 @@ private sealed class FromExistingVolume : VolumeBuilder /// /// Initializes a new instance of the class. /// - public FromExistingVolume() - { - } + public FromExistingVolume() { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. public FromExistingVolume(IVolumeConfiguration dockerResourceConfiguration) - : base(dockerResourceConfiguration) - { - } + : base(dockerResourceConfiguration) { } /// public override IVolume Build() @@ -529,7 +596,10 @@ public override IVolume Build() } /// - protected override VolumeBuilder Merge(IVolumeConfiguration oldValue, IVolumeConfiguration newValue) + protected override VolumeBuilder Merge( + IVolumeConfiguration oldValue, + IVolumeConfiguration newValue + ) { return new FromExistingVolume(new VolumeConfiguration(oldValue, newValue)); } diff --git a/src/Testcontainers/Builders/CredsHelperProvider.cs b/src/Testcontainers/Builders/CredsHelperProvider.cs index 6072f53a1..cf1318a20 100644 --- a/src/Testcontainers/Builders/CredsHelperProvider.cs +++ b/src/Testcontainers/Builders/CredsHelperProvider.cs @@ -20,9 +20,7 @@ internal sealed class CredsHelperProvider : IDockerRegistryAuthenticationProvide /// The logger. [PublicAPI] public CredsHelperProvider(JsonDocument jsonDocument, ILogger logger) - : this(jsonDocument.RootElement, logger) - { - } + : this(jsonDocument.RootElement, logger) { } /// /// Initializes a new instance of the class. @@ -32,14 +30,20 @@ public CredsHelperProvider(JsonDocument jsonDocument, ILogger logger) [PublicAPI] public CredsHelperProvider(JsonElement jsonElement, ILogger logger) { - _rootElement = jsonElement.TryGetProperty("credHelpers", out var credHelpers) ? credHelpers : default; + _rootElement = jsonElement.TryGetProperty("credHelpers", out var credHelpers) + ? credHelpers + : default; _logger = logger; } /// public bool IsApplicable(string hostname) { - return !JsonValueKind.Undefined.Equals(_rootElement.ValueKind) && !JsonValueKind.Null.Equals(_rootElement.ValueKind) && _rootElement.EnumerateObject().Any(property => Base64Provider.HasDockerRegistryName(property, hostname)); + return !JsonValueKind.Undefined.Equals(_rootElement.ValueKind) + && !JsonValueKind.Null.Equals(_rootElement.ValueKind) + && _rootElement + .EnumerateObject() + .Any(property => Base64Provider.HasDockerRegistryName(property, hostname)); } /// @@ -52,7 +56,9 @@ public IDockerRegistryAuthenticationConfiguration GetAuthConfig(string hostname) return null; } - var registryEndpointProperty = _rootElement.EnumerateObject().LastOrDefault(property => Base64Provider.HasDockerRegistryName(property, hostname)); + var registryEndpointProperty = _rootElement + .EnumerateObject() + .LastOrDefault(property => Base64Provider.HasDockerRegistryName(property, hostname)); if (!JsonValueKind.String.Equals(registryEndpointProperty.Value.ValueKind)) { @@ -64,7 +70,10 @@ public IDockerRegistryAuthenticationConfiguration GetAuthConfig(string hostname) return null; } - var credentialProviderOutput = DockerCredentialProcess.Get(registryEndpointProperty.Value.GetString(), hostname); + var credentialProviderOutput = DockerCredentialProcess.Get( + registryEndpointProperty.Value.GetString(), + hostname + ); if (string.IsNullOrEmpty(credentialProviderOutput)) { return null; diff --git a/src/Testcontainers/Builders/CredsStoreProvider.cs b/src/Testcontainers/Builders/CredsStoreProvider.cs index 22fac5595..6832fc477 100644 --- a/src/Testcontainers/Builders/CredsStoreProvider.cs +++ b/src/Testcontainers/Builders/CredsStoreProvider.cs @@ -19,9 +19,7 @@ internal sealed class CredsStoreProvider : IDockerRegistryAuthenticationProvider /// The logger. [PublicAPI] public CredsStoreProvider(JsonDocument jsonDocument, ILogger logger) - : this(jsonDocument.RootElement, logger) - { - } + : this(jsonDocument.RootElement, logger) { } /// /// Initializes a new instance of the class. @@ -31,14 +29,17 @@ public CredsStoreProvider(JsonDocument jsonDocument, ILogger logger) [PublicAPI] public CredsStoreProvider(JsonElement jsonElement, ILogger logger) { - _rootElement = jsonElement.TryGetProperty("credsStore", out var credsStore) ? credsStore : default; + _rootElement = jsonElement.TryGetProperty("credsStore", out var credsStore) + ? credsStore + : default; _logger = logger; } /// public bool IsApplicable(string hostname) { - return !JsonValueKind.Undefined.Equals(_rootElement.ValueKind) && !string.IsNullOrEmpty(_rootElement.GetString()); + return !JsonValueKind.Undefined.Equals(_rootElement.ValueKind) + && !string.IsNullOrEmpty(_rootElement.GetString()); } /// @@ -51,7 +52,10 @@ public IDockerRegistryAuthenticationConfiguration GetAuthConfig(string hostname) return null; } - var credentialProviderOutput = DockerCredentialProcess.Get(_rootElement.GetString(), hostname); + var credentialProviderOutput = DockerCredentialProcess.Get( + _rootElement.GetString(), + hostname + ); if (string.IsNullOrEmpty(credentialProviderOutput)) { return null; diff --git a/src/Testcontainers/Builders/DockerConfig.cs b/src/Testcontainers/Builders/DockerConfig.cs index e66173273..e86455316 100644 --- a/src/Testcontainers/Builders/DockerConfig.cs +++ b/src/Testcontainers/Builders/DockerConfig.cs @@ -16,7 +16,10 @@ namespace DotNet.Testcontainers.Builders /// internal sealed class DockerConfig { - private static readonly string UserProfileDockerConfigDirectoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".docker"); + private static readonly string UserProfileDockerConfigDirectoryPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), + ".docker" + ); private readonly ICustomConfiguration[] _customConfigurations; @@ -29,9 +32,7 @@ internal sealed class DockerConfig /// [PublicAPI] public DockerConfig() - : this(EnvironmentConfiguration.Instance, PropertiesFileConfiguration.Instance) - { - } + : this(EnvironmentConfiguration.Instance, PropertiesFileConfiguration.Instance) { } /// /// Initializes a new instance of the class. @@ -48,8 +49,7 @@ public DockerConfig(params ICustomConfiguration[] customConfigurations) /// /// Gets the instance. /// - public static DockerConfig Instance { get; } - = new DockerConfig(); + public static DockerConfig Instance { get; } = new DockerConfig(); /// public bool Exists => File.Exists(_dockerConfigFilePath); @@ -91,24 +91,40 @@ public Uri GetCurrentEndpoint() var dockerContext = GetCurrentContext(); if (string.IsNullOrEmpty(dockerContext) || defaultDockerContext.Equals(dockerContext)) { - return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? NpipeEndpointAuthenticationProvider.DockerEngine : UnixEndpointAuthenticationProvider.DockerEngine; + return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + ? NpipeEndpointAuthenticationProvider.DockerEngine + : UnixEndpointAuthenticationProvider.DockerEngine; } using (var sha256 = SHA256.Create()) { - var dockerContextHash = BitConverter.ToString(sha256.ComputeHash(Encoding.Default.GetBytes(dockerContext))).Replace("-", string.Empty).ToLowerInvariant(); - var metaFilePath = Path.Combine(_dockerConfigDirectoryPath, "contexts", "meta", dockerContextHash, "meta.json"); + var dockerContextHash = BitConverter + .ToString(sha256.ComputeHash(Encoding.Default.GetBytes(dockerContext))) + .Replace("-", string.Empty) + .ToLowerInvariant(); + var metaFilePath = Path.Combine( + _dockerConfigDirectoryPath, + "contexts", + "meta", + dockerContextHash, + "meta.json" + ); try { using (var metaFileStream = File.OpenRead(metaFilePath)) { - var meta = JsonSerializer.Deserialize(metaFileStream, SourceGenerationContext.Default.DockerContextMeta); + var meta = JsonSerializer.Deserialize( + metaFileStream, + SourceGenerationContext.Default.DockerContextMeta + ); var host = meta.Endpoints?.Docker?.Host; if (string.IsNullOrEmpty(host)) { - throw new DockerConfigurationException($"The Docker host is null or empty in '{metaFilePath}' (JSONPath: Endpoints.docker.Host)."); + throw new DockerConfigurationException( + $"The Docker host is null or empty in '{metaFilePath}' (JSONPath: Endpoints.docker.Host)." + ); } return new Uri(host.Replace("npipe:////./", "npipe://./")); @@ -116,11 +132,17 @@ public Uri GetCurrentEndpoint() } catch (Exception e) when (e is DirectoryNotFoundException or FileNotFoundException) { - throw new DockerConfigurationException($"The Docker context '{dockerContext}' does not exist.", e); + throw new DockerConfigurationException( + $"The Docker context '{dockerContext}' does not exist.", + e + ); } catch (Exception e) when (e is not DockerConfigurationException) { - throw new DockerConfigurationException($"The Docker context '{dockerContext}' failed to load from '{metaFilePath}'.", e); + throw new DockerConfigurationException( + $"The Docker context '{dockerContext}' failed to load from '{metaFilePath}'.", + e + ); } } } @@ -141,7 +163,13 @@ private string GetCurrentContext() using (var dockerConfigJsonDocument = Parse()) { - if (dockerConfigJsonDocument.RootElement.TryGetProperty("currentContext", out var currentContext) && currentContext.ValueKind == JsonValueKind.String) + if ( + dockerConfigJsonDocument.RootElement.TryGetProperty( + "currentContext", + out var currentContext + ) + && currentContext.ValueKind == JsonValueKind.String + ) { return currentContext.GetString(); } @@ -155,20 +183,26 @@ private string GetCurrentContext() [NotNull] private string GetDockerConfig() { - var dockerConfigDirectoryPath = _customConfigurations.Select(customConfiguration => customConfiguration.GetDockerConfig()).FirstOrDefault(dockerConfig => !string.IsNullOrEmpty(dockerConfig)); + var dockerConfigDirectoryPath = _customConfigurations + .Select(customConfiguration => customConfiguration.GetDockerConfig()) + .FirstOrDefault(dockerConfig => !string.IsNullOrEmpty(dockerConfig)); return dockerConfigDirectoryPath ?? UserProfileDockerConfigDirectoryPath; } [CanBeNull] private Uri GetDockerHost() { - return _customConfigurations.Select(customConfiguration => customConfiguration.GetDockerHost()).FirstOrDefault(dockerHost => dockerHost != null); + return _customConfigurations + .Select(customConfiguration => customConfiguration.GetDockerHost()) + .FirstOrDefault(dockerHost => dockerHost != null); } [CanBeNull] private string GetDockerContext() { - return _customConfigurations.Select(customConfiguration => customConfiguration.GetDockerContext()).FirstOrDefault(dockerContext => !string.IsNullOrEmpty(dockerContext)); + return _customConfigurations + .Select(customConfiguration => customConfiguration.GetDockerContext()) + .FirstOrDefault(dockerContext => !string.IsNullOrEmpty(dockerContext)); } internal sealed class DockerContextMeta diff --git a/src/Testcontainers/Builders/DockerConfigurationException.cs b/src/Testcontainers/Builders/DockerConfigurationException.cs index 24bce6403..7e7e38615 100644 --- a/src/Testcontainers/Builders/DockerConfigurationException.cs +++ b/src/Testcontainers/Builders/DockerConfigurationException.cs @@ -14,9 +14,8 @@ public sealed class DockerConfigurationException : Exception /// Initializes a new instance of the class. /// /// The message that describes the error. - public DockerConfigurationException(string message) : base(message) - { - } + public DockerConfigurationException(string message) + : base(message) { } /// /// Initializes a new instance of the class. @@ -24,8 +23,6 @@ public DockerConfigurationException(string message) : base(message) /// The message that describes the error. /// The exception that is the cause of the current exception. public DockerConfigurationException(string message, Exception innerException) - : base(message, innerException) - { - } + : base(message, innerException) { } } } diff --git a/src/Testcontainers/Builders/DockerDesktopEndpointAuthenticationProvider.cs b/src/Testcontainers/Builders/DockerDesktopEndpointAuthenticationProvider.cs index 02d164d6f..40944b4eb 100644 --- a/src/Testcontainers/Builders/DockerDesktopEndpointAuthenticationProvider.cs +++ b/src/Testcontainers/Builders/DockerDesktopEndpointAuthenticationProvider.cs @@ -9,15 +9,15 @@ namespace DotNet.Testcontainers.Builders /// [PublicAPI] - internal sealed class DockerDesktopEndpointAuthenticationProvider : RootlessUnixEndpointAuthenticationProvider, ICustomConfiguration + internal sealed class DockerDesktopEndpointAuthenticationProvider + : RootlessUnixEndpointAuthenticationProvider, + ICustomConfiguration { /// /// Initializes a new instance of the class. /// public DockerDesktopEndpointAuthenticationProvider() - : base(DockerConfig.Instance.GetCurrentEndpoint()) - { - } + : base(DockerConfig.Instance.GetCurrentEndpoint()) { } /// public override bool IsApplicable() diff --git a/src/Testcontainers/Builders/DockerEndpointAuthenticationProvider.cs b/src/Testcontainers/Builders/DockerEndpointAuthenticationProvider.cs index 76d18058a..ea066b97e 100644 --- a/src/Testcontainers/Builders/DockerEndpointAuthenticationProvider.cs +++ b/src/Testcontainers/Builders/DockerEndpointAuthenticationProvider.cs @@ -10,7 +10,12 @@ namespace DotNet.Testcontainers.Builders /// internal class DockerEndpointAuthenticationProvider : IDockerEndpointAuthenticationProvider { - private static readonly TaskFactory TaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default); + private static readonly TaskFactory TaskFactory = new TaskFactory( + CancellationToken.None, + TaskCreationOptions.None, + TaskContinuationOptions.None, + TaskScheduler.Default + ); [CanBeNull] private Exception _cachedException; @@ -37,16 +42,20 @@ public virtual bool IsAvailable() return false; } - return TaskFactory.StartNew(async () => + return TaskFactory + .StartNew(async () => { - using (var dockerClientConfiguration = authConfig.GetDockerClientConfiguration(ResourceReaper.DefaultSessionId)) + using ( + var dockerClientConfiguration = authConfig.GetDockerClientConfiguration( + ResourceReaper.DefaultSessionId + ) + ) { using (var dockerClient = dockerClientConfiguration.CreateClient()) { try { - await dockerClient.System.PingAsync() - .ConfigureAwait(false); + await dockerClient.System.PingAsync().ConfigureAwait(false); _cachedException = null; @@ -54,7 +63,8 @@ await dockerClient.System.PingAsync() } catch (Exception e) { - var message = $"Failed to connect to Docker endpoint at '{dockerClientConfiguration.EndpointBaseUri}'."; + var message = + $"Failed to connect to Docker endpoint at '{dockerClientConfiguration.EndpointBaseUri}'."; _cachedException = new DockerUnavailableException(message, e); return false; diff --git a/src/Testcontainers/Builders/DockerRegistryAuthenticationProvider.cs b/src/Testcontainers/Builders/DockerRegistryAuthenticationProvider.cs index 73bbfcede..7658cd820 100644 --- a/src/Testcontainers/Builders/DockerRegistryAuthenticationProvider.cs +++ b/src/Testcontainers/Builders/DockerRegistryAuthenticationProvider.cs @@ -13,7 +13,11 @@ internal sealed class DockerRegistryAuthenticationProvider : IDockerRegistryAuth { private const string DockerHub = "https://index.docker.io/v1/"; - private static readonly ConcurrentDictionary> Credentials = new ConcurrentDictionary>(); + private static readonly ConcurrentDictionary< + string, + Lazy + > Credentials = + new ConcurrentDictionary>(); private readonly DockerConfig _dockerConfig; @@ -25,9 +29,7 @@ internal sealed class DockerRegistryAuthenticationProvider : IDockerRegistryAuth /// The logger. [PublicAPI] public DockerRegistryAuthenticationProvider(ILogger logger) - : this(DockerConfig.Instance, logger) - { - } + : this(DockerConfig.Instance, logger) { } /// /// Initializes a new instance of the class. @@ -50,13 +52,20 @@ public bool IsApplicable(string hostname) /// public IDockerRegistryAuthenticationConfiguration GetAuthConfig(string hostname) { - var lazyAuthConfig = Credentials.GetOrAdd(hostname ?? DockerHub, key => new Lazy(() => GetUncachedAuthConfig(key))); + var lazyAuthConfig = Credentials.GetOrAdd( + hostname ?? DockerHub, + key => new Lazy(() => + GetUncachedAuthConfig(key) + ) + ); return lazyAuthConfig.Value; } private static JsonDocument GetDefaultDockerAuthConfig() { - return EnvironmentConfiguration.Instance.GetDockerAuthConfig() ?? PropertiesFileConfiguration.Instance.GetDockerAuthConfig() ?? JsonDocument.Parse("{}"); + return EnvironmentConfiguration.Instance.GetDockerAuthConfig() + ?? PropertiesFileConfiguration.Instance.GetDockerAuthConfig() + ?? JsonDocument.Parse("{}"); } private IDockerRegistryAuthenticationConfiguration GetUncachedAuthConfig(string hostname) @@ -70,12 +79,12 @@ private IDockerRegistryAuthenticationConfiguration GetUncachedAuthConfig(string using (var dockerConfigJsonDocument = _dockerConfig.Parse()) { authConfig = new IDockerRegistryAuthenticationProvider[] - { - new CredsHelperProvider(dockerConfigJsonDocument, _logger), - new CredsStoreProvider(dockerConfigJsonDocument, _logger), - new Base64Provider(dockerConfigJsonDocument, _logger), - new Base64Provider(dockerAuthConfigJsonDocument, _logger), - } + { + new CredsHelperProvider(dockerConfigJsonDocument, _logger), + new CredsStoreProvider(dockerConfigJsonDocument, _logger), + new Base64Provider(dockerConfigJsonDocument, _logger), + new Base64Provider(dockerAuthConfigJsonDocument, _logger), + } .AsParallel() .Select(authenticationProvider => authenticationProvider.GetAuthConfig(hostname)) .FirstOrDefault(authenticationProvider => authenticationProvider != null); @@ -84,7 +93,10 @@ private IDockerRegistryAuthenticationConfiguration GetUncachedAuthConfig(string else { _logger.DockerConfigFileNotFound(_dockerConfig.FullName); - IDockerRegistryAuthenticationProvider authConfigProvider = new Base64Provider(dockerAuthConfigJsonDocument, _logger); + IDockerRegistryAuthenticationProvider authConfigProvider = new Base64Provider( + dockerAuthConfigJsonDocument, + _logger + ); authConfig = authConfigProvider.GetAuthConfig(hostname); } diff --git a/src/Testcontainers/Builders/DockerUnavailableException.cs b/src/Testcontainers/Builders/DockerUnavailableException.cs index 1c1b9c903..46bbb1b89 100644 --- a/src/Testcontainers/Builders/DockerUnavailableException.cs +++ b/src/Testcontainers/Builders/DockerUnavailableException.cs @@ -14,9 +14,8 @@ public sealed class DockerUnavailableException : Exception /// Initializes a new instance of the class. /// /// The message that describes the error. - public DockerUnavailableException(string message) : base(message) - { - } + public DockerUnavailableException(string message) + : base(message) { } /// /// Initializes a new instance of the class. @@ -24,8 +23,6 @@ public DockerUnavailableException(string message) : base(message) /// The message that describes the error. /// The exception that is the cause of the current exception. public DockerUnavailableException(string message, Exception innerException) - : base(message, innerException) - { - } + : base(message, innerException) { } } } diff --git a/src/Testcontainers/Builders/EnvironmentEndpointAuthenticationProvider.cs b/src/Testcontainers/Builders/EnvironmentEndpointAuthenticationProvider.cs index f811b3ce1..6e465bb52 100644 --- a/src/Testcontainers/Builders/EnvironmentEndpointAuthenticationProvider.cs +++ b/src/Testcontainers/Builders/EnvironmentEndpointAuthenticationProvider.cs @@ -7,7 +7,8 @@ namespace DotNet.Testcontainers.Builders /// [PublicAPI] - internal sealed class EnvironmentEndpointAuthenticationProvider : DockerEndpointAuthenticationProvider + internal sealed class EnvironmentEndpointAuthenticationProvider + : DockerEndpointAuthenticationProvider { private readonly Uri _dockerEngine; @@ -15,15 +16,15 @@ internal sealed class EnvironmentEndpointAuthenticationProvider : DockerEndpoint /// Initializes a new instance of the class. /// public EnvironmentEndpointAuthenticationProvider() - : this(EnvironmentConfiguration.Instance, PropertiesFileConfiguration.Instance) - { - } + : this(EnvironmentConfiguration.Instance, PropertiesFileConfiguration.Instance) { } /// /// Initializes a new instance of the class. /// /// A list of custom configurations. - public EnvironmentEndpointAuthenticationProvider(params ICustomConfiguration[] customConfigurations) + public EnvironmentEndpointAuthenticationProvider( + params ICustomConfiguration[] customConfigurations + ) { _dockerEngine = customConfigurations .Select(customConfiguration => customConfiguration.GetDockerHost()) diff --git a/src/Testcontainers/Builders/IAbstractBuilder`3.cs b/src/Testcontainers/Builders/IAbstractBuilder`3.cs index aa9a54d55..cddb3b11d 100644 --- a/src/Testcontainers/Builders/IAbstractBuilder`3.cs +++ b/src/Testcontainers/Builders/IAbstractBuilder`3.cs @@ -14,7 +14,11 @@ namespace DotNet.Testcontainers.Builders /// The resource entity. /// The underlying Docker.DotNet resource entity. [PublicAPI] - public interface IAbstractBuilder + public interface IAbstractBuilder< + out TBuilderEntity, + out TResourceEntity, + out TCreateResourceEntity + > { /// /// Sets the Docker API endpoint. @@ -50,7 +54,9 @@ public interface IAbstractBuilderThe Docker endpoint authentication configuration. /// A configured instance of . [PublicAPI] - TBuilderEntity WithDockerEndpoint(IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig); + TBuilderEntity WithDockerEndpoint( + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig + ); /// /// Cleans up the Docker resource after the tests are finished. diff --git a/src/Testcontainers/Builders/IContainerBuilder`2.cs b/src/Testcontainers/Builders/IContainerBuilder`2.cs index b5cbb905e..0021bc496 100644 --- a/src/Testcontainers/Builders/IContainerBuilder`2.cs +++ b/src/Testcontainers/Builders/IContainerBuilder`2.cs @@ -19,7 +19,8 @@ namespace DotNet.Testcontainers.Builders /// The builder entity. /// The resource entity. [PublicAPI] - public interface IContainerBuilder : IAbstractBuilder + public interface IContainerBuilder + : IAbstractBuilder { /// /// Accepts the license agreement. @@ -239,7 +240,11 @@ public interface IContainerBuilder : I /// The POSIX file mode permission. /// A configured instance of . [PublicAPI] - TBuilderEntity WithResourceMapping(byte[] resourceContent, string filePath, UnixFileModes fileMode = Unix.FileMode644); + TBuilderEntity WithResourceMapping( + byte[] resourceContent, + string filePath, + UnixFileModes fileMode = Unix.FileMode644 + ); /// /// Copies the contents of a URL, a test host directory or file to the container before it starts. @@ -257,7 +262,11 @@ public interface IContainerBuilder : I /// The POSIX file mode permission. /// A configured instance of . [PublicAPI] - TBuilderEntity WithResourceMapping(string source, string target, UnixFileModes fileMode = Unix.FileMode644); + TBuilderEntity WithResourceMapping( + string source, + string target, + UnixFileModes fileMode = Unix.FileMode644 + ); /// /// Copies a test host directory or file to the container before it starts. @@ -267,7 +276,11 @@ public interface IContainerBuilder : I /// The POSIX file mode permission. /// A configured instance of . [PublicAPI] - TBuilderEntity WithResourceMapping(DirectoryInfo source, string target, UnixFileModes fileMode = Unix.FileMode644); + TBuilderEntity WithResourceMapping( + DirectoryInfo source, + string target, + UnixFileModes fileMode = Unix.FileMode644 + ); /// /// Copies a test host directory or file to the container before it starts. @@ -277,7 +290,11 @@ public interface IContainerBuilder : I /// The POSIX file mode permission. /// A configured instance of . [PublicAPI] - TBuilderEntity WithResourceMapping(FileInfo source, string target, UnixFileModes fileMode = Unix.FileMode644); + TBuilderEntity WithResourceMapping( + FileInfo source, + string target, + UnixFileModes fileMode = Unix.FileMode644 + ); /// /// Copies a test host file to the container before it starts. @@ -287,7 +304,11 @@ public interface IContainerBuilder : I /// The POSIX file mode permission. /// A configured instance of . [PublicAPI] - TBuilderEntity WithResourceMapping(FileInfo source, FileInfo target, UnixFileModes fileMode = Unix.FileMode644); + TBuilderEntity WithResourceMapping( + FileInfo source, + FileInfo target, + UnixFileModes fileMode = Unix.FileMode644 + ); /// /// Copies a file from a URL to the container before it starts. @@ -306,7 +327,11 @@ public interface IContainerBuilder : I /// The target directory or file path to copy the file to. /// The POSIX file mode permission. /// A configured instance of . - TBuilderEntity WithResourceMapping(Uri source, string target, UnixFileModes fileMode = Unix.FileMode644); + TBuilderEntity WithResourceMapping( + Uri source, + string target, + UnixFileModes fileMode = Unix.FileMode644 + ); /// /// Assigns the mount configuration to manage data in the container. @@ -475,6 +500,8 @@ public interface IContainerBuilder : I /// The callback method to invoke. /// A configured instance of . [PublicAPI] - TBuilderEntity WithStartupCallback(Func startupCallback); + TBuilderEntity WithStartupCallback( + Func startupCallback + ); } } diff --git a/src/Testcontainers/Builders/IImageFromDockerfileBuilder`1.cs b/src/Testcontainers/Builders/IImageFromDockerfileBuilder`1.cs index d8be6544a..d9bf36e19 100644 --- a/src/Testcontainers/Builders/IImageFromDockerfileBuilder`1.cs +++ b/src/Testcontainers/Builders/IImageFromDockerfileBuilder`1.cs @@ -51,7 +51,10 @@ public interface IImageFromDockerfileBuilder /// A relative path or a name value to the Docker build context. /// A configured instance of . [PublicAPI] - TBuilderEntity WithDockerfileDirectory(CommonDirectoryPath commonDirectoryPath, string dockerfileDirectory); + TBuilderEntity WithDockerfileDirectory( + CommonDirectoryPath commonDirectoryPath, + string dockerfileDirectory + ); /// /// Sets the image build policy. diff --git a/src/Testcontainers/Builders/ImageFromDockerfileBuilder.cs b/src/Testcontainers/Builders/ImageFromDockerfileBuilder.cs index 7ddc6e779..970e8857f 100644 --- a/src/Testcontainers/Builders/ImageFromDockerfileBuilder.cs +++ b/src/Testcontainers/Builders/ImageFromDockerfileBuilder.cs @@ -27,7 +27,14 @@ namespace DotNet.Testcontainers.Builders /// /// [PublicAPI] - public class ImageFromDockerfileBuilder : AbstractBuilder, IImageFromDockerfileBuilder + public class ImageFromDockerfileBuilder + : AbstractBuilder< + ImageFromDockerfileBuilder, + IFutureDockerImage, + ImageBuildParameters, + IImageFromDockerfileConfiguration + >, + IImageFromDockerfileBuilder { /// /// Initializes a new instance of the class. @@ -42,7 +49,9 @@ public ImageFromDockerfileBuilder() /// Initializes a new instance of the class. /// /// The Docker resource configuration. - private ImageFromDockerfileBuilder(IImageFromDockerfileConfiguration dockerResourceConfiguration) + private ImageFromDockerfileBuilder( + IImageFromDockerfileConfiguration dockerResourceConfiguration + ) : base(dockerResourceConfiguration) { DockerResourceConfiguration = dockerResourceConfiguration; @@ -60,46 +69,81 @@ public ImageFromDockerfileBuilder WithName(string name) /// public ImageFromDockerfileBuilder WithName(IImage image) { - return Merge(DockerResourceConfiguration, new ImageFromDockerfileConfiguration(image: image.ApplyHubImageNamePrefix())); + return Merge( + DockerResourceConfiguration, + new ImageFromDockerfileConfiguration(image: image.ApplyHubImageNamePrefix()) + ); } /// public ImageFromDockerfileBuilder WithDockerfile(string dockerfile) { - var dockerfileFilePath = Regex.Replace(dockerfile, "^\\.(\\/|\\\\)", string.Empty, RegexOptions.None, TimeSpan.FromSeconds(1)); - return Merge(DockerResourceConfiguration, new ImageFromDockerfileConfiguration(dockerfile: dockerfileFilePath)); + var dockerfileFilePath = Regex.Replace( + dockerfile, + "^\\.(\\/|\\\\)", + string.Empty, + RegexOptions.None, + TimeSpan.FromSeconds(1) + ); + return Merge( + DockerResourceConfiguration, + new ImageFromDockerfileConfiguration(dockerfile: dockerfileFilePath) + ); } /// public ImageFromDockerfileBuilder WithDockerfileDirectory(string dockerfileDirectory) { - return Merge(DockerResourceConfiguration, new ImageFromDockerfileConfiguration(dockerfileDirectory: dockerfileDirectory)); + return Merge( + DockerResourceConfiguration, + new ImageFromDockerfileConfiguration(dockerfileDirectory: dockerfileDirectory) + ); } /// - public ImageFromDockerfileBuilder WithDockerfileDirectory(CommonDirectoryPath commonDirectoryPath, string dockerfileDirectory) + public ImageFromDockerfileBuilder WithDockerfileDirectory( + CommonDirectoryPath commonDirectoryPath, + string dockerfileDirectory + ) { - var dockerfileDirectoryPath = Path.Combine(commonDirectoryPath.DirectoryPath, dockerfileDirectory); - return Merge(DockerResourceConfiguration, new ImageFromDockerfileConfiguration(dockerfileDirectory: dockerfileDirectoryPath)); + var dockerfileDirectoryPath = Path.Combine( + commonDirectoryPath.DirectoryPath, + dockerfileDirectory + ); + return Merge( + DockerResourceConfiguration, + new ImageFromDockerfileConfiguration(dockerfileDirectory: dockerfileDirectoryPath) + ); } /// - public ImageFromDockerfileBuilder WithImageBuildPolicy(Func imageBuildPolicy) + public ImageFromDockerfileBuilder WithImageBuildPolicy( + Func imageBuildPolicy + ) { - return Merge(DockerResourceConfiguration, new ImageFromDockerfileConfiguration(imageBuildPolicy: imageBuildPolicy)); + return Merge( + DockerResourceConfiguration, + new ImageFromDockerfileConfiguration(imageBuildPolicy: imageBuildPolicy) + ); } /// public ImageFromDockerfileBuilder WithDeleteIfExists(bool deleteIfExists) { - return Merge(DockerResourceConfiguration, new ImageFromDockerfileConfiguration(deleteIfExists: deleteIfExists)); + return Merge( + DockerResourceConfiguration, + new ImageFromDockerfileConfiguration(deleteIfExists: deleteIfExists) + ); } /// public ImageFromDockerfileBuilder WithBuildArgument(string name, string value) { var buildArguments = new Dictionary { { name, value } }; - return Merge(DockerResourceConfiguration, new ImageFromDockerfileConfiguration(buildArguments: buildArguments)); + return Merge( + DockerResourceConfiguration, + new ImageFromDockerfileConfiguration(buildArguments: buildArguments) + ); } /// @@ -112,7 +156,15 @@ public override IFutureDockerImage Build() /// protected sealed override ImageFromDockerfileBuilder Init() { - return base.Init().WithImageBuildPolicy(PullPolicy.Always).WithDockerfile("Dockerfile").WithDockerfileDirectory(Directory.GetCurrentDirectory()).WithName(new DockerImage(string.Join("/", "localhost", "testcontainers", Guid.NewGuid().ToString("D")))); + return base.Init() + .WithImageBuildPolicy(PullPolicy.Always) + .WithDockerfile("Dockerfile") + .WithDockerfileDirectory(Directory.GetCurrentDirectory()) + .WithName( + new DockerImage( + string.Join("/", "localhost", "testcontainers", Guid.NewGuid().ToString("D")) + ) + ); } /// @@ -120,21 +172,36 @@ protected override void Validate() { base.Validate(); - const string reuseNotSupported = "Building an image does not support the reuse feature. To keep the built image, disable the cleanup."; - _ = Guard.Argument(DockerResourceConfiguration, nameof(IImageFromDockerfileConfiguration.Reuse)) - .ThrowIf(argument => argument.Value.Reuse.HasValue && argument.Value.Reuse.Value, argument => new ArgumentException(reuseNotSupported, argument.Name)); + const string reuseNotSupported = + "Building an image does not support the reuse feature. To keep the built image, disable the cleanup."; + _ = Guard + .Argument(DockerResourceConfiguration, nameof(IImageFromDockerfileConfiguration.Reuse)) + .ThrowIf( + argument => argument.Value.Reuse.HasValue && argument.Value.Reuse.Value, + argument => new ArgumentException(reuseNotSupported, argument.Name) + ); } /// - protected override ImageFromDockerfileBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override ImageFromDockerfileBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new ImageFromDockerfileConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new ImageFromDockerfileConfiguration(resourceConfiguration) + ); } /// - protected override ImageFromDockerfileBuilder Merge(IImageFromDockerfileConfiguration oldValue, IImageFromDockerfileConfiguration newValue) + protected override ImageFromDockerfileBuilder Merge( + IImageFromDockerfileConfiguration oldValue, + IImageFromDockerfileConfiguration newValue + ) { - return new ImageFromDockerfileBuilder(new ImageFromDockerfileConfiguration(oldValue, newValue)); + return new ImageFromDockerfileBuilder( + new ImageFromDockerfileConfiguration(oldValue, newValue) + ); } } } diff --git a/src/Testcontainers/Builders/MTlsEndpointAuthenticationProvider.cs b/src/Testcontainers/Builders/MTlsEndpointAuthenticationProvider.cs index 7beb6d400..3cc035152 100644 --- a/src/Testcontainers/Builders/MTlsEndpointAuthenticationProvider.cs +++ b/src/Testcontainers/Builders/MTlsEndpointAuthenticationProvider.cs @@ -16,24 +16,24 @@ internal sealed class MTlsEndpointAuthenticationProvider : TlsEndpointAuthentica /// Initializes a new instance of the class. /// public MTlsEndpointAuthenticationProvider() - : this(EnvironmentConfiguration.Instance, PropertiesFileConfiguration.Instance) - { - } + : this(EnvironmentConfiguration.Instance, PropertiesFileConfiguration.Instance) { } /// /// Initializes a new instance of the class. /// /// A list of custom configurations. public MTlsEndpointAuthenticationProvider(params ICustomConfiguration[] customConfigurations) - : base(customConfigurations) - { - } + : base(customConfigurations) { } /// public override bool IsApplicable() { var certificatesFiles = new[] { ClientCertificateFileName, ClientCertificateKeyFileName }; - return TlsEnabled && TlsVerifyEnabled && certificatesFiles.Select(fileName => Path.Combine(CertificatesDirectoryPath, fileName)).All(File.Exists); + return TlsEnabled + && TlsVerifyEnabled + && certificatesFiles + .Select(fileName => Path.Combine(CertificatesDirectoryPath, fileName)) + .All(File.Exists); } /// @@ -47,19 +47,38 @@ public override IDockerEndpointAuthenticationConfiguration GetAuthConfig() /// protected override X509Certificate2 GetClientCertificate() { - var clientCertificateFilePath = Path.Combine(CertificatesDirectoryPath, ClientCertificateFileName); - var clientCertificateKeyFilePath = Path.Combine(CertificatesDirectoryPath, ClientCertificateKeyFileName); + var clientCertificateFilePath = Path.Combine( + CertificatesDirectoryPath, + ClientCertificateFileName + ); + var clientCertificateKeyFilePath = Path.Combine( + CertificatesDirectoryPath, + ClientCertificateKeyFileName + ); // The certificate must be exported to PFX on Windows to avoid "No credentials are available in the security package": // https://stackoverflow.com/questions/72096812/loading-x509certificate2-from-pem-file-results-in-no-credentials-are-available/72101855#72101855. #if NETSTANDARD - return Polyfills.X509Certificate2.CreateFromPemFile(clientCertificateFilePath, clientCertificateKeyFilePath); + return Polyfills.X509Certificate2.CreateFromPemFile( + clientCertificateFilePath, + clientCertificateKeyFilePath + ); #elif NET9_0_OR_GREATER - var certificate = X509Certificate2.CreateFromPemFile(clientCertificateFilePath, clientCertificateKeyFilePath); - return OperatingSystem.IsWindows() ? X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pfx), null) : certificate; + var certificate = X509Certificate2.CreateFromPemFile( + clientCertificateFilePath, + clientCertificateKeyFilePath + ); + return OperatingSystem.IsWindows() + ? X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pfx), null) + : certificate; #elif NET6_0_OR_GREATER - var certificate = X509Certificate2.CreateFromPemFile(clientCertificateFilePath, clientCertificateKeyFilePath); - return OperatingSystem.IsWindows() ? new X509Certificate2(certificate.Export(X509ContentType.Pfx)) : certificate; + var certificate = X509Certificate2.CreateFromPemFile( + clientCertificateFilePath, + clientCertificateKeyFilePath + ); + return OperatingSystem.IsWindows() + ? new X509Certificate2(certificate.Export(X509ContentType.Pfx)) + : certificate; #endif } } diff --git a/src/Testcontainers/Builders/NetworkBuilder.cs b/src/Testcontainers/Builders/NetworkBuilder.cs index 43b7b957c..a5967a5b8 100644 --- a/src/Testcontainers/Builders/NetworkBuilder.cs +++ b/src/Testcontainers/Builders/NetworkBuilder.cs @@ -22,7 +22,9 @@ namespace DotNet.Testcontainers.Builders /// /// [PublicAPI] - public class NetworkBuilder : AbstractBuilder, INetworkBuilder + public class NetworkBuilder + : AbstractBuilder, + INetworkBuilder { /// /// Initializes a new instance of the class. @@ -83,19 +85,25 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Name, nameof(INetworkConfiguration.Name)) + _ = Guard + .Argument(DockerResourceConfiguration.Name, nameof(INetworkConfiguration.Name)) .NotNull() .NotEmpty(); } /// - protected override NetworkBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override NetworkBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new NetworkConfiguration(resourceConfiguration)); } /// - protected override NetworkBuilder Merge(INetworkConfiguration oldValue, INetworkConfiguration newValue) + protected override NetworkBuilder Merge( + INetworkConfiguration oldValue, + INetworkConfiguration newValue + ) { return new NetworkBuilder(new NetworkConfiguration(oldValue, newValue)); } diff --git a/src/Testcontainers/Builders/NpipeEndpointAuthenticationProvider.cs b/src/Testcontainers/Builders/NpipeEndpointAuthenticationProvider.cs index 0c319bad4..3d25d2e30 100644 --- a/src/Testcontainers/Builders/NpipeEndpointAuthenticationProvider.cs +++ b/src/Testcontainers/Builders/NpipeEndpointAuthenticationProvider.cs @@ -12,8 +12,7 @@ internal sealed class NpipeEndpointAuthenticationProvider : DockerEndpointAuthen /// /// Gets the named pipe Docker Engine endpoint. /// - public static Uri DockerEngine { get; } - = new Uri("npipe://./pipe/docker_engine"); + public static Uri DockerEngine { get; } = new Uri("npipe://./pipe/docker_engine"); /// public override bool IsApplicable() diff --git a/src/Testcontainers/Builders/RootlessUnixEndpointAuthenticationProvider.cs b/src/Testcontainers/Builders/RootlessUnixEndpointAuthenticationProvider.cs index 738a78dc2..487d63670 100644 --- a/src/Testcontainers/Builders/RootlessUnixEndpointAuthenticationProvider.cs +++ b/src/Testcontainers/Builders/RootlessUnixEndpointAuthenticationProvider.cs @@ -8,7 +8,8 @@ namespace DotNet.Testcontainers.Builders /// [PublicAPI] - internal partial class RootlessUnixEndpointAuthenticationProvider : DockerEndpointAuthenticationProvider + internal partial class RootlessUnixEndpointAuthenticationProvider + : DockerEndpointAuthenticationProvider { private const string DockerSocket = "docker.sock"; @@ -16,9 +17,7 @@ internal partial class RootlessUnixEndpointAuthenticationProvider : DockerEndpoi /// Initializes a new instance of the class. /// public RootlessUnixEndpointAuthenticationProvider() - : this(GetSocketPathFromEnv(), GetSocketPathFromHomeRunDir(), GetSocketPathFromRunDir()) - { - } + : this(GetSocketPathFromEnv(), GetSocketPathFromHomeRunDir(), GetSocketPathFromRunDir()) { } /// /// Initializes a new instance of the class. @@ -64,12 +63,24 @@ protected static string GetSocketPathFromEnv() protected static string GetSocketPathFromHomeDesktopDir() { - return string.Join("/", Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".docker", "desktop", DockerSocket); + return string.Join( + "/", + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), + ".docker", + "desktop", + DockerSocket + ); } protected static string GetSocketPathFromHomeRunDir() { - return string.Join("/", Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".docker", "run", DockerSocket); + return string.Join( + "/", + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), + ".docker", + "run", + DockerSocket + ); } protected static string GetSocketPathFromRunDir() diff --git a/src/Testcontainers/Builders/TestcontainersEndpointAuthenticationProvider.cs b/src/Testcontainers/Builders/TestcontainersEndpointAuthenticationProvider.cs index 04335eb00..6f92a2d1b 100644 --- a/src/Testcontainers/Builders/TestcontainersEndpointAuthenticationProvider.cs +++ b/src/Testcontainers/Builders/TestcontainersEndpointAuthenticationProvider.cs @@ -16,7 +16,9 @@ namespace DotNet.Testcontainers.Builders /// Testcontainers Cloud if it is running. /// [PublicAPI] - internal sealed class TestcontainersEndpointAuthenticationProvider : DockerEndpointAuthenticationProvider, ICustomConfiguration + internal sealed class TestcontainersEndpointAuthenticationProvider + : DockerEndpointAuthenticationProvider, + ICustomConfiguration { private readonly ICustomConfiguration _customConfiguration; @@ -26,18 +28,14 @@ internal sealed class TestcontainersEndpointAuthenticationProvider : DockerEndpo /// Initializes a new instance of the class. /// public TestcontainersEndpointAuthenticationProvider() - : this(new TestcontainersConfiguration()) - { - } + : this(new TestcontainersConfiguration()) { } /// /// Initializes a new instance of the class. /// /// A list of Java properties file lines. public TestcontainersEndpointAuthenticationProvider(params string[] lines) - : this(new TestcontainersConfiguration(lines)) - { - } + : this(new TestcontainersConfiguration(lines)) { } private TestcontainersEndpointAuthenticationProvider(ICustomConfiguration customConfiguration) { @@ -48,7 +46,8 @@ private TestcontainersEndpointAuthenticationProvider(ICustomConfiguration custom /// public override bool IsApplicable() { - return _dockerEngine != null && "tcp".Equals(_dockerEngine.Scheme, StringComparison.OrdinalIgnoreCase); + return _dockerEngine != null + && "tcp".Equals(_dockerEngine.Scheme, StringComparison.OrdinalIgnoreCase); } /// @@ -161,14 +160,10 @@ public string GetHubImageNamePrefix() private sealed class TestcontainersConfiguration : PropertiesFileConfiguration { - public TestcontainersConfiguration() - { - } + public TestcontainersConfiguration() { } public TestcontainersConfiguration(params string[] lines) - : base(lines) - { - } + : base(lines) { } protected override Uri GetDockerHost(string propertyName) { diff --git a/src/Testcontainers/Builders/TlsCredentials.cs b/src/Testcontainers/Builders/TlsCredentials.cs index d0bdb3890..c1cd1434d 100644 --- a/src/Testcontainers/Builders/TlsCredentials.cs +++ b/src/Testcontainers/Builders/TlsCredentials.cs @@ -7,9 +7,7 @@ namespace DotNet.Testcontainers.Builders internal sealed class TlsCredentials : CertificateCredentials { public TlsCredentials() - : base(null) - { - } + : base(null) { } public override bool IsTlsCredentials() { diff --git a/src/Testcontainers/Builders/TlsEndpointAuthenticationProvider.cs b/src/Testcontainers/Builders/TlsEndpointAuthenticationProvider.cs index bfc7acb7b..e6d6ce529 100644 --- a/src/Testcontainers/Builders/TlsEndpointAuthenticationProvider.cs +++ b/src/Testcontainers/Builders/TlsEndpointAuthenticationProvider.cs @@ -23,28 +23,31 @@ internal class TlsEndpointAuthenticationProvider : DockerEndpointAuthenticationP /// Initializes a new instance of the class. /// public TlsEndpointAuthenticationProvider() - : this(EnvironmentConfiguration.Instance, PropertiesFileConfiguration.Instance) - { - } + : this(EnvironmentConfiguration.Instance, PropertiesFileConfiguration.Instance) { } /// /// Initializes a new instance of the class. /// /// A list of custom configurations. public TlsEndpointAuthenticationProvider(params ICustomConfiguration[] customConfigurations) - : this(customConfigurations - .OrderByDescending(item => item.GetDockerTlsVerify()) - .ThenByDescending(item => item.GetDockerTls()) - .DefaultIfEmpty(new PropertiesFileConfiguration(Array.Empty())) - .First()) - { - } + : this( + customConfigurations + .OrderByDescending(item => item.GetDockerTlsVerify()) + .ThenByDescending(item => item.GetDockerTls()) + .DefaultIfEmpty(new PropertiesFileConfiguration(Array.Empty())) + .First() + ) { } private TlsEndpointAuthenticationProvider(ICustomConfiguration customConfiguration) { TlsEnabled = customConfiguration.GetDockerTls() || customConfiguration.GetDockerTlsVerify(); TlsVerifyEnabled = customConfiguration.GetDockerTlsVerify(); - CertificatesDirectoryPath = customConfiguration.GetDockerCertPath() ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".docker"); + CertificatesDirectoryPath = + customConfiguration.GetDockerCertPath() + ?? Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), + ".docker" + ); DockerEngine = customConfiguration.GetDockerHost() ?? new Uri("tcp://localhost:2376"); } @@ -77,7 +80,9 @@ public override IDockerEndpointAuthenticationConfiguration GetAuthConfig() protected virtual X509Certificate2 GetCaCertificate() { #if NET9_0_OR_GREATER - return X509CertificateLoader.LoadCertificateFromFile(Path.Combine(CertificatesDirectoryPath, CaCertificateFileName)); + return X509CertificateLoader.LoadCertificateFromFile( + Path.Combine(CertificatesDirectoryPath, CaCertificateFileName) + ); #else return new X509Certificate2(Path.Combine(CertificatesDirectoryPath, CaCertificateFileName)); #endif @@ -93,7 +98,12 @@ protected virtual X509Certificate2 GetClientCertificate() } /// - protected virtual bool ServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + protected virtual bool ServerCertificateValidationCallback( + object sender, + X509Certificate certificate, + X509Chain chain, + SslPolicyErrors sslPolicyErrors + ) { switch (sslPolicyErrors) { @@ -108,11 +118,19 @@ protected virtual bool ServerCertificateValidationCallback(object sender, X509Ce { var validationChain = new X509Chain(); validationChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; - validationChain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; + validationChain.ChainPolicy.VerificationFlags = + X509VerificationFlags.AllowUnknownCertificateAuthority; validationChain.ChainPolicy.ExtraStore.Add(caCertificate); - validationChain.ChainPolicy.ExtraStore.AddRange(chain.ChainElements.OfType().Select(element => element.Certificate).ToArray()); + validationChain.ChainPolicy.ExtraStore.AddRange( + chain + .ChainElements.OfType() + .Select(element => element.Certificate) + .ToArray() + ); var isVerified = validationChain.Build(new X509Certificate2(certificate)); - var isSignedByExpectedRoot = validationChain.ChainElements[validationChain.ChainElements.Count - 1].Certificate.RawData.SequenceEqual(caCertificate.RawData); + var isSignedByExpectedRoot = validationChain + .ChainElements[validationChain.ChainElements.Count - 1] + .Certificate.RawData.SequenceEqual(caCertificate.RawData); return isVerified && isSignedByExpectedRoot; } } diff --git a/src/Testcontainers/Builders/UnixEndpointAuthenticationProvider.cs b/src/Testcontainers/Builders/UnixEndpointAuthenticationProvider.cs index 5d03d8e48..929fdff61 100644 --- a/src/Testcontainers/Builders/UnixEndpointAuthenticationProvider.cs +++ b/src/Testcontainers/Builders/UnixEndpointAuthenticationProvider.cs @@ -12,8 +12,7 @@ internal sealed class UnixEndpointAuthenticationProvider : DockerEndpointAuthent /// /// Gets the Unix socket Docker Engine endpoint. /// - public static Uri DockerEngine { get; } - = new Uri("unix:///var/run/docker.sock"); + public static Uri DockerEngine { get; } = new Uri("unix:///var/run/docker.sock"); /// public override bool IsApplicable() diff --git a/src/Testcontainers/Builders/VolumeBuilder.cs b/src/Testcontainers/Builders/VolumeBuilder.cs index a56d246d1..690f8fd07 100644 --- a/src/Testcontainers/Builders/VolumeBuilder.cs +++ b/src/Testcontainers/Builders/VolumeBuilder.cs @@ -20,7 +20,9 @@ namespace DotNet.Testcontainers.Builders /// /// [PublicAPI] - public class VolumeBuilder : AbstractBuilder, IVolumeBuilder + public class VolumeBuilder + : AbstractBuilder, + IVolumeBuilder { /// /// Initializes a new instance of the class. @@ -68,19 +70,25 @@ protected override void Validate() { base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Name, nameof(IVolumeConfiguration.Name)) + _ = Guard + .Argument(DockerResourceConfiguration.Name, nameof(IVolumeConfiguration.Name)) .NotNull() .NotEmpty(); } /// - protected override VolumeBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override VolumeBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new VolumeConfiguration(resourceConfiguration)); } /// - protected override VolumeBuilder Merge(IVolumeConfiguration oldValue, IVolumeConfiguration newValue) + protected override VolumeBuilder Merge( + IVolumeConfiguration oldValue, + IVolumeConfiguration newValue + ) { return new VolumeBuilder(new VolumeConfiguration(oldValue, newValue)); } diff --git a/src/Testcontainers/Clients/CollectionConverter.cs b/src/Testcontainers/Clients/CollectionConverter.cs index 3dbd8915f..c86d1328c 100644 --- a/src/Testcontainers/Clients/CollectionConverter.cs +++ b/src/Testcontainers/Clients/CollectionConverter.cs @@ -7,15 +7,14 @@ namespace DotNet.Testcontainers.Clients /// /// Testcontainer configuration type. /// Official Docker configuration type. - internal abstract class CollectionConverter : BaseConverter, IEnumerable> + internal abstract class CollectionConverter + : BaseConverter, IEnumerable> { /// /// Initializes a new instance of the class. /// /// Name of the converter. protected CollectionConverter(string name) - : base(name) - { - } + : base(name) { } } } diff --git a/src/Testcontainers/Clients/ContainerConfigurationConverter.cs b/src/Testcontainers/Clients/ContainerConfigurationConverter.cs index 39a684e04..b618b3368 100644 --- a/src/Testcontainers/Clients/ContainerConfigurationConverter.cs +++ b/src/Testcontainers/Clients/ContainerConfigurationConverter.cs @@ -16,7 +16,12 @@ internal sealed class ContainerConfigurationConverter private const string SctpProtocolSuffix = "/sctp"; - private static readonly string[] Protocols = new[] { UdpProtocolSuffix, TcpProtocolSuffix, SctpProtocolSuffix }; + private static readonly string[] Protocols = new[] + { + UdpProtocolSuffix, + TcpProtocolSuffix, + SctpProtocolSuffix, + }; public ContainerConfigurationConverter(IContainerConfiguration configuration) { @@ -24,11 +29,19 @@ public ContainerConfigurationConverter(IContainerConfiguration configuration) Command = new ToCollection().Convert(configuration.Command)?.ToList(); ExtraHosts = new ToCollection().Convert(configuration.ExtraHosts)?.ToList(); Environments = new ToMappedList().Convert(configuration.Environments)?.ToList(); - Labels = new ToDictionary().Convert(configuration.Labels)?.ToDictionary(item => item.Key, item => item.Value); - ExposedPorts = new ToExposedPorts().Convert(configuration.ExposedPorts)?.ToDictionary(item => item.Key, item => item.Value); - PortBindings = new ToPortBindings().Convert(configuration.PortBindings)?.ToDictionary(item => item.Key, item => item.Value); + Labels = new ToDictionary() + .Convert(configuration.Labels) + ?.ToDictionary(item => item.Key, item => item.Value); + ExposedPorts = new ToExposedPorts() + .Convert(configuration.ExposedPorts) + ?.ToDictionary(item => item.Key, item => item.Value); + PortBindings = new ToPortBindings() + .Convert(configuration.PortBindings) + ?.ToDictionary(item => item.Key, item => item.Value); Mounts = new ToMounts().Convert(configuration.Mounts)?.ToList(); - Networks = new ToNetworks(configuration).Convert(configuration.Networks)?.ToDictionary(item => item.Key, item => item.Value); + Networks = new ToNetworks(configuration) + .Convert(configuration.Networks) + ?.ToDictionary(item => item.Key, item => item.Value); } public IList Entrypoint { get; } @@ -51,16 +64,18 @@ public ContainerConfigurationConverter(IContainerConfiguration configuration) public static string GetQualifiedPort(string containerPort) { - return Array.Exists(Protocols, portSuffix => containerPort.EndsWith(portSuffix, StringComparison.OrdinalIgnoreCase)) - ? containerPort.ToLowerInvariant() : containerPort + TcpProtocolSuffix; + return Array.Exists( + Protocols, + portSuffix => containerPort.EndsWith(portSuffix, StringComparison.OrdinalIgnoreCase) + ) + ? containerPort.ToLowerInvariant() + : containerPort + TcpProtocolSuffix; } private sealed class ToCollection : CollectionConverter { public ToCollection() - : base(nameof(ToCollection)) - { - } + : base(nameof(ToCollection)) { } public override IEnumerable Convert([CanBeNull] IEnumerable source) { @@ -71,21 +86,26 @@ public override IEnumerable Convert([CanBeNull] IEnumerable sour private sealed class ToMounts : CollectionConverter { public ToMounts() - : base(nameof(ToMounts)) - { - } + : base(nameof(ToMounts)) { } public override IEnumerable Convert([CanBeNull] IEnumerable source) { return source?.Select(mount => { var readOnly = AccessMode.ReadOnly.Equals(mount.AccessMode); - return new Mount { Type = mount.Type.Type, Source = mount.Source, Target = mount.Target, ReadOnly = readOnly }; + return new Mount + { + Type = mount.Type.Type, + Source = mount.Source, + Target = mount.Target, + ReadOnly = readOnly, + }; }); } } - private sealed class ToNetworks : CollectionConverter> + private sealed class ToNetworks + : CollectionConverter> { private readonly IContainerConfiguration _configuration; @@ -95,63 +115,75 @@ public ToNetworks(IContainerConfiguration configuration) _configuration = configuration; } - public override IEnumerable> Convert([CanBeNull] IEnumerable source) + public override IEnumerable> Convert( + [CanBeNull] IEnumerable source + ) { - return source?.Select(network => new KeyValuePair(network.Name, new EndpointSettings { Aliases = _configuration.NetworkAliases?.ToList() })); + return source?.Select(network => new KeyValuePair( + network.Name, + new EndpointSettings { Aliases = _configuration.NetworkAliases?.ToList() } + )); } } private sealed class ToMappedList : DictionaryConverter> { public ToMappedList() - : base(nameof(ToMappedList)) - { - } + : base(nameof(ToMappedList)) { } - public override IEnumerable Convert([CanBeNull] IEnumerable> source) + public override IEnumerable Convert( + [CanBeNull] IEnumerable> source + ) { return source?.Select(item => string.Join("=", item.Key, item.Value)); } } - private sealed class ToDictionary : DictionaryConverter>> + private sealed class ToDictionary + : DictionaryConverter>> { public ToDictionary() - : base(nameof(ToDictionary)) - { - } + : base(nameof(ToDictionary)) { } - public override IEnumerable> Convert([CanBeNull] IEnumerable> source) + public override IEnumerable> Convert( + [CanBeNull] IEnumerable> source + ) { return source; } } - private sealed class ToExposedPorts : DictionaryConverter>> + private sealed class ToExposedPorts + : DictionaryConverter>> { public ToExposedPorts() - : base(nameof(ToExposedPorts)) - { - } + : base(nameof(ToExposedPorts)) { } - public override IEnumerable> Convert([CanBeNull] IEnumerable> source) + public override IEnumerable> Convert( + [CanBeNull] IEnumerable> source + ) { return source?.Select(exposedPort => new KeyValuePair( - GetQualifiedPort(exposedPort.Key), default)); + GetQualifiedPort(exposedPort.Key), + default + )); } } - private sealed class ToPortBindings : DictionaryConverter>>> + private sealed class ToPortBindings + : DictionaryConverter>>> { public ToPortBindings() - : base(nameof(ToPortBindings)) - { - } + : base(nameof(ToPortBindings)) { } - public override IEnumerable>> Convert([CanBeNull] IEnumerable> source) + public override IEnumerable>> Convert( + [CanBeNull] IEnumerable> source + ) { return source?.Select(portBinding => new KeyValuePair>( - GetQualifiedPort(portBinding.Key), new[] { new PortBinding { HostPort = portBinding.Value } })); + GetQualifiedPort(portBinding.Key), + new[] { new PortBinding { HostPort = portBinding.Value } } + )); } } } diff --git a/src/Testcontainers/Clients/DefaultLabels.cs b/src/Testcontainers/Clients/DefaultLabels.cs index f3a54461f..b174f543e 100644 --- a/src/Testcontainers/Clients/DefaultLabels.cs +++ b/src/Testcontainers/Clients/DefaultLabels.cs @@ -6,23 +6,26 @@ namespace DotNet.Testcontainers.Clients internal sealed class DefaultLabels : ReadOnlyDictionary { - static DefaultLabels() - { - } + static DefaultLabels() { } private DefaultLabels() - : base(new Dictionary - { - { TestcontainersClient.TestcontainersLabel, bool.TrueString.ToLowerInvariant() }, - { TestcontainersClient.TestcontainersLangLabel, "dotnet" }, - { TestcontainersClient.TestcontainersVersionLabel, TestcontainersClient.Version }, - { TestcontainersClient.TestcontainersSessionIdLabel, ResourceReaper.DefaultSessionId.ToString("D") }, - { ResourceReaper.ResourceReaperSessionLabel, ResourceReaper.DefaultSessionId.ToString("D") }, - }) - { - } + : base( + new Dictionary + { + { TestcontainersClient.TestcontainersLabel, bool.TrueString.ToLowerInvariant() }, + { TestcontainersClient.TestcontainersLangLabel, "dotnet" }, + { TestcontainersClient.TestcontainersVersionLabel, TestcontainersClient.Version }, + { + TestcontainersClient.TestcontainersSessionIdLabel, + ResourceReaper.DefaultSessionId.ToString("D") + }, + { + ResourceReaper.ResourceReaperSessionLabel, + ResourceReaper.DefaultSessionId.ToString("D") + }, + } + ) { } - public static IReadOnlyDictionary Instance { get; } - = new DefaultLabels(); + public static IReadOnlyDictionary Instance { get; } = new DefaultLabels(); } } diff --git a/src/Testcontainers/Clients/DictionaryConverter.cs b/src/Testcontainers/Clients/DictionaryConverter.cs index 08c069b96..e2eb6ed74 100644 --- a/src/Testcontainers/Clients/DictionaryConverter.cs +++ b/src/Testcontainers/Clients/DictionaryConverter.cs @@ -6,15 +6,14 @@ namespace DotNet.Testcontainers.Clients /// Converts or maps Testcontainers dictionary configurations to official Docker configurations. /// /// Official Docker configuration type. - internal abstract class DictionaryConverter : BaseConverter>, TTarget> + internal abstract class DictionaryConverter + : BaseConverter>, TTarget> { /// /// Initializes a new instance of the class. /// /// Name of the converter. protected DictionaryConverter(string name) - : base(name) - { - } + : base(name) { } } } diff --git a/src/Testcontainers/Clients/DockerApiClient.cs b/src/Testcontainers/Clients/DockerApiClient.cs index f0436a287..f8efd9558 100644 --- a/src/Testcontainers/Clients/DockerApiClient.cs +++ b/src/Testcontainers/Clients/DockerApiClient.cs @@ -18,7 +18,8 @@ namespace DotNet.Testcontainers.Clients /// internal class DockerApiClient { - private static readonly ConcurrentDictionary> Clients = new ConcurrentDictionary>(); + private static readonly ConcurrentDictionary> Clients = + new ConcurrentDictionary>(); private static readonly ISet ProcessedHashCodes = new HashSet(); @@ -30,10 +31,20 @@ internal class DockerApiClient /// The test session id. /// The Docker endpoint authentication configuration. /// The logger. - protected DockerApiClient(Guid sessionId, IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, ILogger logger) - : this(Clients.GetOrAdd(dockerEndpointAuthConfig.Endpoint, _ => new Lazy(() => GetDockerClient(sessionId, dockerEndpointAuthConfig))).Value, logger) - { - } + protected DockerApiClient( + Guid sessionId, + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, + ILogger logger + ) + : this( + Clients + .GetOrAdd( + dockerEndpointAuthConfig.Endpoint, + _ => new Lazy(() => GetDockerClient(sessionId, dockerEndpointAuthConfig)) + ) + .Value, + logger + ) { } /// /// Initializes a new instance of the class. @@ -70,8 +81,7 @@ public async Task LogContainerRuntimeInfoAsync(CancellationToken ct = default) { var hashCode = HashCode.Combine(DockerClient, Logger); - await RuntimeInitialized.WaitAsync(ct) - .ConfigureAwait(false); + await RuntimeInitialized.WaitAsync(ct).ConfigureAwait(false); try { @@ -84,11 +94,9 @@ await RuntimeInitialized.WaitAsync(ct) var byteUnits = new[] { "KB", "MB", "GB" }; - var dockerInfo = await DockerClient.System.GetSystemInfoAsync(ct) - .ConfigureAwait(false); + var dockerInfo = await DockerClient.System.GetSystemInfoAsync(ct).ConfigureAwait(false); - var dockerVersion = await DockerClient.System.GetVersionAsync(ct) - .ConfigureAwait(false); + var dockerVersion = await DockerClient.System.GetVersionAsync(ct).ConfigureAwait(false); runtimeInfo.AppendLine("Connected to Docker:"); @@ -108,18 +116,25 @@ await RuntimeInitialized.WaitAsync(ct) runtimeInfo.AppendLine(dockerInfo.OperatingSystem); runtimeInfo.Append(" Total Memory: "); - runtimeInfo.AppendFormat(CultureInfo.InvariantCulture, "{0:F} {1}", dockerInfo.MemTotal / Math.Pow(1024, byteUnits.Length), byteUnits[byteUnits.Length - 1]); + runtimeInfo.AppendFormat( + CultureInfo.InvariantCulture, + "{0:F} {1}", + dockerInfo.MemTotal / Math.Pow(1024, byteUnits.Length), + byteUnits[byteUnits.Length - 1] + ); var labels = dockerInfo.Labels; if (labels != null && labels.Count > 0) { runtimeInfo.AppendLine(); runtimeInfo.AppendLine(" Labels: "); - runtimeInfo.Append(string.Join(Environment.NewLine, labels.Select(label => " " + label))); + runtimeInfo.Append( + string.Join(Environment.NewLine, labels.Select(label => " " + label)) + ); } Logger.LogInformation("{RuntimeInfo}", runtimeInfo); } - catch(Exception e) + catch (Exception e) { Logger.LogError(e, "Failed to retrieve Docker container runtime information"); } @@ -130,9 +145,16 @@ await RuntimeInitialized.WaitAsync(ct) } } - private static IDockerClient GetDockerClient(Guid sessionId, IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig) + private static IDockerClient GetDockerClient( + Guid sessionId, + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig + ) { - using (var dockerClientConfiguration = dockerEndpointAuthConfig.GetDockerClientConfiguration(sessionId)) + using ( + var dockerClientConfiguration = dockerEndpointAuthConfig.GetDockerClientConfiguration( + sessionId + ) + ) { return dockerClientConfiguration.CreateClient(); } diff --git a/src/Testcontainers/Clients/DockerContainerOperations.cs b/src/Testcontainers/Clients/DockerContainerOperations.cs index 340f92410..1217beabd 100644 --- a/src/Testcontainers/Clients/DockerContainerOperations.cs +++ b/src/Testcontainers/Clients/DockerContainerOperations.cs @@ -14,35 +14,45 @@ namespace DotNet.Testcontainers.Clients internal sealed class DockerContainerOperations : DockerApiClient, IDockerContainerOperations { - public DockerContainerOperations(Guid sessionId, IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, ILogger logger) - : base(sessionId, dockerEndpointAuthConfig, logger) + public DockerContainerOperations( + Guid sessionId, + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, + ILogger logger + ) + : base(sessionId, dockerEndpointAuthConfig, logger) { } + + public async Task> GetAllAsync( + CancellationToken ct = default + ) { - } - - public async Task> GetAllAsync(CancellationToken ct = default) - { - return await DockerClient.Containers.ListContainersAsync(new ContainersListParameters { All = true }, ct) + return await DockerClient + .Containers.ListContainersAsync(new ContainersListParameters { All = true }, ct) .ConfigureAwait(false); } - public async Task> GetAllAsync(FilterByProperty filters, CancellationToken ct = default) + public async Task> GetAllAsync( + FilterByProperty filters, + CancellationToken ct = default + ) { - return await DockerClient.Containers.ListContainersAsync(new ContainersListParameters { All = true, Filters = filters }, ct) + return await DockerClient + .Containers.ListContainersAsync( + new ContainersListParameters { All = true, Filters = filters }, + ct + ) .ConfigureAwait(false); } public async Task ByIdAsync(string id, CancellationToken ct = default) { - return await DockerClient.Containers.InspectContainerAsync(id, ct) - .ConfigureAwait(false); + return await DockerClient.Containers.InspectContainerAsync(id, ct).ConfigureAwait(false); } public async Task ExistsWithIdAsync(string id, CancellationToken ct = default) { try { - _ = await ByIdAsync(id, ct) - .ConfigureAwait(false); + _ = await ByIdAsync(id, ct).ConfigureAwait(false); return true; } @@ -54,28 +64,37 @@ public async Task ExistsWithIdAsync(string id, CancellationToken ct = defa public async Task GetExitCodeAsync(string id, CancellationToken ct = default) { - var response = await DockerClient.Containers.WaitContainerAsync(id, ct) - .ConfigureAwait(false); + var response = await DockerClient.Containers.WaitContainerAsync(id, ct).ConfigureAwait(false); return response.StatusCode; } - public async Task<(string Stdout, string Stderr)> GetLogsAsync(string id, TimeSpan since, TimeSpan until, bool timestampsEnabled = true, CancellationToken ct = default) + public async Task<(string Stdout, string Stderr)> GetLogsAsync( + string id, + TimeSpan since, + TimeSpan until, + bool timestampsEnabled = true, + CancellationToken ct = default + ) { var logsParameters = new ContainerLogsParameters { ShowStdout = true, ShowStderr = true, - Since = Math.Max(0, Math.Floor(since.TotalSeconds)).ToString("0", CultureInfo.InvariantCulture), - Until = Math.Max(0, Math.Floor(until.TotalSeconds)).ToString("0", CultureInfo.InvariantCulture), + Since = Math.Max(0, Math.Floor(since.TotalSeconds)) + .ToString("0", CultureInfo.InvariantCulture), + Until = Math.Max(0, Math.Floor(until.TotalSeconds)) + .ToString("0", CultureInfo.InvariantCulture), Timestamps = timestampsEnabled, }; - using (var stdOutAndErrStream = await DockerClient.Containers.GetContainerLogsAsync(id, logsParameters, ct) - .ConfigureAwait(false)) + using ( + var stdOutAndErrStream = await DockerClient + .Containers.GetContainerLogsAsync(id, logsParameters, ct) + .ConfigureAwait(false) + ) { - return await stdOutAndErrStream.ReadOutputToEndAsync(ct) - .ConfigureAwait(false); + return await stdOutAndErrStream.ReadOutputToEndAsync(ct).ConfigureAwait(false); } } @@ -106,26 +125,54 @@ public Task UnpauseAsync(string id, CancellationToken ct = default) public Task RemoveAsync(string id, CancellationToken ct = default) { Logger.DeleteDockerContainer(id); - return DockerClient.Containers.RemoveContainerAsync(id, new ContainerRemoveParameters { Force = true, RemoveVolumes = true }, ct); + return DockerClient.Containers.RemoveContainerAsync( + id, + new ContainerRemoveParameters { Force = true, RemoveVolumes = true }, + ct + ); } - public Task ExtractArchiveToContainerAsync(string id, string path, TarOutputMemoryStream tarStream, CancellationToken ct = default) + public Task ExtractArchiveToContainerAsync( + string id, + string path, + TarOutputMemoryStream tarStream, + CancellationToken ct = default + ) { Logger.CopyArchiveToDockerContainer(id, tarStream.ContentLength); - return DockerClient.Containers.ExtractArchiveToContainerAsync(id, new ContainerPathStatParameters { Path = path }, tarStream, ct); + return DockerClient.Containers.ExtractArchiveToContainerAsync( + id, + new ContainerPathStatParameters { Path = path }, + tarStream, + ct + ); } - public async Task GetArchiveFromContainerAsync(string id, string path, CancellationToken ct = default) + public async Task GetArchiveFromContainerAsync( + string id, + string path, + CancellationToken ct = default + ) { Logger.ReadArchiveFromDockerContainer(id, path); - var tarResponse = await DockerClient.Containers.GetArchiveFromContainerAsync(id, new ContainerPathStatParameters { Path = path }, false, ct) + var tarResponse = await DockerClient + .Containers.GetArchiveFromContainerAsync( + id, + new ContainerPathStatParameters { Path = path }, + false, + ct + ) .ConfigureAwait(false); return tarResponse.Stream; } - public async Task AttachAsync(string id, IOutputConsumer outputConsumer, CancellationToken ct = default) + public async Task AttachAsync( + string id, + IOutputConsumer outputConsumer, + CancellationToken ct = default + ) { if (!outputConsumer.Enabled) { @@ -141,14 +188,20 @@ public async Task AttachAsync(string id, IOutputConsumer outputConsumer, Cancell Stream = true, }; - var stream = await DockerClient.Containers.AttachContainerAsync(id, attachParameters, ct) + var stream = await DockerClient + .Containers.AttachContainerAsync(id, attachParameters, ct) .ConfigureAwait(false); - _ = stream.CopyOutputToAsync(Stream.Null, outputConsumer.Stdout, outputConsumer.Stderr, ct) + _ = stream + .CopyOutputToAsync(Stream.Null, outputConsumer.Stdout, outputConsumer.Stderr, ct) .ConfigureAwait(false); } - public async Task ExecAsync(string id, IList command, CancellationToken ct = default) + public async Task ExecAsync( + string id, + IList command, + CancellationToken ct = default + ) { Logger.ExecuteCommandInDockerContainer(id, command); @@ -159,23 +212,36 @@ public async Task ExecAsync(string id, IList command, Cancel AttachStderr = true, }; - var execCreateResponse = await DockerClient.Exec.CreateContainerExecAsync(id, execCreateParameters, ct) + var execCreateResponse = await DockerClient + .Exec.CreateContainerExecAsync(id, execCreateParameters, ct) .ConfigureAwait(false); - using (var stdOutAndErrStream = await DockerClient.Exec.StartContainerExecAsync(execCreateResponse.ID, new ContainerExecStartParameters(), ct) - .ConfigureAwait(false)) + using ( + var stdOutAndErrStream = await DockerClient + .Exec.StartContainerExecAsync( + execCreateResponse.ID, + new ContainerExecStartParameters(), + ct + ) + .ConfigureAwait(false) + ) { - var (stdout, stderr) = await stdOutAndErrStream.ReadOutputToEndAsync(ct) + var (stdout, stderr) = await stdOutAndErrStream + .ReadOutputToEndAsync(ct) .ConfigureAwait(false); - var execInspectResponse = await DockerClient.Exec.InspectContainerExecAsync(execCreateResponse.ID, ct) + var execInspectResponse = await DockerClient + .Exec.InspectContainerExecAsync(execCreateResponse.ID, ct) .ConfigureAwait(false); return new ExecResult(stdout, stderr, execInspectResponse.ExitCode); } } - public async Task RunAsync(IContainerConfiguration configuration, CancellationToken ct = default) + public async Task RunAsync( + IContainerConfiguration configuration, + CancellationToken ct = default + ) { var converter = new ContainerConfigurationConverter(configuration); @@ -188,10 +254,7 @@ public async Task RunAsync(IContainerConfiguration configuration, Cancel Mounts = converter.Mounts, }; - var networkingConfig = new NetworkingConfig - { - EndpointsConfig = converter.Networks, - }; + var networkingConfig = new NetworkingConfig { EndpointsConfig = converter.Networks }; var createParameters = new CreateContainerParameters { @@ -211,7 +274,10 @@ public async Task RunAsync(IContainerConfiguration configuration, Cancel if (configuration.Reuse.HasValue && configuration.Reuse.Value) { - createParameters.Labels.Add(TestcontainersClient.TestcontainersReuseHashLabel, configuration.GetReuseHash()); + createParameters.Labels.Add( + TestcontainersClient.TestcontainersReuseHashLabel, + configuration.GetReuseHash() + ); } if (configuration.ParameterModifiers != null) @@ -222,7 +288,8 @@ public async Task RunAsync(IContainerConfiguration configuration, Cancel } } - var createContainerResponse = await DockerClient.Containers.CreateContainerAsync(createParameters, ct) + var createContainerResponse = await DockerClient + .Containers.CreateContainerAsync(createParameters, ct) .ConfigureAwait(false); Logger.DockerContainerCreated(createContainerResponse.ID); diff --git a/src/Testcontainers/Clients/DockerImageOperations.cs b/src/Testcontainers/Clients/DockerImageOperations.cs index 1b55f6b4a..2e152912a 100644 --- a/src/Testcontainers/Clients/DockerImageOperations.cs +++ b/src/Testcontainers/Clients/DockerImageOperations.cs @@ -16,7 +16,11 @@ internal sealed class DockerImageOperations : DockerApiClient, IDockerImageOpera { private readonly TraceProgress _traceProgress; - public DockerImageOperations(Guid sessionId, IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, ILogger logger) + public DockerImageOperations( + Guid sessionId, + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, + ILogger logger + ) : base(sessionId, dockerEndpointAuthConfig, logger) { _traceProgress = new TraceProgress(logger); @@ -24,28 +28,31 @@ public DockerImageOperations(Guid sessionId, IDockerEndpointAuthenticationConfig public async Task> GetAllAsync(CancellationToken ct = default) { - return await DockerClient.Images.ListImagesAsync(new ImagesListParameters { All = true }, ct) + return await DockerClient + .Images.ListImagesAsync(new ImagesListParameters { All = true }, ct) .ConfigureAwait(false); } - public async Task> GetAllAsync(FilterByProperty filters, CancellationToken ct = default) + public async Task> GetAllAsync( + FilterByProperty filters, + CancellationToken ct = default + ) { - return await DockerClient.Images.ListImagesAsync(new ImagesListParameters { All = true, Filters = filters }, ct) + return await DockerClient + .Images.ListImagesAsync(new ImagesListParameters { All = true, Filters = filters }, ct) .ConfigureAwait(false); } public async Task ByIdAsync(string id, CancellationToken ct = default) { - return await DockerClient.Images.InspectImageAsync(id, ct) - .ConfigureAwait(false); + return await DockerClient.Images.InspectImageAsync(id, ct).ConfigureAwait(false); } public async Task ExistsWithIdAsync(string id, CancellationToken ct = default) { try { - _ = await ByIdAsync(id, ct) - .ConfigureAwait(false); + _ = await ByIdAsync(id, ct).ConfigureAwait(false); return true; } @@ -55,12 +62,13 @@ public async Task ExistsWithIdAsync(string id, CancellationToken ct = defa } } - public async Task CreateAsync(IImage image, IDockerRegistryAuthenticationConfiguration dockerRegistryAuthConfig, CancellationToken ct = default) + public async Task CreateAsync( + IImage image, + IDockerRegistryAuthenticationConfiguration dockerRegistryAuthConfig, + CancellationToken ct = default + ) { - var createParameters = new ImagesCreateParameters - { - FromImage = image.FullName, - }; + var createParameters = new ImagesCreateParameters { FromImage = image.FullName }; var authConfig = new AuthConfig { @@ -70,7 +78,8 @@ public async Task CreateAsync(IImage image, IDockerRegistryAuthenticationConfigu IdentityToken = dockerRegistryAuthConfig.IdentityToken, }; - await DockerClient.Images.CreateImageAsync(createParameters, authConfig, _traceProgress, ct) + await DockerClient + .Images.CreateImageAsync(createParameters, authConfig, _traceProgress, ct) .ConfigureAwait(false); Logger.DockerImageCreated(image); @@ -79,20 +88,30 @@ await DockerClient.Images.CreateImageAsync(createParameters, authConfig, _traceP public Task DeleteAsync(IImage image, CancellationToken ct = default) { Logger.DeleteDockerImage(image); - return DockerClient.Images.DeleteImageAsync(image.FullName, new ImageDeleteParameters { Force = true }, ct); + return DockerClient.Images.DeleteImageAsync( + image.FullName, + new ImageDeleteParameters { Force = true }, + ct + ); } - public async Task BuildAsync(IImageFromDockerfileConfiguration configuration, ITarArchive dockerfileArchive, CancellationToken ct = default) + public async Task BuildAsync( + IImageFromDockerfileConfiguration configuration, + ITarArchive dockerfileArchive, + CancellationToken ct = default + ) { var image = configuration.Image; - var imageExists = await ExistsWithIdAsync(image.FullName, ct) - .ConfigureAwait(false); + var imageExists = await ExistsWithIdAsync(image.FullName, ct).ConfigureAwait(false); - if (imageExists && configuration.DeleteIfExists.HasValue && configuration.DeleteIfExists.Value) + if ( + imageExists + && configuration.DeleteIfExists.HasValue + && configuration.DeleteIfExists.Value + ) { - await DeleteAsync(image, ct) - .ConfigureAwait(false); + await DeleteAsync(image, ct).ConfigureAwait(false); } var buildParameters = new ImageBuildParameters @@ -111,14 +130,27 @@ await DeleteAsync(image, ct) } } - var dockerfileArchiveFilePath = await dockerfileArchive.Tar(ct) - .ConfigureAwait(false); + var dockerfileArchiveFilePath = await dockerfileArchive.Tar(ct).ConfigureAwait(false); try { - using (var dockerfileArchiveStream = new FileStream(dockerfileArchiveFilePath, FileMode.Open, FileAccess.Read)) + using ( + var dockerfileArchiveStream = new FileStream( + dockerfileArchiveFilePath, + FileMode.Open, + FileAccess.Read + ) + ) { - await DockerClient.Images.BuildImageFromDockerfileAsync(buildParameters, dockerfileArchiveStream, Array.Empty(), new Dictionary(), _traceProgress, ct) + await DockerClient + .Images.BuildImageFromDockerfileAsync( + buildParameters, + dockerfileArchiveStream, + Array.Empty(), + new Dictionary(), + _traceProgress, + ct + ) .ConfigureAwait(false); var imageHasBeenCreated = await ExistsWithIdAsync(image.FullName, ct) @@ -126,7 +158,9 @@ await DeleteAsync(image, ct) if (!imageHasBeenCreated) { - throw new InvalidOperationException($"Docker image {image.FullName} has not been created."); + throw new InvalidOperationException( + $"Docker image {image.FullName} has not been created." + ); } } } diff --git a/src/Testcontainers/Clients/DockerNetworkOperations.cs b/src/Testcontainers/Clients/DockerNetworkOperations.cs index 982ad2822..5b291ec96 100644 --- a/src/Testcontainers/Clients/DockerNetworkOperations.cs +++ b/src/Testcontainers/Clients/DockerNetworkOperations.cs @@ -12,35 +12,40 @@ namespace DotNet.Testcontainers.Clients internal sealed class DockerNetworkOperations : DockerApiClient, IDockerNetworkOperations { - public DockerNetworkOperations(Guid sessionId, IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, ILogger logger) - : base(sessionId, dockerEndpointAuthConfig, logger) - { - } + public DockerNetworkOperations( + Guid sessionId, + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, + ILogger logger + ) + : base(sessionId, dockerEndpointAuthConfig, logger) { } public async Task> GetAllAsync(CancellationToken ct = default) { - return await DockerClient.Networks.ListNetworksAsync(new NetworksListParameters(), ct) + return await DockerClient + .Networks.ListNetworksAsync(new NetworksListParameters(), ct) .ConfigureAwait(false); } - public async Task> GetAllAsync(FilterByProperty filters, CancellationToken ct = default) + public async Task> GetAllAsync( + FilterByProperty filters, + CancellationToken ct = default + ) { - return await DockerClient.Networks.ListNetworksAsync(new NetworksListParameters { Filters = filters }, ct) + return await DockerClient + .Networks.ListNetworksAsync(new NetworksListParameters { Filters = filters }, ct) .ConfigureAwait(false); } public async Task ByIdAsync(string id, CancellationToken ct = default) { - return await DockerClient.Networks.InspectNetworkAsync(id, ct) - .ConfigureAwait(false); + return await DockerClient.Networks.InspectNetworkAsync(id, ct).ConfigureAwait(false); } public async Task ExistsWithIdAsync(string id, CancellationToken ct = default) { try { - _ = await ByIdAsync(id, ct) - .ConfigureAwait(false); + _ = await ByIdAsync(id, ct).ConfigureAwait(false); return true; } @@ -50,7 +55,10 @@ public async Task ExistsWithIdAsync(string id, CancellationToken ct = defa } } - public async Task CreateAsync(INetworkConfiguration configuration, CancellationToken ct = default) + public async Task CreateAsync( + INetworkConfiguration configuration, + CancellationToken ct = default + ) { var createParameters = new NetworksCreateParameters { @@ -62,7 +70,10 @@ public async Task CreateAsync(INetworkConfiguration configuration, Cance if (configuration.Reuse.HasValue && configuration.Reuse.Value) { - createParameters.Labels.Add(TestcontainersClient.TestcontainersReuseHashLabel, configuration.GetReuseHash()); + createParameters.Labels.Add( + TestcontainersClient.TestcontainersReuseHashLabel, + configuration.GetReuseHash() + ); } if (configuration.ParameterModifiers != null) @@ -73,7 +84,8 @@ public async Task CreateAsync(INetworkConfiguration configuration, Cance } } - var createNetworkResponse = await DockerClient.Networks.CreateNetworkAsync(createParameters, ct) + var createNetworkResponse = await DockerClient + .Networks.CreateNetworkAsync(createParameters, ct) .ConfigureAwait(false); Logger.DockerNetworkCreated(createNetworkResponse.ID); @@ -89,7 +101,11 @@ public Task DeleteAsync(string id, CancellationToken ct = default) public Task ConnectAsync(string networkId, string containerId, CancellationToken ct = default) { Logger.ConnectToDockerNetwork(networkId, containerId); - return DockerClient.Networks.ConnectNetworkAsync(networkId, new NetworkConnectParameters { Container = containerId }, ct); + return DockerClient.Networks.ConnectNetworkAsync( + networkId, + new NetworkConnectParameters { Container = containerId }, + ct + ); } } } diff --git a/src/Testcontainers/Clients/DockerSystemOperations.cs b/src/Testcontainers/Clients/DockerSystemOperations.cs index 628f02894..39ab58385 100644 --- a/src/Testcontainers/Clients/DockerSystemOperations.cs +++ b/src/Testcontainers/Clients/DockerSystemOperations.cs @@ -9,15 +9,16 @@ namespace DotNet.Testcontainers.Clients internal sealed class DockerSystemOperations : DockerApiClient, IDockerSystemOperations { - public DockerSystemOperations(Guid sessionId, IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, ILogger logger) - : base(sessionId, dockerEndpointAuthConfig, logger) - { - } + public DockerSystemOperations( + Guid sessionId, + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, + ILogger logger + ) + : base(sessionId, dockerEndpointAuthConfig, logger) { } public async Task GetIsWindowsEngineEnabled(CancellationToken ct = default) { - var version = await GetVersionAsync(ct) - .ConfigureAwait(false); + var version = await GetVersionAsync(ct).ConfigureAwait(false); return version.Os.IndexOf("Windows", StringComparison.OrdinalIgnoreCase) > -1; } diff --git a/src/Testcontainers/Clients/DockerVolumeOperations.cs b/src/Testcontainers/Clients/DockerVolumeOperations.cs index c04fd42a4..70612ddad 100644 --- a/src/Testcontainers/Clients/DockerVolumeOperations.cs +++ b/src/Testcontainers/Clients/DockerVolumeOperations.cs @@ -12,22 +12,27 @@ namespace DotNet.Testcontainers.Clients internal sealed class DockerVolumeOperations : DockerApiClient, IDockerVolumeOperations { - public DockerVolumeOperations(Guid sessionId, IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, ILogger logger) - : base(sessionId, dockerEndpointAuthConfig, logger) - { - } + public DockerVolumeOperations( + Guid sessionId, + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, + ILogger logger + ) + : base(sessionId, dockerEndpointAuthConfig, logger) { } public async Task> GetAllAsync(CancellationToken ct = default) { - var response = await DockerClient.Volumes.ListAsync(ct) - .ConfigureAwait(false); + var response = await DockerClient.Volumes.ListAsync(ct).ConfigureAwait(false); return response.Volumes; } - public async Task> GetAllAsync(FilterByProperty filters, CancellationToken ct = default) + public async Task> GetAllAsync( + FilterByProperty filters, + CancellationToken ct = default + ) { - var response = await DockerClient.Volumes.ListAsync(new VolumesListParameters { Filters = filters }, ct) + var response = await DockerClient + .Volumes.ListAsync(new VolumesListParameters { Filters = filters }, ct) .ConfigureAwait(false); return response.Volumes; @@ -35,16 +40,14 @@ public async Task> GetAllAsync(FilterByProperty filt public async Task ByIdAsync(string id, CancellationToken ct = default) { - return await DockerClient.Volumes.InspectAsync(id, ct) - .ConfigureAwait(false); + return await DockerClient.Volumes.InspectAsync(id, ct).ConfigureAwait(false); } public async Task ExistsWithIdAsync(string id, CancellationToken ct = default) { try { - _ = await ByIdAsync(id, ct) - .ConfigureAwait(false); + _ = await ByIdAsync(id, ct).ConfigureAwait(false); return true; } @@ -54,7 +57,10 @@ public async Task ExistsWithIdAsync(string id, CancellationToken ct = defa } } - public async Task CreateAsync(IVolumeConfiguration configuration, CancellationToken ct = default) + public async Task CreateAsync( + IVolumeConfiguration configuration, + CancellationToken ct = default + ) { var createParameters = new VolumesCreateParameters { @@ -64,7 +70,10 @@ public async Task CreateAsync(IVolumeConfiguration configuration, Cancel if (configuration.Reuse.HasValue && configuration.Reuse.Value) { - createParameters.Labels.Add(TestcontainersClient.TestcontainersReuseHashLabel, configuration.GetReuseHash()); + createParameters.Labels.Add( + TestcontainersClient.TestcontainersReuseHashLabel, + configuration.GetReuseHash() + ); } if (configuration.ParameterModifiers != null) @@ -75,7 +84,8 @@ public async Task CreateAsync(IVolumeConfiguration configuration, Cancel } } - var createVolumeResponse = await DockerClient.Volumes.CreateAsync(createParameters, ct) + var createVolumeResponse = await DockerClient + .Volumes.CreateAsync(createParameters, ct) .ConfigureAwait(false); Logger.DockerVolumeCreated(createVolumeResponse.Name); diff --git a/src/Testcontainers/Clients/FilterByProperty.cs b/src/Testcontainers/Clients/FilterByProperty.cs index d1887a0a3..f0c29c996 100644 --- a/src/Testcontainers/Clients/FilterByProperty.cs +++ b/src/Testcontainers/Clients/FilterByProperty.cs @@ -17,19 +17,13 @@ public FilterByProperty Add(string property, string value) public sealed class FilterByReuseHash : FilterByProperty { public FilterByReuseHash(IContainerConfiguration resourceConfiguration) - : this(resourceConfiguration.GetReuseHash()) - { - } + : this(resourceConfiguration.GetReuseHash()) { } public FilterByReuseHash(INetworkConfiguration resourceConfiguration) - : this(resourceConfiguration.GetReuseHash()) - { - } + : this(resourceConfiguration.GetReuseHash()) { } public FilterByReuseHash(IVolumeConfiguration resourceConfiguration) - : this(resourceConfiguration.GetReuseHash()) - { - } + : this(resourceConfiguration.GetReuseHash()) { } private FilterByReuseHash(string hash) { diff --git a/src/Testcontainers/Clients/IDockerContainerOperations.cs b/src/Testcontainers/Clients/IDockerContainerOperations.cs index a7f98d530..ab2dd307a 100644 --- a/src/Testcontainers/Clients/IDockerContainerOperations.cs +++ b/src/Testcontainers/Clients/IDockerContainerOperations.cs @@ -9,11 +9,18 @@ namespace DotNet.Testcontainers.Clients using DotNet.Testcontainers.Configurations; using DotNet.Testcontainers.Containers; - internal interface IDockerContainerOperations : IHasListOperations + internal interface IDockerContainerOperations + : IHasListOperations { Task GetExitCodeAsync(string id, CancellationToken ct = default); - Task<(string Stdout, string Stderr)> GetLogsAsync(string id, TimeSpan since, TimeSpan until, bool timestampsEnabled = true, CancellationToken ct = default); + Task<(string Stdout, string Stderr)> GetLogsAsync( + string id, + TimeSpan since, + TimeSpan until, + bool timestampsEnabled = true, + CancellationToken ct = default + ); Task StartAsync(string id, CancellationToken ct = default); @@ -25,9 +32,18 @@ internal interface IDockerContainerOperations : IHasListOperations GetArchiveFromContainerAsync(string id, string path, CancellationToken ct = default); + Task ExtractArchiveToContainerAsync( + string id, + string path, + TarOutputMemoryStream tarStream, + CancellationToken ct = default + ); + + Task GetArchiveFromContainerAsync( + string id, + string path, + CancellationToken ct = default + ); Task AttachAsync(string id, IOutputConsumer outputConsumer, CancellationToken ct = default); diff --git a/src/Testcontainers/Clients/IDockerImageOperations.cs b/src/Testcontainers/Clients/IDockerImageOperations.cs index f93cdf70d..9dfacf1dd 100644 --- a/src/Testcontainers/Clients/IDockerImageOperations.cs +++ b/src/Testcontainers/Clients/IDockerImageOperations.cs @@ -6,12 +6,21 @@ namespace DotNet.Testcontainers.Clients using DotNet.Testcontainers.Configurations; using DotNet.Testcontainers.Images; - internal interface IDockerImageOperations : IHasListOperations + internal interface IDockerImageOperations + : IHasListOperations { - Task CreateAsync(IImage image, IDockerRegistryAuthenticationConfiguration dockerRegistryAuthConfig, CancellationToken ct = default); + Task CreateAsync( + IImage image, + IDockerRegistryAuthenticationConfiguration dockerRegistryAuthConfig, + CancellationToken ct = default + ); Task DeleteAsync(IImage image, CancellationToken ct = default); - Task BuildAsync(IImageFromDockerfileConfiguration configuration, ITarArchive dockerfileArchive, CancellationToken ct = default); + Task BuildAsync( + IImageFromDockerfileConfiguration configuration, + ITarArchive dockerfileArchive, + CancellationToken ct = default + ); } } diff --git a/src/Testcontainers/Clients/IHasListOperations.cs b/src/Testcontainers/Clients/IHasListOperations.cs index e5421df1d..c444effdc 100644 --- a/src/Testcontainers/Clients/IHasListOperations.cs +++ b/src/Testcontainers/Clients/IHasListOperations.cs @@ -8,7 +8,10 @@ internal interface IHasListOperations { Task> GetAllAsync(CancellationToken ct = default); - Task> GetAllAsync(FilterByProperty filters, CancellationToken ct = default); + Task> GetAllAsync( + FilterByProperty filters, + CancellationToken ct = default + ); Task ByIdAsync(string id, CancellationToken ct = default); diff --git a/src/Testcontainers/Clients/ITestcontainersClient.cs b/src/Testcontainers/Clients/ITestcontainersClient.cs index 0c9a81f66..4ce54fd73 100644 --- a/src/Testcontainers/Clients/ITestcontainersClient.cs +++ b/src/Testcontainers/Clients/ITestcontainersClient.cs @@ -60,7 +60,13 @@ internal interface ITestcontainersClient /// Determines whether every log line contains a timestamp or not. /// Cancellation token. /// Task that gets the container logs. - Task<(string Stdout, string Stderr)> GetContainerLogsAsync(string id, DateTime since = default, DateTime until = default, bool timestampsEnabled = true, CancellationToken ct = default); + Task<(string Stdout, string Stderr)> GetContainerLogsAsync( + string id, + DateTime since = default, + DateTime until = default, + bool timestampsEnabled = true, + CancellationToken ct = default + ); /// /// Starts the container. @@ -138,7 +144,13 @@ internal interface ITestcontainersClient /// The POSIX file mode permission. /// Cancellation token. /// A task that completes when the directory has been copied. - Task CopyAsync(string id, DirectoryInfo source, string target, UnixFileModes fileMode, CancellationToken ct = default); + Task CopyAsync( + string id, + DirectoryInfo source, + string target, + UnixFileModes fileMode, + CancellationToken ct = default + ); /// /// Copies a test host file to the container. @@ -149,7 +161,13 @@ internal interface ITestcontainersClient /// The POSIX file mode permission. /// Cancellation token. /// A task that completes when the file has been copied. - Task CopyAsync(string id, FileInfo source, string target, UnixFileModes fileMode, CancellationToken ct = default); + Task CopyAsync( + string id, + FileInfo source, + string target, + UnixFileModes fileMode, + CancellationToken ct = default + ); /// /// Reads a file from the container. @@ -174,6 +192,9 @@ internal interface ITestcontainersClient /// The Dockerfile configuration. /// Cancellation token. /// Task that completes when the Docker image has been built. - Task BuildAsync(IImageFromDockerfileConfiguration configuration, CancellationToken ct = default); + Task BuildAsync( + IImageFromDockerfileConfiguration configuration, + CancellationToken ct = default + ); } } diff --git a/src/Testcontainers/Clients/TestcontainersClient.cs b/src/Testcontainers/Clients/TestcontainersClient.cs index ec504c53d..dce844c8a 100644 --- a/src/Testcontainers/Clients/TestcontainersClient.cs +++ b/src/Testcontainers/Clients/TestcontainersClient.cs @@ -30,9 +30,13 @@ internal sealed class TestcontainersClient : ITestcontainersClient public const string TestcontainersReuseHashLabel = TestcontainersLabel + ".reuse-hash"; - public static readonly string Version = typeof(TestcontainersClient).Assembly.GetCustomAttribute()!.InformationalVersion; + public static readonly string Version = typeof(TestcontainersClient) + .Assembly.GetCustomAttribute()! + .InformationalVersion; - private static readonly string OSRootDirectory = Path.GetPathRoot(Directory.GetCurrentDirectory()); + private static readonly string OSRootDirectory = Path.GetPathRoot( + Directory.GetCurrentDirectory() + ); private readonly DockerRegistryAuthenticationProvider _registryAuthenticationProvider; @@ -44,7 +48,11 @@ internal sealed class TestcontainersClient : ITestcontainersClient /// The session id. /// The Docker endpoint authentication configuration. /// The logger. - public TestcontainersClient(Guid sessionId, IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, ILogger logger) + public TestcontainersClient( + Guid sessionId, + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, + ILogger logger + ) : this( new DockerContainerOperations(sessionId, dockerEndpointAuthConfig, logger), new DockerImageOperations(sessionId, dockerEndpointAuthConfig, logger), @@ -52,9 +60,8 @@ public TestcontainersClient(Guid sessionId, IDockerEndpointAuthenticationConfigu new DockerVolumeOperations(sessionId, dockerEndpointAuthConfig, logger), new DockerSystemOperations(sessionId, dockerEndpointAuthConfig, logger), new DockerRegistryAuthenticationProvider(logger), - logger) - { - } + logger + ) { } private TestcontainersClient( IDockerContainerOperations containerOperations, @@ -63,7 +70,8 @@ private TestcontainersClient( IDockerVolumeOperations volumeOperations, IDockerSystemOperations systemOperations, DockerRegistryAuthenticationProvider registryAuthenticationProvider, - ILogger logger) + ILogger logger + ) { _registryAuthenticationProvider = registryAuthenticationProvider; _logger = logger; @@ -99,7 +107,13 @@ public Task GetContainerExitCodeAsync(string id, CancellationToken ct = de } /// - public Task<(string Stdout, string Stderr)> GetContainerLogsAsync(string id, DateTime since = default, DateTime until = default, bool timestampsEnabled = true, CancellationToken ct = default) + public Task<(string Stdout, string Stderr)> GetContainerLogsAsync( + string id, + DateTime since = default, + DateTime until = default, + bool timestampsEnabled = true, + CancellationToken ct = default + ) { #if NETSTANDARD2_0 var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); @@ -117,63 +131,59 @@ public Task GetContainerExitCodeAsync(string id, CancellationToken ct = de until = unixEpoch; } - return Container.GetLogsAsync(id, since.ToUniversalTime().Subtract(unixEpoch), until.ToUniversalTime().Subtract(unixEpoch), timestampsEnabled, ct); + return Container.GetLogsAsync( + id, + since.ToUniversalTime().Subtract(unixEpoch), + until.ToUniversalTime().Subtract(unixEpoch), + timestampsEnabled, + ct + ); } /// public async Task StartAsync(string id, CancellationToken ct = default) { - if (await Container.ExistsWithIdAsync(id, ct) - .ConfigureAwait(false)) + if (await Container.ExistsWithIdAsync(id, ct).ConfigureAwait(false)) { - await Container.StartAsync(id, ct) - .ConfigureAwait(false); + await Container.StartAsync(id, ct).ConfigureAwait(false); } } /// public async Task StopAsync(string id, CancellationToken ct = default) { - if (await Container.ExistsWithIdAsync(id, ct) - .ConfigureAwait(false)) + if (await Container.ExistsWithIdAsync(id, ct).ConfigureAwait(false)) { - await Container.StopAsync(id, ct) - .ConfigureAwait(false); + await Container.StopAsync(id, ct).ConfigureAwait(false); } } /// public async Task PauseAsync(string id, CancellationToken ct = default) { - if (await Container.ExistsWithIdAsync(id, ct) - .ConfigureAwait(false)) + if (await Container.ExistsWithIdAsync(id, ct).ConfigureAwait(false)) { - await Container.PauseAsync(id, ct) - .ConfigureAwait(false); + await Container.PauseAsync(id, ct).ConfigureAwait(false); } } /// public async Task UnpauseAsync(string id, CancellationToken ct = default) { - if (await Container.ExistsWithIdAsync(id, ct) - .ConfigureAwait(false)) + if (await Container.ExistsWithIdAsync(id, ct).ConfigureAwait(false)) { - await Container.UnpauseAsync(id, ct) - .ConfigureAwait(false); + await Container.UnpauseAsync(id, ct).ConfigureAwait(false); } } /// public async Task RemoveAsync(string id, CancellationToken ct = default) { - if (await Container.ExistsWithIdAsync(id, ct) - .ConfigureAwait(false)) + if (await Container.ExistsWithIdAsync(id, ct).ConfigureAwait(false)) { try { - await Container.RemoveAsync(id, ct) - .ConfigureAwait(false); + await Container.RemoveAsync(id, ct).ConfigureAwait(false); } catch (DockerApiException e) { @@ -188,23 +198,41 @@ await Container.RemoveAsync(id, ct) } /// - public Task AttachAsync(string id, IOutputConsumer outputConsumer, CancellationToken ct = default) + public Task AttachAsync( + string id, + IOutputConsumer outputConsumer, + CancellationToken ct = default + ) { return Container.AttachAsync(id, outputConsumer, ct); } /// - public Task ExecAsync(string id, IList command, CancellationToken ct = default) + public Task ExecAsync( + string id, + IList command, + CancellationToken ct = default + ) { return Container.ExecAsync(id, command, ct); } /// - public async Task CopyAsync(string id, IResourceMapping resourceMapping, CancellationToken ct = default) + public async Task CopyAsync( + string id, + IResourceMapping resourceMapping, + CancellationToken ct = default + ) { if (Directory.Exists(resourceMapping.Source)) { - await CopyAsync(id, new DirectoryInfo(resourceMapping.Source), resourceMapping.Target, resourceMapping.FileMode, ct) + await CopyAsync( + id, + new DirectoryInfo(resourceMapping.Source), + resourceMapping.Target, + resourceMapping.FileMode, + ct + ) .ConfigureAwait(false); return; @@ -212,7 +240,13 @@ public async Task CopyAsync(string id, IResourceMapping resourceMapping, Cancell if (File.Exists(resourceMapping.Source)) { - await CopyAsync(id, new FileInfo(resourceMapping.Source), resourceMapping.Target, resourceMapping.FileMode, ct) + await CopyAsync( + id, + new FileInfo(resourceMapping.Source), + resourceMapping.Target, + resourceMapping.FileMode, + ct + ) .ConfigureAwait(false); return; @@ -220,51 +254,67 @@ public async Task CopyAsync(string id, IResourceMapping resourceMapping, Cancell using (var tarOutputMemStream = new TarOutputMemoryStream(_logger)) { - await tarOutputMemStream.AddAsync(resourceMapping, ct) - .ConfigureAwait(false); + await tarOutputMemStream.AddAsync(resourceMapping, ct).ConfigureAwait(false); tarOutputMemStream.Close(); tarOutputMemStream.Seek(0, SeekOrigin.Begin); - await Container.ExtractArchiveToContainerAsync(id, "/", tarOutputMemStream, ct) + await Container + .ExtractArchiveToContainerAsync(id, "/", tarOutputMemStream, ct) .ConfigureAwait(false); } } /// - public async Task CopyAsync(string id, DirectoryInfo source, string target, UnixFileModes fileMode, CancellationToken ct = default) + public async Task CopyAsync( + string id, + DirectoryInfo source, + string target, + UnixFileModes fileMode, + CancellationToken ct = default + ) { using (var tarOutputMemStream = new TarOutputMemoryStream(target, _logger)) { - await tarOutputMemStream.AddAsync(source, true, fileMode, ct) - .ConfigureAwait(false); + await tarOutputMemStream.AddAsync(source, true, fileMode, ct).ConfigureAwait(false); tarOutputMemStream.Close(); tarOutputMemStream.Seek(0, SeekOrigin.Begin); - await Container.ExtractArchiveToContainerAsync(id, "/", tarOutputMemStream, ct) + await Container + .ExtractArchiveToContainerAsync(id, "/", tarOutputMemStream, ct) .ConfigureAwait(false); } } /// - public async Task CopyAsync(string id, FileInfo source, string target, UnixFileModes fileMode, CancellationToken ct = default) + public async Task CopyAsync( + string id, + FileInfo source, + string target, + UnixFileModes fileMode, + CancellationToken ct = default + ) { using (var tarOutputMemStream = new TarOutputMemoryStream(target, _logger)) { - await tarOutputMemStream.AddAsync(source, fileMode, ct) - .ConfigureAwait(false); + await tarOutputMemStream.AddAsync(source, fileMode, ct).ConfigureAwait(false); tarOutputMemStream.Close(); tarOutputMemStream.Seek(0, SeekOrigin.Begin); - await Container.ExtractArchiveToContainerAsync(id, "/", tarOutputMemStream, ct) + await Container + .ExtractArchiveToContainerAsync(id, "/", tarOutputMemStream, ct) .ConfigureAwait(false); } } /// - public async Task ReadFileAsync(string id, string filePath, CancellationToken ct = default) + public async Task ReadFileAsync( + string id, + string filePath, + CancellationToken ct = default + ) { Stream tarStream; @@ -272,7 +322,8 @@ public async Task ReadFileAsync(string id, string filePath, Cancellation try { - tarStream = await Container.GetArchiveFromContainerAsync(id, containerPath, ct) + tarStream = await Container + .GetArchiveFromContainerAsync(id, containerPath, ct) .ConfigureAwait(false); } catch (DockerContainerNotFoundException e) @@ -284,8 +335,7 @@ public async Task ReadFileAsync(string id, string filePath, Cancellation { tarInputStream.IsStreamOwner = true; - var entry = await tarInputStream.GetNextEntryAsync(ct) - .ConfigureAwait(false); + var entry = await tarInputStream.GetNextEntryAsync(ct).ConfigureAwait(false); if (entry.IsDirectory) { @@ -295,11 +345,11 @@ public async Task ReadFileAsync(string id, string filePath, Cancellation var readBytes = new byte[entry.Size]; #if NETSTANDARD2_0 - _ = await tarInputStream.ReadAsync(readBytes, 0, readBytes.Length, ct) + _ = await tarInputStream + .ReadAsync(readBytes, 0, readBytes.Length, ct) .ConfigureAwait(false); #else - _ = await tarInputStream.ReadAsync(readBytes, ct) - .ConfigureAwait(false); + _ = await tarInputStream.ReadAsync(readBytes, ct).ConfigureAwait(false); #endif return readBytes; @@ -307,23 +357,35 @@ public async Task ReadFileAsync(string id, string filePath, Cancellation } /// - public async Task RunAsync(IContainerConfiguration configuration, CancellationToken ct = default) + public async Task RunAsync( + IContainerConfiguration configuration, + CancellationToken ct = default + ) { ImageInspectResponse cachedImage; - if (TestcontainersSettings.ResourceReaperEnabled && ResourceReaper.DefaultSessionId.Equals(configuration.SessionId)) + if ( + TestcontainersSettings.ResourceReaperEnabled + && ResourceReaper.DefaultSessionId.Equals(configuration.SessionId) + ) { - var isWindowsEngineEnabled = await System.GetIsWindowsEngineEnabled(ct) + var isWindowsEngineEnabled = await System + .GetIsWindowsEngineEnabled(ct) .ConfigureAwait(false); - _ = await ResourceReaper.GetAndStartDefaultAsync(configuration.DockerEndpointAuthConfig, configuration.Logger, isWindowsEngineEnabled, ct) + _ = await ResourceReaper + .GetAndStartDefaultAsync( + configuration.DockerEndpointAuthConfig, + configuration.Logger, + isWindowsEngineEnabled, + ct + ) .ConfigureAwait(false); } try { - cachedImage = await Image.ByIdAsync(configuration.Image.FullName, ct) - .ConfigureAwait(false); + cachedImage = await Image.ByIdAsync(configuration.Image.FullName, ct).ConfigureAwait(false); } catch (DockerImageNotFoundException) { @@ -332,22 +394,27 @@ public async Task RunAsync(IContainerConfiguration configuration, Cancel if (configuration.ImagePullPolicy(cachedImage)) { - await PullImageAsync(configuration.Image, ct) - .ConfigureAwait(false); + await PullImageAsync(configuration.Image, ct).ConfigureAwait(false); } - var id = await Container.RunAsync(configuration, ct) - .ConfigureAwait(false); + var id = await Container.RunAsync(configuration, ct).ConfigureAwait(false); - if (configuration.Networks.Any() && PortForwardingContainer.Instance != null && TestcontainersStates.Running.Equals(PortForwardingContainer.Instance.State)) + if ( + configuration.Networks.Any() + && PortForwardingContainer.Instance != null + && TestcontainersStates.Running.Equals(PortForwardingContainer.Instance.State) + ) { - await Network.ConnectAsync("bridge", id, ct) - .ConfigureAwait(false); + await Network.ConnectAsync("bridge", id, ct).ConfigureAwait(false); } if (configuration.ResourceMappings.Any()) { - await Task.WhenAll(configuration.ResourceMappings.Select(resourceMapping => CopyAsync(id, resourceMapping, ct))) + await Task.WhenAll( + configuration.ResourceMappings.Select(resourceMapping => + CopyAsync(id, resourceMapping, ct) + ) + ) .ConfigureAwait(false); } @@ -355,14 +422,16 @@ await Task.WhenAll(configuration.ResourceMappings.Select(resourceMapping => Copy } /// - public async Task BuildAsync(IImageFromDockerfileConfiguration configuration, CancellationToken ct = default) + public async Task BuildAsync( + IImageFromDockerfileConfiguration configuration, + CancellationToken ct = default + ) { ImageInspectResponse cachedImage; try { - cachedImage = await Image.ByIdAsync(configuration.Image.FullName, ct) - .ConfigureAwait(false); + cachedImage = await Image.ByIdAsync(configuration.Image.FullName, ct).ConfigureAwait(false); } catch (DockerImageNotFoundException) { @@ -371,24 +440,34 @@ public async Task BuildAsync(IImageFromDockerfileConfiguration configura if (configuration.ImageBuildPolicy(cachedImage)) { - var dockerfileArchive = new DockerfileArchive(configuration.DockerfileDirectory, configuration.Dockerfile, configuration.Image, _logger); + var dockerfileArchive = new DockerfileArchive( + configuration.DockerfileDirectory, + configuration.Dockerfile, + configuration.Image, + _logger + ); var baseImages = dockerfileArchive.GetBaseImages().ToArray(); - var filters = baseImages.Aggregate(new FilterByProperty(), (dictionary, baseImage) => dictionary.Add("reference", baseImage.FullName)); + var filters = baseImages.Aggregate( + new FilterByProperty(), + (dictionary, baseImage) => dictionary.Add("reference", baseImage.FullName) + ); - var cachedImages = await Image.GetAllAsync(filters, ct) - .ConfigureAwait(false); + var cachedImages = await Image.GetAllAsync(filters, ct).ConfigureAwait(false); - var repositoryTags = new HashSet(cachedImages.SelectMany(image => image.RepoTags ?? Array.Empty())); + var repositoryTags = new HashSet( + cachedImages.SelectMany(image => image.RepoTags ?? Array.Empty()) + ); - var uncachedImages = baseImages.Where(baseImage => !repositoryTags.Contains(baseImage.FullName)); + var uncachedImages = baseImages.Where(baseImage => + !repositoryTags.Contains(baseImage.FullName) + ); await Task.WhenAll(uncachedImages.Select(image => PullImageAsync(image, ct))) .ConfigureAwait(false); - _ = await Image.BuildAsync(configuration, dockerfileArchive, ct) - .ConfigureAwait(false); + _ = await Image.BuildAsync(configuration, dockerfileArchive, ct).ConfigureAwait(false); } return configuration.Image.FullName; @@ -411,16 +490,14 @@ private async Task PullImageAsync(IImage image, CancellationToken ct = default) return; } - var info = await System.GetInfoAsync(ct) - .ConfigureAwait(false); + var info = await System.GetInfoAsync(ct).ConfigureAwait(false); dockerRegistryServerAddress = info.IndexServerAddress; } var authConfig = _registryAuthenticationProvider.GetAuthConfig(dockerRegistryServerAddress); - await Image.CreateAsync(image, authConfig, ct) - .ConfigureAwait(false); + await Image.CreateAsync(image, authConfig, ct).ConfigureAwait(false); } } } diff --git a/src/Testcontainers/Configurations/AuthConfigs/DockerEndpointAuthenticationConfiguration.cs b/src/Testcontainers/Configurations/AuthConfigs/DockerEndpointAuthenticationConfiguration.cs index 94a0103fa..11b733391 100644 --- a/src/Testcontainers/Configurations/AuthConfigs/DockerEndpointAuthenticationConfiguration.cs +++ b/src/Testcontainers/Configurations/AuthConfigs/DockerEndpointAuthenticationConfiguration.cs @@ -8,7 +8,8 @@ namespace DotNet.Testcontainers.Configurations /// [PublicAPI] - public readonly struct DockerEndpointAuthenticationConfiguration : IDockerEndpointAuthenticationConfiguration + public readonly struct DockerEndpointAuthenticationConfiguration + : IDockerEndpointAuthenticationConfiguration { // Since the static `TestcontainersSettings` class holds the detected container // runtime information from the auto-discovery mechanism, we can't add a static @@ -17,7 +18,10 @@ namespace DotNet.Testcontainers.Configurations // class or stop exposing the `TestcontainersSettings` properties publicly. // Instead, we could rely only on custom configurations via environment variables // or the properties file. - private static readonly TimeSpan NamedPipeConnectionTimeout = EnvironmentConfiguration.Instance.GetNamedPipeConnectionTimeout() ?? PropertiesFileConfiguration.Instance.GetNamedPipeConnectionTimeout() ?? TimeSpan.FromSeconds(1); + private static readonly TimeSpan NamedPipeConnectionTimeout = + EnvironmentConfiguration.Instance.GetNamedPipeConnectionTimeout() + ?? PropertiesFileConfiguration.Instance.GetNamedPipeConnectionTimeout() + ?? TimeSpan.FromSeconds(1); /// /// Initializes a new instance of the struct. @@ -43,7 +47,12 @@ public DockerClientConfiguration GetDockerClientConfiguration(Guid sessionId = d defaultHttpRequestHeaders.Add("User-Agent", "tc-dotnet/" + TestcontainersClient.Version); defaultHttpRequestHeaders.Add("x-tc-sid", sessionId.ToString("D")); - return new DockerClientConfiguration(Endpoint, Credentials, namedPipeConnectTimeout: NamedPipeConnectionTimeout, defaultHttpRequestHeaders: defaultHttpRequestHeaders); + return new DockerClientConfiguration( + Endpoint, + Credentials, + namedPipeConnectTimeout: NamedPipeConnectionTimeout, + defaultHttpRequestHeaders: defaultHttpRequestHeaders + ); } } } diff --git a/src/Testcontainers/Configurations/AuthConfigs/DockerRegistryAuthenticationConfiguration.cs b/src/Testcontainers/Configurations/AuthConfigs/DockerRegistryAuthenticationConfiguration.cs index 2fbc7e4f6..901f3c418 100644 --- a/src/Testcontainers/Configurations/AuthConfigs/DockerRegistryAuthenticationConfiguration.cs +++ b/src/Testcontainers/Configurations/AuthConfigs/DockerRegistryAuthenticationConfiguration.cs @@ -4,7 +4,8 @@ namespace DotNet.Testcontainers.Configurations using System.Text.Json; /// - internal readonly struct DockerRegistryAuthenticationConfiguration : IDockerRegistryAuthenticationConfiguration + internal readonly struct DockerRegistryAuthenticationConfiguration + : IDockerRegistryAuthenticationConfiguration { /// /// Initializes a new instance of the struct. @@ -17,7 +18,8 @@ public DockerRegistryAuthenticationConfiguration( string registryEndpoint = null, string username = null, string password = null, - string identityToken = null) + string identityToken = null + ) { RegistryEndpoint = registryEndpoint; Username = username; @@ -32,11 +34,16 @@ public DockerRegistryAuthenticationConfiguration( /// The CredHelpers or CredsStore JSON response. public DockerRegistryAuthenticationConfiguration( string registryEndpoint, - JsonElement credential) + JsonElement credential + ) { - var username = credential.TryGetProperty(nameof(Username), out var usernameProperty) ? usernameProperty.GetString() : null; + var username = credential.TryGetProperty(nameof(Username), out var usernameProperty) + ? usernameProperty.GetString() + : null; - var password = credential.TryGetProperty("Secret", out var passwordProperty) ? passwordProperty.GetString() : null; + var password = credential.TryGetProperty("Secret", out var passwordProperty) + ? passwordProperty.GetString() + : null; if ("".Equals(username, StringComparison.OrdinalIgnoreCase)) { diff --git a/src/Testcontainers/Configurations/Commons/AppendDictionary`2.cs b/src/Testcontainers/Configurations/Commons/AppendDictionary`2.cs index f20f1cb69..ce1c21188 100644 --- a/src/Testcontainers/Configurations/Commons/AppendDictionary`2.cs +++ b/src/Testcontainers/Configurations/Commons/AppendDictionary`2.cs @@ -1,8 +1,8 @@ namespace DotNet.Testcontainers.Configurations { using System.Collections.Generic; - using JetBrains.Annotations; using DotNet.Testcontainers.Builders; + using JetBrains.Annotations; /// /// Represents a composable dictionary that combines its elements by appending @@ -18,12 +18,12 @@ public sealed class AppendDictionary : ComposableDictionary /// The dictionary whose elements are copied to the new dictionary. public AppendDictionary(IReadOnlyDictionary dictionary) - : base(dictionary) - { - } + : base(dictionary) { } /// - public override ComposableDictionary Compose(IReadOnlyDictionary other) + public override ComposableDictionary Compose( + IReadOnlyDictionary other + ) { return new AppendDictionary(BuildConfiguration.Combine(other, this)); } diff --git a/src/Testcontainers/Configurations/Commons/AppendEnumerable`1.cs b/src/Testcontainers/Configurations/Commons/AppendEnumerable`1.cs index 49c94c189..858f1e3d1 100644 --- a/src/Testcontainers/Configurations/Commons/AppendEnumerable`1.cs +++ b/src/Testcontainers/Configurations/Commons/AppendEnumerable`1.cs @@ -1,8 +1,8 @@ namespace DotNet.Testcontainers.Configurations { using System.Collections.Generic; - using JetBrains.Annotations; using DotNet.Testcontainers.Builders; + using JetBrains.Annotations; /// /// Represents a composable collection that combines its elements by appending @@ -17,9 +17,7 @@ public sealed class AppendEnumerable : ComposableEnumerable /// /// The collection of items. If null, an empty collection is used. public AppendEnumerable(IEnumerable collection) - : base(collection) - { - } + : base(collection) { } /// public override ComposableEnumerable Compose(IEnumerable other) diff --git a/src/Testcontainers/Configurations/Commons/ComposableDictionary`2.cs b/src/Testcontainers/Configurations/Commons/ComposableDictionary`2.cs index f677e6097..aa298a1c2 100644 --- a/src/Testcontainers/Configurations/Commons/ComposableDictionary`2.cs +++ b/src/Testcontainers/Configurations/Commons/ComposableDictionary`2.cs @@ -24,7 +24,8 @@ public abstract class ComposableDictionary : IReadOnlyDictionaryThe dictionary of items. If null, an empty dictionary is used. protected ComposableDictionary(IReadOnlyDictionary dictionary) { - _dictionary = dictionary ?? new ReadOnlyDictionary(new Dictionary()); + _dictionary = + dictionary ?? new ReadOnlyDictionary(new Dictionary()); } /// @@ -37,7 +38,9 @@ protected ComposableDictionary(IReadOnlyDictionary dictionary) /// /// The incoming dictionary to compose with this dictionary. /// A new that contains the result of the composition. - public abstract ComposableDictionary Compose([NotNull] IReadOnlyDictionary other); + public abstract ComposableDictionary Compose( + [NotNull] IReadOnlyDictionary other + ); /// public IEnumerable Keys => _dictionary.Keys; diff --git a/src/Testcontainers/Configurations/Commons/JsonIgnoreRuntimeResourceLabels.cs b/src/Testcontainers/Configurations/Commons/JsonIgnoreRuntimeResourceLabels.cs index 14badf1c1..0c9652c4b 100644 --- a/src/Testcontainers/Configurations/Commons/JsonIgnoreRuntimeResourceLabels.cs +++ b/src/Testcontainers/Configurations/Commons/JsonIgnoreRuntimeResourceLabels.cs @@ -8,23 +8,39 @@ namespace DotNet.Testcontainers.Configurations using DotNet.Testcontainers.Clients; using DotNet.Testcontainers.Containers; - internal sealed class JsonIgnoreRuntimeResourceLabels : JsonConverter> + internal sealed class JsonIgnoreRuntimeResourceLabels + : JsonConverter> { - private static readonly ISet IgnoreLabels = new HashSet { ResourceReaper.ResourceReaperSessionLabel, TestcontainersClient.TestcontainersVersionLabel, TestcontainersClient.TestcontainersSessionIdLabel }; + private static readonly ISet IgnoreLabels = new HashSet + { + ResourceReaper.ResourceReaperSessionLabel, + TestcontainersClient.TestcontainersVersionLabel, + TestcontainersClient.TestcontainersSessionIdLabel, + }; public override bool CanConvert(Type typeToConvert) { return typeof(IEnumerable>).IsAssignableFrom(typeToConvert); } - public override IReadOnlyDictionary Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override IReadOnlyDictionary Read( + ref Utf8JsonReader reader, + Type typeToConvert, + JsonSerializerOptions options + ) { return JsonSerializer.Deserialize>(ref reader); } - public override void Write(Utf8JsonWriter writer, IReadOnlyDictionary value, JsonSerializerOptions options) + public override void Write( + Utf8JsonWriter writer, + IReadOnlyDictionary value, + JsonSerializerOptions options + ) { - var labels = value.Where(label => !IgnoreLabels.Contains(label.Key)).ToDictionary(label => label.Key, label => label.Value); + var labels = value + .Where(label => !IgnoreLabels.Contains(label.Key)) + .ToDictionary(label => label.Key, label => label.Value); writer.WriteStartObject(); diff --git a/src/Testcontainers/Configurations/Commons/OverwriteDictionary`2.cs b/src/Testcontainers/Configurations/Commons/OverwriteDictionary`2.cs index cd0631ebf..c4f952671 100644 --- a/src/Testcontainers/Configurations/Commons/OverwriteDictionary`2.cs +++ b/src/Testcontainers/Configurations/Commons/OverwriteDictionary`2.cs @@ -17,12 +17,12 @@ public sealed class OverwriteDictionary : ComposableDictionary /// The dictionary whose elements are copied to the new dictionary. public OverwriteDictionary(IReadOnlyDictionary dictionary) - : base(dictionary) - { - } + : base(dictionary) { } /// - public override ComposableDictionary Compose(IReadOnlyDictionary other) + public override ComposableDictionary Compose( + IReadOnlyDictionary other + ) { // Ignores all previous configurations. return this; diff --git a/src/Testcontainers/Configurations/Commons/OverwriteEnumerable`1.cs b/src/Testcontainers/Configurations/Commons/OverwriteEnumerable`1.cs index 7b7ed1b01..3ad2911ca 100644 --- a/src/Testcontainers/Configurations/Commons/OverwriteEnumerable`1.cs +++ b/src/Testcontainers/Configurations/Commons/OverwriteEnumerable`1.cs @@ -16,9 +16,7 @@ public sealed class OverwriteEnumerable : ComposableEnumerable /// /// The collection of items. If null, an empty collection is used. public OverwriteEnumerable(IEnumerable collection) - : base(collection) - { - } + : base(collection) { } /// public override ComposableEnumerable Compose(IEnumerable other) diff --git a/src/Testcontainers/Configurations/Commons/ResourceConfiguration.cs b/src/Testcontainers/Configurations/Commons/ResourceConfiguration.cs index 10ebbd52d..1d579aa51 100644 --- a/src/Testcontainers/Configurations/Commons/ResourceConfiguration.cs +++ b/src/Testcontainers/Configurations/Commons/ResourceConfiguration.cs @@ -12,7 +12,8 @@ namespace DotNet.Testcontainers.Configurations /// [PublicAPI] - public class ResourceConfiguration : IResourceConfiguration + public class ResourceConfiguration + : IResourceConfiguration { /// /// Initializes a new instance of the class. @@ -27,9 +28,18 @@ public ResourceConfiguration( IReadOnlyDictionary labels = null, IReadOnlyList> parameterModifiers = null, bool? reuse = null, - ILogger logger = null) + ILogger logger = null + ) { - SessionId = labels != null && labels.TryGetValue(ResourceReaper.ResourceReaperSessionLabel, out var resourceReaperSessionId) && Guid.TryParseExact(resourceReaperSessionId, "D", out var sessionId) ? sessionId : Guid.Empty; + SessionId = + labels != null + && labels.TryGetValue( + ResourceReaper.ResourceReaperSessionLabel, + out var resourceReaperSessionId + ) + && Guid.TryParseExact(resourceReaperSessionId, "D", out var sessionId) + ? sessionId + : Guid.Empty; DockerEndpointAuthConfig = dockerEndpointAuthenticationConfiguration; Labels = labels; ParameterModifiers = parameterModifiers; @@ -41,25 +51,34 @@ public ResourceConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - protected ResourceConfiguration(IResourceConfiguration resourceConfiguration) - : this(new ResourceConfiguration(), resourceConfiguration) - { - } + protected ResourceConfiguration( + IResourceConfiguration resourceConfiguration + ) + : this(new ResourceConfiguration(), resourceConfiguration) { } /// /// Initializes a new instance of the class. /// /// The old Docker resource configuration. /// The new Docker resource configuration. - protected ResourceConfiguration(IResourceConfiguration oldValue, IResourceConfiguration newValue) + protected ResourceConfiguration( + IResourceConfiguration oldValue, + IResourceConfiguration newValue + ) : this( - dockerEndpointAuthenticationConfiguration: BuildConfiguration.Combine(oldValue.DockerEndpointAuthConfig, newValue.DockerEndpointAuthConfig), + dockerEndpointAuthenticationConfiguration: BuildConfiguration.Combine( + oldValue.DockerEndpointAuthConfig, + newValue.DockerEndpointAuthConfig + ), labels: BuildConfiguration.Combine(oldValue.Labels, newValue.Labels), - parameterModifiers: BuildConfiguration.Combine(oldValue.ParameterModifiers, newValue.ParameterModifiers), - reuse: (oldValue.Reuse.HasValue && oldValue.Reuse.Value) || (newValue.Reuse.HasValue && newValue.Reuse.Value), - logger: BuildConfiguration.Combine(oldValue.Logger, newValue.Logger)) - { - } + parameterModifiers: BuildConfiguration.Combine( + oldValue.ParameterModifiers, + newValue.ParameterModifiers + ), + reuse: (oldValue.Reuse.HasValue && oldValue.Reuse.Value) + || (newValue.Reuse.HasValue && newValue.Reuse.Value), + logger: BuildConfiguration.Combine(oldValue.Logger, newValue.Logger) + ) { } /// [JsonIgnore] diff --git a/src/Testcontainers/Configurations/Containers/ContainerConfiguration.cs b/src/Testcontainers/Configurations/Containers/ContainerConfiguration.cs index 4a3c2b4aa..1238422c6 100644 --- a/src/Testcontainers/Configurations/Containers/ContainerConfiguration.cs +++ b/src/Testcontainers/Configurations/Containers/ContainerConfiguration.cs @@ -14,7 +14,9 @@ namespace DotNet.Testcontainers.Configurations /// [PublicAPI] - public class ContainerConfiguration : ResourceConfiguration, IContainerConfiguration + public class ContainerConfiguration + : ResourceConfiguration, + IContainerConfiguration { /// /// Initializes a new instance of the class. @@ -63,7 +65,8 @@ public ContainerConfiguration( IEnumerable waitStrategies = null, Func startupCallback = null, bool? autoRemove = null, - bool? privileged = null) + bool? privileged = null + ) { AutoRemove = autoRemove; Privileged = privileged; @@ -93,50 +96,73 @@ public ContainerConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public ContainerConfiguration(IResourceConfiguration resourceConfiguration) - : base(resourceConfiguration) - { - } + public ContainerConfiguration( + IResourceConfiguration resourceConfiguration + ) + : base(resourceConfiguration) { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. public ContainerConfiguration(IContainerConfiguration resourceConfiguration) - : this(new ContainerConfiguration(), resourceConfiguration) - { - } + : this(new ContainerConfiguration(), resourceConfiguration) { } /// /// Initializes a new instance of the class. /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public ContainerConfiguration(IContainerConfiguration oldValue, IContainerConfiguration newValue) + public ContainerConfiguration( + IContainerConfiguration oldValue, + IContainerConfiguration newValue + ) : base(oldValue, newValue) { Image = BuildConfiguration.Combine(oldValue.Image, newValue.Image); - ImagePullPolicy = BuildConfiguration.Combine(oldValue.ImagePullPolicy, newValue.ImagePullPolicy); + ImagePullPolicy = BuildConfiguration.Combine( + oldValue.ImagePullPolicy, + newValue.ImagePullPolicy + ); Name = BuildConfiguration.Combine(oldValue.Name, newValue.Name); Hostname = BuildConfiguration.Combine(oldValue.Hostname, newValue.Hostname); MacAddress = BuildConfiguration.Combine(oldValue.MacAddress, newValue.MacAddress); - WorkingDirectory = BuildConfiguration.Combine(oldValue.WorkingDirectory, newValue.WorkingDirectory); - Entrypoint = BuildConfiguration.Combine>(oldValue.Entrypoint, newValue.Entrypoint); + WorkingDirectory = BuildConfiguration.Combine( + oldValue.WorkingDirectory, + newValue.WorkingDirectory + ); + Entrypoint = BuildConfiguration.Combine>( + oldValue.Entrypoint, + newValue.Entrypoint + ); Command = BuildConfiguration.Combine(oldValue.Command, newValue.Command); Environments = BuildConfiguration.Combine(oldValue.Environments, newValue.Environments); ExposedPorts = BuildConfiguration.Combine(oldValue.ExposedPorts, newValue.ExposedPorts); PortBindings = BuildConfiguration.Combine(oldValue.PortBindings, newValue.PortBindings); - ResourceMappings = BuildConfiguration.Combine(oldValue.ResourceMappings, newValue.ResourceMappings); + ResourceMappings = BuildConfiguration.Combine( + oldValue.ResourceMappings, + newValue.ResourceMappings + ); Containers = BuildConfiguration.Combine(oldValue.Containers, newValue.Containers); Mounts = BuildConfiguration.Combine(oldValue.Mounts, newValue.Mounts); Networks = BuildConfiguration.Combine(oldValue.Networks, newValue.Networks); NetworkAliases = BuildConfiguration.Combine(oldValue.NetworkAliases, newValue.NetworkAliases); ExtraHosts = BuildConfiguration.Combine(oldValue.ExtraHosts, newValue.ExtraHosts); OutputConsumer = BuildConfiguration.Combine(oldValue.OutputConsumer, newValue.OutputConsumer); - WaitStrategies = BuildConfiguration.Combine>(oldValue.WaitStrategies, newValue.WaitStrategies); - StartupCallback = BuildConfiguration.Combine(oldValue.StartupCallback, newValue.StartupCallback); - AutoRemove = (oldValue.AutoRemove.HasValue && oldValue.AutoRemove.Value) || (newValue.AutoRemove.HasValue && newValue.AutoRemove.Value); - Privileged = (oldValue.Privileged.HasValue && oldValue.Privileged.Value) || (newValue.Privileged.HasValue && newValue.Privileged.Value); + WaitStrategies = BuildConfiguration.Combine>( + oldValue.WaitStrategies, + newValue.WaitStrategies + ); + StartupCallback = BuildConfiguration.Combine( + oldValue.StartupCallback, + newValue.StartupCallback + ); + AutoRemove = + (oldValue.AutoRemove.HasValue && oldValue.AutoRemove.Value) + || (newValue.AutoRemove.HasValue && newValue.AutoRemove.Value); + Privileged = + (oldValue.Privileged.HasValue && oldValue.Privileged.Value) + || (newValue.Privileged.HasValue && newValue.Privileged.Value); } /// diff --git a/src/Testcontainers/Configurations/CustomConfiguration.cs b/src/Testcontainers/Configurations/CustomConfiguration.cs index 81c79c003..6e0861699 100644 --- a/src/Testcontainers/Configurations/CustomConfiguration.cs +++ b/src/Testcontainers/Configurations/CustomConfiguration.cs @@ -22,7 +22,12 @@ protected virtual string GetDockerConfig(string propertyName) protected virtual Uri GetDockerHost(string propertyName) { - return _properties.TryGetValue(propertyName, out var propertyValue) && !string.IsNullOrEmpty(propertyValue) && Uri.TryCreate(propertyValue, UriKind.RelativeOrAbsolute, out var dockerHost) ? dockerHost : null; + return + _properties.TryGetValue(propertyName, out var propertyValue) + && !string.IsNullOrEmpty(propertyValue) + && Uri.TryCreate(propertyValue, UriKind.RelativeOrAbsolute, out var dockerHost) + ? dockerHost + : null; } protected virtual string GetDockerContext(string propertyName) @@ -138,19 +143,36 @@ private T GetPropertyValue(string propertyName) if (typeof(TimeSpan) == type) { - return (T)(object)(hasValue && TimeSpan.TryParse(propertyValue, CultureInfo.InvariantCulture, out var result) && result > TimeSpan.Zero ? result : null); + return (T) + (object)( + hasValue + && TimeSpan.TryParse(propertyValue, CultureInfo.InvariantCulture, out var result) + && result > TimeSpan.Zero + ? result + : null + ); } switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: { - return (T)(object)(hasValue && bool.TryParse(propertyValue, out var result) ? result : isNullable ? null : "1".Equals(propertyValue, StringComparison.Ordinal)); + return (T) + (object)( + hasValue && bool.TryParse(propertyValue, out var result) ? result + : isNullable ? null + : "1".Equals(propertyValue, StringComparison.Ordinal) + ); } case TypeCode.UInt16: { - return (T)(object)(hasValue && ushort.TryParse(propertyValue, out var result) ? result : isNullable ? null : 0); + return (T) + (object)( + hasValue && ushort.TryParse(propertyValue, out var result) ? result + : isNullable ? null + : 0 + ); } case TypeCode.String: diff --git a/src/Testcontainers/Configurations/EnvironmentConfiguration.cs b/src/Testcontainers/Configurations/EnvironmentConfiguration.cs index 7a2f9b9c3..7ed65f3ea 100644 --- a/src/Testcontainers/Configurations/EnvironmentConfiguration.cs +++ b/src/Testcontainers/Configurations/EnvironmentConfiguration.cs @@ -42,17 +42,17 @@ internal class EnvironmentConfiguration : CustomConfiguration, ICustomConfigurat private const string WaitStrategyTimeout = "TESTCONTAINERS_WAIT_STRATEGY_TIMEOUT"; - private const string NamedPipeConnectionTimeout = "TESTCONTAINERS_NAMED_PIPE_CONNECTION_TIMEOUT"; + private const string NamedPipeConnectionTimeout = + "TESTCONTAINERS_NAMED_PIPE_CONNECTION_TIMEOUT"; - static EnvironmentConfiguration() - { - } + static EnvironmentConfiguration() { } /// /// Initializes a new instance of the class. /// public EnvironmentConfiguration() - : base(new[] + : base( + new[] { DockerAuthConfig, DockerCertPath, @@ -71,16 +71,13 @@ public EnvironmentConfiguration() WaitStrategyInterval, WaitStrategyTimeout, NamedPipeConnectionTimeout, - } - .ToDictionary(key => key, Environment.GetEnvironmentVariable)) - { - } + }.ToDictionary(key => key, Environment.GetEnvironmentVariable) + ) { } /// /// Gets the instance. /// - public static ICustomConfiguration Instance { get; } - = new EnvironmentConfiguration(); + public static ICustomConfiguration Instance { get; } = new EnvironmentConfiguration(); /// public string GetDockerConfig() diff --git a/src/Testcontainers/Configurations/Images/ImageFromDockerfileConfiguration.cs b/src/Testcontainers/Configurations/Images/ImageFromDockerfileConfiguration.cs index a3c59509c..a6824f2a1 100644 --- a/src/Testcontainers/Configurations/Images/ImageFromDockerfileConfiguration.cs +++ b/src/Testcontainers/Configurations/Images/ImageFromDockerfileConfiguration.cs @@ -10,7 +10,9 @@ namespace DotNet.Testcontainers.Configurations /// [PublicAPI] - internal sealed class ImageFromDockerfileConfiguration : ResourceConfiguration, IImageFromDockerfileConfiguration + internal sealed class ImageFromDockerfileConfiguration + : ResourceConfiguration, + IImageFromDockerfileConfiguration { /// /// Initializes a new instance of the class. @@ -27,7 +29,8 @@ public ImageFromDockerfileConfiguration( IImage image = null, Func imageBuildPolicy = null, IReadOnlyDictionary buildArguments = null, - bool? deleteIfExists = null) + bool? deleteIfExists = null + ) { Dockerfile = dockerfile; DockerfileDirectory = dockerfileDirectory; @@ -41,34 +44,43 @@ public ImageFromDockerfileConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public ImageFromDockerfileConfiguration(IResourceConfiguration resourceConfiguration) - : base(resourceConfiguration) - { - } + public ImageFromDockerfileConfiguration( + IResourceConfiguration resourceConfiguration + ) + : base(resourceConfiguration) { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. public ImageFromDockerfileConfiguration(IImageFromDockerfileConfiguration resourceConfiguration) - : this(new ImageFromDockerfileConfiguration(), resourceConfiguration) - { - } + : this(new ImageFromDockerfileConfiguration(), resourceConfiguration) { } /// /// Initializes a new instance of the class. /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public ImageFromDockerfileConfiguration(IImageFromDockerfileConfiguration oldValue, IImageFromDockerfileConfiguration newValue) + public ImageFromDockerfileConfiguration( + IImageFromDockerfileConfiguration oldValue, + IImageFromDockerfileConfiguration newValue + ) : base(oldValue, newValue) { Dockerfile = BuildConfiguration.Combine(oldValue.Dockerfile, newValue.Dockerfile); - DockerfileDirectory = BuildConfiguration.Combine(oldValue.DockerfileDirectory, newValue.DockerfileDirectory); + DockerfileDirectory = BuildConfiguration.Combine( + oldValue.DockerfileDirectory, + newValue.DockerfileDirectory + ); Image = BuildConfiguration.Combine(oldValue.Image, newValue.Image); - ImageBuildPolicy = BuildConfiguration.Combine(oldValue.ImageBuildPolicy, newValue.ImageBuildPolicy); + ImageBuildPolicy = BuildConfiguration.Combine( + oldValue.ImageBuildPolicy, + newValue.ImageBuildPolicy + ); BuildArguments = BuildConfiguration.Combine(oldValue.BuildArguments, newValue.BuildArguments); - DeleteIfExists = (oldValue.DeleteIfExists.HasValue && oldValue.DeleteIfExists.Value) || (newValue.DeleteIfExists.HasValue && newValue.DeleteIfExists.Value); + DeleteIfExists = + (oldValue.DeleteIfExists.HasValue && oldValue.DeleteIfExists.Value) + || (newValue.DeleteIfExists.HasValue && newValue.DeleteIfExists.Value); } /// diff --git a/src/Testcontainers/Configurations/Networks/NetworkConfiguration.cs b/src/Testcontainers/Configurations/Networks/NetworkConfiguration.cs index 1c20822d3..a84559b2d 100644 --- a/src/Testcontainers/Configurations/Networks/NetworkConfiguration.cs +++ b/src/Testcontainers/Configurations/Networks/NetworkConfiguration.cs @@ -8,7 +8,9 @@ namespace DotNet.Testcontainers.Configurations /// [PublicAPI] - internal sealed class NetworkConfiguration : ResourceConfiguration, INetworkConfiguration + internal sealed class NetworkConfiguration + : ResourceConfiguration, + INetworkConfiguration { /// /// Initializes a new instance of the class. @@ -19,7 +21,8 @@ internal sealed class NetworkConfiguration : ResourceConfiguration options = null) + IReadOnlyDictionary options = null + ) { Name = name; Driver = driver; @@ -30,19 +33,17 @@ public NetworkConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public NetworkConfiguration(IResourceConfiguration resourceConfiguration) - : base(resourceConfiguration) - { - } + public NetworkConfiguration( + IResourceConfiguration resourceConfiguration + ) + : base(resourceConfiguration) { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. public NetworkConfiguration(INetworkConfiguration resourceConfiguration) - : this(new NetworkConfiguration(), resourceConfiguration) - { - } + : this(new NetworkConfiguration(), resourceConfiguration) { } /// /// Initializes a new instance of the class. diff --git a/src/Testcontainers/Configurations/OutputConsumers/RedirectStdoutAndStderrToNull.cs b/src/Testcontainers/Configurations/OutputConsumers/RedirectStdoutAndStderrToNull.cs index c27bf7738..adb1ccc68 100644 --- a/src/Testcontainers/Configurations/OutputConsumers/RedirectStdoutAndStderrToNull.cs +++ b/src/Testcontainers/Configurations/OutputConsumers/RedirectStdoutAndStderrToNull.cs @@ -18,8 +18,7 @@ private RedirectStdoutAndStderrToNull() /// /// Gets the instance. /// - public static IOutputConsumer Instance { get; } - = new RedirectStdoutAndStderrToNull(); + public static IOutputConsumer Instance { get; } = new RedirectStdoutAndStderrToNull(); /// public bool Enabled { get; } diff --git a/src/Testcontainers/Configurations/OutputConsumers/RedirectStdoutAndStderrToStream.cs b/src/Testcontainers/Configurations/OutputConsumers/RedirectStdoutAndStderrToStream.cs index 9cc7edbdf..6546edfa7 100644 --- a/src/Testcontainers/Configurations/OutputConsumers/RedirectStdoutAndStderrToStream.cs +++ b/src/Testcontainers/Configurations/OutputConsumers/RedirectStdoutAndStderrToStream.cs @@ -14,9 +14,7 @@ internal sealed class RedirectStdoutAndStderrToStream : IOutputConsumer /// Initializes a new instance of the class. /// public RedirectStdoutAndStderrToStream() - : this(Console.OpenStandardOutput(), Console.OpenStandardError()) - { - } + : this(Console.OpenStandardOutput(), Console.OpenStandardError()) { } /// /// Initializes a new instance of the class. @@ -36,12 +34,10 @@ public RedirectStdoutAndStderrToStream(Stream stdout, Stream stderr) public bool Enabled { get; } /// - public Stream Stdout - => _stdout.BaseStream; + public Stream Stdout => _stdout.BaseStream; /// - public Stream Stderr - => _stderr.BaseStream; + public Stream Stderr => _stderr.BaseStream; /// public void Dispose() diff --git a/src/Testcontainers/Configurations/PropertiesFileConfiguration.cs b/src/Testcontainers/Configurations/PropertiesFileConfiguration.cs index 7ae19fe46..13813d8d2 100644 --- a/src/Testcontainers/Configurations/PropertiesFileConfiguration.cs +++ b/src/Testcontainers/Configurations/PropertiesFileConfiguration.cs @@ -11,50 +11,52 @@ namespace DotNet.Testcontainers.Configurations /// internal class PropertiesFileConfiguration : CustomConfiguration, ICustomConfiguration { - static PropertiesFileConfiguration() - { - } + static PropertiesFileConfiguration() { } /// /// Initializes a new instance of the class. /// public PropertiesFileConfiguration() - : this(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".testcontainers.properties")) - { - } + : this( + Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), + ".testcontainers.properties" + ) + ) { } /// /// Initializes a new instance of the class. /// /// The Java properties file path. public PropertiesFileConfiguration(string propertiesFilePath) - : this(File.Exists(propertiesFilePath) - ? File.ReadAllLines(propertiesFilePath) - : Array.Empty()) - { - } + : this( + File.Exists(propertiesFilePath) + ? File.ReadAllLines(propertiesFilePath) + : Array.Empty() + ) { } /// /// Initializes a new instance of the class. /// /// A list of Java properties file lines. public PropertiesFileConfiguration(params string[] lines) - : base(lines - .Select(line => line.Trim()) - .Where(line => !string.IsNullOrEmpty(line)) - .Where(line => !line.StartsWith("#", StringComparison.Ordinal)) - .Where(line => !line.StartsWith("!", StringComparison.Ordinal)) - .Select(line => line.Split(new[] { '=', ':', ' ' }, 2, StringSplitOptions.RemoveEmptyEntries)) - .Where(property => 2.Equals(property.Length)) - .ToDictionary(property => property[0], property => property[1])) - { - } + : base( + lines + .Select(line => line.Trim()) + .Where(line => !string.IsNullOrEmpty(line)) + .Where(line => !line.StartsWith("#", StringComparison.Ordinal)) + .Where(line => !line.StartsWith("!", StringComparison.Ordinal)) + .Select(line => + line.Split(new[] { '=', ':', ' ' }, 2, StringSplitOptions.RemoveEmptyEntries) + ) + .Where(property => 2.Equals(property.Length)) + .ToDictionary(property => property[0], property => property[1]) + ) { } /// /// Gets the instance. /// - public static ICustomConfiguration Instance { get; } - = new PropertiesFileConfiguration(); + public static ICustomConfiguration Instance { get; } = new PropertiesFileConfiguration(); /// public string GetDockerConfig() diff --git a/src/Testcontainers/Configurations/TestcontainersSettings.cs b/src/Testcontainers/Configurations/TestcontainersSettings.cs index cf72ac995..de531beb3 100644 --- a/src/Testcontainers/Configurations/TestcontainersSettings.cs +++ b/src/Testcontainers/Configurations/TestcontainersSettings.cs @@ -17,8 +17,8 @@ namespace DotNet.Testcontainers.Configurations [PublicAPI] public static class TestcontainersSettings { - internal static readonly List DockerEndpointAuthProviders - = new List + internal static readonly List DockerEndpointAuthProviders = + new List { new TestcontainersEndpointAuthenticationProvider(), new MTlsEndpointAuthenticationProvider(), @@ -31,51 +31,59 @@ internal static readonly List DockerEndpoi }; [CanBeNull] - private static readonly IDockerEndpointAuthenticationProvider DockerEndpointAuthProvider - = DockerEndpointAuthProviders.FirstOrDefault(authProvider => authProvider.IsApplicable() && authProvider.IsAvailable()); + private static readonly IDockerEndpointAuthenticationProvider DockerEndpointAuthProvider = + DockerEndpointAuthProviders.FirstOrDefault(authProvider => + authProvider.IsApplicable() && authProvider.IsAvailable() + ); [CanBeNull] - private static readonly IDockerEndpointAuthenticationConfiguration DockerEndpointAuthConfig - = DockerEndpointAuthProvider?.GetAuthConfig(); + private static readonly IDockerEndpointAuthenticationConfiguration DockerEndpointAuthConfig = + DockerEndpointAuthProvider?.GetAuthConfig(); - static TestcontainersSettings() - { - } + static TestcontainersSettings() { } /// /// Gets or sets the Docker host override value. /// [CanBeNull] - public static string DockerHostOverride { get; set; } - = DockerEndpointAuthProvider is ICustomConfiguration config - ? config.GetDockerHostOverride() : EnvironmentConfiguration.Instance.GetDockerHostOverride() ?? PropertiesFileConfiguration.Instance.GetDockerHostOverride(); + public static string DockerHostOverride { get; set; } = + DockerEndpointAuthProvider is ICustomConfiguration config + ? config.GetDockerHostOverride() + : EnvironmentConfiguration.Instance.GetDockerHostOverride() + ?? PropertiesFileConfiguration.Instance.GetDockerHostOverride(); /// /// Gets or sets the Docker socket override value. /// [CanBeNull] - public static string DockerSocketOverride { get; set; } - = DockerEndpointAuthProvider is ICustomConfiguration config - ? config.GetDockerSocketOverride() : EnvironmentConfiguration.Instance.GetDockerSocketOverride() ?? PropertiesFileConfiguration.Instance.GetDockerSocketOverride(); + public static string DockerSocketOverride { get; set; } = + DockerEndpointAuthProvider is ICustomConfiguration config + ? config.GetDockerSocketOverride() + : EnvironmentConfiguration.Instance.GetDockerSocketOverride() + ?? PropertiesFileConfiguration.Instance.GetDockerSocketOverride(); /// /// Gets or sets a value indicating whether the is enabled or not. /// - public static bool ResourceReaperEnabled { get; set; } - = !EnvironmentConfiguration.Instance.GetRyukDisabled() && !PropertiesFileConfiguration.Instance.GetRyukDisabled(); + public static bool ResourceReaperEnabled { get; set; } = + !EnvironmentConfiguration.Instance.GetRyukDisabled() + && !PropertiesFileConfiguration.Instance.GetRyukDisabled(); /// /// Gets or sets a value indicating whether the privileged mode is enabled or not. /// - public static bool ResourceReaperPrivilegedModeEnabled { get; set; } - = EnvironmentConfiguration.Instance.GetRyukContainerPrivileged() ?? PropertiesFileConfiguration.Instance.GetRyukContainerPrivileged() ?? true; + public static bool ResourceReaperPrivilegedModeEnabled { get; set; } = + EnvironmentConfiguration.Instance.GetRyukContainerPrivileged() + ?? PropertiesFileConfiguration.Instance.GetRyukContainerPrivileged() + ?? true; /// /// Gets or sets the image. /// [CanBeNull] - public static IImage ResourceReaperImage { get; set; } - = EnvironmentConfiguration.Instance.GetRyukContainerImage() ?? PropertiesFileConfiguration.Instance.GetRyukContainerImage(); + public static IImage ResourceReaperImage { get; set; } = + EnvironmentConfiguration.Instance.GetRyukContainerImage() + ?? PropertiesFileConfiguration.Instance.GetRyukContainerImage(); /// /// Gets or sets the public host port. @@ -87,9 +95,13 @@ static TestcontainersSettings() /// - https://github.com/docker/for-win/issues/11584. /// [NotNull] - [Obsolete("The Resource Reaper will use Docker's assigned random host port. This property is no longer supported. For DinD configurations see: https://dotnet.testcontainers.org/examples/dind/.")] - public static Func ResourceReaperPublicHostPort { get; set; } - = _ => 0; + [Obsolete( + "The Resource Reaper will use Docker's assigned random host port. This property is no longer supported. For DinD configurations see: https://dotnet.testcontainers.org/examples/dind/." + )] + public static Func< + IDockerEndpointAuthenticationConfiguration, + ushort + > ResourceReaperPublicHostPort { get; set; } = _ => 0; /// /// Gets or sets a prefix that applies to every image that is pulled from Docker Hub. @@ -98,8 +110,9 @@ static TestcontainersSettings() /// Please verify that all required images exist in your registry. /// [CanBeNull] - public static string HubImageNamePrefix { get; set; } - = EnvironmentConfiguration.Instance.GetHubImageNamePrefix() ?? PropertiesFileConfiguration.Instance.GetHubImageNamePrefix(); + public static string HubImageNamePrefix { get; set; } = + EnvironmentConfiguration.Instance.GetHubImageNamePrefix() + ?? PropertiesFileConfiguration.Instance.GetHubImageNamePrefix(); /// /// Gets or sets the wait strategy retry count. @@ -110,8 +123,9 @@ static TestcontainersSettings() /// https://dotnet.testcontainers.org/api/wait_strategies/. /// [CanBeNull] - public static ushort? WaitStrategyRetries { get; set; } - = EnvironmentConfiguration.Instance.GetWaitStrategyRetries() ?? PropertiesFileConfiguration.Instance.GetWaitStrategyRetries(); + public static ushort? WaitStrategyRetries { get; set; } = + EnvironmentConfiguration.Instance.GetWaitStrategyRetries() + ?? PropertiesFileConfiguration.Instance.GetWaitStrategyRetries(); /// /// Gets or sets the wait strategy interval. @@ -122,8 +136,9 @@ static TestcontainersSettings() /// https://dotnet.testcontainers.org/api/wait_strategies/. /// [CanBeNull] - public static TimeSpan? WaitStrategyInterval { get; set; } - = EnvironmentConfiguration.Instance.GetWaitStrategyInterval() ?? PropertiesFileConfiguration.Instance.GetWaitStrategyInterval(); + public static TimeSpan? WaitStrategyInterval { get; set; } = + EnvironmentConfiguration.Instance.GetWaitStrategyInterval() + ?? PropertiesFileConfiguration.Instance.GetWaitStrategyInterval(); /// /// Gets or sets the wait strategy timeout. @@ -134,28 +149,32 @@ static TestcontainersSettings() /// https://dotnet.testcontainers.org/api/wait_strategies/. /// [CanBeNull] - public static TimeSpan? WaitStrategyTimeout { get; set; } - = EnvironmentConfiguration.Instance.GetWaitStrategyTimeout() ?? PropertiesFileConfiguration.Instance.GetWaitStrategyTimeout(); + public static TimeSpan? WaitStrategyTimeout { get; set; } = + EnvironmentConfiguration.Instance.GetWaitStrategyTimeout() + ?? PropertiesFileConfiguration.Instance.GetWaitStrategyTimeout(); /// /// Gets or sets the host operating system. /// [NotNull] - public static IOperatingSystem OS { get; set; } - = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? new Windows(DockerEndpointAuthConfig) : new Unix(DockerEndpointAuthConfig); + public static IOperatingSystem OS { get; set; } = + RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + ? new Windows(DockerEndpointAuthConfig) + : new Unix(DockerEndpointAuthConfig); /// - public static Task ExposeHostPortsAsync(ushort port, CancellationToken ct = default) - => ExposeHostPortsAsync(new[] { port }, ct); + public static Task ExposeHostPortsAsync(ushort port, CancellationToken ct = default) => + ExposeHostPortsAsync(new[] { port }, ct); /// - public static async Task ExposeHostPortsAsync(IEnumerable ports, CancellationToken ct = default) + public static async Task ExposeHostPortsAsync( + IEnumerable ports, + CancellationToken ct = default + ) { - await PortForwardingContainer.Instance.StartAsync(ct) - .ConfigureAwait(false); + await PortForwardingContainer.Instance.StartAsync(ct).ConfigureAwait(false); - await PortForwardingContainer.Instance.ExposeHostPortsAsync(ports, ct) - .ConfigureAwait(false); + await PortForwardingContainer.Instance.ExposeHostPortsAsync(ports, ct).ConfigureAwait(false); } } } diff --git a/src/Testcontainers/Configurations/Unix.cs b/src/Testcontainers/Configurations/Unix.cs index d6e8da664..8f34f3255 100644 --- a/src/Testcontainers/Configurations/Unix.cs +++ b/src/Testcontainers/Configurations/Unix.cs @@ -14,68 +14,62 @@ public sealed class Unix : IOperatingSystem /// Represents the Unix file mode 644, which grants read and write permissions to the user and read permissions to the group and others. /// public const UnixFileModes FileMode644 = - UnixFileModes.UserRead | - UnixFileModes.UserWrite | - UnixFileModes.GroupRead | - UnixFileModes.OtherRead; + UnixFileModes.UserRead + | UnixFileModes.UserWrite + | UnixFileModes.GroupRead + | UnixFileModes.OtherRead; /// /// Represents the Unix file mode 666, which grants read and write permissions to the user, group, and others. /// public const UnixFileModes FileMode666 = - UnixFileModes.UserRead | - UnixFileModes.UserWrite | - UnixFileModes.GroupRead | - UnixFileModes.GroupWrite | - UnixFileModes.OtherRead | - UnixFileModes.OtherWrite; + UnixFileModes.UserRead + | UnixFileModes.UserWrite + | UnixFileModes.GroupRead + | UnixFileModes.GroupWrite + | UnixFileModes.OtherRead + | UnixFileModes.OtherWrite; /// /// Represents the Unix file mode 700, which grants read, write, and execute permissions to the user, and no permissions to the group and others. /// public const UnixFileModes FileMode700 = - UnixFileModes.UserRead | - UnixFileModes.UserWrite | - UnixFileModes.UserExecute; + UnixFileModes.UserRead | UnixFileModes.UserWrite | UnixFileModes.UserExecute; /// /// Represents the Unix file mode 755, which grants read, write, and execute permissions to the user, and read and execute permissions to the group and others. /// public const UnixFileModes FileMode755 = - UnixFileModes.UserRead | - UnixFileModes.UserWrite | - UnixFileModes.UserExecute | - UnixFileModes.GroupRead | - UnixFileModes.GroupExecute | - UnixFileModes.OtherRead | - UnixFileModes.OtherExecute; + UnixFileModes.UserRead + | UnixFileModes.UserWrite + | UnixFileModes.UserExecute + | UnixFileModes.GroupRead + | UnixFileModes.GroupExecute + | UnixFileModes.OtherRead + | UnixFileModes.OtherExecute; /// /// Represents the Unix file mode 777, which grants read, write, and execute permissions to the user, group, and others. /// public const UnixFileModes FileMode777 = - UnixFileModes.UserRead | - UnixFileModes.UserWrite | - UnixFileModes.UserExecute | - UnixFileModes.GroupRead | - UnixFileModes.GroupWrite | - UnixFileModes.GroupExecute | - UnixFileModes.OtherRead | - UnixFileModes.OtherWrite | - UnixFileModes.OtherExecute; + UnixFileModes.UserRead + | UnixFileModes.UserWrite + | UnixFileModes.UserExecute + | UnixFileModes.GroupRead + | UnixFileModes.GroupWrite + | UnixFileModes.GroupExecute + | UnixFileModes.OtherRead + | UnixFileModes.OtherWrite + | UnixFileModes.OtherExecute; - static Unix() - { - } + static Unix() { } /// /// Initializes a new instance of the class. /// [PublicAPI] public Unix() - : this(UnixEndpointAuthenticationProvider.DockerEngine) - { - } + : this(UnixEndpointAuthenticationProvider.DockerEngine) { } /// /// Initializes a new instance of the class. @@ -83,9 +77,7 @@ public Unix() /// The Docker API endpoint. [PublicAPI] public Unix(string endpoint) - : this(new Uri(endpoint)) - { - } + : this(new Uri(endpoint)) { } /// /// Initializes a new instance of the class. @@ -93,9 +85,7 @@ public Unix(string endpoint) /// The Docker API endpoint. [PublicAPI] public Unix(Uri endpoint) - : this(new DockerEndpointAuthenticationConfiguration(endpoint)) - { - } + : this(new DockerEndpointAuthenticationConfiguration(endpoint)) { } /// /// Initializes a new instance of the class. @@ -110,8 +100,7 @@ public Unix(IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig) /// /// Gets the instance. /// - public static IOperatingSystem Instance { get; } - = new Unix(dockerEndpointAuthConfig: null); + public static IOperatingSystem Instance { get; } = new Unix(dockerEndpointAuthConfig: null); /// public IDockerEndpointAuthenticationConfiguration DockerEndpointAuthConfig { get; } diff --git a/src/Testcontainers/Configurations/Volumes/BinaryResourceMapping.cs b/src/Testcontainers/Configurations/Volumes/BinaryResourceMapping.cs index 8036d7411..85c3b24c3 100644 --- a/src/Testcontainers/Configurations/Volumes/BinaryResourceMapping.cs +++ b/src/Testcontainers/Configurations/Volumes/BinaryResourceMapping.cs @@ -14,7 +14,11 @@ internal class BinaryResourceMapping : FileResourceMapping /// The byte array content to map in the container. /// The absolute path of a file to map in the container. /// The POSIX file mode permission. - public BinaryResourceMapping(byte[] resourceContent, string containerPath, UnixFileModes fileMode) + public BinaryResourceMapping( + byte[] resourceContent, + string containerPath, + UnixFileModes fileMode + ) : base(string.Empty, containerPath, fileMode) { _resourceContent = resourceContent; diff --git a/src/Testcontainers/Configurations/Volumes/UriResourceMapping.cs b/src/Testcontainers/Configurations/Volumes/UriResourceMapping.cs index 10c3a6f68..6489decc9 100644 --- a/src/Testcontainers/Configurations/Volumes/UriResourceMapping.cs +++ b/src/Testcontainers/Configurations/Volumes/UriResourceMapping.cs @@ -53,11 +53,9 @@ public async Task GetAllBytesAsync(CancellationToken ct = default) using (var httpClient = new HttpClient()) { #if NET6_0_OR_GREATER - return await httpClient.GetByteArrayAsync(_uri, ct) - .ConfigureAwait(false); + return await httpClient.GetByteArrayAsync(_uri, ct).ConfigureAwait(false); #else - return await httpClient.GetByteArrayAsync(_uri) - .ConfigureAwait(false); + return await httpClient.GetByteArrayAsync(_uri).ConfigureAwait(false); #endif } } diff --git a/src/Testcontainers/Configurations/Volumes/VolumeConfiguration.cs b/src/Testcontainers/Configurations/Volumes/VolumeConfiguration.cs index 166b86b20..9eee259b7 100644 --- a/src/Testcontainers/Configurations/Volumes/VolumeConfiguration.cs +++ b/src/Testcontainers/Configurations/Volumes/VolumeConfiguration.cs @@ -6,14 +6,15 @@ namespace DotNet.Testcontainers.Configurations /// [PublicAPI] - internal sealed class VolumeConfiguration : ResourceConfiguration, IVolumeConfiguration + internal sealed class VolumeConfiguration + : ResourceConfiguration, + IVolumeConfiguration { /// /// Initializes a new instance of the class. /// /// The name. - public VolumeConfiguration( - string name = null) + public VolumeConfiguration(string name = null) { Name = name; } @@ -22,19 +23,17 @@ public VolumeConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public VolumeConfiguration(IResourceConfiguration resourceConfiguration) - : base(resourceConfiguration) - { - } + public VolumeConfiguration( + IResourceConfiguration resourceConfiguration + ) + : base(resourceConfiguration) { } /// /// Initializes a new instance of the class. /// /// The Docker resource configuration. public VolumeConfiguration(IVolumeConfiguration resourceConfiguration) - : this(new VolumeConfiguration(), resourceConfiguration) - { - } + : this(new VolumeConfiguration(), resourceConfiguration) { } /// /// Initializes a new instance of the class. diff --git a/src/Testcontainers/Configurations/WaitStrategies/HttpWaitStrategy.cs b/src/Testcontainers/Configurations/WaitStrategies/HttpWaitStrategy.cs index 3f457177d..f96f44d55 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/HttpWaitStrategy.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/HttpWaitStrategy.cs @@ -45,14 +45,22 @@ public sealed class HttpWaitStrategy : IWaitUntil /// public HttpWaitStrategy() { - _ = WithMethod(HttpMethod.Get).UsingTls(false).ForPath("/").ForResponseMessageMatching(_ => Task.FromResult(true)).WithContent(() => null); + _ = WithMethod(HttpMethod.Get) + .UsingTls(false) + .ForPath("/") + .ForResponseMessageMatching(_ => Task.FromResult(true)) + .WithContent(() => null); } /// public async Task UntilAsync(IContainer container) { // Java falls back to the first exposed port. The .NET wait strategies do not have access to the exposed port information yet. - var containerPort = _portNumber.GetValueOrDefault(Uri.UriSchemeHttp.Equals(_schemeName, StringComparison.OrdinalIgnoreCase) ? HttpPort : HttpsPort); + var containerPort = _portNumber.GetValueOrDefault( + Uri.UriSchemeHttp.Equals(_schemeName, StringComparison.OrdinalIgnoreCase) + ? HttpPort + : HttpsPort + ); string host; @@ -68,9 +76,19 @@ public async Task UntilAsync(IContainer container) return false; } - using (var httpClient = new HttpClient(_httpMessageHandler ?? new HttpClientHandler(), disposeHandler: _httpMessageHandler == null)) + using ( + var httpClient = new HttpClient( + _httpMessageHandler ?? new HttpClientHandler(), + disposeHandler: _httpMessageHandler == null + ) + ) { - using (var httpRequestMessage = new HttpRequestMessage(_httpMethod, new UriBuilder(_schemeName, host, port, _pathValue).Uri)) + using ( + var httpRequestMessage = new HttpRequestMessage( + _httpMethod, + new UriBuilder(_schemeName, host, port, _pathValue).Uri + ) + ) { foreach (var httpHeader in _httpHeaders) { @@ -83,7 +101,8 @@ public async Task UntilAsync(IContainer container) try { - httpResponseMessage = await httpClient.SendAsync(httpRequestMessage) + httpResponseMessage = await httpClient + .SendAsync(httpRequestMessage) .ConfigureAwait(false); } catch (HttpRequestException) @@ -103,7 +122,9 @@ public async Task UntilAsync(IContainer container) } else if (_httpStatusCodes.Any()) { - predicate = statusCode => _httpStatusCodes.Contains(statusCode) || _httpStatusCodePredicate.Invoke(statusCode); + predicate = statusCode => + _httpStatusCodes.Contains(statusCode) + || _httpStatusCodePredicate.Invoke(statusCode); } else { @@ -112,7 +133,8 @@ public async Task UntilAsync(IContainer container) try { - var responseMessagePredicate = await _httpResponseMessagePredicate.Invoke(httpResponseMessage) + var responseMessagePredicate = await _httpResponseMessagePredicate + .Invoke(httpResponseMessage) .ConfigureAwait(false); return responseMessagePredicate && predicate.Invoke(httpResponseMessage.StatusCode); @@ -157,7 +179,9 @@ public HttpWaitStrategy ForStatusCodeMatching(Predicate statusCo /// /// The predicate to test the HTTP response against. /// A configured instance of . - public HttpWaitStrategy ForResponseMessageMatching(Func> responseMessagePredicate) + public HttpWaitStrategy ForResponseMessageMatching( + Func> responseMessagePredicate + ) { _httpResponseMessagePredicate = responseMessagePredicate; return this; @@ -235,7 +259,13 @@ public HttpWaitStrategy WithMethod(HttpMethod method) /// A configured instance of . public HttpWaitStrategy WithBasicAuthentication(string username, string password) { - return WithHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Join(":", username, password)))); + return WithHeader( + "Authorization", + "Basic " + + Convert.ToBase64String( + Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Join(":", username, password)) + ) + ); } /// @@ -257,7 +287,10 @@ public HttpWaitStrategy WithHeader(string name, string value) /// A configured instance of . public HttpWaitStrategy WithHeaders(IReadOnlyDictionary headers) { - return headers.Aggregate(this, (httpWaitStrategy, header) => httpWaitStrategy.WithHeader(header.Key, header.Value)); + return headers.Aggregate( + this, + (httpWaitStrategy, header) => httpWaitStrategy.WithHeader(header.Key, header.Value) + ); } /// diff --git a/src/Testcontainers/Configurations/WaitStrategies/IWaitForContainerOS.cs b/src/Testcontainers/Configurations/WaitStrategies/IWaitForContainerOS.cs index 246d008e8..4b7fba820 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/IWaitForContainerOS.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/IWaitForContainerOS.cs @@ -21,7 +21,10 @@ public interface IWaitForContainerOS /// A configured instance of . /// Already contains as default wait strategy. [PublicAPI] - IWaitForContainerOS AddCustomWaitStrategy(IWaitUntil waitUntil, Action waitStrategyModifier = null); + IWaitForContainerOS AddCustomWaitStrategy( + IWaitUntil waitUntil, + Action waitStrategyModifier = null + ); /// /// Waits until the command is completed successfully. @@ -43,7 +46,10 @@ public interface IWaitForContainerOS /// A configured instance of . /// Invokes the operating system command shell. Expects the exit code to be 0. [PublicAPI] - IWaitForContainerOS UntilCommandIsCompleted(string command, Action waitStrategyModifier = null); + IWaitForContainerOS UntilCommandIsCompleted( + string command, + Action waitStrategyModifier = null + ); /// /// Waits until the command is completed successfully. @@ -56,7 +62,10 @@ public interface IWaitForContainerOS /// Normal shell processing does not happen. Expects the exit code to be 0. /// [PublicAPI] - IWaitForContainerOS UntilCommandIsCompleted(IEnumerable command, Action waitStrategyModifier = null); + IWaitForContainerOS UntilCommandIsCompleted( + IEnumerable command, + Action waitStrategyModifier = null + ); /// /// Waits until the port is available. @@ -65,8 +74,13 @@ public interface IWaitForContainerOS /// The wait strategy modifier to cancel the readiness check. /// A configured instance of . [PublicAPI] - [Obsolete("Use UntilInternalTcpPortIsAvailable or UntilExternalTcpPortIsAvailable instead. This method corresponds to the internal variant.")] - IWaitForContainerOS UntilPortIsAvailable(int port, Action waitStrategyModifier = null); + [Obsolete( + "Use UntilInternalTcpPortIsAvailable or UntilExternalTcpPortIsAvailable instead. This method corresponds to the internal variant." + )] + IWaitForContainerOS UntilPortIsAvailable( + int port, + Action waitStrategyModifier = null + ); /// /// Waits until a TCP port is available from within the container itself. @@ -76,7 +90,10 @@ public interface IWaitForContainerOS /// The wait strategy modifier to cancel the readiness check. /// A configured instance of . [PublicAPI] - IWaitForContainerOS UntilInternalTcpPortIsAvailable(int containerPort, Action waitStrategyModifier = null); + IWaitForContainerOS UntilInternalTcpPortIsAvailable( + int containerPort, + Action waitStrategyModifier = null + ); /// /// Waits until a TCP port is available from the test host to the container. @@ -97,7 +114,10 @@ public interface IWaitForContainerOS /// The wait strategy modifier to cancel the readiness check. /// A configured instance of . [PublicAPI] - IWaitForContainerOS UntilExternalTcpPortIsAvailable(int containerPort, Action waitStrategyModifier = null); + IWaitForContainerOS UntilExternalTcpPortIsAvailable( + int containerPort, + Action waitStrategyModifier = null + ); /// /// Waits until the file exists. @@ -107,7 +127,11 @@ public interface IWaitForContainerOS /// The wait strategy modifier to cancel the readiness check. /// A configured instance of . [PublicAPI] - IWaitForContainerOS UntilFileExists(string filePath, FileSystem fileSystem = FileSystem.Host, Action waitStrategyModifier = null); + IWaitForContainerOS UntilFileExists( + string filePath, + FileSystem fileSystem = FileSystem.Host, + Action waitStrategyModifier = null + ); /// /// Waits until the message is logged. @@ -116,7 +140,10 @@ public interface IWaitForContainerOS /// The wait strategy modifier to cancel the readiness check. /// A configured instance of . [PublicAPI] - IWaitForContainerOS UntilMessageIsLogged(string pattern, Action waitStrategyModifier = null); + IWaitForContainerOS UntilMessageIsLogged( + string pattern, + Action waitStrategyModifier = null + ); /// /// Waits until the message is logged. @@ -125,7 +152,10 @@ public interface IWaitForContainerOS /// The wait strategy modifier to cancel the readiness check. /// A configured instance of . [PublicAPI] - IWaitForContainerOS UntilMessageIsLogged(Regex pattern, Action waitStrategyModifier = null); + IWaitForContainerOS UntilMessageIsLogged( + Regex pattern, + Action waitStrategyModifier = null + ); /// /// Waits until the http request is completed successfully. @@ -134,7 +164,10 @@ public interface IWaitForContainerOS /// The wait strategy modifier to cancel the readiness check. /// A configured instance of . [PublicAPI] - IWaitForContainerOS UntilHttpRequestIsSucceeded(Func request, Action waitStrategyModifier = null); + IWaitForContainerOS UntilHttpRequestIsSucceeded( + Func request, + Action waitStrategyModifier = null + ); /// /// Waits until the container is healthy. @@ -144,7 +177,10 @@ public interface IWaitForContainerOS /// A configured instance of . /// Thrown when number of failed operations exceeded . [PublicAPI] - IWaitForContainerOS UntilContainerIsHealthy(long failingStreak = 3, Action waitStrategyModifier = null); + IWaitForContainerOS UntilContainerIsHealthy( + long failingStreak = 3, + Action waitStrategyModifier = null + ); /// /// Waits until a successful connection to the database can be established. @@ -156,7 +192,10 @@ public interface IWaitForContainerOS /// The wait strategy modifier to cancel the readiness check. /// A configured instance of . [PublicAPI] - IWaitForContainerOS UntilDatabaseIsAvailable(DbProviderFactory dbProviderFactory, Action waitStrategyModifier = null); + IWaitForContainerOS UntilDatabaseIsAvailable( + DbProviderFactory dbProviderFactory, + Action waitStrategyModifier = null + ); /// /// Returns a collection with all configured wait strategies. diff --git a/src/Testcontainers/Configurations/WaitStrategies/RetryLimitExceededException.cs b/src/Testcontainers/Configurations/WaitStrategies/RetryLimitExceededException.cs index 9e5728220..79fd84de3 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/RetryLimitExceededException.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/RetryLimitExceededException.cs @@ -5,8 +5,6 @@ namespace DotNet.Testcontainers.Configurations public sealed class RetryLimitExceededException : Exception { public RetryLimitExceededException(string message) - : base(message) - { - } + : base(message) { } } } diff --git a/src/Testcontainers/Configurations/WaitStrategies/UntilContainerIsHealthy.cs b/src/Testcontainers/Configurations/WaitStrategies/UntilContainerIsHealthy.cs index 09e16288f..3c798ff1f 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/UntilContainerIsHealthy.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/UntilContainerIsHealthy.cs @@ -22,7 +22,9 @@ public Task UntilAsync(IContainer container) if (_failingStreak < container.HealthCheckFailingStreak) { - throw new TimeoutException($"Number of failed operations exceeded max count ({_failingStreak})."); + throw new TimeoutException( + $"Number of failed operations exceeded max count ({_failingStreak})." + ); } return Task.FromResult(TestcontainersHealthStatus.Healthy.Equals(container.Health)); diff --git a/src/Testcontainers/Configurations/WaitStrategies/UntilContainerIsRunning.cs b/src/Testcontainers/Configurations/WaitStrategies/UntilContainerIsRunning.cs index cf9ab2146..be9771bc1 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/UntilContainerIsRunning.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/UntilContainerIsRunning.cs @@ -5,7 +5,8 @@ namespace DotNet.Testcontainers.Configurations internal class UntilContainerIsRunning : IWaitUntil { - private const TestcontainersStates ContainerHasBeenRunningStates = TestcontainersStates.Running | TestcontainersStates.Exited; + private const TestcontainersStates ContainerHasBeenRunningStates = + TestcontainersStates.Running | TestcontainersStates.Exited; public Task UntilAsync(IContainer container) { diff --git a/src/Testcontainers/Configurations/WaitStrategies/UntilDatabaseIsAvailable.cs b/src/Testcontainers/Configurations/WaitStrategies/UntilDatabaseIsAvailable.cs index c36e43bc2..76046f213 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/UntilDatabaseIsAvailable.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/UntilDatabaseIsAvailable.cs @@ -19,23 +19,24 @@ public async Task UntilAsync(IContainer container) if (container is not IDatabaseContainer dbContainer) { throw new NotSupportedException( - $"The 'UntilDatabaseIsAvailable' wait strategy can only be used with database containers. " + - $"The provided container type '{container.GetType().FullName}' does not implement '{nameof(IDatabaseContainer)}'."); + $"The 'UntilDatabaseIsAvailable' wait strategy can only be used with database containers. " + + $"The provided container type '{container.GetType().FullName}' does not implement '{nameof(IDatabaseContainer)}'." + ); } var connection = _dbProviderFactory.CreateConnection(); if (connection == null) { throw new InvalidOperationException( - $"Failed to create a database connection. The factory '{_dbProviderFactory.GetType().FullName}' returned null from 'CreateConnection()'."); + $"Failed to create a database connection. The factory '{_dbProviderFactory.GetType().FullName}' returned null from 'CreateConnection()'." + ); } try { connection.ConnectionString = dbContainer.GetConnectionString(); - await connection.OpenAsync() - .ConfigureAwait(false); + await connection.OpenAsync().ConfigureAwait(false); return true; } diff --git a/src/Testcontainers/Configurations/WaitStrategies/UntilExternalTcpPortIsAvailable.cs b/src/Testcontainers/Configurations/WaitStrategies/UntilExternalTcpPortIsAvailable.cs index 3625996d1..b305f63bf 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/UntilExternalTcpPortIsAvailable.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/UntilExternalTcpPortIsAvailable.cs @@ -21,8 +21,7 @@ public async Task UntilAsync(IContainer container) try { - await tcpClient.ConnectAsync(container.Hostname, hostPort) - .ConfigureAwait(false); + await tcpClient.ConnectAsync(container.Hostname, hostPort).ConfigureAwait(false); return true; } diff --git a/src/Testcontainers/Configurations/WaitStrategies/UntilFileExistsInContainer.cs b/src/Testcontainers/Configurations/WaitStrategies/UntilFileExistsInContainer.cs index 63b410ada..dec128567 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/UntilFileExistsInContainer.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/UntilFileExistsInContainer.cs @@ -17,8 +17,7 @@ public async Task UntilAsync(IContainer container) { try { - _ = await container.ReadFileAsync(_file) - .ConfigureAwait(false); + _ = await container.ReadFileAsync(_file).ConfigureAwait(false); return true; } diff --git a/src/Testcontainers/Configurations/WaitStrategies/UntilInternalTcpPortIsAvailableOnUnix.cs b/src/Testcontainers/Configurations/WaitStrategies/UntilInternalTcpPortIsAvailableOnUnix.cs index ba7c0457a..f83113b08 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/UntilInternalTcpPortIsAvailableOnUnix.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/UntilInternalTcpPortIsAvailableOnUnix.cs @@ -3,8 +3,11 @@ namespace DotNet.Testcontainers.Configurations internal class UntilInternalTcpPortIsAvailableOnUnix : UntilUnixCommandIsCompleted { public UntilInternalTcpPortIsAvailableOnUnix(int containerPort) - : base(string.Format("true && (grep -i ':0*{0:X}' /proc/net/tcp* || nc -vz -w 1 localhost {0:D} || /bin/bash -c ' UntilAsync(IContainer container) { - var maxTime = container.StoppedTime > container.CreatedTime ? container.StoppedTime : container.CreatedTime; + var maxTime = + container.StoppedTime > container.CreatedTime + ? container.StoppedTime + : container.CreatedTime; - var (stdout, stderr) = await container.GetLogsAsync(since: maxTime, timestampsEnabled: false) + var (stdout, stderr) = await container + .GetLogsAsync(since: maxTime, timestampsEnabled: false) .ConfigureAwait(false); return _pattern.IsMatch(stdout) || _pattern.IsMatch(stderr); diff --git a/src/Testcontainers/Configurations/WaitStrategies/UntilUnixCommandIsCompleted.cs b/src/Testcontainers/Configurations/WaitStrategies/UntilUnixCommandIsCompleted.cs index 8f33c809d..4941474a6 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/UntilUnixCommandIsCompleted.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/UntilUnixCommandIsCompleted.cs @@ -8,9 +8,7 @@ internal class UntilUnixCommandIsCompleted : IWaitUntil private readonly string[] _command; public UntilUnixCommandIsCompleted(string command) - : this("/bin/sh", "-c", command) - { - } + : this("/bin/sh", "-c", command) { } public UntilUnixCommandIsCompleted(params string[] command) { @@ -19,8 +17,7 @@ public UntilUnixCommandIsCompleted(params string[] command) public virtual async Task UntilAsync(IContainer container) { - var execResult = await container.ExecAsync(_command) - .ConfigureAwait(false); + var execResult = await container.ExecAsync(_command).ConfigureAwait(false); return 0L.Equals(execResult.ExitCode); } diff --git a/src/Testcontainers/Configurations/WaitStrategies/UntilWindowsCommandIsCompleted.cs b/src/Testcontainers/Configurations/WaitStrategies/UntilWindowsCommandIsCompleted.cs index 8fa6183aa..bc250e540 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/UntilWindowsCommandIsCompleted.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/UntilWindowsCommandIsCompleted.cs @@ -3,13 +3,9 @@ namespace DotNet.Testcontainers.Configurations internal class UntilWindowsCommandIsCompleted : UntilUnixCommandIsCompleted { public UntilWindowsCommandIsCompleted(string command) - : this("PowerShell", "-Command", command) - { - } + : this("PowerShell", "-Command", command) { } public UntilWindowsCommandIsCompleted(params string[] command) - : base(command) - { - } + : base(command) { } } } diff --git a/src/Testcontainers/Configurations/WaitStrategies/WaitForContainerOS.cs b/src/Testcontainers/Configurations/WaitStrategies/WaitForContainerOS.cs index f08c472a1..e78fac567 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/WaitForContainerOS.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/WaitForContainerOS.cs @@ -22,19 +22,34 @@ protected WaitForContainerOS() public abstract IWaitForContainerOS UntilCommandIsCompleted(params string[] command); /// - public abstract IWaitForContainerOS UntilCommandIsCompleted(string command, Action waitStrategyModifier = null); + public abstract IWaitForContainerOS UntilCommandIsCompleted( + string command, + Action waitStrategyModifier = null + ); /// - public abstract IWaitForContainerOS UntilCommandIsCompleted(IEnumerable command, Action waitStrategyModifier = null); + public abstract IWaitForContainerOS UntilCommandIsCompleted( + IEnumerable command, + Action waitStrategyModifier = null + ); /// - public abstract IWaitForContainerOS UntilPortIsAvailable(int port, Action waitStrategyModifier = null); + public abstract IWaitForContainerOS UntilPortIsAvailable( + int port, + Action waitStrategyModifier = null + ); /// - public abstract IWaitForContainerOS UntilInternalTcpPortIsAvailable(int containerPort, Action waitStrategyModifier = null); + public abstract IWaitForContainerOS UntilInternalTcpPortIsAvailable( + int containerPort, + Action waitStrategyModifier = null + ); /// - public virtual IWaitForContainerOS AddCustomWaitStrategy(IWaitUntil waitUntil, Action waitStrategyModifier = null) + public virtual IWaitForContainerOS AddCustomWaitStrategy( + IWaitUntil waitUntil, + Action waitStrategyModifier = null + ) { var waitStrategy = new WaitStrategy(waitUntil); @@ -48,18 +63,31 @@ public virtual IWaitForContainerOS AddCustomWaitStrategy(IWaitUntil waitUntil, A } /// - public IWaitForContainerOS UntilExternalTcpPortIsAvailable(int containerPort, Action waitStrategyModifier = null) + public IWaitForContainerOS UntilExternalTcpPortIsAvailable( + int containerPort, + Action waitStrategyModifier = null + ) { - return AddCustomWaitStrategy(new UntilExternalTcpPortIsAvailable(containerPort), waitStrategyModifier); + return AddCustomWaitStrategy( + new UntilExternalTcpPortIsAvailable(containerPort), + waitStrategyModifier + ); } /// - public virtual IWaitForContainerOS UntilFileExists(string filePath, FileSystem fileSystem = FileSystem.Host, Action waitStrategyModifier = null) + public virtual IWaitForContainerOS UntilFileExists( + string filePath, + FileSystem fileSystem = FileSystem.Host, + Action waitStrategyModifier = null + ) { switch (fileSystem) { case FileSystem.Container: - return AddCustomWaitStrategy(new UntilFileExistsInContainer(filePath), waitStrategyModifier); + return AddCustomWaitStrategy( + new UntilFileExistsInContainer(filePath), + waitStrategyModifier + ); case FileSystem.Host: default: return AddCustomWaitStrategy(new UntilFileExistsOnHost(filePath), waitStrategyModifier); @@ -67,33 +95,54 @@ public virtual IWaitForContainerOS UntilFileExists(string filePath, FileSystem f } /// - public IWaitForContainerOS UntilMessageIsLogged(string pattern, Action waitStrategyModifier = null) + public IWaitForContainerOS UntilMessageIsLogged( + string pattern, + Action waitStrategyModifier = null + ) { return AddCustomWaitStrategy(new UntilMessageIsLogged(pattern), waitStrategyModifier); } /// - public IWaitForContainerOS UntilMessageIsLogged(Regex pattern, Action waitStrategyModifier = null) + public IWaitForContainerOS UntilMessageIsLogged( + Regex pattern, + Action waitStrategyModifier = null + ) { return AddCustomWaitStrategy(new UntilMessageIsLogged(pattern), waitStrategyModifier); } /// - public virtual IWaitForContainerOS UntilHttpRequestIsSucceeded(Func request, Action waitStrategyModifier = null) + public virtual IWaitForContainerOS UntilHttpRequestIsSucceeded( + Func request, + Action waitStrategyModifier = null + ) { return AddCustomWaitStrategy(request.Invoke(new HttpWaitStrategy()), waitStrategyModifier); } /// - public virtual IWaitForContainerOS UntilContainerIsHealthy(long failingStreak = 3, Action waitStrategyModifier = null) + public virtual IWaitForContainerOS UntilContainerIsHealthy( + long failingStreak = 3, + Action waitStrategyModifier = null + ) { - return AddCustomWaitStrategy(new UntilContainerIsHealthy(failingStreak), waitStrategyModifier); + return AddCustomWaitStrategy( + new UntilContainerIsHealthy(failingStreak), + waitStrategyModifier + ); } /// - public virtual IWaitForContainerOS UntilDatabaseIsAvailable(DbProviderFactory dbProviderFactory, Action waitStrategyModifier = null) + public virtual IWaitForContainerOS UntilDatabaseIsAvailable( + DbProviderFactory dbProviderFactory, + Action waitStrategyModifier = null + ) { - return AddCustomWaitStrategy(new UntilDatabaseIsAvailable(dbProviderFactory), waitStrategyModifier); + return AddCustomWaitStrategy( + new UntilDatabaseIsAvailable(dbProviderFactory), + waitStrategyModifier + ); } /// diff --git a/src/Testcontainers/Configurations/WaitStrategies/WaitForContainerUnix.cs b/src/Testcontainers/Configurations/WaitStrategies/WaitForContainerUnix.cs index 93a9c2005..6ab8c6e63 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/WaitForContainerUnix.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/WaitForContainerUnix.cs @@ -14,27 +14,45 @@ public override IWaitForContainerOS UntilCommandIsCompleted(params string[] comm } /// - public override IWaitForContainerOS UntilCommandIsCompleted(string command, Action waitStrategyModifier = null) + public override IWaitForContainerOS UntilCommandIsCompleted( + string command, + Action waitStrategyModifier = null + ) { return AddCustomWaitStrategy(new UntilUnixCommandIsCompleted(command), waitStrategyModifier); } /// - public override IWaitForContainerOS UntilCommandIsCompleted(IEnumerable command, Action waitStrategyModifier = null) + public override IWaitForContainerOS UntilCommandIsCompleted( + IEnumerable command, + Action waitStrategyModifier = null + ) { - return AddCustomWaitStrategy(new UntilUnixCommandIsCompleted(command.ToArray()), waitStrategyModifier); + return AddCustomWaitStrategy( + new UntilUnixCommandIsCompleted(command.ToArray()), + waitStrategyModifier + ); } /// - public override IWaitForContainerOS UntilPortIsAvailable(int port, Action waitStrategyModifier = null) + public override IWaitForContainerOS UntilPortIsAvailable( + int port, + Action waitStrategyModifier = null + ) { return UntilInternalTcpPortIsAvailable(port, waitStrategyModifier); } /// - public override IWaitForContainerOS UntilInternalTcpPortIsAvailable(int containerPort, Action waitStrategyModifier = null) + public override IWaitForContainerOS UntilInternalTcpPortIsAvailable( + int containerPort, + Action waitStrategyModifier = null + ) { - return AddCustomWaitStrategy(new UntilInternalTcpPortIsAvailableOnUnix(containerPort), waitStrategyModifier); + return AddCustomWaitStrategy( + new UntilInternalTcpPortIsAvailableOnUnix(containerPort), + waitStrategyModifier + ); } } } diff --git a/src/Testcontainers/Configurations/WaitStrategies/WaitForContainerWindows.cs b/src/Testcontainers/Configurations/WaitStrategies/WaitForContainerWindows.cs index c2ae1f95b..2c1991a79 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/WaitForContainerWindows.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/WaitForContainerWindows.cs @@ -14,27 +14,48 @@ public override IWaitForContainerOS UntilCommandIsCompleted(params string[] comm } /// - public override IWaitForContainerOS UntilCommandIsCompleted(string command, Action waitStrategyModifier = null) + public override IWaitForContainerOS UntilCommandIsCompleted( + string command, + Action waitStrategyModifier = null + ) { - return AddCustomWaitStrategy(new UntilWindowsCommandIsCompleted(command), waitStrategyModifier); + return AddCustomWaitStrategy( + new UntilWindowsCommandIsCompleted(command), + waitStrategyModifier + ); } /// - public override IWaitForContainerOS UntilCommandIsCompleted(IEnumerable command, Action waitStrategyModifier = null) + public override IWaitForContainerOS UntilCommandIsCompleted( + IEnumerable command, + Action waitStrategyModifier = null + ) { - return AddCustomWaitStrategy(new UntilWindowsCommandIsCompleted(command.ToArray()), waitStrategyModifier); + return AddCustomWaitStrategy( + new UntilWindowsCommandIsCompleted(command.ToArray()), + waitStrategyModifier + ); } /// - public override IWaitForContainerOS UntilPortIsAvailable(int port, Action waitStrategyModifier = null) + public override IWaitForContainerOS UntilPortIsAvailable( + int port, + Action waitStrategyModifier = null + ) { return UntilInternalTcpPortIsAvailable(port, waitStrategyModifier); } /// - public override IWaitForContainerOS UntilInternalTcpPortIsAvailable(int containerPort, Action waitStrategyModifier = null) + public override IWaitForContainerOS UntilInternalTcpPortIsAvailable( + int containerPort, + Action waitStrategyModifier = null + ) { - return AddCustomWaitStrategy(new UntilInternalTcpPortIsAvailableOnWindows(containerPort), waitStrategyModifier); + return AddCustomWaitStrategy( + new UntilInternalTcpPortIsAvailableOnWindows(containerPort), + waitStrategyModifier + ); } } } diff --git a/src/Testcontainers/Configurations/WaitStrategies/WaitStrategy.cs b/src/Testcontainers/Configurations/WaitStrategies/WaitStrategy.cs index 48c74d36f..d9a05286d 100644 --- a/src/Testcontainers/Configurations/WaitStrategies/WaitStrategy.cs +++ b/src/Testcontainers/Configurations/WaitStrategies/WaitStrategy.cs @@ -10,7 +10,8 @@ namespace DotNet.Testcontainers.Configurations [PublicAPI] public class WaitStrategy : IWaitStrategy { - private const string MaximumRetryExceededException = "The maximum number of retries has been exceeded."; + private const string MaximumRetryExceededException = + "The maximum number of retries has been exceeded."; private IWaitWhile _waitWhile; @@ -19,9 +20,7 @@ public class WaitStrategy : IWaitStrategy /// /// Initializes a new instance of the class. /// - public WaitStrategy() - { - } + public WaitStrategy() { } /// /// Initializes a new instance of the class. @@ -44,20 +43,19 @@ public WaitStrategy(IWaitUntil waitUntil) /// /// Gets the number of retries. /// - public ushort Retries { get; private set; } - = TestcontainersSettings.WaitStrategyRetries ?? 0; + public ushort Retries { get; private set; } = TestcontainersSettings.WaitStrategyRetries ?? 0; /// /// Gets the interval between retries. /// - public TimeSpan Interval { get; private set; } - = TestcontainersSettings.WaitStrategyInterval ?? TimeSpan.FromSeconds(1); + public TimeSpan Interval { get; private set; } = + TestcontainersSettings.WaitStrategyInterval ?? TimeSpan.FromSeconds(1); /// /// Gets the timeout. /// - public TimeSpan Timeout { get; private set; } - = TestcontainersSettings.WaitStrategyTimeout ?? TimeSpan.FromHours(1); + public TimeSpan Timeout { get; private set; } = + TestcontainersSettings.WaitStrategyTimeout ?? TimeSpan.FromHours(1); /// public IWaitStrategy WithRetries(ushort retries) @@ -117,7 +115,13 @@ public virtual Task UntilAsync(IContainer container, CancellationToken ct /// Thrown when the number of retries is exceeded. /// A task that represents the asynchronous block operation. [PublicAPI] - public static async Task WaitWhileAsync(Func> wait, TimeSpan interval, TimeSpan timeout, int retries = 0, CancellationToken ct = default) + public static async Task WaitWhileAsync( + Func> wait, + TimeSpan interval, + TimeSpan timeout, + int retries = 0, + CancellationToken ct = default + ) { ushort actualRetries = 0; @@ -125,19 +129,21 @@ async Task WhileAsync() { while (!ct.IsCancellationRequested) { - var isSuccessful = await wait.Invoke() - .ConfigureAwait(false); + var isSuccessful = await wait.Invoke().ConfigureAwait(false); if (!isSuccessful) { break; } - _ = Guard.Argument(retries, nameof(retries)) - .ThrowIf(_ => retries > 0 && ++actualRetries > retries, _ => throw new RetryLimitExceededException(MaximumRetryExceededException)); + _ = Guard + .Argument(retries, nameof(retries)) + .ThrowIf( + _ => retries > 0 && ++actualRetries > retries, + _ => throw new RetryLimitExceededException(MaximumRetryExceededException) + ); - await Task.Delay(interval, ct) - .ConfigureAwait(false); + await Task.Delay(interval, ct).ConfigureAwait(false); } } @@ -145,8 +151,8 @@ await Task.Delay(interval, ct) var timeoutTask = Task.Delay(timeout, ct); - var isTimeoutTask = timeoutTask == await Task.WhenAny(waitTask, timeoutTask) - .ConfigureAwait(false); + var isTimeoutTask = + timeoutTask == await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(false); if (isTimeoutTask) { @@ -154,8 +160,7 @@ await Task.Delay(interval, ct) } // Rethrows exceptions. - await waitTask - .ConfigureAwait(false); + await waitTask.ConfigureAwait(false); } /// @@ -173,7 +178,13 @@ await waitTask /// Thrown when the number of retries is exceeded. /// A task that represents the asynchronous block operation. [PublicAPI] - public static async Task WaitUntilAsync(Func> wait, TimeSpan interval, TimeSpan timeout, int retries = 0, CancellationToken ct = default) + public static async Task WaitUntilAsync( + Func> wait, + TimeSpan interval, + TimeSpan timeout, + int retries = 0, + CancellationToken ct = default + ) { ushort actualRetries = 0; @@ -181,19 +192,21 @@ async Task UntilAsync() { while (!ct.IsCancellationRequested) { - var isSuccessful = await wait.Invoke() - .ConfigureAwait(false); + var isSuccessful = await wait.Invoke().ConfigureAwait(false); if (isSuccessful) { break; } - _ = Guard.Argument(retries, nameof(retries)) - .ThrowIf(_ => retries > 0 && ++actualRetries > retries, _ => throw new RetryLimitExceededException(MaximumRetryExceededException)); + _ = Guard + .Argument(retries, nameof(retries)) + .ThrowIf( + _ => retries > 0 && ++actualRetries > retries, + _ => throw new RetryLimitExceededException(MaximumRetryExceededException) + ); - await Task.Delay(interval, ct) - .ConfigureAwait(false); + await Task.Delay(interval, ct).ConfigureAwait(false); } } @@ -201,8 +214,8 @@ await Task.Delay(interval, ct) var timeoutTask = Task.Delay(timeout, ct); - var isTimeoutTask = timeoutTask == await Task.WhenAny(waitTask, timeoutTask) - .ConfigureAwait(false); + var isTimeoutTask = + timeoutTask == await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(false); if (isTimeoutTask) { @@ -210,8 +223,7 @@ await Task.Delay(interval, ct) } // Rethrows exceptions. - await waitTask - .ConfigureAwait(false); + await waitTask.ConfigureAwait(false); } /// diff --git a/src/Testcontainers/Configurations/Windows.cs b/src/Testcontainers/Configurations/Windows.cs index bdf53a285..243f7b919 100644 --- a/src/Testcontainers/Configurations/Windows.cs +++ b/src/Testcontainers/Configurations/Windows.cs @@ -10,18 +10,14 @@ namespace DotNet.Testcontainers.Configurations [PublicAPI] public sealed class Windows : IOperatingSystem { - static Windows() - { - } + static Windows() { } /// /// Initializes a new instance of the class. /// [PublicAPI] public Windows() - : this(NpipeEndpointAuthenticationProvider.DockerEngine) - { - } + : this(NpipeEndpointAuthenticationProvider.DockerEngine) { } /// /// Initializes a new instance of the class. @@ -29,9 +25,7 @@ public Windows() /// The Docker API endpoint. [PublicAPI] public Windows(string endpoint) - : this(new Uri(endpoint)) - { - } + : this(new Uri(endpoint)) { } /// /// Initializes a new instance of the class. @@ -39,9 +33,7 @@ public Windows(string endpoint) /// The Docker API endpoint. [PublicAPI] public Windows(Uri endpoint) - : this(new DockerEndpointAuthenticationConfiguration(endpoint)) - { - } + : this(new DockerEndpointAuthenticationConfiguration(endpoint)) { } /// /// Initializes a new instance of the class. @@ -56,8 +48,7 @@ public Windows(IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConf /// /// Gets the instance. /// - public static IOperatingSystem Instance { get; } - = new Windows(dockerEndpointAuthConfig: null); + public static IOperatingSystem Instance { get; } = new Windows(dockerEndpointAuthConfig: null); /// public IDockerEndpointAuthenticationConfiguration DockerEndpointAuthConfig { get; } diff --git a/src/Testcontainers/Containers/DockerContainer.cs b/src/Testcontainers/Containers/DockerContainer.cs index 7162efd47..22ed30f7e 100644 --- a/src/Testcontainers/Containers/DockerContainer.cs +++ b/src/Testcontainers/Containers/DockerContainer.cs @@ -19,9 +19,16 @@ namespace DotNet.Testcontainers.Containers [PublicAPI] public class DockerContainer : Resource, IContainer { - private const TestcontainersStates ContainerHasBeenCreatedStates = TestcontainersStates.Created | TestcontainersStates.Running | TestcontainersStates.Paused | TestcontainersStates.Exited; + private const TestcontainersStates ContainerHasBeenCreatedStates = + TestcontainersStates.Created + | TestcontainersStates.Running + | TestcontainersStates.Paused + | TestcontainersStates.Exited; - private const TestcontainersHealthStatus ContainerHasHealthCheck = TestcontainersHealthStatus.Starting | TestcontainersHealthStatus.Healthy | TestcontainersHealthStatus.Unhealthy; + private const TestcontainersHealthStatus ContainerHasHealthCheck = + TestcontainersHealthStatus.Starting + | TestcontainersHealthStatus.Healthy + | TestcontainersHealthStatus.Unhealthy; private readonly ITestcontainersClient _client; @@ -35,7 +42,11 @@ public class DockerContainer : Resource, IContainer /// The container configuration. public DockerContainer(IContainerConfiguration configuration) { - _client = new TestcontainersClient(configuration.SessionId, configuration.DockerEndpointAuthConfig, configuration.Logger); + _client = new TestcontainersClient( + configuration.SessionId, + configuration.DockerEndpointAuthConfig, + configuration.Logger + ); _configuration = configuration; } @@ -87,10 +98,7 @@ public DockerContainer(IContainerConfiguration configuration) /// public ILogger Logger { - get - { - return _configuration.Logger; - } + get { return _configuration.Logger; } } /// @@ -174,7 +182,9 @@ public string Hostname } default: - throw new InvalidOperationException($"Docker endpoint {dockerEndpoint} is not supported."); + throw new InvalidOperationException( + $"Docker endpoint {dockerEndpoint} is not supported." + ); } } } @@ -182,10 +192,7 @@ public string Hostname /// public IImage Image { - get - { - return _configuration.Image; - } + get { return _configuration.Image; } } /// @@ -201,7 +208,8 @@ public TestcontainersStates State try { #if NETSTANDARD2_0 - return (TestcontainersStates)Enum.Parse(typeof(TestcontainersStates), _container.State.Status, true); + return (TestcontainersStates) + Enum.Parse(typeof(TestcontainersStates), _container.State.Status, true); #else return Enum.Parse(_container.State.Status, true); #endif @@ -231,7 +239,8 @@ public TestcontainersHealthStatus Health try { #if NETSTANDARD2_0 - return (TestcontainersHealthStatus)Enum.Parse(typeof(TestcontainersHealthStatus), _container.State.Health.Status, true); + return (TestcontainersHealthStatus) + Enum.Parse(typeof(TestcontainersHealthStatus), _container.State.Health.Status, true); #else return Enum.Parse(_container.State.Health.Status, true); #endif @@ -256,7 +265,9 @@ public long HealthCheckFailingStreak public ushort GetMappedPublicPort() { using var enumerator = GetMappedPublicPorts().Values.GetEnumerator(); - return enumerator.MoveNext() ? enumerator.Current : throw new InvalidOperationException("No mapped port found."); + return enumerator.MoveNext() + ? enumerator.Current + : throw new InvalidOperationException("No mapped port found."); } /// @@ -272,13 +283,18 @@ public ushort GetMappedPublicPort(string containerPort) var qualifiedContainerPort = ContainerConfigurationConverter.GetQualifiedPort(containerPort); - if (_container.NetworkSettings.Ports.TryGetValue(qualifiedContainerPort, out var portBindings) && ushort.TryParse(portBindings[0].HostPort, out var hostPort)) + if ( + _container.NetworkSettings.Ports.TryGetValue(qualifiedContainerPort, out var portBindings) + && ushort.TryParse(portBindings[0].HostPort, out var hostPort) + ) { return hostPort; } else { - throw new InvalidOperationException($"Exposed port {qualifiedContainerPort} is not mapped."); + throw new InvalidOperationException( + $"Exposed port {qualifiedContainerPort} is not mapped." + ); } } @@ -287,12 +303,11 @@ public IReadOnlyDictionary GetMappedPublicPorts() { ThrowIfResourceNotFound(); - return _container.NetworkSettings.Ports - .Where( - kvp => - { - return kvp.Key.Contains('/') && kvp.Value != null && kvp.Value.Count > 0; - }) + return _container + .NetworkSettings.Ports.Where(kvp => + { + return kvp.Key.Contains('/') && kvp.Value != null && kvp.Value.Count > 0; + }) .ToDictionary( kvp => { @@ -303,7 +318,8 @@ public IReadOnlyDictionary GetMappedPublicPorts() { var hostPort = kvp.Value[0].HostPort; return ushort.Parse(hostPort); - }); + } + ); } /// @@ -313,7 +329,12 @@ public Task GetExitCodeAsync(CancellationToken ct = default) } /// - public Task<(string Stdout, string Stderr)> GetLogsAsync(DateTime since = default, DateTime until = default, bool timestampsEnabled = true, CancellationToken ct = default) + public Task<(string Stdout, string Stderr)> GetLogsAsync( + DateTime since = default, + DateTime until = default, + bool timestampsEnabled = true, + CancellationToken ct = default + ) { return _client.GetContainerLogsAsync(Id, since, until, timestampsEnabled, ct); } @@ -321,10 +342,10 @@ public Task GetExitCodeAsync(CancellationToken ct = default) /// public virtual async Task StartAsync(CancellationToken ct = default) { - using var disposable = await AcquireLockAsync(ct) - .ConfigureAwait(false); + using var disposable = await AcquireLockAsync(ct).ConfigureAwait(false); - var futureResources = Array.Empty() + var futureResources = Array + .Empty() .Concat(_configuration.Mounts) .Concat(_configuration.Networks); @@ -334,51 +355,53 @@ await Task.WhenAll(futureResources.Select(resource => resource.CreateAsync(ct))) await Task.WhenAll(_configuration.Containers.Select(resource => resource.StartAsync(ct))) .ConfigureAwait(false); - await UnsafeCreateAsync(ct) - .ConfigureAwait(false); + await UnsafeCreateAsync(ct).ConfigureAwait(false); - await UnsafeStartAsync(ct) - .ConfigureAwait(false); + await UnsafeStartAsync(ct).ConfigureAwait(false); } /// public virtual async Task StopAsync(CancellationToken ct = default) { - using var disposable = await AcquireLockAsync(ct) - .ConfigureAwait(false); + using var disposable = await AcquireLockAsync(ct).ConfigureAwait(false); - await UnsafeStopAsync(ct) - .ConfigureAwait(false); + await UnsafeStopAsync(ct).ConfigureAwait(false); } /// public async Task PauseAsync(CancellationToken ct = default) { - using var disposable = await AcquireLockAsync(ct) - .ConfigureAwait(false); + using var disposable = await AcquireLockAsync(ct).ConfigureAwait(false); - await UnsafePauseAsync(ct) - .ConfigureAwait(false); + await UnsafePauseAsync(ct).ConfigureAwait(false); } /// public async Task UnpauseAsync(CancellationToken ct = default) { - using var disposable = await AcquireLockAsync(ct) - .ConfigureAwait(false); + using var disposable = await AcquireLockAsync(ct).ConfigureAwait(false); - await UnsafeUnpauseAsync(ct) - .ConfigureAwait(false); + await UnsafeUnpauseAsync(ct).ConfigureAwait(false); } /// - public Task CopyAsync(byte[] fileContent, string filePath, UnixFileModes fileMode = Unix.FileMode644, CancellationToken ct = default) + public Task CopyAsync( + byte[] fileContent, + string filePath, + UnixFileModes fileMode = Unix.FileMode644, + CancellationToken ct = default + ) { return _client.CopyAsync(Id, new BinaryResourceMapping(fileContent, filePath, fileMode), ct); } /// - public Task CopyAsync(string source, string target, UnixFileModes fileMode = Unix.FileMode644, CancellationToken ct = default) + public Task CopyAsync( + string source, + string target, + UnixFileModes fileMode = Unix.FileMode644, + CancellationToken ct = default + ) { var fileAttributes = File.GetAttributes(source); @@ -393,13 +416,23 @@ public Task CopyAsync(string source, string target, UnixFileModes fileMode = Uni } /// - public Task CopyAsync(FileInfo source, string target, UnixFileModes fileMode = Unix.FileMode644, CancellationToken ct = default) + public Task CopyAsync( + FileInfo source, + string target, + UnixFileModes fileMode = Unix.FileMode644, + CancellationToken ct = default + ) { return _client.CopyAsync(Id, source, target, fileMode, ct); } /// - public Task CopyAsync(DirectoryInfo source, string target, UnixFileModes fileMode = Unix.FileMode644, CancellationToken ct = default) + public Task CopyAsync( + DirectoryInfo source, + string target, + UnixFileModes fileMode = Unix.FileMode644, + CancellationToken ct = default + ) { return _client.CopyAsync(Id, source, target, fileMode, ct); } @@ -424,23 +457,19 @@ protected override async ValueTask DisposeAsyncCore() return; } - using (_ = await AcquireLockAsync() - .ConfigureAwait(false)) + using (_ = await AcquireLockAsync().ConfigureAwait(false)) { if (Guid.Empty.Equals(_configuration.SessionId)) { - await UnsafeStopAsync() - .ConfigureAwait(false); + await UnsafeStopAsync().ConfigureAwait(false); } else { - await UnsafeDeleteAsync() - .ConfigureAwait(false); + await UnsafeDeleteAsync().ConfigureAwait(false); } } - await base.DisposeAsyncCore() - .ConfigureAwait(false); + await base.DisposeAsyncCore().ConfigureAwait(false); } /// @@ -456,8 +485,7 @@ protected override async Task UnsafeCreateAsync(CancellationToken ct = default) return; } - await _client.System.LogContainerRuntimeInfoAsync(ct) - .ConfigureAwait(false); + await _client.System.LogContainerRuntimeInfoAsync(ct).ConfigureAwait(false); Creating?.Invoke(this, EventArgs.Empty); @@ -469,7 +497,8 @@ await _client.System.LogContainerRuntimeInfoAsync(ct) var filters = new FilterByReuseHash(_configuration); - var reusableContainers = await _client.Container.GetAllAsync(filters, ct) + var reusableContainers = await _client + .Container.GetAllAsync(filters, ct) .ConfigureAwait(false); var reusableContainer = reusableContainers.SingleOrDefault(); @@ -484,18 +513,15 @@ await _client.System.LogContainerRuntimeInfoAsync(ct) { Logger.ReusableResourceNotFound(); - id = await _client.RunAsync(_configuration, ct) - .ConfigureAwait(false); + id = await _client.RunAsync(_configuration, ct).ConfigureAwait(false); } } else { - id = await _client.RunAsync(_configuration, ct) - .ConfigureAwait(false); + id = await _client.RunAsync(_configuration, ct).ConfigureAwait(false); } - _container = await _client.Container.ByIdAsync(id, ct) - .ConfigureAwait(false); + _container = await _client.Container.ByIdAsync(id, ct).ConfigureAwait(false); CreatedTime = _container.Created; Created?.Invoke(this, EventArgs.Empty); @@ -514,8 +540,7 @@ protected override async Task UnsafeDeleteAsync(CancellationToken ct = default) return; } - await _client.RemoveAsync(_container.ID, ct) - .ConfigureAwait(false); + await _client.RemoveAsync(_container.ID, ct).ConfigureAwait(false); _container = new ContainerInspectResponse(); @@ -538,28 +563,32 @@ protected virtual async Task UnsafeStartAsync(CancellationToken ct = default) WaitStrategy portBindingsMapped = new WaitUntilPortBindingsMapped(this); - await _client.AttachAsync(_container.ID, _configuration.OutputConsumer, ct) + await _client + .AttachAsync(_container.ID, _configuration.OutputConsumer, ct) .ConfigureAwait(false); - await _client.StartAsync(_container.ID, ct) - .ConfigureAwait(false); + await _client.StartAsync(_container.ID, ct).ConfigureAwait(false); - _ = await CheckReadinessAsync(new[] { portBindingsMapped }, ct) - .ConfigureAwait(false); + _ = await CheckReadinessAsync(new[] { portBindingsMapped }, ct).ConfigureAwait(false); Starting?.Invoke(this, EventArgs.Empty); - await _configuration.StartupCallback(this, ct) - .ConfigureAwait(false); + await _configuration.StartupCallback(this, ct).ConfigureAwait(false); Logger.StartReadinessCheck(_container.ID); - _ = await CheckReadinessAsync(_configuration.WaitStrategies, ct) - .ConfigureAwait(false); + _ = await CheckReadinessAsync(_configuration.WaitStrategies, ct).ConfigureAwait(false); Logger.CompleteReadinessCheck(_container.ID); - StartedTime = DateTime.TryParse(_container.State!.StartedAt, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var startedTime) ? startedTime : DateTime.UtcNow; + StartedTime = DateTime.TryParse( + _container.State!.StartedAt, + CultureInfo.InvariantCulture, + DateTimeStyles.AdjustToUniversal, + out var startedTime + ) + ? startedTime + : DateTime.UtcNow; Started?.Invoke(this, EventArgs.Empty); } @@ -582,20 +611,25 @@ protected virtual async Task UnsafeStopAsync(CancellationToken ct = default) Stopping?.Invoke(this, EventArgs.Empty); - await _client.StopAsync(_container.ID, ct) - .ConfigureAwait(false); + await _client.StopAsync(_container.ID, ct).ConfigureAwait(false); try { - _container = await _client.Container.ByIdAsync(_container.ID, ct) - .ConfigureAwait(false); + _container = await _client.Container.ByIdAsync(_container.ID, ct).ConfigureAwait(false); } catch (DockerContainerNotFoundException) { _container = new ContainerInspectResponse(); } - StoppedTime = DateTime.TryParse(_container.State?.FinishedAt, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var stoppedTime) ? stoppedTime : DateTime.UtcNow; + StoppedTime = DateTime.TryParse( + _container.State?.FinishedAt, + CultureInfo.InvariantCulture, + DateTimeStyles.AdjustToUniversal, + out var stoppedTime + ) + ? stoppedTime + : DateTime.UtcNow; Stopped?.Invoke(this, EventArgs.Empty); } @@ -618,11 +652,9 @@ protected virtual async Task UnsafePauseAsync(CancellationToken ct = default) Pausing?.Invoke(this, EventArgs.Empty); - await _client.PauseAsync(_container.ID, ct) - .ConfigureAwait(false); + await _client.PauseAsync(_container.ID, ct).ConfigureAwait(false); - _container = await _client.Container.ByIdAsync(_container.ID, ct) - .ConfigureAwait(false); + _container = await _client.Container.ByIdAsync(_container.ID, ct).ConfigureAwait(false); PausedTime = DateTime.UtcNow; Paused?.Invoke(this, EventArgs.Empty); @@ -647,11 +679,9 @@ protected virtual async Task UnsafeUnpauseAsync(CancellationToken ct = default) Unpausing?.Invoke(this, EventArgs.Empty); - await _client.UnpauseAsync(_container.ID, ct) - .ConfigureAwait(false); + await _client.UnpauseAsync(_container.ID, ct).ConfigureAwait(false); - _container = await _client.Container.ByIdAsync(_container.ID, ct) - .ConfigureAwait(false); + _container = await _client.Container.ByIdAsync(_container.ID, ct).ConfigureAwait(false); UnpausedTime = DateTime.UtcNow; Unpaused?.Invoke(this, EventArgs.Empty); @@ -669,13 +699,14 @@ protected override bool Exists() /// The wait strategy to execute. /// Cancellation token. /// A task representing the asynchronous operation, returning true if the wait strategy indicates readiness; otherwise, false. - private async Task CheckReadinessAsync(WaitStrategy waitStrategy, CancellationToken ct = default) + private async Task CheckReadinessAsync( + WaitStrategy waitStrategy, + CancellationToken ct = default + ) { - _container = await _client.Container.ByIdAsync(_container.ID, ct) - .ConfigureAwait(false); + _container = await _client.Container.ByIdAsync(_container.ID, ct).ConfigureAwait(false); - return await waitStrategy.UntilAsync(this, ct) - .ConfigureAwait(false); + return await waitStrategy.UntilAsync(this, ct).ConfigureAwait(false); } /// @@ -688,11 +719,21 @@ private async Task CheckReadinessAsync(WaitStrategy waitStrategy, Cancella /// The wait strategies to execute. /// Cancellation token. /// A task representing the asynchronous operation, returning true if the wait strategies indicate readiness; otherwise, false. - private async Task CheckReadinessAsync(IEnumerable waitStrategies, CancellationToken ct = default) + private async Task CheckReadinessAsync( + IEnumerable waitStrategies, + CancellationToken ct = default + ) { foreach (var waitStrategy in waitStrategies) { - await WaitStrategy.WaitUntilAsync(() => CheckReadinessAsync(waitStrategy, ct), waitStrategy.Interval, waitStrategy.Timeout, waitStrategy.Retries, ct) + await WaitStrategy + .WaitUntilAsync( + () => CheckReadinessAsync(waitStrategy, ct), + waitStrategy.Interval, + waitStrategy.Timeout, + waitStrategy.Retries, + ct + ) .ConfigureAwait(false); } @@ -712,8 +753,17 @@ public WaitUntilPortBindingsMapped(DockerContainer parent) public override Task UntilAsync(IContainer container, CancellationToken ct = default) { - var boundPorts = _parent._container.NetworkSettings.Ports.Values.Where(portBindings => portBindings != null).SelectMany(portBinding => portBinding).Count(portBinding => !string.IsNullOrEmpty(portBinding.HostPort)); - return Task.FromResult(_parent._configuration.PortBindings == null || /* IPv4 or IPv6 */ _parent._configuration.PortBindings.Count == boundPorts || /* IPv4 and IPv6 */ 2 * _parent._configuration.PortBindings.Count == boundPorts); + var boundPorts = _parent + ._container.NetworkSettings.Ports.Values.Where(portBindings => portBindings != null) + .SelectMany(portBinding => portBinding) + .Count(portBinding => !string.IsNullOrEmpty(portBinding.HostPort)); + return Task.FromResult( + _parent._configuration.PortBindings == null + || /* IPv4 or IPv6 */ + _parent._configuration.PortBindings.Count == boundPorts + || /* IPv4 and IPv6 */ + 2 * _parent._configuration.PortBindings.Count == boundPorts + ); } } } diff --git a/src/Testcontainers/Containers/ExecFailedException.cs b/src/Testcontainers/Containers/ExecFailedException.cs index 804db385a..64f7b292b 100644 --- a/src/Testcontainers/Containers/ExecFailedException.cs +++ b/src/Testcontainers/Containers/ExecFailedException.cs @@ -36,8 +36,8 @@ private static string CreateMessage(ExecResult execResult) if (!string.IsNullOrEmpty(execResult.Stdout)) { - var stdoutLines = execResult.Stdout - .Split(LineEndings, StringSplitOptions.RemoveEmptyEntries) + var stdoutLines = execResult + .Stdout.Split(LineEndings, StringSplitOptions.RemoveEmptyEntries) .Select(line => " " + line); exceptionInfo.AppendLine(); @@ -47,8 +47,8 @@ private static string CreateMessage(ExecResult execResult) if (!string.IsNullOrEmpty(execResult.Stderr)) { - var stderrLines = execResult.Stderr - .Split(LineEndings, StringSplitOptions.RemoveEmptyEntries) + var stderrLines = execResult + .Stderr.Split(LineEndings, StringSplitOptions.RemoveEmptyEntries) .Select(line => " " + line); exceptionInfo.AppendLine(); diff --git a/src/Testcontainers/Containers/ExecResultExtensions.cs b/src/Testcontainers/Containers/ExecResultExtensions.cs index 8f961349a..9281a9cf2 100644 --- a/src/Testcontainers/Containers/ExecResultExtensions.cs +++ b/src/Testcontainers/Containers/ExecResultExtensions.cs @@ -15,12 +15,17 @@ public static class ExecResultExtensions /// A list of exit codes that should be treated as successful. If none are provided, only exit code 0 is treated as successful. /// The if the exit code is in the list of success exit codes. /// Thrown if the exit code is not in the list of success exit codes. - public static async Task ThrowOnFailure(this Task execTask, params long[] successExitCodes) + public static async Task ThrowOnFailure( + this Task execTask, + params long[] successExitCodes + ) { - successExitCodes = successExitCodes == null || successExitCodes.Length == 0 ? new long[] { 0 } : successExitCodes; + successExitCodes = + successExitCodes == null || successExitCodes.Length == 0 + ? new long[] { 0 } + : successExitCodes; - var execResult = await execTask - .ConfigureAwait(false); + var execResult = await execTask.ConfigureAwait(false); if (Array.IndexOf(successExitCodes, execResult.ExitCode) < 0) { diff --git a/src/Testcontainers/Containers/IContainer.cs b/src/Testcontainers/Containers/IContainer.cs index 761b6a74c..145e779bf 100644 --- a/src/Testcontainers/Containers/IContainer.cs +++ b/src/Testcontainers/Containers/IContainer.cs @@ -213,7 +213,12 @@ public interface IContainer : IAsyncDisposable /// Determines whether every log line contains a timestamp or not. /// Cancellation token. /// Returns the container logs. - Task<(string Stdout, string Stderr)> GetLogsAsync(DateTime since = default, DateTime until = default, bool timestampsEnabled = true, CancellationToken ct = default); + Task<(string Stdout, string Stderr)> GetLogsAsync( + DateTime since = default, + DateTime until = default, + bool timestampsEnabled = true, + CancellationToken ct = default + ); /// /// Starts the container. @@ -260,7 +265,12 @@ public interface IContainer : IAsyncDisposable /// The POSIX file mode permission. /// Cancellation token. /// - Task CopyAsync(byte[] fileContent, string filePath, UnixFileModes fileMode = Unix.FileMode644, CancellationToken ct = default); + Task CopyAsync( + byte[] fileContent, + string filePath, + UnixFileModes fileMode = Unix.FileMode644, + CancellationToken ct = default + ); /// /// Copies a test host directory or file to the container. @@ -270,7 +280,12 @@ public interface IContainer : IAsyncDisposable /// The POSIX file mode permission. /// Cancellation token. /// A task that completes when the directory or file has been copied. - Task CopyAsync(string source, string target, UnixFileModes fileMode = Unix.FileMode644, CancellationToken ct = default); + Task CopyAsync( + string source, + string target, + UnixFileModes fileMode = Unix.FileMode644, + CancellationToken ct = default + ); /// /// Copies a test host directory to the container. @@ -280,7 +295,12 @@ public interface IContainer : IAsyncDisposable /// The POSIX file mode permission. /// Cancellation token. /// A task that completes when the directory has been copied. - Task CopyAsync(DirectoryInfo source, string target, UnixFileModes fileMode = Unix.FileMode644, CancellationToken ct = default); + Task CopyAsync( + DirectoryInfo source, + string target, + UnixFileModes fileMode = Unix.FileMode644, + CancellationToken ct = default + ); /// /// Copies a test host file to the container. @@ -290,7 +310,12 @@ public interface IContainer : IAsyncDisposable /// The POSIX file mode permission. /// Cancellation token. /// A task that completes when the file has been copied. - Task CopyAsync(FileInfo source, string target, UnixFileModes fileMode = Unix.FileMode644, CancellationToken ct = default); + Task CopyAsync( + FileInfo source, + string target, + UnixFileModes fileMode = Unix.FileMode644, + CancellationToken ct = default + ); /// /// Reads a file from the container. diff --git a/src/Testcontainers/Containers/PortForwarding.cs b/src/Testcontainers/Containers/PortForwarding.cs index dcb768900..03f5a2d82 100644 --- a/src/Testcontainers/Containers/PortForwarding.cs +++ b/src/Testcontainers/Containers/PortForwarding.cs @@ -17,9 +17,7 @@ internal sealed class PortForwardingContainer : DockerContainer { private readonly PortForwardingConfiguration _configuration; - static PortForwardingContainer() - { - } + static PortForwardingContainer() { } /// /// Initializes a new instance of the class. @@ -34,8 +32,7 @@ private PortForwardingContainer(PortForwardingConfiguration configuration) /// /// Gets the instance. /// - public static PortForwardingContainer Instance { get; } - = new PortForwardingBuilder().Build(); + public static PortForwardingContainer Instance { get; } = new PortForwardingBuilder().Build(); /// /// Exposes the host ports using SSH port forwarding. @@ -45,10 +42,22 @@ private PortForwardingContainer(PortForwardingConfiguration configuration) /// A task that completes when the host ports are forwarded. public Task ExposeHostPortsAsync(IEnumerable ports, CancellationToken ct = default) { - var sshClient = new SshClient(Hostname, GetMappedPublicPort(PortForwardingBuilder.SshdPort), _configuration.Username, _configuration.Password); + var sshClient = new SshClient( + Hostname, + GetMappedPublicPort(PortForwardingBuilder.SshdPort), + _configuration.Username, + _configuration.Password + ); sshClient.Connect(); - foreach (var forwardedPort in ports.Select(port => new ForwardedPortRemote(IPAddress.Loopback, port, IPAddress.Loopback, port))) + foreach ( + var forwardedPort in ports.Select(port => new ForwardedPortRemote( + IPAddress.Loopback, + port, + IPAddress.Loopback, + port + )) + ) { sshClient.AddForwardedPort(forwardedPort); forwardedPort.Start(); @@ -59,7 +68,12 @@ public Task ExposeHostPortsAsync(IEnumerable ports, CancellationToken ct /// [PublicAPI] - private sealed class PortForwardingBuilder : ContainerBuilder + private sealed class PortForwardingBuilder + : ContainerBuilder< + PortForwardingBuilder, + PortForwardingContainer, + PortForwardingConfiguration + > { public const string SshdImage = "testcontainers/sshd:1.2.0"; @@ -96,7 +110,9 @@ public override PortForwardingContainer Build() // instance of the port forwarding container. To improve the user experience, it // is preferable to stop supporting `WithDockerEndpoint(string)` and instead rely // on the environment variables or the properties file custom configurations. - return DockerResourceConfiguration.DockerEndpointAuthConfig == null ? null : new PortForwardingContainer(DockerResourceConfiguration); + return DockerResourceConfiguration.DockerEndpointAuthConfig == null + ? null + : new PortForwardingContainer(DockerResourceConfiguration); } /// @@ -111,19 +127,30 @@ protected override PortForwardingBuilder Init() } /// - protected override PortForwardingBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override PortForwardingBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { - return Merge(DockerResourceConfiguration, new PortForwardingConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new PortForwardingConfiguration(resourceConfiguration) + ); } /// protected override PortForwardingBuilder Clone(IContainerConfiguration resourceConfiguration) { - return Merge(DockerResourceConfiguration, new PortForwardingConfiguration(resourceConfiguration)); + return Merge( + DockerResourceConfiguration, + new PortForwardingConfiguration(resourceConfiguration) + ); } /// - protected override PortForwardingBuilder Merge(PortForwardingConfiguration oldValue, PortForwardingConfiguration newValue) + protected override PortForwardingBuilder Merge( + PortForwardingConfiguration oldValue, + PortForwardingConfiguration newValue + ) { return new PortForwardingBuilder(new PortForwardingConfiguration(oldValue, newValue)); } @@ -135,7 +162,10 @@ protected override PortForwardingBuilder Merge(PortForwardingConfiguration oldVa /// A configured instance of . private PortForwardingBuilder WithUsername(string username) { - return Merge(DockerResourceConfiguration, new PortForwardingConfiguration(username: username)) + return Merge( + DockerResourceConfiguration, + new PortForwardingConfiguration(username: username) + ) .WithEnvironment("USERNAME", username); } @@ -146,7 +176,10 @@ private PortForwardingBuilder WithUsername(string username) /// A configured instance of . private PortForwardingBuilder WithPassword(string password) { - return Merge(DockerResourceConfiguration, new PortForwardingConfiguration(password: password)) + return Merge( + DockerResourceConfiguration, + new PortForwardingConfiguration(password: password) + ) .WithEnvironment("PASSWORD", password); } } @@ -160,9 +193,7 @@ public sealed class PortForwardingConfiguration : ContainerConfiguration /// /// The OpenSSH daemon username. /// The OpenSSH daemon password. - public PortForwardingConfiguration( - string username = null, - string password = null) + public PortForwardingConfiguration(string username = null, string password = null) { Username = username; Password = password; @@ -172,7 +203,9 @@ public PortForwardingConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public PortForwardingConfiguration(IResourceConfiguration resourceConfiguration) + public PortForwardingConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. @@ -203,7 +236,10 @@ public PortForwardingConfiguration(PortForwardingConfiguration resourceConfigura /// /// The old Docker resource configuration. /// The new Docker resource configuration. - public PortForwardingConfiguration(PortForwardingConfiguration oldValue, PortForwardingConfiguration newValue) + public PortForwardingConfiguration( + PortForwardingConfiguration oldValue, + PortForwardingConfiguration newValue + ) : base(oldValue, newValue) { Username = BuildConfiguration.Combine(oldValue.Username, newValue.Username); diff --git a/src/Testcontainers/Containers/ResourceReaper.cs b/src/Testcontainers/Containers/ResourceReaper.cs index 70d672871..bad9c7463 100644 --- a/src/Testcontainers/Containers/ResourceReaper.cs +++ b/src/Testcontainers/Containers/ResourceReaper.cs @@ -19,7 +19,8 @@ namespace DotNet.Testcontainers.Containers [PublicAPI] public sealed class ResourceReaper : IAsyncDisposable { - public const string ResourceReaperSessionLabel = TestcontainersClient.TestcontainersLabel + ".resource-reaper-session"; + public const string ResourceReaperSessionLabel = + TestcontainersClient.TestcontainersLabel + ".resource-reaper-session"; private const ushort RyukPort = 8080; @@ -49,11 +50,16 @@ public sealed class ResourceReaper : IAsyncDisposable private bool _disposed; - static ResourceReaper() - { - } + static ResourceReaper() { } - private ResourceReaper(Guid sessionId, IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, IImage resourceReaperImage, IMount dockerSocket, ILogger logger, bool requiresPrivilegedMode) + private ResourceReaper( + Guid sessionId, + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, + IImage resourceReaperImage, + IMount dockerSocket, + ILogger logger, + bool requiresPrivilegedMode + ) { _resourceReaperContainer = new ContainerBuilder() .WithName($"testcontainers-ryuk-{sessionId:D}") @@ -62,7 +68,10 @@ private ResourceReaper(Guid sessionId, IDockerEndpointAuthenticationConfiguratio .WithPrivileged(requiresPrivilegedMode) .WithAutoRemove(true) .WithCleanUp(false) - .WithPortBinding(TestcontainersSettings.ResourceReaperPublicHostPort.Invoke(dockerEndpointAuthConfig), RyukPort) + .WithPortBinding( + TestcontainersSettings.ResourceReaperPublicHostPort.Invoke(dockerEndpointAuthConfig), + RyukPort + ) .WithMount(dockerSocket) .WithLogger(logger) .Build(); @@ -87,8 +96,7 @@ private ResourceReaper(Guid sessionId, IDockerEndpointAuthenticationConfiguratio /// or if a is configured with . /// [PublicAPI] - public static Guid DefaultSessionId { get; } - = Guid.NewGuid(); + public static Guid DefaultSessionId { get; } = Guid.NewGuid(); /// /// Gets the session id. @@ -105,7 +113,12 @@ private ResourceReaper(Guid sessionId, IDockerEndpointAuthenticationConfiguratio /// The cancellation token to cancel the initialization. /// Task that completes when the has been started. [PublicAPI] - public static async Task GetAndStartDefaultAsync(IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, ILogger logger, bool isWindowsEngineEnabled = false, CancellationToken ct = default) + public static async Task GetAndStartDefaultAsync( + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, + ILogger logger, + bool isWindowsEngineEnabled = false, + CancellationToken ct = default + ) { if (isWindowsEngineEnabled) { @@ -117,8 +130,7 @@ public static async Task GetAndStartDefaultAsync(IDockerEndpoint return _defaultInstance; } - await DefaultLock.WaitAsync(ct) - .ConfigureAwait(false); + await DefaultLock.WaitAsync(ct).ConfigureAwait(false); if (_defaultInstance != null && !_defaultInstance._disposed) { @@ -132,7 +144,15 @@ await DefaultLock.WaitAsync(ct) var requiresPrivilegedMode = TestcontainersSettings.ResourceReaperPrivilegedModeEnabled; - _defaultInstance = await GetAndStartNewAsync(DefaultSessionId, dockerEndpointAuthConfig, resourceReaperImage, new UnixSocketMount(dockerEndpointAuthConfig.Endpoint), logger, requiresPrivilegedMode, ct: ct) + _defaultInstance = await GetAndStartNewAsync( + DefaultSessionId, + dockerEndpointAuthConfig, + resourceReaperImage, + new UnixSocketMount(dockerEndpointAuthConfig.Endpoint), + logger, + requiresPrivilegedMode, + ct: ct + ) .ConfigureAwait(false); return _defaultInstance; @@ -157,15 +177,13 @@ public async ValueTask DisposeAsync() try { #if NET6_0_OR_GREATER - await _maintainConnectionCts.CancelAsync() - .ConfigureAwait(false); + await _maintainConnectionCts.CancelAsync().ConfigureAwait(false); #else _maintainConnectionCts.Cancel(); #endif // Close connection before disposing Resource Reaper. - await _maintainConnectionTask - .ConfigureAwait(false); + await _maintainConnectionTask.ConfigureAwait(false); } finally { @@ -174,8 +192,7 @@ await _maintainConnectionTask if (_resourceReaperContainer != null) { - await _resourceReaperContainer.DisposeAsync() - .ConfigureAwait(false); + await _resourceReaperContainer.DisposeAsync().ConfigureAwait(false); } } @@ -191,9 +208,26 @@ await _resourceReaperContainer.DisposeAsync() /// The cancellation token to cancel the initialization. /// Task that completes when the has been started. [PublicAPI] - private static Task GetAndStartNewAsync(IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, IImage resourceReaperImage, IMount dockerSocket, ILogger logger, bool requiresPrivilegedMode = false, TimeSpan initTimeout = default, CancellationToken ct = default) + private static Task GetAndStartNewAsync( + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, + IImage resourceReaperImage, + IMount dockerSocket, + ILogger logger, + bool requiresPrivilegedMode = false, + TimeSpan initTimeout = default, + CancellationToken ct = default + ) { - return GetAndStartNewAsync(Guid.NewGuid(), dockerEndpointAuthConfig, resourceReaperImage, dockerSocket, logger, requiresPrivilegedMode, initTimeout, ct); + return GetAndStartNewAsync( + Guid.NewGuid(), + dockerEndpointAuthConfig, + resourceReaperImage, + dockerSocket, + logger, + requiresPrivilegedMode, + initTimeout, + ct + ); } /// @@ -209,41 +243,79 @@ private static Task GetAndStartNewAsync(IDockerEndpointAuthentic /// The cancellation token to cancel the initialization. /// Task that completes when the has been started. [PublicAPI] - private static async Task GetAndStartNewAsync(Guid sessionId, IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, IImage resourceReaperImage, IMount dockerSocket, ILogger logger, bool requiresPrivilegedMode = false, TimeSpan initTimeout = default, CancellationToken ct = default) + private static async Task GetAndStartNewAsync( + Guid sessionId, + IDockerEndpointAuthenticationConfiguration dockerEndpointAuthConfig, + IImage resourceReaperImage, + IMount dockerSocket, + ILogger logger, + bool requiresPrivilegedMode = false, + TimeSpan initTimeout = default, + CancellationToken ct = default + ) { var ryukInitializedTaskSource = new TaskCompletionSource(); - var resourceReaper = new ResourceReaper(sessionId, dockerEndpointAuthConfig, resourceReaperImage, dockerSocket, logger, requiresPrivilegedMode); + var resourceReaper = new ResourceReaper( + sessionId, + dockerEndpointAuthConfig, + resourceReaperImage, + dockerSocket, + logger, + requiresPrivilegedMode + ); - initTimeout = TimeSpan.Equals(TimeSpan.Zero, initTimeout) ? TimeSpan.FromSeconds(ConnectionTimeoutInSeconds) : initTimeout; + initTimeout = TimeSpan.Equals(TimeSpan.Zero, initTimeout) + ? TimeSpan.FromSeconds(ConnectionTimeoutInSeconds) + : initTimeout; try { - StateChanged?.Invoke(null, new ResourceReaperStateEventArgs(resourceReaper, ResourceReaperState.Created)); + StateChanged?.Invoke( + null, + new ResourceReaperStateEventArgs(resourceReaper, ResourceReaperState.Created) + ); - await resourceReaper._resourceReaperContainer.StartAsync(ct) - .ConfigureAwait(false); + await resourceReaper._resourceReaperContainer.StartAsync(ct).ConfigureAwait(false); - StateChanged?.Invoke(null, new ResourceReaperStateEventArgs(resourceReaper, ResourceReaperState.InitializingConnection)); + StateChanged?.Invoke( + null, + new ResourceReaperStateEventArgs( + resourceReaper, + ResourceReaperState.InitializingConnection + ) + ); using (var initTimeoutCts = new CancellationTokenSource()) { - using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(initTimeoutCts.Token, ct)) + using ( + var linkedCts = CancellationTokenSource.CreateLinkedTokenSource( + initTimeoutCts.Token, + ct + ) + ) { - resourceReaper._maintainConnectionTask = resourceReaper.MaintainRyukConnection(ryukInitializedTaskSource, linkedCts.Token); + resourceReaper._maintainConnectionTask = resourceReaper.MaintainRyukConnection( + ryukInitializedTaskSource, + linkedCts.Token + ); initTimeoutCts.CancelAfter(initTimeout); - await ryukInitializedTaskSource.Task - .ConfigureAwait(false); + await ryukInitializedTaskSource.Task.ConfigureAwait(false); } } - StateChanged?.Invoke(null, new ResourceReaperStateEventArgs(resourceReaper, ResourceReaperState.MaintainingConnection)); + StateChanged?.Invoke( + null, + new ResourceReaperStateEventArgs( + resourceReaper, + ResourceReaperState.MaintainingConnection + ) + ); } catch (Exception) { - await resourceReaper.DisposeAsync() - .ConfigureAwait(false); + await resourceReaper.DisposeAsync().ConfigureAwait(false); throw; } @@ -283,9 +355,17 @@ private bool TryGetEndpoint(out string host, out ushort port) /// /// The task that completes after the initialization. /// The cancellation token to cancel the initialization. This will not cancel the maintained connection. - private async Task MaintainRyukConnection(TaskCompletionSource ryukInitializedTaskSource, CancellationToken ct) + private async Task MaintainRyukConnection( + TaskCompletionSource ryukInitializedTaskSource, + CancellationToken ct + ) { - connect_to_ryuk: while (!_maintainConnectionCts.IsCancellationRequested && !ct.IsCancellationRequested && !ryukInitializedTaskSource.Task.IsCompleted) + connect_to_ryuk: + while ( + !_maintainConnectionCts.IsCancellationRequested + && !ct.IsCancellationRequested + && !ryukInitializedTaskSource.Task.IsCompleted + ) { if (!TryGetEndpoint(out var host, out var port)) { @@ -302,11 +382,9 @@ await Task.Delay(TimeSpan.FromSeconds(RetryTimeoutInSeconds), CancellationToken. try { #if NET6_0_OR_GREATER - await tcpClient.ConnectAsync(host, port, ct) - .ConfigureAwait(false); + await tcpClient.ConnectAsync(host, port, ct).ConfigureAwait(false); #else - await tcpClient.ConnectAsync(host, port) - .ConfigureAwait(false); + await tcpClient.ConnectAsync(host, port).ConfigureAwait(false); #endif var stream = tcpClient.GetStream(); @@ -322,26 +400,23 @@ await tcpClient.ConnectAsync(host, port) using (var messageBuffer = new MemoryStream()) { #if NETSTANDARD2_0 - await stream.WriteAsync(sendBytes, 0, sendBytes.Length, ct) - .ConfigureAwait(false); + await stream.WriteAsync(sendBytes, 0, sendBytes.Length, ct).ConfigureAwait(false); #else - await stream.WriteAsync(sendBytes, ct) - .ConfigureAwait(false); + await stream.WriteAsync(sendBytes, ct).ConfigureAwait(false); #endif - await stream.FlushAsync(ct) - .ConfigureAwait(false); + await stream.FlushAsync(ct).ConfigureAwait(false); bool hasAcknowledge; do { #if NETSTANDARD2_0 - var numberOfBytes = await stream.ReadAsync(readBytes, 0, readBytes.Length, ct) + var numberOfBytes = await stream + .ReadAsync(readBytes, 0, readBytes.Length, ct) .ConfigureAwait(false); #else - var numberOfBytes = await stream.ReadAsync(readBytes, ct) - .ConfigureAwait(false); + var numberOfBytes = await stream.ReadAsync(readBytes, ct).ConfigureAwait(false); #endif if (numberOfBytes == 0) @@ -364,10 +439,12 @@ await Task.Delay(TimeSpan.FromSeconds(RetryTimeoutInSeconds), ct) { // We have not received the entire message yet. Read from stream again. #if NETSTANDARD2_0 - await messageBuffer.WriteAsync(readBytes, 0, numberOfBytes, ct) + await messageBuffer + .WriteAsync(readBytes, 0, numberOfBytes, ct) .ConfigureAwait(false); #else - await messageBuffer.WriteAsync(readBytes.AsMemory(0, numberOfBytes), ct) + await messageBuffer + .WriteAsync(readBytes.AsMemory(0, numberOfBytes), ct) .ConfigureAwait(false); #endif @@ -376,18 +453,22 @@ await messageBuffer.WriteAsync(readBytes.AsMemory(0, numberOfBytes), ct) else { #if NETSTANDARD2_0 - await messageBuffer.WriteAsync(readBytes, 0, indexOfNewLine, ct) + await messageBuffer + .WriteAsync(readBytes, 0, indexOfNewLine, ct) .ConfigureAwait(false); #else - await messageBuffer.WriteAsync(readBytes.AsMemory(0, indexOfNewLine), ct) + await messageBuffer + .WriteAsync(readBytes.AsMemory(0, indexOfNewLine), ct) .ConfigureAwait(false); #endif - hasAcknowledge = "ack".Equals(Encoding.ASCII.GetString(messageBuffer.ToArray()), StringComparison.OrdinalIgnoreCase); + hasAcknowledge = "ack".Equals( + Encoding.ASCII.GetString(messageBuffer.ToArray()), + StringComparison.OrdinalIgnoreCase + ); messageBuffer.SetLength(0); } - } - while (!hasAcknowledge); + } while (!hasAcknowledge); ryukInitializedTaskSource.SetResult(true); } @@ -397,10 +478,12 @@ await messageBuffer.WriteAsync(readBytes.AsMemory(0, indexOfNewLine), ct) { // Keep the connection to Ryuk up. #if NETSTANDARD2_0 - _ = await stream.ReadAsync(readBytes, 0, readBytes.Length, _maintainConnectionCts.Token) + _ = await stream + .ReadAsync(readBytes, 0, readBytes.Length, _maintainConnectionCts.Token) .ConfigureAwait(false); #else - _ = await stream.ReadAsync(readBytes, _maintainConnectionCts.Token) + _ = await stream + .ReadAsync(readBytes, _maintainConnectionCts.Token) .ConfigureAwait(false); #endif } @@ -418,7 +501,12 @@ await Task.Delay(TimeSpan.FromSeconds(RetryTimeoutInSeconds), CancellationToken. } catch (Exception e) { - _resourceReaperContainer.Logger.LostConnectionToResourceReaper(SessionId, host, port, e); + _resourceReaperContainer.Logger.LostConnectionToResourceReaper( + SessionId, + host, + port, + e + ); await Task.Delay(TimeSpan.FromSeconds(RetryTimeoutInSeconds), CancellationToken.None) .ConfigureAwait(false); @@ -428,17 +516,24 @@ await Task.Delay(TimeSpan.FromSeconds(RetryTimeoutInSeconds), CancellationToken. if (ryukInitializedTaskSource.Task.IsCompleted) { - StateChanged?.Invoke(null, new ResourceReaperStateEventArgs(this, ResourceReaperState.ConnectionTerminated)); + StateChanged?.Invoke( + null, + new ResourceReaperStateEventArgs(this, ResourceReaperState.ConnectionTerminated) + ); return; } if (ct.IsCancellationRequested) { - ryukInitializedTaskSource.SetException(new ResourceReaperException("Initialization has been cancelled.")); + ryukInitializedTaskSource.SetException( + new ResourceReaperException("Initialization has been cancelled.") + ); } else { - ryukInitializedTaskSource.SetException(new ResourceReaperException("Initialization failed.")); + ryukInitializedTaskSource.SetException( + new ResourceReaperException("Initialization failed.") + ); } } @@ -449,18 +544,20 @@ private sealed class UnixSocketMount : IMount public UnixSocketMount([NotNull] Uri dockerEndpoint) { // If the Docker endpoint is a Unix socket, extract the socket path from the URI; otherwise, fallback to the default Unix socket path. - Source = "unix".Equals(dockerEndpoint.Scheme, StringComparison.OrdinalIgnoreCase) ? dockerEndpoint.AbsolutePath : DockerSocketFilePath; + Source = "unix".Equals(dockerEndpoint.Scheme, StringComparison.OrdinalIgnoreCase) + ? dockerEndpoint.AbsolutePath + : DockerSocketFilePath; // If the user has overridden the Docker socket path, use the user-specified path; otherwise, keep the previously determined source. - Source = !string.IsNullOrEmpty(TestcontainersSettings.DockerSocketOverride) ? TestcontainersSettings.DockerSocketOverride : Source; + Source = !string.IsNullOrEmpty(TestcontainersSettings.DockerSocketOverride) + ? TestcontainersSettings.DockerSocketOverride + : Source; Target = DockerSocketFilePath; } - public MountType Type - => MountType.Bind; + public MountType Type => MountType.Bind; - public AccessMode AccessMode - => AccessMode.ReadOnly; + public AccessMode AccessMode => AccessMode.ReadOnly; public string Source { get; } diff --git a/src/Testcontainers/Containers/ResourceReaperException.cs b/src/Testcontainers/Containers/ResourceReaperException.cs index f1784141b..8035744ae 100644 --- a/src/Testcontainers/Containers/ResourceReaperException.cs +++ b/src/Testcontainers/Containers/ResourceReaperException.cs @@ -5,8 +5,6 @@ namespace DotNet.Testcontainers.Containers public sealed class ResourceReaperException : Exception { public ResourceReaperException(string message) - : base(message) - { - } + : base(message) { } } } diff --git a/src/Testcontainers/Containers/ResourceReaperStateEventArgs.cs b/src/Testcontainers/Containers/ResourceReaperStateEventArgs.cs index 61d70b554..39adf739f 100644 --- a/src/Testcontainers/Containers/ResourceReaperStateEventArgs.cs +++ b/src/Testcontainers/Containers/ResourceReaperStateEventArgs.cs @@ -14,7 +14,10 @@ public sealed class ResourceReaperStateEventArgs : EventArgs /// /// The Resource Reaper instance. /// The Resource Reaper state. - public ResourceReaperStateEventArgs(ResourceReaper resourceReaper, ResourceReaperState resourceReaperState) + public ResourceReaperStateEventArgs( + ResourceReaper resourceReaper, + ResourceReaperState resourceReaperState + ) { Instance = resourceReaper; State = resourceReaperState; diff --git a/src/Testcontainers/Containers/SocatBuilder.cs b/src/Testcontainers/Containers/SocatBuilder.cs index fef22f990..1df88302d 100644 --- a/src/Testcontainers/Containers/SocatBuilder.cs +++ b/src/Testcontainers/Containers/SocatBuilder.cs @@ -10,7 +10,8 @@ namespace DotNet.Testcontainers.Containers /// [PublicAPI] - public sealed class SocatBuilder : ContainerBuilder + public sealed class SocatBuilder + : ContainerBuilder { public const string SocatImage = "alpine/socat:1.7.4.3-r0"; @@ -68,11 +69,17 @@ public override SocatContainer Build() const string argument = "socat TCP-LISTEN:{0},fork,reuseaddr TCP:{1}"; - var command = string.Join(" & ", DockerResourceConfiguration.Targets - .Select(item => string.Format(argument, item.Key, item.Value))); + var command = string.Join( + " & ", + DockerResourceConfiguration.Targets.Select(item => + string.Format(argument, item.Key, item.Value) + ) + ); - var waitStrategy = DockerResourceConfiguration.Targets - .Aggregate(Wait.ForUnixContainer(), (waitStrategy, item) => waitStrategy.UntilPortIsAvailable(item.Key)); + var waitStrategy = DockerResourceConfiguration.Targets.Aggregate( + Wait.ForUnixContainer(), + (waitStrategy, item) => waitStrategy.UntilPortIsAvailable(item.Key) + ); var socatBuilder = WithCommand(command).WithWaitStrategy(waitStrategy); return new SocatContainer(socatBuilder.DockerResourceConfiguration); @@ -81,9 +88,7 @@ public override SocatContainer Build() /// protected override SocatBuilder Init() { - return base.Init() - .WithImage(SocatImage) - .WithEntrypoint("/bin/sh", "-c"); + return base.Init().WithImage(SocatImage).WithEntrypoint("/bin/sh", "-c"); } /// @@ -93,12 +98,18 @@ protected override void Validate() base.Validate(); - _ = Guard.Argument(DockerResourceConfiguration.Targets, nameof(DockerResourceConfiguration.Targets)) - .ThrowIf(argument => argument.Value.Count == 0, argument => new ArgumentException(message, argument.Name)); + _ = Guard + .Argument(DockerResourceConfiguration.Targets, nameof(DockerResourceConfiguration.Targets)) + .ThrowIf( + argument => argument.Value.Count == 0, + argument => new ArgumentException(message, argument.Name) + ); } /// - protected override SocatBuilder Clone(IResourceConfiguration resourceConfiguration) + protected override SocatBuilder Clone( + IResourceConfiguration resourceConfiguration + ) { return Merge(DockerResourceConfiguration, new SocatConfiguration(resourceConfiguration)); } diff --git a/src/Testcontainers/Containers/SocatConfiguration.cs b/src/Testcontainers/Containers/SocatConfiguration.cs index e1f9c0384..8bb29ae79 100644 --- a/src/Testcontainers/Containers/SocatConfiguration.cs +++ b/src/Testcontainers/Containers/SocatConfiguration.cs @@ -14,8 +14,7 @@ public sealed class SocatConfiguration : ContainerConfiguration /// Initializes a new instance of the class. /// /// A list of target addresses. - public SocatConfiguration( - IReadOnlyDictionary targets = null) + public SocatConfiguration(IReadOnlyDictionary targets = null) { Targets = targets; } @@ -24,7 +23,9 @@ public SocatConfiguration( /// Initializes a new instance of the class. /// /// The Docker resource configuration. - public SocatConfiguration(IResourceConfiguration resourceConfiguration) + public SocatConfiguration( + IResourceConfiguration resourceConfiguration + ) : base(resourceConfiguration) { // Passes the configuration upwards to the base implementations to create an updated immutable copy. diff --git a/src/Testcontainers/Containers/SocatContainer.cs b/src/Testcontainers/Containers/SocatContainer.cs index c18f20b29..f9a6faaba 100644 --- a/src/Testcontainers/Containers/SocatContainer.cs +++ b/src/Testcontainers/Containers/SocatContainer.cs @@ -11,8 +11,6 @@ public sealed class SocatContainer : DockerContainer /// /// The container configuration. public SocatContainer(SocatConfiguration configuration) - : base(configuration) - { - } + : base(configuration) { } } } diff --git a/src/Testcontainers/Containers/TarOutputMemoryStream.cs b/src/Testcontainers/Containers/TarOutputMemoryStream.cs index 99ae0d99c..f265258ae 100644 --- a/src/Testcontainers/Containers/TarOutputMemoryStream.cs +++ b/src/Testcontainers/Containers/TarOutputMemoryStream.cs @@ -58,8 +58,7 @@ public TarOutputMemoryStream(ILogger logger) /// Cancellation token. public async Task AddAsync(IResourceMapping resourceMapping, CancellationToken ct = default) { - var fileContent = await resourceMapping.GetAllBytesAsync(ct) - .ConfigureAwait(false); + var fileContent = await resourceMapping.GetAllBytesAsync(ct).ConfigureAwait(false); var targetFilePath = Unix.Instance.NormalizePath(resourceMapping.Target); @@ -69,21 +68,21 @@ public async Task AddAsync(IResourceMapping resourceMapping, CancellationToken c tarEntry.TarHeader.ModTime = DateTime.UtcNow; tarEntry.Size = fileContent.Length; - _logger.LogInformation("Add file to tar archive: Content length: {Length} byte(s), Target file: \"{Target}\"", tarEntry.Size, targetFilePath); + _logger.LogInformation( + "Add file to tar archive: Content length: {Length} byte(s), Target file: \"{Target}\"", + tarEntry.Size, + targetFilePath + ); - await PutNextEntryAsync(tarEntry, ct) - .ConfigureAwait(false); + await PutNextEntryAsync(tarEntry, ct).ConfigureAwait(false); #if NETSTANDARD2_0 - await WriteAsync(fileContent, 0, fileContent.Length, ct) - .ConfigureAwait(false); + await WriteAsync(fileContent, 0, fileContent.Length, ct).ConfigureAwait(false); #else - await WriteAsync(fileContent, ct) - .ConfigureAwait(false); + await WriteAsync(fileContent, ct).ConfigureAwait(false); #endif - await CloseEntryAsync(ct) - .ConfigureAwait(false); + await CloseEntryAsync(ct).ConfigureAwait(false); _ = Interlocked.Add(ref _contentLength, tarEntry.Size); } @@ -107,14 +106,18 @@ public Task AddAsync(FileInfo file, UnixFileModes fileMode, CancellationToken ct /// A value indicating whether the current directory and all its subdirectories are included or not. /// The POSIX file mode permission. /// Cancellation token. - public async Task AddAsync(DirectoryInfo directory, bool recurse, UnixFileModes fileMode, CancellationToken ct = default) + public async Task AddAsync( + DirectoryInfo directory, + bool recurse, + UnixFileModes fileMode, + CancellationToken ct = default + ) { var searchOption = recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; foreach (var file in directory.GetFiles("*", searchOption)) { - await AddAsync(directory, file, fileMode, ct) - .ConfigureAwait(false); + await AddAsync(directory, file, fileMode, ct).ConfigureAwait(false); } } @@ -125,11 +128,23 @@ await AddAsync(directory, file, fileMode, ct) /// The file to add to the archive. /// The POSIX file mode permission. /// Cancellation token. - public async Task AddAsync(DirectoryInfo directory, FileInfo file, UnixFileModes fileMode, CancellationToken ct = default) + public async Task AddAsync( + DirectoryInfo directory, + FileInfo file, + UnixFileModes fileMode, + CancellationToken ct = default + ) { using (var stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) { - var targetFilePath = Unix.Instance.NormalizePath(Path.Combine(_targetDirectoryPath, file.FullName.Substring(directory.FullName.TrimEnd(Path.DirectorySeparatorChar).Length + 1))); + var targetFilePath = Unix.Instance.NormalizePath( + Path.Combine( + _targetDirectoryPath, + file.FullName.Substring( + directory.FullName.TrimEnd(Path.DirectorySeparatorChar).Length + 1 + ) + ) + ); var tarEntry = new TarEntry(new TarHeader()); tarEntry.TarHeader.Name = targetFilePath; @@ -137,16 +152,17 @@ public async Task AddAsync(DirectoryInfo directory, FileInfo file, UnixFileModes tarEntry.TarHeader.ModTime = file.LastWriteTimeUtc; tarEntry.Size = stream.Length; - _logger.LogInformation("Add file to tar archive: Source file: \"{Source}\", Target file: \"{Target}\"", tarEntry.TarHeader.Name, targetFilePath); + _logger.LogInformation( + "Add file to tar archive: Source file: \"{Source}\", Target file: \"{Target}\"", + tarEntry.TarHeader.Name, + targetFilePath + ); - await PutNextEntryAsync(tarEntry, ct) - .ConfigureAwait(false); + await PutNextEntryAsync(tarEntry, ct).ConfigureAwait(false); - await stream.CopyToAsync(this, 81920, ct) - .ConfigureAwait(false); + await stream.CopyToAsync(this, 81920, ct).ConfigureAwait(false); - await CloseEntryAsync(ct) - .ConfigureAwait(false); + await CloseEntryAsync(ct).ConfigureAwait(false); _ = Interlocked.Add(ref _contentLength, tarEntry.Size); } diff --git a/src/Testcontainers/Guard.Null.cs b/src/Testcontainers/Guard.Null.cs index 67d3b4a2c..627613c7f 100644 --- a/src/Testcontainers/Guard.Null.cs +++ b/src/Testcontainers/Guard.Null.cs @@ -16,7 +16,10 @@ public static partial class Guard /// The type. /// An instance of the struct. /// Thrown when the condition is not met. - public static ref readonly ArgumentInfo Null(in this ArgumentInfo argument, string exceptionMessage = null) + public static ref readonly ArgumentInfo Null( + in this ArgumentInfo argument, + string exceptionMessage = null + ) where TType : class { if (!argument.HasValue()) @@ -25,7 +28,10 @@ public static ref readonly ArgumentInfo Null(in this ArgumentInfo< } const string message = "'{0}' must be null."; - throw new ArgumentException(exceptionMessage ?? string.Format(CultureInfo.InvariantCulture, message, argument.Name), argument.Name); + throw new ArgumentException( + exceptionMessage ?? string.Format(CultureInfo.InvariantCulture, message, argument.Name), + argument.Name + ); } /// @@ -36,7 +42,10 @@ public static ref readonly ArgumentInfo Null(in this ArgumentInfo< /// The type. /// An instance of the struct. /// Thrown when the condition is not met. - public static ref readonly ArgumentInfo NotNull(in this ArgumentInfo argument, string exceptionMessage = null) + public static ref readonly ArgumentInfo NotNull( + in this ArgumentInfo argument, + string exceptionMessage = null + ) where TType : class { if (argument.HasValue()) @@ -45,7 +54,10 @@ public static ref readonly ArgumentInfo NotNull(in this ArgumentIn } const string message = "'{0}' cannot be null."; - throw new ArgumentException(exceptionMessage ?? string.Format(CultureInfo.InvariantCulture, message, argument.Name), argument.Name); + throw new ArgumentException( + exceptionMessage ?? string.Format(CultureInfo.InvariantCulture, message, argument.Name), + argument.Name + ); } /// @@ -57,7 +69,11 @@ public static ref readonly ArgumentInfo NotNull(in this ArgumentIn /// The type. /// An instance of the struct. /// Thrown when the condition is not met. - public static ArgumentInfo ThrowIf(in this ArgumentInfo argument, Func, bool> condition, Func, Exception> ifClause) + public static ArgumentInfo ThrowIf( + in this ArgumentInfo argument, + Func, bool> condition, + Func, Exception> ifClause + ) { return condition(argument) ? throw ifClause(argument) : argument; } diff --git a/src/Testcontainers/Guard.String.cs b/src/Testcontainers/Guard.String.cs index dad27dc7f..d921f2682 100644 --- a/src/Testcontainers/Guard.String.cs +++ b/src/Testcontainers/Guard.String.cs @@ -16,7 +16,10 @@ public static partial class Guard /// The exception message. /// An instance of the struct. /// Thrown when the condition is not met. - public static ref readonly ArgumentInfo Empty(in this ArgumentInfo argument, string exceptionMessage = null) + public static ref readonly ArgumentInfo Empty( + in this ArgumentInfo argument, + string exceptionMessage = null + ) { if (argument.Value.Length == 0) { @@ -24,7 +27,10 @@ public static ref readonly ArgumentInfo Empty(in this ArgumentInfo @@ -34,7 +40,10 @@ public static ref readonly ArgumentInfo Empty(in this ArgumentInfoThe exception message. /// An instance of the struct. /// Thrown when the condition is not met. - public static ref readonly ArgumentInfo NotEmpty(in this ArgumentInfo argument, string exceptionMessage = null) + public static ref readonly ArgumentInfo NotEmpty( + in this ArgumentInfo argument, + string exceptionMessage = null + ) { if (argument.Value.Length > 0) { @@ -42,7 +51,10 @@ public static ref readonly ArgumentInfo NotEmpty(in this ArgumentInfo @@ -52,7 +64,10 @@ public static ref readonly ArgumentInfo NotEmpty(in this ArgumentInfoThe exception message. /// An instance of the struct. /// Thrown when the condition is not met. - public static ref readonly ArgumentInfo NotUppercase(in this ArgumentInfo argument, string exceptionMessage = null) + public static ref readonly ArgumentInfo NotUppercase( + in this ArgumentInfo argument, + string exceptionMessage = null + ) { if (!argument.Value.Any(char.IsUpper)) { @@ -60,7 +75,10 @@ public static ref readonly ArgumentInfo NotUppercase(in this ArgumentInf } const string message = "'{0}' cannot contain uppercase characters."; - throw new ArgumentException(exceptionMessage ?? string.Format(CultureInfo.InvariantCulture, message, argument.Name), argument.Name); + throw new ArgumentException( + exceptionMessage ?? string.Format(CultureInfo.InvariantCulture, message, argument.Name), + argument.Name + ); } } } diff --git a/src/Testcontainers/Images/DockerIgnoreFile.cs b/src/Testcontainers/Images/DockerIgnoreFile.cs index ccd2e059c..e538777f8 100644 --- a/src/Testcontainers/Images/DockerIgnoreFile.cs +++ b/src/Testcontainers/Images/DockerIgnoreFile.cs @@ -18,10 +18,14 @@ internal sealed class DockerIgnoreFile : IgnoreFile /// .dockerignore file name. /// Dockerfile file name. /// The logger. - public DockerIgnoreFile(string dockerignoreFileDirectory, string dockerignoreFile, string dockerfileFile, ILogger logger) + public DockerIgnoreFile( + string dockerignoreFileDirectory, + string dockerignoreFile, + string dockerfileFile, + ILogger logger + ) : this(new DirectoryInfo(dockerignoreFileDirectory), dockerignoreFile, dockerfileFile, logger) - { - } + { } /// /// Initializes a new instance of the class. @@ -30,19 +34,27 @@ public DockerIgnoreFile(string dockerignoreFileDirectory, string dockerignoreFil /// .dockerignore file name. /// Dockerfile file name. /// The logger. - public DockerIgnoreFile(FileSystemInfo dockerignoreFileDirectory, string dockerignoreFile, string dockerfileFile, ILogger logger) - : base(GetPatterns(dockerignoreFileDirectory, dockerignoreFile, dockerfileFile), logger) - { - } + public DockerIgnoreFile( + FileSystemInfo dockerignoreFileDirectory, + string dockerignoreFile, + string dockerfileFile, + ILogger logger + ) + : base(GetPatterns(dockerignoreFileDirectory, dockerignoreFile, dockerfileFile), logger) { } - private static IEnumerable GetPatterns(FileSystemInfo dockerignoreFileDirectory, string dockerignoreFile, string dockerfileFile) + private static IEnumerable GetPatterns( + FileSystemInfo dockerignoreFileDirectory, + string dockerignoreFile, + string dockerfileFile + ) { var dockerignoreFilePath = Path.Combine(dockerignoreFileDirectory.FullName, dockerignoreFile); // These files are necessary and sent to the Docker daemon. The ADD and COPY instructions do not copy them to the image: // https://docs.docker.com/engine/reference/builder/#dockerignore-file. - var negateNecessaryFiles = new[] { dockerignoreFile, dockerfileFile } - .Select(file => "!" + file); + var negateNecessaryFiles = new[] { dockerignoreFile, dockerfileFile }.Select(file => + "!" + file + ); var dockerignorePatterns = File.Exists(dockerignoreFilePath) ? File.ReadLines(dockerignoreFilePath) diff --git a/src/Testcontainers/Images/DockerImage.cs b/src/Testcontainers/Images/DockerImage.cs index d41a4c1d7..fb2d6f41c 100644 --- a/src/Testcontainers/Images/DockerImage.cs +++ b/src/Testcontainers/Images/DockerImage.cs @@ -36,9 +36,7 @@ public sealed class DockerImage : IImage /// /// The image. public DockerImage(IImage image) - : this(image.Repository, image.Registry, image.Tag, image.Digest) - { - } + : this(image.Repository, image.Registry, image.Tag, image.Digest) { } /// /// Initializes a new instance of the class. @@ -46,9 +44,7 @@ public DockerImage(IImage image) /// The image. /// fedora/httpd:version1.0 where fedora/httpd is the repository and version1.0 the tag. public DockerImage(string image) - : this(GetDockerImage(image)) - { - } + : this(GetDockerImage(image)) { } /// /// Initializes a new instance of the class. @@ -64,30 +60,31 @@ public DockerImage( string registry = null, string tag = null, string digest = null, - string hubImageNamePrefix = null) + string hubImageNamePrefix = null + ) : this( TrimOrDefault(repository), TrimOrDefault(registry), TrimOrDefault(tag, tag == null && digest == null ? LatestTag : null), TrimOrDefault(digest), - hubImageNamePrefix == null ? [] : hubImageNamePrefix.Trim(TrimChars).Split(SlashChar, 2, StringSplitOptions.RemoveEmptyEntries)) - { - } + hubImageNamePrefix == null + ? [] + : hubImageNamePrefix + .Trim(TrimChars) + .Split(SlashChar, 2, StringSplitOptions.RemoveEmptyEntries) + ) { } private DockerImage( string repository, string registry, string tag, string digest, - string[] substitutions) + string[] substitutions + ) { - _ = Guard.Argument(repository, nameof(repository)) - .NotNull() - .NotEmpty() - .NotUppercase(); + _ = Guard.Argument(repository, nameof(repository)).NotNull().NotEmpty().NotUppercase(); - _ = Guard.Argument(substitutions, nameof(substitutions)) - .NotNull(); + _ = Guard.Argument(substitutions, nameof(substitutions)).NotNull(); // The Docker Hub image name prefix may include namespaces, which we need to extract // and prepend to the repository name. The registry itself contains only the hostname. @@ -161,7 +158,12 @@ public bool MatchVersion(Predicate predicate) return false; } - var versionMatch = Regex.Match(Tag, "^(\\d+)(\\.\\d+)?(\\.\\d+)?", RegexOptions.None, TimeSpan.FromSeconds(1)); + var versionMatch = Regex.Match( + Tag, + "^(\\d+)(\\.\\d+)?(\\.\\d+)?", + RegexOptions.None, + TimeSpan.FromSeconds(1) + ); if (!versionMatch.Success) { diff --git a/src/Testcontainers/Images/DockerfileArchive.cs b/src/Testcontainers/Images/DockerfileArchive.cs index 500d49bcb..61e09eb94 100644 --- a/src/Testcontainers/Images/DockerfileArchive.cs +++ b/src/Testcontainers/Images/DockerfileArchive.cs @@ -17,7 +17,11 @@ namespace DotNet.Testcontainers.Images /// internal sealed class DockerfileArchive : ITarArchive { - private static readonly Regex FromLinePattern = new Regex("FROM (?--\\S+\\s)*(?\\S+).*", RegexOptions.None, TimeSpan.FromSeconds(1)); + private static readonly Regex FromLinePattern = new Regex( + "FROM (?--\\S+\\s)*(?\\S+).*", + RegexOptions.None, + TimeSpan.FromSeconds(1) + ); private readonly DirectoryInfo _dockerfileDirectory; @@ -35,10 +39,13 @@ internal sealed class DockerfileArchive : ITarArchive /// Docker image information to create the tar archive for. /// The logger. /// Thrown when the Dockerfile directory does not exist or the directory does not contain a Dockerfile. - public DockerfileArchive(string dockerfileDirectory, string dockerfile, IImage image, ILogger logger) - : this(new DirectoryInfo(dockerfileDirectory), new FileInfo(dockerfile), image, logger) - { - } + public DockerfileArchive( + string dockerfileDirectory, + string dockerfile, + IImage image, + ILogger logger + ) + : this(new DirectoryInfo(dockerfileDirectory), new FileInfo(dockerfile), image, logger) { } /// /// Initializes a new instance of the class. @@ -48,16 +55,26 @@ public DockerfileArchive(string dockerfileDirectory, string dockerfile, IImage i /// Docker image information to create the tar archive for. /// The logger. /// Thrown when the Dockerfile directory does not exist or the directory does not contain a Dockerfile. - public DockerfileArchive(DirectoryInfo dockerfileDirectory, FileInfo dockerfile, IImage image, ILogger logger) + public DockerfileArchive( + DirectoryInfo dockerfileDirectory, + FileInfo dockerfile, + IImage image, + ILogger logger + ) { if (!dockerfileDirectory.Exists) { throw new ArgumentException($"Directory '{dockerfileDirectory.FullName}' does not exist."); } - if (dockerfileDirectory.GetFiles(dockerfile.ToString(), SearchOption.TopDirectoryOnly).Length == 0) + if ( + dockerfileDirectory.GetFiles(dockerfile.ToString(), SearchOption.TopDirectoryOnly).Length + == 0 + ) { - throw new ArgumentException($"{dockerfile} does not exist in '{dockerfileDirectory.FullName}'."); + throw new ArgumentException( + $"{dockerfile} does not exist in '{dockerfileDirectory.FullName}'." + ); } _dockerfileDirectory = dockerfileDirectory; @@ -83,7 +100,9 @@ public IEnumerable GetBaseImages() { const string imageGroup = "image"; - var lines = File.ReadAllLines(Path.Combine(_dockerfileDirectory.FullName, _dockerfile.ToString())) + var lines = File.ReadAllLines( + Path.Combine(_dockerfileDirectory.FullName, _dockerfile.ToString()) + ) .Select(line => line.Trim()) .Where(line => !string.IsNullOrEmpty(line)) .Where(line => !line.StartsWith("#", StringComparison.Ordinal)) @@ -93,7 +112,12 @@ public IEnumerable GetBaseImages() var stages = lines .Select(line => line.Value) - .Select(line => line.Split(new[] { " AS ", " As ", " aS ", " as " }, StringSplitOptions.RemoveEmptyEntries)) + .Select(line => + line.Split( + new[] { " AS ", " As ", " aS ", " as " }, + StringSplitOptions.RemoveEmptyEntries + ) + ) .Where(substrings => substrings.Length > 1) .Select(substrings => substrings[substrings.Length - 1]) .Distinct() @@ -121,13 +145,29 @@ public async Task Tar(CancellationToken ct = default) var dockerfileFilePath = Unix.Instance.NormalizePath(_dockerfile.ToString()); - var dockerfileArchiveFileName = Regex.Replace(_image.FullName, "[^a-zA-Z0-9]", "-", RegexOptions.None, TimeSpan.FromSeconds(1)).ToLowerInvariant(); - - var dockerfileArchiveFilePath = Path.Combine(Path.GetTempPath(), $"{dockerfileArchiveFileName}.tar"); - - var dockerIgnoreFile = new DockerIgnoreFile(dockerfileDirectoryPath, ".dockerignore", dockerfileFilePath, _logger); - - using (var tarOutputFileStream = new FileStream(dockerfileArchiveFilePath, FileMode.Create, FileAccess.Write)) + var dockerfileArchiveFileName = Regex + .Replace(_image.FullName, "[^a-zA-Z0-9]", "-", RegexOptions.None, TimeSpan.FromSeconds(1)) + .ToLowerInvariant(); + + var dockerfileArchiveFilePath = Path.Combine( + Path.GetTempPath(), + $"{dockerfileArchiveFileName}.tar" + ); + + var dockerIgnoreFile = new DockerIgnoreFile( + dockerfileDirectoryPath, + ".dockerignore", + dockerfileFilePath, + _logger + ); + + using ( + var tarOutputFileStream = new FileStream( + dockerfileArchiveFilePath, + FileMode.Create, + FileAccess.Write + ) + ) { using (var tarOutputStream = new TarOutputStream(tarOutputFileStream, Encoding.Default)) { @@ -136,7 +176,9 @@ public async Task Tar(CancellationToken ct = default) foreach (var absoluteFilePath in GetFiles(dockerfileDirectoryPath)) { // SharpZipLib drops the root path: https://github.com/icsharpcode/SharpZipLib/pull/582. - var relativeFilePath = absoluteFilePath.Substring(dockerfileDirectoryPath.TrimEnd(Path.AltDirectorySeparatorChar).Length + 1); + var relativeFilePath = absoluteFilePath.Substring( + dockerfileDirectoryPath.TrimEnd(Path.AltDirectorySeparatorChar).Length + 1 + ); if (dockerIgnoreFile.Denies(relativeFilePath)) { @@ -145,20 +187,19 @@ public async Task Tar(CancellationToken ct = default) try { - using (var inputStream = new FileStream(absoluteFilePath, FileMode.Open, FileAccess.Read)) + using ( + var inputStream = new FileStream(absoluteFilePath, FileMode.Open, FileAccess.Read) + ) { var entry = TarEntry.CreateTarEntry(relativeFilePath); entry.TarHeader.Size = inputStream.Length; entry.TarHeader.Mode = GetUnixFileMode(absoluteFilePath); - await tarOutputStream.PutNextEntryAsync(entry, ct) - .ConfigureAwait(false); + await tarOutputStream.PutNextEntryAsync(entry, ct).ConfigureAwait(false); - await inputStream.CopyToAsync(tarOutputStream, 81920, ct) - .ConfigureAwait(false); + await inputStream.CopyToAsync(tarOutputStream, 81920, ct).ConfigureAwait(false); - await tarOutputStream.CloseEntryAsync(ct) - .ConfigureAwait(false); + await tarOutputStream.CloseEntryAsync(ct).ConfigureAwait(false); } } catch (IOException e) @@ -179,7 +220,8 @@ await tarOutputStream.CloseEntryAsync(ct) /// Returns a list with all accepted Docker archive files. private static IEnumerable GetFiles(string directory) { - return Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories) + return Directory + .EnumerateFiles(directory, "*", SearchOption.AllDirectories) .AsParallel() .Select(Path.GetFullPath) .Select(Unix.Instance.NormalizePath) diff --git a/src/Testcontainers/Images/FutureDockerImage.cs b/src/Testcontainers/Images/FutureDockerImage.cs index 32a44ee96..f9d3a99ed 100644 --- a/src/Testcontainers/Images/FutureDockerImage.cs +++ b/src/Testcontainers/Images/FutureDockerImage.cs @@ -24,7 +24,11 @@ internal sealed class FutureDockerImage : Resource, IFutureDockerImage /// The image configuration. public FutureDockerImage(IImageFromDockerfileConfiguration configuration) { - _client = new TestcontainersClient(configuration.SessionId, configuration.DockerEndpointAuthConfig, configuration.Logger); + _client = new TestcontainersClient( + configuration.SessionId, + configuration.DockerEndpointAuthConfig, + configuration.Logger + ); _configuration = configuration; } @@ -106,21 +110,17 @@ public bool MatchVersion(Predicate predicate) /// public async Task CreateAsync(CancellationToken ct = default) { - using var disposable = await AcquireLockAsync(ct) - .ConfigureAwait(false); + using var disposable = await AcquireLockAsync(ct).ConfigureAwait(false); - await UnsafeCreateAsync(ct) - .ConfigureAwait(false); + await UnsafeCreateAsync(ct).ConfigureAwait(false); } /// public async Task DeleteAsync(CancellationToken ct = default) { - using var disposable = await AcquireLockAsync(ct) - .ConfigureAwait(false); + using var disposable = await AcquireLockAsync(ct).ConfigureAwait(false); - await UnsafeDeleteAsync(ct) - .ConfigureAwait(false); + await UnsafeDeleteAsync(ct).ConfigureAwait(false); } /// @@ -139,13 +139,12 @@ protected override async Task UnsafeCreateAsync(CancellationToken ct = default) return; } - await _client.System.LogContainerRuntimeInfoAsync(ct) - .ConfigureAwait(false); + await _client.System.LogContainerRuntimeInfoAsync(ct).ConfigureAwait(false); - _ = await _client.BuildAsync(_configuration, ct) - .ConfigureAwait(false); + _ = await _client.BuildAsync(_configuration, ct).ConfigureAwait(false); - _image = await _client.Image.ByIdAsync(_configuration.Image.FullName, ct) + _image = await _client + .Image.ByIdAsync(_configuration.Image.FullName, ct) .ConfigureAwait(false); } @@ -159,8 +158,7 @@ protected override async Task UnsafeDeleteAsync(CancellationToken ct = default) return; } - await _client.Image.DeleteAsync(_configuration.Image, ct) - .ConfigureAwait(false); + await _client.Image.DeleteAsync(_configuration.Image, ct).ConfigureAwait(false); _image = new ImageInspectResponse(); } diff --git a/src/Testcontainers/Images/IFutureDockerImage.cs b/src/Testcontainers/Images/IFutureDockerImage.cs index 29036c5a1..55911f928 100644 --- a/src/Testcontainers/Images/IFutureDockerImage.cs +++ b/src/Testcontainers/Images/IFutureDockerImage.cs @@ -7,7 +7,5 @@ namespace DotNet.Testcontainers.Images /// A future image instance. /// [PublicAPI] - public interface IFutureDockerImage : IImage, IFutureResource, IAsyncDisposable - { - } + public interface IFutureDockerImage : IImage, IFutureResource, IAsyncDisposable { } } diff --git a/src/Testcontainers/Images/IImageExtensions.cs b/src/Testcontainers/Images/IImageExtensions.cs index 55067ae80..dc76f1edf 100644 --- a/src/Testcontainers/Images/IImageExtensions.cs +++ b/src/Testcontainers/Images/IImageExtensions.cs @@ -27,7 +27,13 @@ public static IImage ApplyHubImageNamePrefix(this IImage image) return image; } - return new DockerImage(image.Repository, image.Registry, image.Tag, image.Digest, TestcontainersSettings.HubImageNamePrefix); + return new DockerImage( + image.Repository, + image.Registry, + image.Tag, + image.Digest, + TestcontainersSettings.HubImageNamePrefix + ); } } } diff --git a/src/Testcontainers/Images/IgnoreFile.cs b/src/Testcontainers/Images/IgnoreFile.cs index e61c75ce4..b61971245 100644 --- a/src/Testcontainers/Images/IgnoreFile.cs +++ b/src/Testcontainers/Images/IgnoreFile.cs @@ -11,7 +11,13 @@ namespace DotNet.Testcontainers.Images /// public class IgnoreFile { - private static readonly ISearchAndReplace[] PrepareRegex = { default(EscapeRegex), default(PrepareRecursiveWildcards), default(PrepareNonRecursiveWildcards), default(PrepareZeroOrOneQuantifier) }; + private static readonly ISearchAndReplace[] PrepareRegex = + { + default(EscapeRegex), + default(PrepareRecursiveWildcards), + default(PrepareNonRecursiveWildcards), + default(PrepareZeroOrOneQuantifier), + }; private readonly IEnumerable> _ignorePatterns; @@ -25,86 +31,93 @@ public IgnoreFile(IEnumerable patterns, ILogger logger) { _ignorePatterns = patterns .AsParallel() - // Keep the order. .AsOrdered() - // Trim each line. .Select(line => line.Trim()) - // Remove empty line. .Where(line => !string.IsNullOrEmpty(line)) - // Remove comment. .Where(line => !line.StartsWith("#", StringComparison.Ordinal)) - // Exclude files and directories. .Select(line => line.TrimEnd('/')) - // Exclude files and directories. .Select(line => { const string filesAndDirectories = "/*"; - return line.EndsWith(filesAndDirectories, StringComparison.InvariantCulture) ? line.Substring(0, line.Length - filesAndDirectories.Length) : line; + return line.EndsWith(filesAndDirectories, StringComparison.InvariantCulture) + ? line.Substring(0, line.Length - filesAndDirectories.Length) + : line; }) - // Exclude all files and directories (https://github.com/testcontainers/testcontainers-dotnet/issues/618). .Select(line => "*".Equals(line, StringComparison.OrdinalIgnoreCase) ? "**" : line) - // Check if the pattern contains an optional prefix ("!"), which negates the pattern. - .Aggregate(new List>(), (lines, line) => - { - switch (line[0]) + .Aggregate( + new List>(), + (lines, line) => { - case '!': - lines.Add(new KeyValuePair(line.Substring(1), true)); - break; - case '/': - lines.Add(new KeyValuePair(line.Substring(1), false)); - break; - default: - lines.Add(new KeyValuePair(line, false)); - break; + switch (line[0]) + { + case '!': + lines.Add(new KeyValuePair(line.Substring(1), true)); + break; + case '/': + lines.Add(new KeyValuePair(line.Substring(1), false)); + break; + default: + lines.Add(new KeyValuePair(line, false)); + break; + } + + return lines; } - - return lines; - }) - + ) // Prepare exact and partial patterns. - .Aggregate(new List>(), (lines, line) => - { - const string globstar = "**/"; - - if (line.Key.Contains(globstar)) + .Aggregate( + new List>(), + (lines, line) => { - lines.Add(line); - lines.Add(new KeyValuePair(line.Key.Replace(globstar, string.Empty), line.Value)); + const string globstar = "**/"; + + if (line.Key.Contains(globstar)) + { + lines.Add(line); + lines.Add( + new KeyValuePair(line.Key.Replace(globstar, string.Empty), line.Value) + ); + } + else + { + lines.Add(line); + } + + return lines; } - else + ) + // Prepare regular expressions to accept and deny files. + .Select( + (ignorePattern, index) => { - lines.Add(line); + var key = ignorePattern.Key; + var value = ignorePattern.Value; + key = PrepareRegex.Aggregate( + key, + (current, prepareRegex) => prepareRegex.Replace(current) + ); + key = 0.Equals(index) ? key : $"([\\\\\\/]?({key}\\b|$))"; + key = $"^{key}"; + return new KeyValuePair(key, value); } - - return lines; - }) - - // Prepare regular expressions to accept and deny files. - .Select((ignorePattern, index) => - { - var key = ignorePattern.Key; - var value = ignorePattern.Value; - key = PrepareRegex.Aggregate(key, (current, prepareRegex) => prepareRegex.Replace(current)); - key = 0.Equals(index) ? key : $"([\\\\\\/]?({key}\\b|$))"; - key = $"^{key}"; - return new KeyValuePair(key, value); - }) - + ) // Cache regular expression to increase the performance. .Select(ignorePattern => { var key = ignorePattern.Key; var value = ignorePattern.Value; - return new KeyValuePair(new Regex(key, RegexOptions.None, TimeSpan.FromSeconds(1)), value); + return new KeyValuePair( + new Regex(key, RegexOptions.None, TimeSpan.FromSeconds(1)), + value + ); }) .ToArray(); @@ -135,7 +148,10 @@ private interface ISearchAndReplace /// True if the file path does not match any ignore pattern, otherwise false. public bool Accepts(string file) { - var matches = _ignorePatterns.AsParallel().Where(ignorePattern => ignorePattern.Key.IsMatch(file)).ToArray(); + var matches = _ignorePatterns + .AsParallel() + .Where(ignorePattern => ignorePattern.Key.IsMatch(file)) + .ToArray(); return matches.Length == 0 || matches[matches.Length - 1].Value; } @@ -154,7 +170,11 @@ public bool Denies(string file) /// private readonly struct EscapeRegex : ISearchAndReplace { - private static readonly Regex Pattern = new Regex("[\\-\\[\\]\\/\\{\\}\\(\\)\\+\\?\\.\\\\\\^\\$\\|]", RegexOptions.None, TimeSpan.FromSeconds(1)); + private static readonly Regex Pattern = new Regex( + "[\\-\\[\\]\\/\\{\\}\\(\\)\\+\\?\\.\\\\\\^\\$\\|]", + RegexOptions.None, + TimeSpan.FromSeconds(1) + ); /// public string Replace(string input) diff --git a/src/Testcontainers/Images/MatchImage.cs b/src/Testcontainers/Images/MatchImage.cs index 681fe4330..0082e8d00 100644 --- a/src/Testcontainers/Images/MatchImage.cs +++ b/src/Testcontainers/Images/MatchImage.cs @@ -8,16 +8,22 @@ internal static class MatchImage { public static IImage Match(string image) { - _ = Guard.Argument(image, nameof(image)) - .NotNull() - .NotEmpty(); + _ = Guard.Argument(image, nameof(image)).NotNull().NotEmpty(); - const string invalidReferenceFormat = "Error parsing reference: '{0}' is not a valid repository/tag."; + const string invalidReferenceFormat = + "Error parsing reference: '{0}' is not a valid repository/tag."; var referenceMatch = ReferenceRegex.Instance.Match(image); - _ = Guard.Argument(referenceMatch, nameof(image)) - .ThrowIf(argument => !argument.Value.Success, argument => new ArgumentException(string.Format(CultureInfo.InvariantCulture, invalidReferenceFormat, image), argument.Name)); + _ = Guard + .Argument(referenceMatch, nameof(image)) + .ThrowIf( + argument => !argument.Value.Success, + argument => new ArgumentException( + string.Format(CultureInfo.InvariantCulture, invalidReferenceFormat, image), + argument.Name + ) + ); var remoteName = referenceMatch.Groups["remote_name"].Value; var tag = referenceMatch.Groups["tag"].Value; @@ -29,7 +35,10 @@ public static IImage Match(string image) // The following part does not implement the entire Go implementation. It does // not resolve or set the default domain and repository prefix. This is not // necessary at the moment, and it is something we can address later. - var (registry, repository) = slices.Length == 2 && slices[0].LastIndexOfAny(['.', ':']) > -1 ? (slices[0], slices[1]) : (null, remoteName); + var (registry, repository) = + slices.Length == 2 && slices[0].LastIndexOfAny(['.', ':']) > -1 + ? (slices[0], slices[1]) + : (null, remoteName); return new DockerImage(repository, registry, tag, digest); } @@ -37,19 +46,15 @@ public static IImage Match(string image) // https://github.com/distribution/reference/blob/8c942b0459dfdcc5b6685581dd0a5a470f615bff/reference.go. private sealed class ReferenceRegex : Regex { - private const string Pattern = "^(?(?:(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])(?:\\.(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]))*|\\[(?:[a-fA-F0-9:]+)\\])(?::[0-9]+)?\\/)?[a-z0-9]+(?:(?:[._]|__|[-]+)[a-z0-9]+)*(?:\\/[a-z0-9]+(?:(?:[._]|__|[-]+)[a-z0-9]+)*)*)(?::(?[\\w][\\w.-]{0,127}))?(?:@(?[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][0-9A-Fa-f]{32,}))?$"; + private const string Pattern = + "^(?(?:(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])(?:\\.(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]))*|\\[(?:[a-fA-F0-9:]+)\\])(?::[0-9]+)?\\/)?[a-z0-9]+(?:(?:[._]|__|[-]+)[a-z0-9]+)*(?:\\/[a-z0-9]+(?:(?:[._]|__|[-]+)[a-z0-9]+)*)*)(?::(?[\\w][\\w.-]{0,127}))?(?:@(?[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][0-9A-Fa-f]{32,}))?$"; - static ReferenceRegex() - { - } + static ReferenceRegex() { } private ReferenceRegex() - : base(Pattern, RegexOptions.Compiled, TimeSpan.FromSeconds(1)) - { - } + : base(Pattern, RegexOptions.Compiled, TimeSpan.FromSeconds(1)) { } - public static Regex Instance { get; } - = new ReferenceRegex(); + public static Regex Instance { get; } = new ReferenceRegex(); } } } diff --git a/src/Testcontainers/Images/PullPolicy.cs b/src/Testcontainers/Images/PullPolicy.cs index b5a852d2c..9389fde21 100644 --- a/src/Testcontainers/Images/PullPolicy.cs +++ b/src/Testcontainers/Images/PullPolicy.cs @@ -15,10 +15,7 @@ public static class PullPolicy /// public static Func Never { - get - { - return _ => false; - } + get { return _ => false; } } /// @@ -26,10 +23,7 @@ public static Func Never /// public static Func Missing { - get - { - return cachedImage => cachedImage == null; - } + get { return cachedImage => cachedImage == null; } } /// @@ -37,10 +31,7 @@ public static Func Missing /// public static Func Always { - get - { - return _ => true; - } + get { return _ => true; } } } } diff --git a/src/Testcontainers/Logger.cs b/src/Testcontainers/Logger.cs index 1b908c5d5..136b363d0 100644 --- a/src/Testcontainers/Logger.cs +++ b/src/Testcontainers/Logger.cs @@ -61,13 +61,15 @@ public sealed class ConsoleLogger : ILogger, IDisposable private LogLevel _minLogLevel = LogLevel.Information; - static ConsoleLogger() - { - } + static ConsoleLogger() { } private ConsoleLogger() { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !Console.IsOutputRedirected && !Console.IsErrorRedirected) + if ( + RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + && !Console.IsOutputRedirected + && !Console.IsErrorRedirected + ) { Console.BufferWidth = short.MaxValue - 1; } @@ -76,23 +78,15 @@ private ConsoleLogger() /// /// Gets the instance. /// - public static ConsoleLogger Instance { get; } - = new ConsoleLogger(); + public static ConsoleLogger Instance { get; } = new ConsoleLogger(); /// /// Gets a value indicating whether the debug log level is enabled or not. /// public bool DebugLogLevelEnabled { - get - { - return LogLevel.Debug.Equals(_minLogLevel); - } - - set - { - _minLogLevel = value ? LogLevel.Debug : LogLevel.Information; - } + get { return LogLevel.Debug.Equals(_minLogLevel); } + set { _minLogLevel = value ? LogLevel.Debug : LogLevel.Information; } } /// @@ -102,12 +96,25 @@ public void Dispose() } /// - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception exception, + Func formatter + ) { if (IsEnabled(logLevel)) { - var message = exception == null ? formatter.Invoke(state, null) : string.Join(Environment.NewLine, formatter.Invoke(state, exception), exception); - Console.Out.WriteLine("[testcontainers.org {0:hh\\:mm\\:ss\\.ff}] {1}", _stopwatch.Elapsed, message); + var message = + exception == null + ? formatter.Invoke(state, null) + : string.Join(Environment.NewLine, formatter.Invoke(state, exception), exception); + Console.Out.WriteLine( + "[testcontainers.org {0:hh\\:mm\\:ss\\.ff}] {1}", + _stopwatch.Elapsed, + message + ); } } diff --git a/src/Testcontainers/Logging.cs b/src/Testcontainers/Logging.cs index 014bbc667..24ca2e7b3 100644 --- a/src/Testcontainers/Logging.cs +++ b/src/Testcontainers/Logging.cs @@ -11,110 +11,224 @@ internal static class Logging { #pragma warning disable InconsistentNaming, SA1309 - private static readonly Action _IgnorePatternAdded - = LoggerMessage.Define(LogLevel.Information, default, "Pattern {IgnorePattern} added to the regex cache"); - - private static readonly Action _DockerContainerCreated - = LoggerMessage.Define(LogLevel.Information, default, "Docker container {Id} created"); - - private static readonly Action _StartDockerContainer - = LoggerMessage.Define(LogLevel.Information, default, "Start Docker container {Id}"); - - private static readonly Action _StopDockerContainer - = LoggerMessage.Define(LogLevel.Information, default, "Stop Docker container {Id}"); - - private static readonly Action _PauseDockerContainer - = LoggerMessage.Define(LogLevel.Information, default, "Pause Docker container {Id}"); - - private static readonly Action _UnpauseDockerContainer - = LoggerMessage.Define(LogLevel.Information, default, "Unpause Docker container {Id}"); - - private static readonly Action _DeleteDockerContainer - = LoggerMessage.Define(LogLevel.Information, default, "Delete Docker container {Id}"); - - private static readonly Action _StartReadinessCheck - = LoggerMessage.Define(LogLevel.Information, default, "Wait for Docker container {Id} to complete readiness checks"); - - private static readonly Action _CompleteReadinessCheck - = LoggerMessage.Define(LogLevel.Information, default, "Docker container {Id} ready"); - - private static readonly Action _CopyArchiveToDockerContainer - = LoggerMessage.Define(LogLevel.Information, default, "Copy tar archive to container: Content length: {Length} byte(s), Docker container: {Id}"); - - private static readonly Action _ReadArchiveFromDockerContainer - = LoggerMessage.Define(LogLevel.Information, default, "Read \"{Path}\" from Docker container {Id}"); - - private static readonly Action _AttachToDockerContainer - = LoggerMessage.Define(LogLevel.Information, default, "Attach {OutputConsumer} at Docker container {Id}"); - - private static readonly Action _ConnectToDockerNetwork - = LoggerMessage.Define(LogLevel.Information, default, "Connect Docker container {ContainerId} to Docker network {NetworkId}"); - - private static readonly Action _ExecuteCommandInDockerContainer - = LoggerMessage.Define(LogLevel.Information, default, "Execute \"{Command}\" at Docker container {Id}"); - - private static readonly Action _DockerImageCreated - = LoggerMessage.Define(LogLevel.Information, default, "Docker image {FullName} created"); - - private static readonly Action _DockerImageBuilt - = LoggerMessage.Define(LogLevel.Information, default, "Docker image {FullName} built"); - - private static readonly Action _DeleteDockerImage - = LoggerMessage.Define(LogLevel.Information, default, "Delete Docker image {FullName}"); - - private static readonly Action _DockerNetworkCreated - = LoggerMessage.Define(LogLevel.Information, default, "Docker network {Id} created"); - - private static readonly Action _DeleteDockerNetwork - = LoggerMessage.Define(LogLevel.Information, default, "Delete Docker network {Id}"); - - private static readonly Action _DockerVolumeCreated - = LoggerMessage.Define(LogLevel.Information, default, "Docker volume {Name} created"); - - private static readonly Action _DeleteDockerVolume - = LoggerMessage.Define(LogLevel.Information, default, "Delete Docker volume {Name}"); - - private static readonly Action _CanNotGetResourceReaperEndpoint - = LoggerMessage.Define(LogLevel.Debug, default, "Cannot get resource reaper {Id} endpoint"); - - private static readonly Action _CanNotConnectToResourceReaper - = LoggerMessage.Define(LogLevel.Debug, default, "Cannot connect to resource reaper {Id} at {Endpoint}"); - - private static readonly Action _LostConnectionToResourceReaper - = LoggerMessage.Define(LogLevel.Debug, default, "Lost connection to resource reaper {Id} at {Endpoint}"); - - private static readonly Action _DockerConfigFileNotFound - = LoggerMessage.Define(LogLevel.Information, default, "Docker config \"{DockerConfigFilePath}\" not found"); - - private static readonly Action _SearchingDockerRegistryCredential - = LoggerMessage.Define(LogLevel.Information, default, "Searching Docker registry credential in {CredentialStore}"); - - private static readonly Action _DockerRegistryAuthPropertyValueKindInvalid - = LoggerMessage.Define(LogLevel.Warning, default, "The \"auth\" property value kind for {DockerRegistry} is invalid: {ValueKind}"); - - private static readonly Action _DockerRegistryAuthPropertyValueNotFound - = LoggerMessage.Define(LogLevel.Warning, default, "The \"auth\" property value for {DockerRegistry} not found"); - - private static readonly Action _DockerRegistryAuthPropertyValueInvalidBase64 - = LoggerMessage.Define(LogLevel.Warning, default, "The \"auth\" property value for {DockerRegistry} is not a valid Base64 string"); - - private static readonly Action _DockerRegistryAuthPropertyValueInvalidBasicAuthenticationFormat - = LoggerMessage.Define(LogLevel.Warning, default, "The \"auth\" property value for {DockerRegistry} should contain one colon separating the username and the password (basic authentication)"); - - private static readonly Action _DockerRegistryCredentialNotFound - = LoggerMessage.Define(LogLevel.Information, default, "Docker registry credential {DockerRegistry} not found"); - - private static readonly Action _DockerRegistryCredentialFound - = LoggerMessage.Define(LogLevel.Information, default, "Docker registry credential {DockerRegistry} found"); - - private static readonly Action _ReusableExperimentalFeature - = LoggerMessage.Define(LogLevel.Warning, default, "Reuse is an experimental feature. For more information, visit: https://dotnet.testcontainers.org/api/resource_reuse/"); - - private static readonly Action _ReusableResourceFound - = LoggerMessage.Define(LogLevel.Information, default, "Reusable resource found"); - - private static readonly Action _ReusableResourceNotFound - = LoggerMessage.Define(LogLevel.Information, default, "Reusable resource not found, create resource"); + private static readonly Action _IgnorePatternAdded = + LoggerMessage.Define( + LogLevel.Information, + default, + "Pattern {IgnorePattern} added to the regex cache" + ); + + private static readonly Action _DockerContainerCreated = + LoggerMessage.Define(LogLevel.Information, default, "Docker container {Id} created"); + + private static readonly Action _StartDockerContainer = + LoggerMessage.Define(LogLevel.Information, default, "Start Docker container {Id}"); + + private static readonly Action _StopDockerContainer = + LoggerMessage.Define(LogLevel.Information, default, "Stop Docker container {Id}"); + + private static readonly Action _PauseDockerContainer = + LoggerMessage.Define(LogLevel.Information, default, "Pause Docker container {Id}"); + + private static readonly Action _UnpauseDockerContainer = + LoggerMessage.Define(LogLevel.Information, default, "Unpause Docker container {Id}"); + + private static readonly Action _DeleteDockerContainer = + LoggerMessage.Define(LogLevel.Information, default, "Delete Docker container {Id}"); + + private static readonly Action _StartReadinessCheck = + LoggerMessage.Define( + LogLevel.Information, + default, + "Wait for Docker container {Id} to complete readiness checks" + ); + + private static readonly Action _CompleteReadinessCheck = + LoggerMessage.Define(LogLevel.Information, default, "Docker container {Id} ready"); + + private static readonly Action _CopyArchiveToDockerContainer = + LoggerMessage.Define( + LogLevel.Information, + default, + "Copy tar archive to container: Content length: {Length} byte(s), Docker container: {Id}" + ); + + private static readonly Action< + ILogger, + string, + string, + Exception + > _ReadArchiveFromDockerContainer = LoggerMessage.Define( + LogLevel.Information, + default, + "Read \"{Path}\" from Docker container {Id}" + ); + + private static readonly Action _AttachToDockerContainer = + LoggerMessage.Define( + LogLevel.Information, + default, + "Attach {OutputConsumer} at Docker container {Id}" + ); + + private static readonly Action _ConnectToDockerNetwork = + LoggerMessage.Define( + LogLevel.Information, + default, + "Connect Docker container {ContainerId} to Docker network {NetworkId}" + ); + + private static readonly Action< + ILogger, + string, + string, + Exception + > _ExecuteCommandInDockerContainer = LoggerMessage.Define( + LogLevel.Information, + default, + "Execute \"{Command}\" at Docker container {Id}" + ); + + private static readonly Action _DockerImageCreated = + LoggerMessage.Define( + LogLevel.Information, + default, + "Docker image {FullName} created" + ); + + private static readonly Action _DockerImageBuilt = + LoggerMessage.Define(LogLevel.Information, default, "Docker image {FullName} built"); + + private static readonly Action _DeleteDockerImage = + LoggerMessage.Define(LogLevel.Information, default, "Delete Docker image {FullName}"); + + private static readonly Action _DockerNetworkCreated = + LoggerMessage.Define(LogLevel.Information, default, "Docker network {Id} created"); + + private static readonly Action _DeleteDockerNetwork = + LoggerMessage.Define(LogLevel.Information, default, "Delete Docker network {Id}"); + + private static readonly Action _DockerVolumeCreated = + LoggerMessage.Define(LogLevel.Information, default, "Docker volume {Name} created"); + + private static readonly Action _DeleteDockerVolume = + LoggerMessage.Define(LogLevel.Information, default, "Delete Docker volume {Name}"); + + private static readonly Action _CanNotGetResourceReaperEndpoint = + LoggerMessage.Define( + LogLevel.Debug, + default, + "Cannot get resource reaper {Id} endpoint" + ); + + private static readonly Action< + ILogger, + Guid, + string, + Exception + > _CanNotConnectToResourceReaper = LoggerMessage.Define( + LogLevel.Debug, + default, + "Cannot connect to resource reaper {Id} at {Endpoint}" + ); + + private static readonly Action< + ILogger, + Guid, + string, + Exception + > _LostConnectionToResourceReaper = LoggerMessage.Define( + LogLevel.Debug, + default, + "Lost connection to resource reaper {Id} at {Endpoint}" + ); + + private static readonly Action _DockerConfigFileNotFound = + LoggerMessage.Define( + LogLevel.Information, + default, + "Docker config \"{DockerConfigFilePath}\" not found" + ); + + private static readonly Action _SearchingDockerRegistryCredential = + LoggerMessage.Define( + LogLevel.Information, + default, + "Searching Docker registry credential in {CredentialStore}" + ); + + private static readonly Action< + ILogger, + string, + JsonValueKind, + Exception + > _DockerRegistryAuthPropertyValueKindInvalid = LoggerMessage.Define( + LogLevel.Warning, + default, + "The \"auth\" property value kind for {DockerRegistry} is invalid: {ValueKind}" + ); + + private static readonly Action< + ILogger, + string, + Exception + > _DockerRegistryAuthPropertyValueNotFound = LoggerMessage.Define( + LogLevel.Warning, + default, + "The \"auth\" property value for {DockerRegistry} not found" + ); + + private static readonly Action< + ILogger, + string, + Exception + > _DockerRegistryAuthPropertyValueInvalidBase64 = LoggerMessage.Define( + LogLevel.Warning, + default, + "The \"auth\" property value for {DockerRegistry} is not a valid Base64 string" + ); + + private static readonly Action< + ILogger, + string, + Exception + > _DockerRegistryAuthPropertyValueInvalidBasicAuthenticationFormat = + LoggerMessage.Define( + LogLevel.Warning, + default, + "The \"auth\" property value for {DockerRegistry} should contain one colon separating the username and the password (basic authentication)" + ); + + private static readonly Action _DockerRegistryCredentialNotFound = + LoggerMessage.Define( + LogLevel.Information, + default, + "Docker registry credential {DockerRegistry} not found" + ); + + private static readonly Action _DockerRegistryCredentialFound = + LoggerMessage.Define( + LogLevel.Information, + default, + "Docker registry credential {DockerRegistry} found" + ); + + private static readonly Action _ReusableExperimentalFeature = + LoggerMessage.Define( + LogLevel.Warning, + default, + "Reuse is an experimental feature. For more information, visit: https://dotnet.testcontainers.org/api/resource_reuse/" + ); + + private static readonly Action _ReusableResourceFound = + LoggerMessage.Define(LogLevel.Information, default, "Reusable resource found"); + + private static readonly Action _ReusableResourceNotFound = + LoggerMessage.Define( + LogLevel.Information, + default, + "Reusable resource not found, create resource" + ); #pragma warning restore InconsistentNaming, SA1309 @@ -178,12 +292,20 @@ public static void AttachToDockerContainer(this ILogger logger, string id, Type _AttachToDockerContainer(logger, type, TruncId(id), null); } - public static void ConnectToDockerNetwork(this ILogger logger, string networkId, string containerId) + public static void ConnectToDockerNetwork( + this ILogger logger, + string networkId, + string containerId + ) { _ConnectToDockerNetwork(logger, TruncId(containerId), TruncId(networkId), null); } - public static void ExecuteCommandInDockerContainer(this ILogger logger, string id, IEnumerable command) + public static void ExecuteCommandInDockerContainer( + this ILogger logger, + string id, + IEnumerable command + ) { _ExecuteCommandInDockerContainer(logger, string.Join(" ", command), TruncId(id), null); } @@ -228,13 +350,25 @@ public static void CanNotGetResourceReaperEndpoint(this ILogger logger, Guid id, _CanNotGetResourceReaperEndpoint(logger, id, logger.IsEnabled(LogLevel.Debug) ? e : null); } - public static void CanNotConnectToResourceReaper(this ILogger logger, Guid id, string host, ushort port, Exception e) + public static void CanNotConnectToResourceReaper( + this ILogger logger, + Guid id, + string host, + ushort port, + Exception e + ) { var endpoint = $"{host}:{port}"; _CanNotConnectToResourceReaper(logger, id, endpoint, e); } - public static void LostConnectionToResourceReaper(this ILogger logger, Guid id, string host, ushort port, Exception e) + public static void LostConnectionToResourceReaper( + this ILogger logger, + Guid id, + string host, + ushort port, + Exception e + ) { var endpoint = $"{host}:{port}"; _LostConnectionToResourceReaper(logger, id, endpoint, e); @@ -245,29 +379,50 @@ public static void DockerConfigFileNotFound(this ILogger logger, string dockerCo _DockerConfigFileNotFound(logger, dockerConfigFilePath, null); } - public static void SearchingDockerRegistryCredential(this ILogger logger, string credentialStore) + public static void SearchingDockerRegistryCredential( + this ILogger logger, + string credentialStore + ) { _SearchingDockerRegistryCredential(logger, credentialStore, null); } - public static void DockerRegistryAuthPropertyValueKindInvalid(this ILogger logger, string dockerRegistry, JsonValueKind valueKind) + public static void DockerRegistryAuthPropertyValueKindInvalid( + this ILogger logger, + string dockerRegistry, + JsonValueKind valueKind + ) { _DockerRegistryAuthPropertyValueKindInvalid(logger, dockerRegistry, valueKind, null); } - public static void DockerRegistryAuthPropertyValueNotFound(this ILogger logger, string dockerRegistry) + public static void DockerRegistryAuthPropertyValueNotFound( + this ILogger logger, + string dockerRegistry + ) { _DockerRegistryAuthPropertyValueNotFound(logger, dockerRegistry, null); } - public static void DockerRegistryAuthPropertyValueInvalidBase64(this ILogger logger, string dockerRegistry, Exception e) + public static void DockerRegistryAuthPropertyValueInvalidBase64( + this ILogger logger, + string dockerRegistry, + Exception e + ) { _DockerRegistryAuthPropertyValueInvalidBase64(logger, dockerRegistry, e); } - public static void DockerRegistryAuthPropertyValueInvalidBasicAuthenticationFormat(this ILogger logger, string dockerRegistry) + public static void DockerRegistryAuthPropertyValueInvalidBasicAuthenticationFormat( + this ILogger logger, + string dockerRegistry + ) { - _DockerRegistryAuthPropertyValueInvalidBasicAuthenticationFormat(logger, dockerRegistry, null); + _DockerRegistryAuthPropertyValueInvalidBasicAuthenticationFormat( + logger, + dockerRegistry, + null + ); } public static void DockerRegistryCredentialNotFound(this ILogger logger, string dockerRegistry) diff --git a/src/Testcontainers/Networks/DockerNetwork.cs b/src/Testcontainers/Networks/DockerNetwork.cs index 7db085d82..a870b4fb0 100644 --- a/src/Testcontainers/Networks/DockerNetwork.cs +++ b/src/Testcontainers/Networks/DockerNetwork.cs @@ -26,7 +26,11 @@ internal sealed class DockerNetwork : Resource, INetwork /// The network configuration. public DockerNetwork(INetworkConfiguration configuration) { - _client = new TestcontainersClient(configuration.SessionId, configuration.DockerEndpointAuthConfig, configuration.Logger); + _client = new TestcontainersClient( + configuration.SessionId, + configuration.DockerEndpointAuthConfig, + configuration.Logger + ); _configuration = configuration; } @@ -43,21 +47,17 @@ public string Name /// public async Task CreateAsync(CancellationToken ct = default) { - using var disposable = await AcquireLockAsync(ct) - .ConfigureAwait(false); + using var disposable = await AcquireLockAsync(ct).ConfigureAwait(false); - await UnsafeCreateAsync(ct) - .ConfigureAwait(false); + await UnsafeCreateAsync(ct).ConfigureAwait(false); } /// public async Task DeleteAsync(CancellationToken ct = default) { - using var disposable = await AcquireLockAsync(ct) - .ConfigureAwait(false); + using var disposable = await AcquireLockAsync(ct).ConfigureAwait(false); - await UnsafeDeleteAsync(ct) - .ConfigureAwait(false); + await UnsafeDeleteAsync(ct).ConfigureAwait(false); } /// @@ -70,12 +70,10 @@ protected override async ValueTask DisposeAsyncCore() if (!Guid.Empty.Equals(_configuration.SessionId)) { - await DeleteAsync() - .ConfigureAwait(false); + await DeleteAsync().ConfigureAwait(false); } - await base.DisposeAsyncCore() - .ConfigureAwait(false); + await base.DisposeAsyncCore().ConfigureAwait(false); } /// @@ -94,8 +92,7 @@ protected override async Task UnsafeCreateAsync(CancellationToken ct = default) return; } - await _client.System.LogContainerRuntimeInfoAsync(ct) - .ConfigureAwait(false); + await _client.System.LogContainerRuntimeInfoAsync(ct).ConfigureAwait(false); string id; @@ -105,8 +102,7 @@ await _client.System.LogContainerRuntimeInfoAsync(ct) var filters = new FilterByReuseHash(_configuration); - var reusableNetworks = await _client.Network.GetAllAsync(filters, ct) - .ConfigureAwait(false); + var reusableNetworks = await _client.Network.GetAllAsync(filters, ct).ConfigureAwait(false); var reusableNetwork = reusableNetworks.SingleOrDefault(); @@ -120,18 +116,15 @@ await _client.System.LogContainerRuntimeInfoAsync(ct) { _configuration.Logger.ReusableResourceNotFound(); - id = await _client.Network.CreateAsync(_configuration, ct) - .ConfigureAwait(false); + id = await _client.Network.CreateAsync(_configuration, ct).ConfigureAwait(false); } } else { - id = await _client.Network.CreateAsync(_configuration, ct) - .ConfigureAwait(false); + id = await _client.Network.CreateAsync(_configuration, ct).ConfigureAwait(false); } - _network = await _client.Network.ByIdAsync(id, ct) - .ConfigureAwait(false); + _network = await _client.Network.ByIdAsync(id, ct).ConfigureAwait(false); } /// @@ -146,8 +139,7 @@ protected override async Task UnsafeDeleteAsync(CancellationToken ct = default) try { - await _client.Network.DeleteAsync(_network.ID, ct) - .ConfigureAwait(false); + await _client.Network.DeleteAsync(_network.ID, ct).ConfigureAwait(false); } catch (DockerApiException) { diff --git a/src/Testcontainers/Polyfills/X509Certificate2.cs b/src/Testcontainers/Polyfills/X509Certificate2.cs index bcbb0da00..9ae1a6c4e 100644 --- a/src/Testcontainers/Polyfills/X509Certificate2.cs +++ b/src/Testcontainers/Polyfills/X509Certificate2.cs @@ -14,7 +14,10 @@ public static class X509Certificate2 { private static readonly X509CertificateParser CertificateParser = new X509CertificateParser(); - public static System.Security.Cryptography.X509Certificates.X509Certificate2 CreateFromPemFile(string certPemFilePath, string keyPemFilePath) + public static System.Security.Cryptography.X509Certificates.X509Certificate2 CreateFromPemFile( + string certPemFilePath, + string keyPemFilePath + ) { if (!File.Exists(certPemFilePath)) { @@ -46,7 +49,10 @@ public static System.Security.Cryptography.X509Certificates.X509Certificate2 Cre using (var certificateStream = new MemoryStream()) { store.Save(certificateStream, password.ToCharArray(), new SecureRandom()); - return new System.Security.Cryptography.X509Certificates.X509Certificate2(Pkcs12Utilities.ConvertToDefiniteLength(certificateStream.ToArray()), password); + return new System.Security.Cryptography.X509Certificates.X509Certificate2( + Pkcs12Utilities.ConvertToDefiniteLength(certificateStream.ToArray()), + password + ); } } } @@ -60,7 +66,10 @@ private static AsymmetricKeyParameter ResolveKeyParameter(object keyObject) case RsaPrivateCrtKeyParameters rpckp: return rpckp; default: - throw new ArgumentOutOfRangeException(nameof(keyObject), $"Unsupported asymmetric key entry encountered while trying to resolve key from input object '{keyObject.GetType()}'."); + throw new ArgumentOutOfRangeException( + nameof(keyObject), + $"Unsupported asymmetric key entry encountered while trying to resolve key from input object '{keyObject.GetType()}'." + ); } } } diff --git a/src/Testcontainers/Resource.cs b/src/Testcontainers/Resource.cs index 48abb05cc..7fff0b250 100644 --- a/src/Testcontainers/Resource.cs +++ b/src/Testcontainers/Resource.cs @@ -24,8 +24,7 @@ public abstract class Resource : IAsyncDisposable /// public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -63,8 +62,7 @@ protected virtual ValueTask DisposeAsyncCore() /// A that releases the lock on . protected virtual async Task AcquireLockAsync(CancellationToken ct = default) { - await _semaphoreSlim.WaitAsync(ct) - .ConfigureAwait(false); + await _semaphoreSlim.WaitAsync(ct).ConfigureAwait(false); return new Lock(_semaphoreSlim); } @@ -75,9 +73,16 @@ await _semaphoreSlim.WaitAsync(ct) /// The resource was not found. protected virtual void ThrowIfResourceNotFound() { - const string message = "Could not find resource '{0}'. Please create the resource by calling StartAsync(CancellationToken) or CreateAsync(CancellationToken)."; - _ = Guard.Argument(this, GetType().Name) - .ThrowIf(argument => !argument.Value.Exists(), argument => new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, message, argument.Name))); + const string message = + "Could not find resource '{0}'. Please create the resource by calling StartAsync(CancellationToken) or CreateAsync(CancellationToken)."; + _ = Guard + .Argument(this, GetType().Name) + .ThrowIf( + argument => !argument.Value.Exists(), + argument => new InvalidOperationException( + string.Format(CultureInfo.InvariantCulture, message, argument.Name) + ) + ); } /// @@ -87,8 +92,12 @@ protected virtual void ThrowIfResourceNotFound() protected virtual void ThrowIfLockNotAcquired() { const string message = "Unsafe method call requires lock."; - _ = Guard.Argument(_semaphoreSlim, nameof(_semaphoreSlim)) - .ThrowIf(argument => argument.Value.CurrentCount > 0, _ => new InvalidOperationException(message)); + _ = Guard + .Argument(_semaphoreSlim, nameof(_semaphoreSlim)) + .ThrowIf( + argument => argument.Value.CurrentCount > 0, + _ => new InvalidOperationException(message) + ); } /// diff --git a/src/Testcontainers/Testcontainers.csproj b/src/Testcontainers/Testcontainers.csproj index e920b73ab..8ce227fc4 100644 --- a/src/Testcontainers/Testcontainers.csproj +++ b/src/Testcontainers/Testcontainers.csproj @@ -9,16 +9,20 @@ true - - - - - - + + + + + + - - - + + + diff --git a/src/Testcontainers/Volumes/DockerVolume.cs b/src/Testcontainers/Volumes/DockerVolume.cs index 3062b44b0..50b89e74a 100644 --- a/src/Testcontainers/Volumes/DockerVolume.cs +++ b/src/Testcontainers/Volumes/DockerVolume.cs @@ -26,7 +26,11 @@ internal sealed class DockerVolume : Resource, IVolume /// The volume configuration. public DockerVolume(IVolumeConfiguration configuration) { - _client = new TestcontainersClient(configuration.SessionId, configuration.DockerEndpointAuthConfig, configuration.Logger); + _client = new TestcontainersClient( + configuration.SessionId, + configuration.DockerEndpointAuthConfig, + configuration.Logger + ); _configuration = configuration; } @@ -43,21 +47,17 @@ public string Name /// public async Task CreateAsync(CancellationToken ct = default) { - using var disposable = await AcquireLockAsync(ct) - .ConfigureAwait(false); + using var disposable = await AcquireLockAsync(ct).ConfigureAwait(false); - await UnsafeCreateAsync(ct) - .ConfigureAwait(false); + await UnsafeCreateAsync(ct).ConfigureAwait(false); } /// public async Task DeleteAsync(CancellationToken ct = default) { - using var disposable = await AcquireLockAsync(ct) - .ConfigureAwait(false); + using var disposable = await AcquireLockAsync(ct).ConfigureAwait(false); - await UnsafeDeleteAsync(ct) - .ConfigureAwait(false); + await UnsafeDeleteAsync(ct).ConfigureAwait(false); } /// @@ -70,12 +70,10 @@ protected override async ValueTask DisposeAsyncCore() if (!Guid.Empty.Equals(_configuration.SessionId)) { - await DeleteAsync() - .ConfigureAwait(false); + await DeleteAsync().ConfigureAwait(false); } - await base.DisposeAsyncCore() - .ConfigureAwait(false); + await base.DisposeAsyncCore().ConfigureAwait(false); } /// @@ -94,8 +92,7 @@ protected override async Task UnsafeCreateAsync(CancellationToken ct = default) return; } - await _client.System.LogContainerRuntimeInfoAsync(ct) - .ConfigureAwait(false); + await _client.System.LogContainerRuntimeInfoAsync(ct).ConfigureAwait(false); string id; @@ -105,8 +102,7 @@ await _client.System.LogContainerRuntimeInfoAsync(ct) var filters = new FilterByReuseHash(_configuration); - var reusableVolumes = await _client.Volume.GetAllAsync(filters, ct) - .ConfigureAwait(false); + var reusableVolumes = await _client.Volume.GetAllAsync(filters, ct).ConfigureAwait(false); var reusableVolume = reusableVolumes.SingleOrDefault(); @@ -120,18 +116,15 @@ await _client.System.LogContainerRuntimeInfoAsync(ct) { _configuration.Logger.ReusableResourceNotFound(); - id = await _client.Volume.CreateAsync(_configuration, ct) - .ConfigureAwait(false); + id = await _client.Volume.CreateAsync(_configuration, ct).ConfigureAwait(false); } } else { - id = await _client.Volume.CreateAsync(_configuration, ct) - .ConfigureAwait(false); + id = await _client.Volume.CreateAsync(_configuration, ct).ConfigureAwait(false); } - _volume = await _client.Volume.ByIdAsync(id, ct) - .ConfigureAwait(false); + _volume = await _client.Volume.ByIdAsync(id, ct).ConfigureAwait(false); } /// @@ -146,8 +139,7 @@ protected override async Task UnsafeDeleteAsync(CancellationToken ct = default) try { - await _client.Volume.DeleteAsync(Name, ct) - .ConfigureAwait(false); + await _client.Volume.DeleteAsync(Name, ct).ConfigureAwait(false); } catch (DockerApiException) { diff --git a/tests/Directory.Build.props b/tests/Directory.Build.props index 89fed359e..f777225c4 100644 --- a/tests/Directory.Build.props +++ b/tests/Directory.Build.props @@ -1,6 +1,6 @@ - + false false diff --git a/tests/Testcontainers.ActiveMq.Tests/ArtemisContainerTest.cs b/tests/Testcontainers.ActiveMq.Tests/ArtemisContainerTest.cs index 425144a6e..cfa020323 100644 --- a/tests/Testcontainers.ActiveMq.Tests/ArtemisContainerTest.cs +++ b/tests/Testcontainers.ActiveMq.Tests/ArtemisContainerTest.cs @@ -9,7 +9,11 @@ public abstract class ArtemisContainerTest : IAsyncLifetime private readonly string _password; - private ArtemisContainerTest(ArtemisContainer artemisContainer, string username, string password) + private ArtemisContainerTest( + ArtemisContainer artemisContainer, + string username, + string password + ) { _artemisContainer = artemisContainer; _username = username; @@ -18,17 +22,16 @@ private ArtemisContainerTest(ArtemisContainer artemisContainer, string username, public async ValueTask InitializeAsync() { - await _artemisContainer.StartAsync() - .ConfigureAwait(false); + await _artemisContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } + // # --8<-- [end:UseArtemisContainer] // # --8<-- [start:EstablishConnection] @@ -42,38 +45,32 @@ public async Task EstablishesConnection() connectionFactory.Password = _password; // When - using var connection = await connectionFactory.CreateConnectionAsync() - .ConfigureAwait(true); + using var connection = await connectionFactory.CreateConnectionAsync().ConfigureAwait(true); - await connection.StartAsync() - .ConfigureAwait(true); + await connection.StartAsync().ConfigureAwait(true); Assert.True(connection.IsStarted); // Then - using var session = await connection.CreateSessionAsync() - .ConfigureAwait(true); + using var session = await connection.CreateSessionAsync().ConfigureAwait(true); - using var queue = await session.CreateTemporaryQueueAsync() - .ConfigureAwait(true); + using var queue = await session.CreateTemporaryQueueAsync().ConfigureAwait(true); - using var producer = await session.CreateProducerAsync(queue) - .ConfigureAwait(true); + using var producer = await session.CreateProducerAsync(queue).ConfigureAwait(true); - using var consumer = await session.CreateConsumerAsync(queue) - .ConfigureAwait(true); + using var consumer = await session.CreateConsumerAsync(queue).ConfigureAwait(true); - var producedMessage = await producer.CreateTextMessageAsync(Guid.NewGuid().ToString("D")) + var producedMessage = await producer + .CreateTextMessageAsync(Guid.NewGuid().ToString("D")) .ConfigureAwait(true); - await producer.SendAsync(producedMessage) - .ConfigureAwait(true); + await producer.SendAsync(producedMessage).ConfigureAwait(true); - var receivedMessage = await consumer.ReceiveAsync() - .ConfigureAwait(true); + var receivedMessage = await consumer.ReceiveAsync().ConfigureAwait(true); Assert.Equal(producedMessage.Text, receivedMessage.Body()); } + // # --8<-- [end:EstablishConnection] protected virtual ValueTask DisposeAsyncCore() @@ -86,10 +83,13 @@ protected virtual ValueTask DisposeAsyncCore() public sealed class DefaultCredentialsConfiguration : ArtemisContainerTest { public DefaultCredentialsConfiguration() - : base(new ArtemisBuilder().Build(), ArtemisBuilder.DefaultUsername, ArtemisBuilder.DefaultPassword) - { - } + : base( + new ArtemisBuilder().Build(), + ArtemisBuilder.DefaultUsername, + ArtemisBuilder.DefaultPassword + ) { } } + // # --8<-- [end:UseArtemisContainerDefaultAuth] // # --8<-- [start:UseArtemisContainerCustomAuth] @@ -101,10 +101,13 @@ public sealed class CustomCredentialsConfiguration : ArtemisContainerTest private static readonly string Password = Guid.NewGuid().ToString("D"); public CustomCredentialsConfiguration() - : base(new ArtemisBuilder().WithUsername(Username).WithPassword(Password).Build(), Username, Password) - { - } + : base( + new ArtemisBuilder().WithUsername(Username).WithPassword(Password).Build(), + Username, + Password + ) { } } + // # --8<-- [end:UseArtemisContainerCustomAuth] // # --8<-- [start:UseArtemisContainerNoAuth] @@ -112,9 +115,11 @@ public CustomCredentialsConfiguration() public sealed class NoAuthCredentialsConfiguration : ArtemisContainerTest { public NoAuthCredentialsConfiguration() - : base(new ArtemisBuilder().WithEnvironment("ANONYMOUS_LOGIN", bool.TrueString).Build(), string.Empty, string.Empty) - { - } + : base( + new ArtemisBuilder().WithEnvironment("ANONYMOUS_LOGIN", bool.TrueString).Build(), + string.Empty, + string.Empty + ) { } } // # --8<-- [end:UseArtemisContainerNoAuth] -} \ No newline at end of file +} diff --git a/tests/Testcontainers.ActiveMq.Tests/Testcontainers.ActiveMq.Tests.csproj b/tests/Testcontainers.ActiveMq.Tests/Testcontainers.ActiveMq.Tests.csproj index 8fcab8ba8..f8bc9a0cd 100644 --- a/tests/Testcontainers.ActiveMq.Tests/Testcontainers.ActiveMq.Tests.csproj +++ b/tests/Testcontainers.ActiveMq.Tests/Testcontainers.ActiveMq.Tests.csproj @@ -1,21 +1,21 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.ActiveMq.Tests/Usings.cs b/tests/Testcontainers.ActiveMq.Tests/Usings.cs index 3e48de0c1..2083f6789 100644 --- a/tests/Testcontainers.ActiveMq.Tests/Usings.cs +++ b/tests/Testcontainers.ActiveMq.Tests/Usings.cs @@ -3,4 +3,4 @@ global using Apache.NMS.ActiveMQ; global using DotNet.Testcontainers.Commons; global using JetBrains.Annotations; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.ArangoDb.Tests/ArangoDbContainerTest.cs b/tests/Testcontainers.ArangoDb.Tests/ArangoDbContainerTest.cs index e9ee8dd0a..7c77233b5 100644 --- a/tests/Testcontainers.ArangoDb.Tests/ArangoDbContainerTest.cs +++ b/tests/Testcontainers.ArangoDb.Tests/ArangoDbContainerTest.cs @@ -6,8 +6,7 @@ public sealed class ArangoDbContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _arangoDbContainer.StartAsync() - .ConfigureAwait(false); + await _arangoDbContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -22,15 +21,20 @@ public async Task RetrievesDatabases() // Given var address = new Uri(_arangoDbContainer.GetTransportAddress()); - using var transport = HttpApiTransport.UsingBasicAuth(address, ArangoDbBuilder.DefaultUsername, ArangoDbBuilder.DefaultPassword); + using var transport = HttpApiTransport.UsingBasicAuth( + address, + ArangoDbBuilder.DefaultUsername, + ArangoDbBuilder.DefaultPassword + ); using var client = new ArangoDBClient(transport); // When - var response = await client.Database.GetDatabasesAsync(TestContext.Current.CancellationToken) + var response = await client + .Database.GetDatabasesAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal(HttpStatusCode.OK, response.Code); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.ArangoDb.Tests/Testcontainers.ArangoDb.Tests.csproj b/tests/Testcontainers.ArangoDb.Tests/Testcontainers.ArangoDb.Tests.csproj index ff0deab9b..3f589217e 100644 --- a/tests/Testcontainers.ArangoDb.Tests/Testcontainers.ArangoDb.Tests.csproj +++ b/tests/Testcontainers.ArangoDb.Tests/Testcontainers.ArangoDb.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.ArangoDb.Tests/Usings.cs b/tests/Testcontainers.ArangoDb.Tests/Usings.cs index 6ef74341d..f7c659e2c 100644 --- a/tests/Testcontainers.ArangoDb.Tests/Usings.cs +++ b/tests/Testcontainers.ArangoDb.Tests/Usings.cs @@ -4,4 +4,4 @@ global using ArangoDBNetStandard; global using ArangoDBNetStandard.Transport.Http; global using DotNet.Testcontainers.Commons; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Azurite.Tests/AzuriteContainerTest.cs b/tests/Testcontainers.Azurite.Tests/AzuriteContainerTest.cs index 95bfc16b1..2cde5a2d4 100644 --- a/tests/Testcontainers.Azurite.Tests/AzuriteContainerTest.cs +++ b/tests/Testcontainers.Azurite.Tests/AzuriteContainerTest.cs @@ -11,14 +11,12 @@ private AzuriteContainerTest(AzuriteContainer azuriteContainer) public async ValueTask InitializeAsync() { - await _azuriteContainer.StartAsync() - .ConfigureAwait(false); + await _azuriteContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -31,7 +29,8 @@ public async Task EstablishesBlobServiceConnection() var client = new BlobServiceClient(_azuriteContainer.GetConnectionString()); // When - var properties = await client.GetPropertiesAsync(TestContext.Current.CancellationToken) + var properties = await client + .GetPropertiesAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -46,7 +45,8 @@ public async Task EstablishesQueueServiceConnection() var client = new QueueServiceClient(_azuriteContainer.GetConnectionString()); // When - var properties = await client.GetPropertiesAsync(TestContext.Current.CancellationToken) + var properties = await client + .GetPropertiesAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -61,7 +61,8 @@ public async Task EstablishesTableServiceConnection() var client = new TableServiceClient(_azuriteContainer.GetConnectionString()); // When - var properties = await client.GetPropertiesAsync(TestContext.Current.CancellationToken) + var properties = await client + .GetPropertiesAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -85,18 +86,14 @@ private static bool HasError(NullableResponse public sealed class AzuriteDefaultConfiguration : AzuriteContainerTest { public AzuriteDefaultConfiguration() - : base(new AzuriteBuilder().Build()) - { - } + : base(new AzuriteBuilder().Build()) { } } [UsedImplicitly] public sealed class AzuriteInMemoryConfiguration : AzuriteContainerTest { public AzuriteInMemoryConfiguration() - : base(new AzuriteBuilder().WithInMemoryPersistence().Build()) - { - } + : base(new AzuriteBuilder().WithInMemoryPersistence().Build()) { } } [UsedImplicitly] @@ -107,23 +104,31 @@ public sealed class AzuriteMemoryLimitConfiguration : AzuriteContainerTest private static readonly string[] LineEndings = { "\r\n", "\n" }; public AzuriteMemoryLimitConfiguration() - : base(new AzuriteBuilder().WithInMemoryPersistence(MemoryLimitInMb).Build()) - { - } + : base(new AzuriteBuilder().WithInMemoryPersistence(MemoryLimitInMb).Build()) { } [Fact] [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public async Task MemoryLimitIsConfigured() { // Given - var (stdout, _) = await _azuriteContainer.GetLogsAsync(timestampsEnabled: false, ct: TestContext.Current.CancellationToken) + var (stdout, _) = await _azuriteContainer + .GetLogsAsync(timestampsEnabled: false, ct: TestContext.Current.CancellationToken) .ConfigureAwait(true); // When - var firstLine = stdout.Split(LineEndings, StringSplitOptions.RemoveEmptyEntries).First(); + var firstLine = stdout + .Split(LineEndings, StringSplitOptions.RemoveEmptyEntries) + .First(); // Then - Assert.StartsWith(string.Format(CultureInfo.InvariantCulture, "In-memory extent storage is enabled with a limit of {0:F2} MB", MemoryLimitInMb), firstLine); + Assert.StartsWith( + string.Format( + CultureInfo.InvariantCulture, + "In-memory extent storage is enabled with a limit of {0:F2} MB", + MemoryLimitInMb + ), + firstLine + ); } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Azurite.Tests/Testcontainers.Azurite.Tests.csproj b/tests/Testcontainers.Azurite.Tests/Testcontainers.Azurite.Tests.csproj index 227a5a87c..31faa3fec 100644 --- a/tests/Testcontainers.Azurite.Tests/Testcontainers.Azurite.Tests.csproj +++ b/tests/Testcontainers.Azurite.Tests/Testcontainers.Azurite.Tests.csproj @@ -1,21 +1,21 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Azurite.Tests/Usings.cs b/tests/Testcontainers.Azurite.Tests/Usings.cs index 645e958bd..1fc37cf24 100644 --- a/tests/Testcontainers.Azurite.Tests/Usings.cs +++ b/tests/Testcontainers.Azurite.Tests/Usings.cs @@ -8,4 +8,4 @@ global using Azure.Storage.Queues; global using DotNet.Testcontainers.Commons; global using JetBrains.Annotations; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.BigQuery.Tests/BigQueryContainerTest.cs b/tests/Testcontainers.BigQuery.Tests/BigQueryContainerTest.cs index b0a5f3daf..dc1a347df 100644 --- a/tests/Testcontainers.BigQuery.Tests/BigQueryContainerTest.cs +++ b/tests/Testcontainers.BigQuery.Tests/BigQueryContainerTest.cs @@ -6,8 +6,7 @@ public sealed class BigQueryContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _bigQueryContainer.StartAsync() - .ConfigureAwait(false); + await _bigQueryContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -24,7 +23,15 @@ public async Task ExecuteQueryReturnsInsertRow() // Storing DateTime.UtcNow in BigQuery loses precision. The query result differs // in the last digit. Truncating milliseconds prevents running into this issue. - var utcNowWithoutMilliseconds = new DateTime(utcNow.Year, utcNow.Month, utcNow.Day, utcNow.Hour, utcNow.Minute, utcNow.Second, DateTimeKind.Utc); + var utcNowWithoutMilliseconds = new DateTime( + utcNow.Year, + utcNow.Month, + utcNow.Day, + utcNow.Hour, + utcNow.Minute, + utcNow.Second, + DateTimeKind.Utc + ); var bigQueryClientBuilder = new BigQueryClientBuilder(); bigQueryClientBuilder.BaseUri = _bigQueryContainer.GetEmulatorEndpoint(); @@ -42,20 +49,36 @@ public async Task ExecuteQueryReturnsInsertRow() expectedRow.Add("gameStarted", utcNowWithoutMilliseconds); expectedRow.Add("score", 85L); - using var bigQueryClient = await bigQueryClientBuilder.BuildAsync(TestContext.Current.CancellationToken) + using var bigQueryClient = await bigQueryClientBuilder + .BuildAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); - var dataset = await bigQueryClient.GetOrCreateDatasetAsync("mydata", cancellationToken: TestContext.Current.CancellationToken) + var dataset = await bigQueryClient + .GetOrCreateDatasetAsync( + "mydata", + cancellationToken: TestContext.Current.CancellationToken + ) .ConfigureAwait(true); // When - var table = await dataset.CreateTableAsync("scores", tableSchema, cancellationToken: TestContext.Current.CancellationToken) + var table = await dataset + .CreateTableAsync( + "scores", + tableSchema, + cancellationToken: TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - _ = await table.InsertRowAsync(expectedRow, cancellationToken: TestContext.Current.CancellationToken) + _ = await table + .InsertRowAsync(expectedRow, cancellationToken: TestContext.Current.CancellationToken) .ConfigureAwait(true); - var results = await bigQueryClient.ExecuteQueryAsync($"SELECT * FROM {table}", null, cancellationToken: TestContext.Current.CancellationToken) + var results = await bigQueryClient + .ExecuteQueryAsync( + $"SELECT * FROM {table}", + null, + cancellationToken: TestContext.Current.CancellationToken + ) .ConfigureAwait(true); // Then @@ -67,13 +90,14 @@ public async Task ExecuteQueryReturnsInsertRow() private sealed class Credential : ICredential { - public void Initialize(ConfigurableHttpClient httpClient) - { - } + public void Initialize(ConfigurableHttpClient httpClient) { } - public Task GetAccessTokenForRequestAsync(string authUri, CancellationToken cancellationToken) + public Task GetAccessTokenForRequestAsync( + string authUri, + CancellationToken cancellationToken + ) { return Task.FromResult(string.Empty); } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.BigQuery.Tests/Testcontainers.BigQuery.Tests.csproj b/tests/Testcontainers.BigQuery.Tests/Testcontainers.BigQuery.Tests.csproj index 40a94e8e6..c8b1b6fa7 100644 --- a/tests/Testcontainers.BigQuery.Tests/Testcontainers.BigQuery.Tests.csproj +++ b/tests/Testcontainers.BigQuery.Tests/Testcontainers.BigQuery.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.BigQuery.Tests/Usings.cs b/tests/Testcontainers.BigQuery.Tests/Usings.cs index e8c0374a0..8c2148dc4 100644 --- a/tests/Testcontainers.BigQuery.Tests/Usings.cs +++ b/tests/Testcontainers.BigQuery.Tests/Usings.cs @@ -1,9 +1,9 @@ global using System; global using System.Linq; +global using System.Threading; global using System.Threading.Tasks; global using DotNet.Testcontainers.Commons; +global using Google.Apis.Auth.OAuth2; +global using Google.Apis.Http; global using Google.Cloud.BigQuery.V2; global using Xunit; -global using System.Threading; -global using Google.Apis.Auth.OAuth2; -global using Google.Apis.Http; \ No newline at end of file diff --git a/tests/Testcontainers.Bigtable.Tests/BigtableContainerTest.cs b/tests/Testcontainers.Bigtable.Tests/BigtableContainerTest.cs index 944c110a4..b680b5802 100644 --- a/tests/Testcontainers.Bigtable.Tests/BigtableContainerTest.cs +++ b/tests/Testcontainers.Bigtable.Tests/BigtableContainerTest.cs @@ -6,8 +6,7 @@ public sealed class BigtableContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _bigtableContainer.StartAsync() - .ConfigureAwait(false); + await _bigtableContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -43,14 +42,15 @@ public async Task GetTableReturnsCreateTable() bigtableClientBuilder.ChannelCredentials = ChannelCredentials.Insecure; // When - var bigtableClient = await bigtableClientBuilder.BuildAsync(TestContext.Current.CancellationToken) + var bigtableClient = await bigtableClientBuilder + .BuildAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); - _ = await bigtableClient.CreateTableAsync(instanceName, tableName.TableId, table) + _ = await bigtableClient + .CreateTableAsync(instanceName, tableName.TableId, table) .ConfigureAwait(true); - var actualTable = await bigtableClient.GetTableAsync(tableName) - .ConfigureAwait(true); + var actualTable = await bigtableClient.GetTableAsync(tableName).ConfigureAwait(true); // Then Assert.NotNull(actualTable); @@ -58,4 +58,4 @@ public async Task GetTableReturnsCreateTable() Assert.Equal(instanceId, actualTable.TableName.InstanceId); Assert.Equal(tableId, actualTable.TableName.TableId); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Bigtable.Tests/Testcontainers.Bigtable.Tests.csproj b/tests/Testcontainers.Bigtable.Tests/Testcontainers.Bigtable.Tests.csproj index 459d32e96..b5165d7ae 100644 --- a/tests/Testcontainers.Bigtable.Tests/Testcontainers.Bigtable.Tests.csproj +++ b/tests/Testcontainers.Bigtable.Tests/Testcontainers.Bigtable.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Bigtable.Tests/Usings.cs b/tests/Testcontainers.Bigtable.Tests/Usings.cs index 17af3445c..78df5cde3 100644 --- a/tests/Testcontainers.Bigtable.Tests/Usings.cs +++ b/tests/Testcontainers.Bigtable.Tests/Usings.cs @@ -4,4 +4,4 @@ global using Google.Cloud.Bigtable.Admin.V2; global using Google.Cloud.Bigtable.Common.V2; global using Grpc.Core; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Cassandra.Tests/CassandraContainerTest.cs b/tests/Testcontainers.Cassandra.Tests/CassandraContainerTest.cs index b36da8da3..b7a7e8810 100644 --- a/tests/Testcontainers.Cassandra.Tests/CassandraContainerTest.cs +++ b/tests/Testcontainers.Cassandra.Tests/CassandraContainerTest.cs @@ -24,7 +24,10 @@ public void ExecuteCqlStatementReturnsExpectedResult() // Given const string selectFromSystemLocalStatement = "SELECT * FROM system.local WHERE key = ?;"; - using var cluster = Cluster.Builder().WithConnectionString(fixture.Container.GetConnectionString()).Build(); + using var cluster = Cluster + .Builder() + .WithConnectionString(fixture.Container.GetConnectionString()) + .Build(); // When using var session = cluster.Connect(); @@ -39,6 +42,7 @@ public void ExecuteCqlStatementReturnsExpectedResult() Assert.Single(rows); Assert.Equal("COMPLETED", rows[0]["bootstrapped"]); } + // # --8<-- [end:UseCassandraContainer] [Fact] @@ -49,7 +53,11 @@ public async Task ExecScriptAsyncReturnsSuccess() const string selectFromSystemLocalStatement = "SELECT * FROM system.local;"; // When - var execResult = await fixture.Container.ExecScriptAsync(selectFromSystemLocalStatement, TestContext.Current.CancellationToken) + var execResult = await fixture + .Container.ExecScriptAsync( + selectFromSystemLocalStatement, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); // Then @@ -60,23 +68,26 @@ public async Task ExecScriptAsyncReturnsSuccess() public class CassandraDefaultFixture(IMessageSink messageSink) : DbContainerFixture(messageSink) { - public override DbProviderFactory DbProviderFactory - => CqlProviderFactory.Instance; + public override DbProviderFactory DbProviderFactory => CqlProviderFactory.Instance; } [UsedImplicitly] public class CassandraWaitForDatabaseFixture(IMessageSink messageSink) : CassandraDefaultFixture(messageSink) { - protected override CassandraBuilder Configure(CassandraBuilder builder) - => builder.WithWaitStrategy(Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory)); + protected override CassandraBuilder Configure(CassandraBuilder builder) => + builder.WithWaitStrategy( + Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory) + ); } [UsedImplicitly] public sealed class CassandraDefaultConfiguration(CassandraDefaultFixture fixture) - : CassandraContainerTest(fixture), IClassFixture; + : CassandraContainerTest(fixture), + IClassFixture; [UsedImplicitly] - public sealed class CassandraWaitForDatabaseConfiguration(CassandraWaitForDatabaseFixture fixture) - : CassandraContainerTest(fixture), IClassFixture; -} \ No newline at end of file + public sealed class CassandraWaitForDatabaseConfiguration( + CassandraWaitForDatabaseFixture fixture + ) : CassandraContainerTest(fixture), IClassFixture; +} diff --git a/tests/Testcontainers.Cassandra.Tests/Testcontainers.Cassandra.Tests.csproj b/tests/Testcontainers.Cassandra.Tests/Testcontainers.Cassandra.Tests.csproj index 6d8069317..8102ecf07 100644 --- a/tests/Testcontainers.Cassandra.Tests/Testcontainers.Cassandra.Tests.csproj +++ b/tests/Testcontainers.Cassandra.Tests/Testcontainers.Cassandra.Tests.csproj @@ -1,22 +1,22 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Cassandra.Tests/Usings.cs b/tests/Testcontainers.Cassandra.Tests/Usings.cs index d54609621..526bea8db 100644 --- a/tests/Testcontainers.Cassandra.Tests/Usings.cs +++ b/tests/Testcontainers.Cassandra.Tests/Usings.cs @@ -9,4 +9,4 @@ global using JetBrains.Annotations; global using Testcontainers.Xunit; global using Xunit; -global using Xunit.Sdk; \ No newline at end of file +global using Xunit.Sdk; diff --git a/tests/Testcontainers.ClickHouse.Tests/ClickHouseContainerTest.cs b/tests/Testcontainers.ClickHouse.Tests/ClickHouseContainerTest.cs index f3e9399af..06a80beac 100644 --- a/tests/Testcontainers.ClickHouse.Tests/ClickHouseContainerTest.cs +++ b/tests/Testcontainers.ClickHouse.Tests/ClickHouseContainerTest.cs @@ -1,6 +1,8 @@ namespace Testcontainers.ClickHouse; -public abstract partial class ClickHouseContainerTest(ClickHouseContainerTest.ClickHouseDefaultFixture fixture) +public abstract partial class ClickHouseContainerTest( + ClickHouseContainerTest.ClickHouseDefaultFixture fixture +) { [Fact] [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] @@ -24,7 +26,8 @@ public async Task ExecScriptReturnsSuccessful() const string scriptContent = "SELECT 1;"; // When - var execResult = await fixture.Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) + var execResult = await fixture + .Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -35,23 +38,26 @@ public async Task ExecScriptReturnsSuccessful() public class ClickHouseDefaultFixture(IMessageSink messageSink) : DbContainerFixture(messageSink) { - public override DbProviderFactory DbProviderFactory - => ClickHouseConnectionFactory.Instance; + public override DbProviderFactory DbProviderFactory => ClickHouseConnectionFactory.Instance; } [UsedImplicitly] public class ClickHouseWaitForDatabaseFixture(IMessageSink messageSink) : ClickHouseDefaultFixture(messageSink) { - protected override ClickHouseBuilder Configure(ClickHouseBuilder builder) - => builder.WithWaitStrategy(Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory)); + protected override ClickHouseBuilder Configure(ClickHouseBuilder builder) => + builder.WithWaitStrategy( + Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory) + ); } [UsedImplicitly] public sealed class ClickHouseDefaultConfiguration(ClickHouseDefaultFixture fixture) - : ClickHouseContainerTest(fixture), IClassFixture; + : ClickHouseContainerTest(fixture), + IClassFixture; [UsedImplicitly] - public sealed class ClickHouseWaitForDatabaseConfiguration(ClickHouseWaitForDatabaseFixture fixture) - : ClickHouseContainerTest(fixture), IClassFixture; -} \ No newline at end of file + public sealed class ClickHouseWaitForDatabaseConfiguration( + ClickHouseWaitForDatabaseFixture fixture + ) : ClickHouseContainerTest(fixture), IClassFixture; +} diff --git a/tests/Testcontainers.ClickHouse.Tests/ClickHouseContainerTest.docs.cs b/tests/Testcontainers.ClickHouse.Tests/ClickHouseContainerTest.docs.cs index fa32aa388..9abb1d7b0 100644 --- a/tests/Testcontainers.ClickHouse.Tests/ClickHouseContainerTest.docs.cs +++ b/tests/Testcontainers.ClickHouse.Tests/ClickHouseContainerTest.docs.cs @@ -9,15 +9,16 @@ public sealed class ClickHouseContainerExample : IAsyncLifetime public async ValueTask InitializeAsync() { - await _clickHouseContainer.StartAsync(TestContext.Current.CancellationToken) + await _clickHouseContainer + .StartAsync(TestContext.Current.CancellationToken) .ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await _clickHouseContainer.DisposeAsync() - .ConfigureAwait(false); + await _clickHouseContainer.DisposeAsync().ConfigureAwait(false); } + // // @@ -26,7 +27,9 @@ await _clickHouseContainer.DisposeAsync() public void ConnectionStateReturnsOpen() { // Given - using DbConnection connection = new ClickHouseConnection(_clickHouseContainer.GetConnectionString()); + using DbConnection connection = new ClickHouseConnection( + _clickHouseContainer.GetConnectionString() + ); // When connection.Open(); @@ -34,6 +37,7 @@ public void ConnectionStateReturnsOpen() // Then Assert.Equal(ConnectionState.Open, connection.State); } + // // @@ -45,7 +49,8 @@ public async Task ExecScriptReturnsSuccessful() const string scriptContent = "SELECT 1;"; // When - var execResult = await _clickHouseContainer.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) + var execResult = await _clickHouseContainer + .ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -54,4 +59,4 @@ public async Task ExecScriptReturnsSuccessful() } // } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.ClickHouse.Tests/Testcontainers.ClickHouse.Tests.csproj b/tests/Testcontainers.ClickHouse.Tests/Testcontainers.ClickHouse.Tests.csproj index 0c41b53d0..1c799443b 100644 --- a/tests/Testcontainers.ClickHouse.Tests/Testcontainers.ClickHouse.Tests.csproj +++ b/tests/Testcontainers.ClickHouse.Tests/Testcontainers.ClickHouse.Tests.csproj @@ -1,22 +1,22 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.ClickHouse.Tests/Usings.cs b/tests/Testcontainers.ClickHouse.Tests/Usings.cs index 937fd7658..92e9c5d9e 100644 --- a/tests/Testcontainers.ClickHouse.Tests/Usings.cs +++ b/tests/Testcontainers.ClickHouse.Tests/Usings.cs @@ -7,4 +7,4 @@ global using JetBrains.Annotations; global using Testcontainers.Xunit; global using Xunit; -global using Xunit.Sdk; \ No newline at end of file +global using Xunit.Sdk; diff --git a/tests/Testcontainers.CockroachDb.Tests/CockroachDbContainerTest.cs b/tests/Testcontainers.CockroachDb.Tests/CockroachDbContainerTest.cs index 3d974e95b..6a34d3593 100644 --- a/tests/Testcontainers.CockroachDb.Tests/CockroachDbContainerTest.cs +++ b/tests/Testcontainers.CockroachDb.Tests/CockroachDbContainerTest.cs @@ -1,6 +1,8 @@ namespace Testcontainers.CockroachDb; -public abstract class CockroachDbContainerTest(CockroachDbContainerTest.CockroachDbDefaultFixture fixture) +public abstract class CockroachDbContainerTest( + CockroachDbContainerTest.CockroachDbDefaultFixture fixture +) { [Fact] [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] @@ -24,7 +26,8 @@ public async Task ExecScriptReturnsSuccessful() const string scriptContent = "SELECT 1;"; // When - var execResult = await fixture.Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) + var execResult = await fixture + .Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -35,23 +38,26 @@ public async Task ExecScriptReturnsSuccessful() public class CockroachDbDefaultFixture(IMessageSink messageSink) : DbContainerFixture(messageSink) { - public override DbProviderFactory DbProviderFactory - => NpgsqlFactory.Instance; + public override DbProviderFactory DbProviderFactory => NpgsqlFactory.Instance; } [UsedImplicitly] public class CockroachDbWaitForDatabaseFixture(IMessageSink messageSink) : CockroachDbDefaultFixture(messageSink) { - protected override CockroachDbBuilder Configure(CockroachDbBuilder builder) - => builder.WithWaitStrategy(Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory)); + protected override CockroachDbBuilder Configure(CockroachDbBuilder builder) => + builder.WithWaitStrategy( + Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory) + ); } [UsedImplicitly] public sealed class CockroachDbDefaultConfiguration(CockroachDbDefaultFixture fixture) - : CockroachDbContainerTest(fixture), IClassFixture; + : CockroachDbContainerTest(fixture), + IClassFixture; [UsedImplicitly] - public sealed class CockroachDbWaitForDatabaseConfiguration(CockroachDbWaitForDatabaseFixture fixture) - : CockroachDbContainerTest(fixture), IClassFixture; -} \ No newline at end of file + public sealed class CockroachDbWaitForDatabaseConfiguration( + CockroachDbWaitForDatabaseFixture fixture + ) : CockroachDbContainerTest(fixture), IClassFixture; +} diff --git a/tests/Testcontainers.CockroachDb.Tests/Testcontainers.CockroachDb.Tests.csproj b/tests/Testcontainers.CockroachDb.Tests/Testcontainers.CockroachDb.Tests.csproj index bfcde5ba7..81d0b5374 100644 --- a/tests/Testcontainers.CockroachDb.Tests/Testcontainers.CockroachDb.Tests.csproj +++ b/tests/Testcontainers.CockroachDb.Tests/Testcontainers.CockroachDb.Tests.csproj @@ -1,20 +1,20 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.CockroachDb.Tests/Usings.cs b/tests/Testcontainers.CockroachDb.Tests/Usings.cs index 57c4abd89..4b3d3ca0f 100644 --- a/tests/Testcontainers.CockroachDb.Tests/Usings.cs +++ b/tests/Testcontainers.CockroachDb.Tests/Usings.cs @@ -7,4 +7,4 @@ global using Npgsql; global using Testcontainers.Xunit; global using Xunit; -global using Xunit.Sdk; \ No newline at end of file +global using Xunit.Sdk; diff --git a/tests/Testcontainers.Commons/CommonCommands.cs b/tests/Testcontainers.Commons/CommonCommands.cs index c33ebf7ee..c64cca382 100644 --- a/tests/Testcontainers.Commons/CommonCommands.cs +++ b/tests/Testcontainers.Commons/CommonCommands.cs @@ -3,5 +3,10 @@ namespace DotNet.Testcontainers.Commons; [PublicAPI] public static class CommonCommands { - public static readonly string[] SleepInfinity = { "/bin/sh", "-c", "trap : TERM INT; sleep infinity & wait" }; -} \ No newline at end of file + public static readonly string[] SleepInfinity = + { + "/bin/sh", + "-c", + "trap : TERM INT; sleep infinity & wait", + }; +} diff --git a/tests/Testcontainers.Commons/CommonCredentials.cs b/tests/Testcontainers.Commons/CommonCredentials.cs index 3e89feb4b..4648f234d 100644 --- a/tests/Testcontainers.Commons/CommonCredentials.cs +++ b/tests/Testcontainers.Commons/CommonCredentials.cs @@ -6,4 +6,4 @@ public static class CommonCredentials public const string AwsAccessKey = "AKIAIOSFODNN7EXAMPLE"; public const string AwsSecretKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"; -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Commons/CommonImages.cs b/tests/Testcontainers.Commons/CommonImages.cs index 6d3eccf36..a40be2b16 100644 --- a/tests/Testcontainers.Commons/CommonImages.cs +++ b/tests/Testcontainers.Commons/CommonImages.cs @@ -15,5 +15,7 @@ public static class CommonImages public static readonly IImage Nginx = new DockerImage("nginx:1.22"); - public static readonly IImage ServerCore = new DockerImage("mcr.microsoft.com/windows/servercore:ltsc2022"); -} \ No newline at end of file + public static readonly IImage ServerCore = new DockerImage( + "mcr.microsoft.com/windows/servercore:ltsc2022" + ); +} diff --git a/tests/Testcontainers.Commons/DockerCli.cs b/tests/Testcontainers.Commons/DockerCli.cs index 9b6d46a93..6b9a51329 100644 --- a/tests/Testcontainers.Commons/DockerCli.cs +++ b/tests/Testcontainers.Commons/DockerCli.cs @@ -44,18 +44,31 @@ public enum DockerResource public static bool PlatformIsEnabled(DockerPlatform platform) { var commandResult = new Command("version", "--format {{.Server.Os}}").Execute(); - return 0.Equals(commandResult.ExitCode) && commandResult.Stdout.Contains(platform.ToString(), StringComparison.OrdinalIgnoreCase); + return 0.Equals(commandResult.ExitCode) + && commandResult.Stdout.Contains( + platform.ToString(), + StringComparison.OrdinalIgnoreCase + ); } public static bool ResourceExists(DockerResource resource, string id) { - var commandResult = new Command("inspect", "--type=" + resource.ToString().ToLowerInvariant(), id).Execute(); + var commandResult = new Command( + "inspect", + "--type=" + resource.ToString().ToLowerInvariant(), + id + ).Execute(); return 0.Equals(commandResult.ExitCode); } public static Uri GetCurrentEndpoint(string context = "") { - var commandResult = new Command("context", "inspect", "--format {{.Endpoints.docker.Host}}", context).Execute(); + var commandResult = new Command( + "context", + "inspect", + "--format {{.Endpoints.docker.Host}}", + context + ).Execute(); commandResult.ThrowIfExecutionFailed(); return new Uri(commandResult.Stdout.Replace("npipe:////./", "npipe://./")); } @@ -105,7 +118,14 @@ public CommandResult Execute() process.ErrorDataReceived -= AppendStderr; } - return new CommandResult(this, process.ExitCode, startTime, exitTime, _stdout.ToString(), _stderr.ToString()); + return new CommandResult( + this, + process.ExitCode, + startTime, + exitTime, + _stdout.ToString(), + _stderr.ToString() + ); } private void AppendStdout(object sender, DataReceivedEventArgs e) @@ -127,7 +147,14 @@ public override string ToString() [PublicAPI] private sealed class CommandResult { - public CommandResult(Command command, int exitCode, DateTime startTime, DateTime exitTime, string stdout, string stderr) + public CommandResult( + Command command, + int exitCode, + DateTime startTime, + DateTime exitTime, + string stdout, + string stderr + ) { Command = command; ExitCode = exitCode; @@ -157,4 +184,4 @@ public void ThrowIfExecutionFailed() } } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Commons/TestSession.cs b/tests/Testcontainers.Commons/TestSession.cs index 832019245..3ae65dfd8 100644 --- a/tests/Testcontainers.Commons/TestSession.cs +++ b/tests/Testcontainers.Commons/TestSession.cs @@ -3,10 +3,14 @@ namespace DotNet.Testcontainers.Commons; [PublicAPI] public static class TestSession { - public static readonly string TempDirectoryPath = Path.Combine(Path.GetTempPath(), "testcontainers-tests", Guid.NewGuid().ToString("D")); + public static readonly string TempDirectoryPath = Path.Combine( + Path.GetTempPath(), + "testcontainers-tests", + Guid.NewGuid().ToString("D") + ); static TestSession() { Directory.CreateDirectory(TempDirectoryPath); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Commons/Testcontainers.Commons.csproj b/tests/Testcontainers.Commons/Testcontainers.Commons.csproj index 33932eacf..5c21d7236 100644 --- a/tests/Testcontainers.Commons/Testcontainers.Commons.csproj +++ b/tests/Testcontainers.Commons/Testcontainers.Commons.csproj @@ -1,16 +1,16 @@ - - net9.0 - false - false - false - true - latest - - - - - - - - \ No newline at end of file + + net9.0 + false + false + false + true + latest + + + + + + + + diff --git a/tests/Testcontainers.Commons/Usings.cs b/tests/Testcontainers.Commons/Usings.cs index 904e633f5..bdf655e42 100644 --- a/tests/Testcontainers.Commons/Usings.cs +++ b/tests/Testcontainers.Commons/Usings.cs @@ -3,4 +3,4 @@ global using System.IO; global using System.Text; global using DotNet.Testcontainers.Images; -global using JetBrains.Annotations; \ No newline at end of file +global using JetBrains.Annotations; diff --git a/tests/Testcontainers.Consul.Tests/ConsulContainerTest.cs b/tests/Testcontainers.Consul.Tests/ConsulContainerTest.cs index e3df11f36..b49fc0694 100644 --- a/tests/Testcontainers.Consul.Tests/ConsulContainerTest.cs +++ b/tests/Testcontainers.Consul.Tests/ConsulContainerTest.cs @@ -6,8 +6,7 @@ public sealed class ConsulContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _consulContainer.StartAsync() - .ConfigureAwait(false); + await _consulContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -33,14 +32,16 @@ public async Task GetItemReturnsPutItem() using var consulClient = new ConsulClient(consulClientConfiguration); // When - _ = await consulClient.KV.Put(expected, TestContext.Current.CancellationToken) + _ = await consulClient + .KV.Put(expected, TestContext.Current.CancellationToken) .ConfigureAwait(true); - var actual = await consulClient.KV.Get(key, TestContext.Current.CancellationToken) + var actual = await consulClient + .KV.Get(key, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal(HttpStatusCode.OK, actual.StatusCode); Assert.Equal(helloWorld, Encoding.Default.GetString(actual.Response.Value)); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Consul.Tests/Testcontainers.Consul.Tests.csproj b/tests/Testcontainers.Consul.Tests/Testcontainers.Consul.Tests.csproj index 2f74bb812..c0f003a8b 100644 --- a/tests/Testcontainers.Consul.Tests/Testcontainers.Consul.Tests.csproj +++ b/tests/Testcontainers.Consul.Tests/Testcontainers.Consul.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Consul.Tests/Usings.cs b/tests/Testcontainers.Consul.Tests/Usings.cs index 639ca0966..bdbd58bd5 100644 --- a/tests/Testcontainers.Consul.Tests/Usings.cs +++ b/tests/Testcontainers.Consul.Tests/Usings.cs @@ -4,4 +4,4 @@ global using System.Threading.Tasks; global using Consul; global using DotNet.Testcontainers.Commons; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.CosmosDb.Tests/CosmosDbContainerTest.cs b/tests/Testcontainers.CosmosDb.Tests/CosmosDbContainerTest.cs index 68aa994b6..278fa5f36 100644 --- a/tests/Testcontainers.CosmosDb.Tests/CosmosDbContainerTest.cs +++ b/tests/Testcontainers.CosmosDb.Tests/CosmosDbContainerTest.cs @@ -6,8 +6,7 @@ public sealed class CosmosDbContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _cosmosDbContainer.StartAsync() - .ConfigureAwait(false); + await _cosmosDbContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -15,7 +14,9 @@ public ValueTask DisposeAsync() return _cosmosDbContainer.DisposeAsync(); } - [Fact(Skip = "The Cosmos DB Linux Emulator Docker image does not run on Microsoft's CI environment (GitHub, Azure DevOps).")] // https://github.com/Azure/azure-cosmos-db-emulator-docker/issues/45. + [Fact( + Skip = "The Cosmos DB Linux Emulator Docker image does not run on Microsoft's CI environment (GitHub, Azure DevOps)." + )] // https://github.com/Azure/azure-cosmos-db-emulator-docker/issues/45. [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public async Task AccountPropertiesIdReturnsLocalhost() { @@ -26,13 +27,15 @@ public async Task AccountPropertiesIdReturnsLocalhost() cosmosClientOptions.ConnectionMode = ConnectionMode.Gateway; cosmosClientOptions.HttpClientFactory = () => httpClient; - using var cosmosClient = new CosmosClient(_cosmosDbContainer.GetConnectionString(), cosmosClientOptions); + using var cosmosClient = new CosmosClient( + _cosmosDbContainer.GetConnectionString(), + cosmosClientOptions + ); // When - var accountProperties = await cosmosClient.ReadAccountAsync() - .ConfigureAwait(true); + var accountProperties = await cosmosClient.ReadAccountAsync().ConfigureAwait(true); // Then Assert.Equal("localhost", accountProperties.Id); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.CosmosDb.Tests/Testcontainers.CosmosDb.Tests.csproj b/tests/Testcontainers.CosmosDb.Tests/Testcontainers.CosmosDb.Tests.csproj index 56531df24..eb1fdb0b7 100644 --- a/tests/Testcontainers.CosmosDb.Tests/Testcontainers.CosmosDb.Tests.csproj +++ b/tests/Testcontainers.CosmosDb.Tests/Testcontainers.CosmosDb.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.CosmosDb.Tests/Usings.cs b/tests/Testcontainers.CosmosDb.Tests/Usings.cs index 3f12d7755..930afa409 100644 --- a/tests/Testcontainers.CosmosDb.Tests/Usings.cs +++ b/tests/Testcontainers.CosmosDb.Tests/Usings.cs @@ -1,4 +1,4 @@ global using System.Threading.Tasks; global using DotNet.Testcontainers.Commons; global using Microsoft.Azure.Cosmos; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.CouchDb.Tests/CouchDbContainerTest.cs b/tests/Testcontainers.CouchDb.Tests/CouchDbContainerTest.cs index b01305c78..efab4c52a 100644 --- a/tests/Testcontainers.CouchDb.Tests/CouchDbContainerTest.cs +++ b/tests/Testcontainers.CouchDb.Tests/CouchDbContainerTest.cs @@ -6,8 +6,7 @@ public sealed class CouchDbContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _couchDbContainer.StartAsync() - .ConfigureAwait(false); + await _couchDbContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -23,10 +22,11 @@ public async Task PutDatabaseReturnsHttpStatusCodeCreated() using var client = new MyCouchClient(_couchDbContainer.GetConnectionString(), "db"); // When - var database = await client.Database.PutAsync(TestContext.Current.CancellationToken) + var database = await client + .Database.PutAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal(HttpStatusCode.Created, database.StatusCode); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.CouchDb.Tests/Testcontainers.CouchDb.Tests.csproj b/tests/Testcontainers.CouchDb.Tests/Testcontainers.CouchDb.Tests.csproj index 3df7fc19f..2d0cc43a0 100644 --- a/tests/Testcontainers.CouchDb.Tests/Testcontainers.CouchDb.Tests.csproj +++ b/tests/Testcontainers.CouchDb.Tests/Testcontainers.CouchDb.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.CouchDb.Tests/Usings.cs b/tests/Testcontainers.CouchDb.Tests/Usings.cs index b66650bf3..584fb1fa0 100644 --- a/tests/Testcontainers.CouchDb.Tests/Usings.cs +++ b/tests/Testcontainers.CouchDb.Tests/Usings.cs @@ -2,4 +2,4 @@ global using System.Threading.Tasks; global using DotNet.Testcontainers.Commons; global using MyCouch; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Couchbase.Tests/CouchbaseContainerTest.cs b/tests/Testcontainers.Couchbase.Tests/CouchbaseContainerTest.cs index 85e08750f..882402009 100644 --- a/tests/Testcontainers.Couchbase.Tests/CouchbaseContainerTest.cs +++ b/tests/Testcontainers.Couchbase.Tests/CouchbaseContainerTest.cs @@ -6,8 +6,7 @@ public sealed class CouchbaseContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _couchbaseContainer.StartAsync() - .ConfigureAwait(false); + await _couchbaseContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -25,14 +24,13 @@ public async Task GetBucketReturnsDefaultBucket() clusterOptions.UserName = CouchbaseBuilder.DefaultUsername; clusterOptions.Password = CouchbaseBuilder.DefaultPassword; - var cluster = await Cluster.ConnectAsync(clusterOptions) - .ConfigureAwait(true); + var cluster = await Cluster.ConnectAsync(clusterOptions).ConfigureAwait(true); // When - var ping = await cluster.PingAsync() - .ConfigureAwait(true); + var ping = await cluster.PingAsync().ConfigureAwait(true); - var bucket = await cluster.BucketAsync(_couchbaseContainer.Buckets.Single().Name) + var bucket = await cluster + .BucketAsync(_couchbaseContainer.Buckets.Single().Name) .ConfigureAwait(true); // Then @@ -40,4 +38,4 @@ public async Task GetBucketReturnsDefaultBucket() Assert.NotEmpty(ping.Services); Assert.NotEmpty(bucket.Name); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Couchbase.Tests/Testcontainers.Couchbase.Tests.csproj b/tests/Testcontainers.Couchbase.Tests/Testcontainers.Couchbase.Tests.csproj index 2439c82c6..7b3259914 100644 --- a/tests/Testcontainers.Couchbase.Tests/Testcontainers.Couchbase.Tests.csproj +++ b/tests/Testcontainers.Couchbase.Tests/Testcontainers.Couchbase.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Couchbase.Tests/Usings.cs b/tests/Testcontainers.Couchbase.Tests/Usings.cs index f19c233d3..34041bbb1 100644 --- a/tests/Testcontainers.Couchbase.Tests/Usings.cs +++ b/tests/Testcontainers.Couchbase.Tests/Usings.cs @@ -2,4 +2,4 @@ global using System.Threading.Tasks; global using Couchbase; global using DotNet.Testcontainers.Commons; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Databases.Tests/DatabasesContainerTest.cs b/tests/Testcontainers.Databases.Tests/DatabasesContainerTest.cs index f4e7d156d..1b182f310 100644 --- a/tests/Testcontainers.Databases.Tests/DatabasesContainerTest.cs +++ b/tests/Testcontainers.Databases.Tests/DatabasesContainerTest.cs @@ -6,38 +6,62 @@ public sealed class DatabaseContainersTest [MemberData(nameof(GetContainerImplementations), arguments: true)] public void ShouldImplementIDatabaseContainer(Type type) { - Assert.True(type.IsAssignableTo(typeof(IDatabaseContainer)), $"The type '{type.Name}' does not implement the database interface."); + Assert.True( + type.IsAssignableTo(typeof(IDatabaseContainer)), + $"The type '{type.Name}' does not implement the database interface." + ); } [Theory] [MemberData(nameof(GetContainerImplementations), arguments: false)] public void ShouldNotImplementIDatabaseContainer(Type type) { - Assert.False(type.IsAssignableTo(typeof(IDatabaseContainer)), $"The type '{type.Name}' does implement the database interface."); + Assert.False( + type.IsAssignableTo(typeof(IDatabaseContainer)), + $"The type '{type.Name}' does implement the database interface." + ); } public static TheoryData GetContainerImplementations(bool expectDataProvider) { var theoryData = new TheoryData(); - var testAssemblies = Directory.GetFiles(".", "Testcontainers.*.Tests.dll", SearchOption.TopDirectoryOnly) + var testAssemblies = Directory + .GetFiles(".", "Testcontainers.*.Tests.dll", SearchOption.TopDirectoryOnly) .Select(Path.GetFullPath) .Select(Assembly.LoadFrom) - .ToDictionary(assembly => assembly, assembly => assembly.GetReferencedAssemblies() - .Where(referencedAssembly => referencedAssembly.Name != null) - .Where(referencedAssembly => !referencedAssembly.Name.StartsWith("System")) - .Where(referencedAssembly => !referencedAssembly.Name.StartsWith("xunit")) - .Where(referencedAssembly => !referencedAssembly.Name.Equals("Microsoft.VisualStudio.TestPlatform.ObjectModel")) - .Where(referencedAssembly => !referencedAssembly.Name.Equals("Docker.DotNet")) - .Where(referencedAssembly => !referencedAssembly.Name.Equals("Testcontainers")) - .Select(Assembly.Load) - .SelectMany(referencedAssembly => referencedAssembly.ExportedTypes) - .ToImmutableList()); + .ToDictionary( + assembly => assembly, + assembly => + assembly + .GetReferencedAssemblies() + .Where(referencedAssembly => referencedAssembly.Name != null) + .Where(referencedAssembly => !referencedAssembly.Name.StartsWith("System")) + .Where(referencedAssembly => !referencedAssembly.Name.StartsWith("xunit")) + .Where(referencedAssembly => + !referencedAssembly.Name.Equals( + "Microsoft.VisualStudio.TestPlatform.ObjectModel" + ) + ) + .Where(referencedAssembly => + !referencedAssembly.Name.Equals("Docker.DotNet") + ) + .Where(referencedAssembly => + !referencedAssembly.Name.Equals("Testcontainers") + ) + .Select(Assembly.Load) + .SelectMany(referencedAssembly => referencedAssembly.ExportedTypes) + .ToImmutableList() + ); foreach (var testAssembly in testAssemblies) { // TODO: If a module contains multiple container implementations, it would require all container implementations to implement the interface. - foreach (var containerType in testAssembly.Value.Where(type => type.IsAssignableTo(typeof(IContainer)))) + foreach ( + var containerType in testAssembly.Value.Where(type => + type.IsAssignableTo(typeof(IContainer)) + ) + ) { var testAssemblyName = testAssembly.Key.GetName().Name!; @@ -47,12 +71,19 @@ public static TheoryData GetContainerImplementations(bool expectDataProvid // if it does not belong to the actual module. For example, the ServiceBus module // utilizes the MsSql module. We do not want to include the MsSqlContainer type // twice or place it in the wrong test. - if (!testAssemblyName.Contains(containerTypeAssemblyName, StringComparison.OrdinalIgnoreCase)) + if ( + !testAssemblyName.Contains( + containerTypeAssemblyName, + StringComparison.OrdinalIgnoreCase + ) + ) { continue; } - var hasDataProvider = testAssembly.Value.Exists(type => type.IsSubclassOf(typeof(DbProviderFactory))); + var hasDataProvider = testAssembly.Value.Exists(type => + type.IsSubclassOf(typeof(DbProviderFactory)) + ); if (expectDataProvider && hasDataProvider) { @@ -68,4 +99,4 @@ public static TheoryData GetContainerImplementations(bool expectDataProvid return theoryData; } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Databases.Tests/Testcontainers.Databases.Tests.csproj b/tests/Testcontainers.Databases.Tests/Testcontainers.Databases.Tests.csproj index f80dbd54b..1991a50cc 100644 --- a/tests/Testcontainers.Databases.Tests/Testcontainers.Databases.Tests.csproj +++ b/tests/Testcontainers.Databases.Tests/Testcontainers.Databases.Tests.csproj @@ -1,20 +1,20 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Databases.Tests/Usings.cs b/tests/Testcontainers.Databases.Tests/Usings.cs index 5eaa436ef..f38b2ccbe 100644 --- a/tests/Testcontainers.Databases.Tests/Usings.cs +++ b/tests/Testcontainers.Databases.Tests/Usings.cs @@ -5,4 +5,4 @@ global using System.Linq; global using System.Reflection; global using DotNet.Testcontainers.Containers; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Db2.Tests/Db2ContainerTest.cs b/tests/Testcontainers.Db2.Tests/Db2ContainerTest.cs index f1a192c37..ee8857fc6 100644 --- a/tests/Testcontainers.Db2.Tests/Db2ContainerTest.cs +++ b/tests/Testcontainers.Db2.Tests/Db2ContainerTest.cs @@ -25,38 +25,44 @@ public async Task ExecScriptReturnsSuccessful() const string scriptContent = "SELECT 1 FROM SYSIBM.SYSDUMMY1;"; // When - var execResult = await fixture.Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) + var execResult = await fixture + .Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.True(0L.Equals(execResult.ExitCode), execResult.Stderr); Assert.Empty(execResult.Stderr); } + // # --8<-- [end:UseDb2Container] public class Db2DefaultFixture(IMessageSink messageSink) : DbContainerFixture(messageSink) { - public override DbProviderFactory DbProviderFactory - => DB2Factory.Instance; + public override DbProviderFactory DbProviderFactory => DB2Factory.Instance; - protected override Db2Builder Configure(Db2Builder builder) - => builder.WithAcceptLicenseAgreement(true); + protected override Db2Builder Configure(Db2Builder builder) => + builder.WithAcceptLicenseAgreement(true); } [UsedImplicitly] public class Db2WaitForDatabaseFixture(IMessageSink messageSink) : Db2DefaultFixture(messageSink) { - protected override Db2Builder Configure(Db2Builder builder) - => base.Configure(builder).WithWaitStrategy(Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory)); + protected override Db2Builder Configure(Db2Builder builder) => + base.Configure(builder) + .WithWaitStrategy( + Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory) + ); } [UsedImplicitly] public sealed class Db2DefaultConfiguration(Db2DefaultFixture fixture) - : Db2ContainerTest(fixture), IClassFixture; + : Db2ContainerTest(fixture), + IClassFixture; [UsedImplicitly] public sealed class Db2WaitForDatabaseConfiguration(Db2WaitForDatabaseFixture fixture) - : Db2ContainerTest(fixture), IClassFixture; -} \ No newline at end of file + : Db2ContainerTest(fixture), + IClassFixture; +} diff --git a/tests/Testcontainers.Db2.Tests/DeclineLicenseAgreementTest.cs b/tests/Testcontainers.Db2.Tests/DeclineLicenseAgreementTest.cs index 08744ea28..b72402192 100644 --- a/tests/Testcontainers.Db2.Tests/DeclineLicenseAgreementTest.cs +++ b/tests/Testcontainers.Db2.Tests/DeclineLicenseAgreementTest.cs @@ -17,7 +17,9 @@ public void WithoutAcceptingLicenseAgreementThrowsArgumentException() [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public void WithLicenseAgreementDeclinedThrowsArgumentException() { - var exception = Assert.Throws(() => new Db2Builder().WithAcceptLicenseAgreement(false).Build()); + var exception = Assert.Throws(() => + new Db2Builder().WithAcceptLicenseAgreement(false).Build() + ); Assert.Matches(LicenseAgreementNotAccepted(), exception.Message); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Db2.Tests/Testcontainers.Db2.Tests.csproj b/tests/Testcontainers.Db2.Tests/Testcontainers.Db2.Tests.csproj index fb08566ec..1f6dc0625 100644 --- a/tests/Testcontainers.Db2.Tests/Testcontainers.Db2.Tests.csproj +++ b/tests/Testcontainers.Db2.Tests/Testcontainers.Db2.Tests.csproj @@ -1,31 +1,34 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Db2.Tests/Testcontainers.Db2.Tests.targets b/tests/Testcontainers.Db2.Tests/Testcontainers.Db2.Tests.targets index 32b2c12b2..b624310a3 100644 --- a/tests/Testcontainers.Db2.Tests/Testcontainers.Db2.Tests.targets +++ b/tests/Testcontainers.Db2.Tests/Testcontainers.Db2.Tests.targets @@ -1,22 +1,22 @@ - - $(MSBuildProjectDirectory)/linux.runsettings - - - - - - - \ No newline at end of file + + $(MSBuildProjectDirectory)/linux.runsettings + + + + + + + diff --git a/tests/Testcontainers.Db2.Tests/Usings.cs b/tests/Testcontainers.Db2.Tests/Usings.cs index 2b89f65a2..004dd02ac 100644 --- a/tests/Testcontainers.Db2.Tests/Usings.cs +++ b/tests/Testcontainers.Db2.Tests/Usings.cs @@ -1,7 +1,7 @@ global using System; global using System.Data; -global using System.Text.RegularExpressions; global using System.Data.Common; +global using System.Text.RegularExpressions; global using System.Threading.Tasks; global using DotNet.Testcontainers.Builders; global using DotNet.Testcontainers.Commons; @@ -9,4 +9,4 @@ global using JetBrains.Annotations; global using Testcontainers.Xunit; global using Xunit; -global using Xunit.Sdk; \ No newline at end of file +global using Xunit.Sdk; diff --git a/tests/Testcontainers.DynamoDb.Tests/DynamoDbContainerTest.cs b/tests/Testcontainers.DynamoDb.Tests/DynamoDbContainerTest.cs index 647d52854..63bc9c492 100644 --- a/tests/Testcontainers.DynamoDb.Tests/DynamoDbContainerTest.cs +++ b/tests/Testcontainers.DynamoDb.Tests/DynamoDbContainerTest.cs @@ -12,8 +12,7 @@ static DynamoDbContainerTest() public async ValueTask InitializeAsync() { - await _dynamoDbContainer.StartAsync() - .ConfigureAwait(false); + await _dynamoDbContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -32,7 +31,8 @@ public async Task ListBucketsReturnsHttpStatusCodeOk() using var client = new AmazonDynamoDBClient(config); // When - var tables = await client.ListTablesAsync(TestContext.Current.CancellationToken) + var tables = await client + .ListTablesAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -55,29 +55,50 @@ public async Task GetItemReturnsPutItem() var tableRequest = new CreateTableRequest(); tableRequest.TableName = tableName; - tableRequest.AttributeDefinitions = new List { new AttributeDefinition("Id", ScalarAttributeType.S) }; - tableRequest.KeySchema = new List { new KeySchemaElement("Id", KeyType.HASH) }; + tableRequest.AttributeDefinitions = new List + { + new AttributeDefinition("Id", ScalarAttributeType.S), + }; + tableRequest.KeySchema = new List + { + new KeySchemaElement("Id", KeyType.HASH), + }; tableRequest.ProvisionedThroughput = new ProvisionedThroughput(10, 5); var putItemRequest = new PutItemRequest(); putItemRequest.TableName = tableName; - putItemRequest.Item = new Dictionary { { "Id", new AttributeValue { S = id } } }; + putItemRequest.Item = new Dictionary + { + { + "Id", + new AttributeValue { S = id } + }, + }; var getItemRequest = new GetItemRequest(); getItemRequest.TableName = tableName; - getItemRequest.Key = new Dictionary { { "Id", new AttributeValue { S = id } } }; + getItemRequest.Key = new Dictionary + { + { + "Id", + new AttributeValue { S = id } + }, + }; // When - _ = await client.CreateTableAsync(tableRequest, TestContext.Current.CancellationToken) + _ = await client + .CreateTableAsync(tableRequest, TestContext.Current.CancellationToken) .ConfigureAwait(true); - _ = await client.PutItemAsync(putItemRequest, TestContext.Current.CancellationToken) + _ = await client + .PutItemAsync(putItemRequest, TestContext.Current.CancellationToken) .ConfigureAwait(true); - var itemResponse = await client.GetItemAsync(getItemRequest, TestContext.Current.CancellationToken) + var itemResponse = await client + .GetItemAsync(getItemRequest, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal(id, itemResponse.Item.Values.Single().S); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.DynamoDb.Tests/Testcontainers.DynamoDb.Tests.csproj b/tests/Testcontainers.DynamoDb.Tests/Testcontainers.DynamoDb.Tests.csproj index 86743dc28..549f6d040 100644 --- a/tests/Testcontainers.DynamoDb.Tests/Testcontainers.DynamoDb.Tests.csproj +++ b/tests/Testcontainers.DynamoDb.Tests/Testcontainers.DynamoDb.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.DynamoDb.Tests/Usings.cs b/tests/Testcontainers.DynamoDb.Tests/Usings.cs index 1629ce9dd..f4d0e94aa 100644 --- a/tests/Testcontainers.DynamoDb.Tests/Usings.cs +++ b/tests/Testcontainers.DynamoDb.Tests/Usings.cs @@ -6,4 +6,4 @@ global using Amazon.DynamoDBv2; global using Amazon.DynamoDBv2.Model; global using DotNet.Testcontainers.Commons; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Elasticsearch.Tests/ElasticsearchContainerTest.cs b/tests/Testcontainers.Elasticsearch.Tests/ElasticsearchContainerTest.cs index dec18b2e5..f34af7789 100644 --- a/tests/Testcontainers.Elasticsearch.Tests/ElasticsearchContainerTest.cs +++ b/tests/Testcontainers.Elasticsearch.Tests/ElasticsearchContainerTest.cs @@ -3,12 +3,12 @@ namespace Testcontainers.Elasticsearch; public sealed class ElasticsearchContainerTest : IAsyncLifetime { // # --8<-- [start:UseElasticsearchContainer] - private readonly ElasticsearchContainer _elasticsearchContainer = new ElasticsearchBuilder().Build(); + private readonly ElasticsearchContainer _elasticsearchContainer = + new ElasticsearchBuilder().Build(); public async ValueTask InitializeAsync() { - await _elasticsearchContainer.StartAsync() - .ConfigureAwait(false); + await _elasticsearchContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -21,7 +21,9 @@ public ValueTask DisposeAsync() public void PingReturnsValidResponse() { // Given - var clientSettings = new ElasticsearchClientSettings(new Uri(_elasticsearchContainer.GetConnectionString())); + var clientSettings = new ElasticsearchClientSettings( + new Uri(_elasticsearchContainer.GetConnectionString()) + ); clientSettings.ServerCertificateValidationCallback(CertificateValidations.AllowAll); var client = new ElasticsearchClient(clientSettings); @@ -33,4 +35,4 @@ public void PingReturnsValidResponse() Assert.True(response.IsValidResponse); } // # --8<-- [end:UseElasticsearchContainer] -} \ 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 aa5df6f31..97d141d89 100644 --- a/tests/Testcontainers.Elasticsearch.Tests/Testcontainers.Elasticsearch.Tests.csproj +++ b/tests/Testcontainers.Elasticsearch.Tests/Testcontainers.Elasticsearch.Tests.csproj @@ -1,21 +1,21 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Elasticsearch.Tests/Usings.cs b/tests/Testcontainers.Elasticsearch.Tests/Usings.cs index 97ffa76b0..487f31e7f 100644 --- a/tests/Testcontainers.Elasticsearch.Tests/Usings.cs +++ b/tests/Testcontainers.Elasticsearch.Tests/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Commons; global using Elastic.Clients.Elasticsearch; global using Elastic.Transport; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.EventHubs.Tests/EventHubsContainerTest.cs b/tests/Testcontainers.EventHubs.Tests/EventHubsContainerTest.cs index 4969e9df0..ab5ba7714 100644 --- a/tests/Testcontainers.EventHubs.Tests/EventHubsContainerTest.cs +++ b/tests/Testcontainers.EventHubs.Tests/EventHubsContainerTest.cs @@ -16,21 +16,26 @@ private EventHubsContainerTest(EventHubsContainer eventHubsContainer) // # --8<-- [start:UseEventHubsContainer] public async ValueTask InitializeAsync() { - await _eventHubsContainer.StartAsync() - .ConfigureAwait(false); + await _eventHubsContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } private static EventHubsServiceConfiguration GetServiceConfiguration() { - return EventHubsServiceConfiguration.Create().WithEntity(EventHubsName, 2, EventHubConsumerClient.DefaultConsumerGroupName, EventHubsConsumerGroupName); + return EventHubsServiceConfiguration + .Create() + .WithEntity( + EventHubsName, + 2, + EventHubConsumerClient.DefaultConsumerGroupName, + EventHubsConsumerGroupName + ); } [Fact] @@ -43,20 +48,30 @@ public async Task SendEventDataBatchShouldNotThrowException() var readOptions = new ReadEventOptions(); readOptions.MaximumWaitTime = TimeSpan.FromSeconds(5); - await using var producer = new EventHubProducerClient(_eventHubsContainer.GetConnectionString(), EventHubsName); + await using var producer = new EventHubProducerClient( + _eventHubsContainer.GetConnectionString(), + EventHubsName + ); - await using var consumer = new EventHubConsumerClient(EventHubsConsumerGroupName, _eventHubsContainer.GetConnectionString(), EventHubsName); + await using var consumer = new EventHubConsumerClient( + EventHubsConsumerGroupName, + _eventHubsContainer.GetConnectionString(), + EventHubsName + ); // When - using var eventDataBatch = await producer.CreateBatchAsync(TestContext.Current.CancellationToken) + using var eventDataBatch = await producer + .CreateBatchAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); _ = eventDataBatch.TryAdd(new EventData(message)); - await producer.SendAsync(eventDataBatch, TestContext.Current.CancellationToken) + await producer + .SendAsync(eventDataBatch, TestContext.Current.CancellationToken) .ConfigureAwait(true); - await using var asyncEnumerator = consumer.ReadEventsAsync(readOptions, TestContext.Current.CancellationToken) + await using var asyncEnumerator = consumer + .ReadEventsAsync(readOptions, TestContext.Current.CancellationToken) .WithCancellation(TestContext.Current.CancellationToken) .GetAsyncEnumerator(); _ = await asyncEnumerator.MoveNextAsync(); @@ -64,6 +79,7 @@ await producer.SendAsync(eventDataBatch, TestContext.Current.CancellationToken) // Then Assert.Equal(message, Encoding.UTF8.GetString(asyncEnumerator.Current.Data.Body.Span)); } + // # --8<-- [end:UseEventHubsContainer] protected virtual ValueTask DisposeAsyncCore() @@ -76,28 +92,35 @@ protected virtual ValueTask DisposeAsyncCore() public sealed class EventHubsDefaultAzuriteConfiguration : EventHubsContainerTest { public EventHubsDefaultAzuriteConfiguration() - : base(new EventHubsBuilder() - .WithAcceptLicenseAgreement(true) - .WithConfigurationBuilder(GetServiceConfiguration()) - .Build()) - { - } + : base( + new EventHubsBuilder() + .WithAcceptLicenseAgreement(true) + .WithConfigurationBuilder(GetServiceConfiguration()) + .Build() + ) { } } + // # --8<-- [end:CreateEventHubsContainer] [UsedImplicitly] - public sealed class EventHubsCustomAzuriteConfiguration : EventHubsContainerTest, IClassFixture + public sealed class EventHubsCustomAzuriteConfiguration + : EventHubsContainerTest, + IClassFixture { public EventHubsCustomAzuriteConfiguration(DatabaseFixture fixture) - : base(new EventHubsBuilder() - .WithAcceptLicenseAgreement(true) - .WithConfigurationBuilder(GetServiceConfiguration()) - // # --8<-- [start:ReuseExistingAzuriteContainer] - .WithAzuriteContainer(fixture.Network, fixture.Container, DatabaseFixture.AzuriteNetworkAlias) - // # --8<-- [end:ReuseExistingAzuriteContainer] - .Build()) - { - } + : base( + new EventHubsBuilder() + .WithAcceptLicenseAgreement(true) + .WithConfigurationBuilder(GetServiceConfiguration()) + // # --8<-- [start:ReuseExistingAzuriteContainer] + .WithAzuriteContainer( + fixture.Network, + fixture.Container, + DatabaseFixture.AzuriteNetworkAlias + ) + // # --8<-- [end:ReuseExistingAzuriteContainer] + .Build() + ) { } } [UsedImplicitly] @@ -105,8 +128,7 @@ public sealed class DatabaseFixture { public DatabaseFixture() { - Network = new NetworkBuilder() - .Build(); + Network = new NetworkBuilder().Build(); Container = new AzuriteBuilder() .WithNetwork(Network) @@ -120,4 +142,4 @@ public DatabaseFixture() public AzuriteContainer Container { get; } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.EventHubs.Tests/Testcontainers.EventHubs.Tests.csproj b/tests/Testcontainers.EventHubs.Tests/Testcontainers.EventHubs.Tests.csproj index 1ad74b4ab..8d6aa96e0 100644 --- a/tests/Testcontainers.EventHubs.Tests/Testcontainers.EventHubs.Tests.csproj +++ b/tests/Testcontainers.EventHubs.Tests/Testcontainers.EventHubs.Tests.csproj @@ -1,21 +1,21 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.EventHubs.Tests/Usings.cs b/tests/Testcontainers.EventHubs.Tests/Usings.cs index 312a0abb6..0ba1738ba 100644 --- a/tests/Testcontainers.EventHubs.Tests/Usings.cs +++ b/tests/Testcontainers.EventHubs.Tests/Usings.cs @@ -9,4 +9,4 @@ global using DotNet.Testcontainers.Networks; global using JetBrains.Annotations; global using Testcontainers.Azurite; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.EventStoreDb.Tests/EventStoreDbContainerTest.cs b/tests/Testcontainers.EventStoreDb.Tests/EventStoreDbContainerTest.cs index f944584df..412163f19 100644 --- a/tests/Testcontainers.EventStoreDb.Tests/EventStoreDbContainerTest.cs +++ b/tests/Testcontainers.EventStoreDb.Tests/EventStoreDbContainerTest.cs @@ -2,12 +2,12 @@ namespace Testcontainers.EventStoreDb; public sealed class EventStoreDbContainerTest : IAsyncLifetime { - private readonly EventStoreDbContainer _eventStoreDbContainer = new EventStoreDbBuilder().Build(); + private readonly EventStoreDbContainer _eventStoreDbContainer = + new EventStoreDbBuilder().Build(); public async ValueTask InitializeAsync() { - await _eventStoreDbContainer.StartAsync() - .ConfigureAwait(false); + await _eventStoreDbContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -24,22 +24,36 @@ public async Task ReadStreamReturnsEvent() const string streamName = "some-stream"; - var settings = EventStoreClientSettings.Create(_eventStoreDbContainer.GetConnectionString()); + var settings = EventStoreClientSettings.Create( + _eventStoreDbContainer.GetConnectionString() + ); using var client = new EventStoreClient(settings); var eventData = new EventData(Uuid.NewUuid(), eventType, Array.Empty()); // When - _ = await client.AppendToStreamAsync(streamName, StreamState.NoStream, new[] { eventData }, cancellationToken: TestContext.Current.CancellationToken) + _ = await client + .AppendToStreamAsync( + streamName, + StreamState.NoStream, + new[] { eventData }, + cancellationToken: TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - var resolvedEvents = client.ReadStreamAsync(Direction.Forwards, streamName, StreamPosition.Start, cancellationToken: TestContext.Current.CancellationToken); + var resolvedEvents = client.ReadStreamAsync( + Direction.Forwards, + streamName, + StreamPosition.Start, + cancellationToken: TestContext.Current.CancellationToken + ); - var resolvedEvent = await resolvedEvents.FirstAsync(cancellationToken: TestContext.Current.CancellationToken) + var resolvedEvent = await resolvedEvents + .FirstAsync(cancellationToken: TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal(eventType, resolvedEvent.Event.EventType); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.EventStoreDb.Tests/Testcontainers.EventStoreDb.Tests.csproj b/tests/Testcontainers.EventStoreDb.Tests/Testcontainers.EventStoreDb.Tests.csproj index 34f2c8aa7..83c29f3ff 100644 --- a/tests/Testcontainers.EventStoreDb.Tests/Testcontainers.EventStoreDb.Tests.csproj +++ b/tests/Testcontainers.EventStoreDb.Tests/Testcontainers.EventStoreDb.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.EventStoreDb.Tests/Usings.cs b/tests/Testcontainers.EventStoreDb.Tests/Usings.cs index 8660e2560..eb7f6b76d 100644 --- a/tests/Testcontainers.EventStoreDb.Tests/Usings.cs +++ b/tests/Testcontainers.EventStoreDb.Tests/Usings.cs @@ -3,4 +3,4 @@ global using System.Threading.Tasks; global using DotNet.Testcontainers.Commons; global using EventStore.Client; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.FakeGcsServer.Tests/FakeGcsServerContainerTest.cs b/tests/Testcontainers.FakeGcsServer.Tests/FakeGcsServerContainerTest.cs index 87c703d55..4c31939a4 100644 --- a/tests/Testcontainers.FakeGcsServer.Tests/FakeGcsServerContainerTest.cs +++ b/tests/Testcontainers.FakeGcsServer.Tests/FakeGcsServerContainerTest.cs @@ -2,12 +2,12 @@ namespace Testcontainers.FakeGcsServer; public sealed class FakeGcsServerContainerTest : IAsyncLifetime { - private readonly FakeGcsServerContainer _fakeGcsServerContainer = new FakeGcsServerBuilder().Build(); + private readonly FakeGcsServerContainer _fakeGcsServerContainer = + new FakeGcsServerBuilder().Build(); public async ValueTask InitializeAsync() { - await _fakeGcsServerContainer.StartAsync() - .ConfigureAwait(false); + await _fakeGcsServerContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -37,19 +37,38 @@ public async Task DownloadObjectReturnsUploadObject() storageClientBuilder.BaseUri = _fakeGcsServerContainer.GetConnectionString(); // When - var client = await storageClientBuilder.BuildAsync(TestContext.Current.CancellationToken) + var client = await storageClientBuilder + .BuildAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); - _ = await client.CreateBucketAsync(project, bucket, cancellationToken: TestContext.Current.CancellationToken) + _ = await client + .CreateBucketAsync( + project, + bucket, + cancellationToken: TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - _ = await client.UploadObjectAsync(bucket, fileName, "text/plain", writeStream, cancellationToken: TestContext.Current.CancellationToken) + _ = await client + .UploadObjectAsync( + bucket, + fileName, + "text/plain", + writeStream, + cancellationToken: TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - _ = await client.DownloadObjectAsync(bucket, fileName, readStream, cancellationToken: TestContext.Current.CancellationToken) + _ = await client + .DownloadObjectAsync( + bucket, + fileName, + readStream, + cancellationToken: TestContext.Current.CancellationToken + ) .ConfigureAwait(true); // Then Assert.Equal(helloWorld, Encoding.Default.GetString(readStream.ToArray())); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.FakeGcsServer.Tests/Testcontainers.FakeGcsServer.Tests.csproj b/tests/Testcontainers.FakeGcsServer.Tests/Testcontainers.FakeGcsServer.Tests.csproj index 95936a7f1..848b004fe 100644 --- a/tests/Testcontainers.FakeGcsServer.Tests/Testcontainers.FakeGcsServer.Tests.csproj +++ b/tests/Testcontainers.FakeGcsServer.Tests/Testcontainers.FakeGcsServer.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.FakeGcsServer.Tests/Usings.cs b/tests/Testcontainers.FakeGcsServer.Tests/Usings.cs index f19546845..bf117759e 100644 --- a/tests/Testcontainers.FakeGcsServer.Tests/Usings.cs +++ b/tests/Testcontainers.FakeGcsServer.Tests/Usings.cs @@ -4,4 +4,4 @@ global using System.Threading.Tasks; global using DotNet.Testcontainers.Commons; global using Google.Cloud.Storage.V1; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.FirebirdSql.Tests/FirebirdSqlContainerTest.cs b/tests/Testcontainers.FirebirdSql.Tests/FirebirdSqlContainerTest.cs index dac883c73..c809666fa 100644 --- a/tests/Testcontainers.FirebirdSql.Tests/FirebirdSqlContainerTest.cs +++ b/tests/Testcontainers.FirebirdSql.Tests/FirebirdSqlContainerTest.cs @@ -1,6 +1,8 @@ namespace Testcontainers.FirebirdSql; -public abstract class FirebirdSqlContainerTest(FirebirdSqlContainerTest.FirebirdSqlDefaultFixture fixture) +public abstract class FirebirdSqlContainerTest( + FirebirdSqlContainerTest.FirebirdSqlDefaultFixture fixture +) { [Fact] [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] @@ -24,7 +26,8 @@ public async Task ExecScriptReturnsSuccessful() const string scriptContent = "SELECT 1 FROM RDB$DATABASE;"; // When - var execResult = await fixture.Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) + var execResult = await fixture + .Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -35,71 +38,78 @@ public async Task ExecScriptReturnsSuccessful() public class FirebirdSqlDefaultFixture(IMessageSink messageSink) : DbContainerFixture(messageSink) { - public override DbProviderFactory DbProviderFactory - => FirebirdClientFactory.Instance; + public override DbProviderFactory DbProviderFactory => FirebirdClientFactory.Instance; } [UsedImplicitly] public class FirebirdSqlWaitForDatabaseFixture(IMessageSink messageSink) : FirebirdSqlDefaultFixture(messageSink) { - protected override FirebirdSqlBuilder Configure(FirebirdSqlBuilder builder) - => builder.WithWaitStrategy(Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory)); + protected override FirebirdSqlBuilder Configure(FirebirdSqlBuilder builder) => + builder.WithWaitStrategy( + Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory) + ); } [UsedImplicitly] public class FirebirdSql25ScFixture(IMessageSink messageSink) : FirebirdSqlDefaultFixture(messageSink) { - protected override FirebirdSqlBuilder Configure(FirebirdSqlBuilder builder) - => builder.WithImage("jacobalberty/firebird:2.5-sc"); + protected override FirebirdSqlBuilder Configure(FirebirdSqlBuilder builder) => + builder.WithImage("jacobalberty/firebird:2.5-sc"); } [UsedImplicitly] public class FirebirdSql25SsFixture(IMessageSink messageSink) : FirebirdSqlDefaultFixture(messageSink) { - protected override FirebirdSqlBuilder Configure(FirebirdSqlBuilder builder) - => builder.WithImage("jacobalberty/firebird:2.5-ss"); + protected override FirebirdSqlBuilder Configure(FirebirdSqlBuilder builder) => + builder.WithImage("jacobalberty/firebird:2.5-ss"); } [UsedImplicitly] public class FirebirdSql30Fixture(IMessageSink messageSink) : FirebirdSqlDefaultFixture(messageSink) { - protected override FirebirdSqlBuilder Configure(FirebirdSqlBuilder builder) - => builder.WithImage("jacobalberty/firebird:v3.0"); + protected override FirebirdSqlBuilder Configure(FirebirdSqlBuilder builder) => + builder.WithImage("jacobalberty/firebird:v3.0"); } [UsedImplicitly] public class FirebirdSqlSysdbaFixture(IMessageSink messageSink) : FirebirdSqlDefaultFixture(messageSink) { - protected override FirebirdSqlBuilder Configure(FirebirdSqlBuilder builder) - => builder.WithUsername("sysdba").WithPassword("some-password"); + protected override FirebirdSqlBuilder Configure(FirebirdSqlBuilder builder) => + builder.WithUsername("sysdba").WithPassword("some-password"); } [UsedImplicitly] public sealed class FirebirdSqlDefaultConfiguration(FirebirdSqlDefaultFixture fixture) - : FirebirdSqlContainerTest(fixture), IClassFixture; + : FirebirdSqlContainerTest(fixture), + IClassFixture; [UsedImplicitly] - public sealed class FirebirdSqlWaitForDatabaseConfiguration(FirebirdSqlWaitForDatabaseFixture fixture) - : FirebirdSqlContainerTest(fixture), IClassFixture; + public sealed class FirebirdSqlWaitForDatabaseConfiguration( + FirebirdSqlWaitForDatabaseFixture fixture + ) : FirebirdSqlContainerTest(fixture), IClassFixture; [UsedImplicitly] public sealed class FirebirdSql25ScConfiguration(FirebirdSql25ScFixture fixture) - : FirebirdSqlContainerTest(fixture), IClassFixture; + : FirebirdSqlContainerTest(fixture), + IClassFixture; [UsedImplicitly] public sealed class FirebirdSql25SsConfiguration(FirebirdSql25SsFixture fixture) - : FirebirdSqlContainerTest(fixture), IClassFixture; + : FirebirdSqlContainerTest(fixture), + IClassFixture; [UsedImplicitly] public sealed class FirebirdSql30Configuration(FirebirdSql30Fixture fixture) - : FirebirdSqlContainerTest(fixture), IClassFixture; + : FirebirdSqlContainerTest(fixture), + IClassFixture; [UsedImplicitly] public sealed class FirebirdSqlSysdbaConfiguration(FirebirdSqlSysdbaFixture fixture) - : FirebirdSqlContainerTest(fixture), IClassFixture; -} \ No newline at end of file + : FirebirdSqlContainerTest(fixture), + IClassFixture; +} diff --git a/tests/Testcontainers.FirebirdSql.Tests/Testcontainers.FirebirdSql.Tests.csproj b/tests/Testcontainers.FirebirdSql.Tests/Testcontainers.FirebirdSql.Tests.csproj index 896010d09..e5089fca7 100644 --- a/tests/Testcontainers.FirebirdSql.Tests/Testcontainers.FirebirdSql.Tests.csproj +++ b/tests/Testcontainers.FirebirdSql.Tests/Testcontainers.FirebirdSql.Tests.csproj @@ -1,20 +1,20 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.FirebirdSql.Tests/Usings.cs b/tests/Testcontainers.FirebirdSql.Tests/Usings.cs index 85a9ff123..6877e29ab 100644 --- a/tests/Testcontainers.FirebirdSql.Tests/Usings.cs +++ b/tests/Testcontainers.FirebirdSql.Tests/Usings.cs @@ -7,4 +7,4 @@ global using JetBrains.Annotations; global using Testcontainers.Xunit; global using Xunit; -global using Xunit.Sdk; \ No newline at end of file +global using Xunit.Sdk; diff --git a/tests/Testcontainers.Firestore.Tests/FirestoreContainerTest.cs b/tests/Testcontainers.Firestore.Tests/FirestoreContainerTest.cs index 1f7da2a8e..97cd9b523 100644 --- a/tests/Testcontainers.Firestore.Tests/FirestoreContainerTest.cs +++ b/tests/Testcontainers.Firestore.Tests/FirestoreContainerTest.cs @@ -6,8 +6,7 @@ public sealed class FirestoreContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _firestoreContainer.StartAsync() - .ConfigureAwait(false); + await _firestoreContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -34,17 +33,28 @@ public async Task GetSnapshotReturnsSetDocument() firestoreDbBuilder.Endpoint = _firestoreContainer.GetEmulatorEndpoint(); firestoreDbBuilder.ChannelCredentials = ChannelCredentials.Insecure; - var firestoreDb = await firestoreDbBuilder.BuildAsync(TestContext.Current.CancellationToken) + var firestoreDb = await firestoreDbBuilder + .BuildAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // When - _ = await firestoreDb.Collection(collection).Document().SetAsync(documentData, cancellationToken: TestContext.Current.CancellationToken) + _ = await firestoreDb + .Collection(collection) + .Document() + .SetAsync(documentData, cancellationToken: TestContext.Current.CancellationToken) .ConfigureAwait(true); - var querySnapshot = await firestoreDb.Collection(collection).GetSnapshotAsync(TestContext.Current.CancellationToken) + var querySnapshot = await firestoreDb + .Collection(collection) + .GetSnapshotAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then - Assert.Equal(documentData, querySnapshot.Documents.Select(document => document.ConvertTo>()).Single()); + Assert.Equal( + documentData, + querySnapshot + .Documents.Select(document => document.ConvertTo>()) + .Single() + ); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Firestore.Tests/Testcontainers.Firestore.Tests.csproj b/tests/Testcontainers.Firestore.Tests/Testcontainers.Firestore.Tests.csproj index a1bea5451..861fc2b20 100644 --- a/tests/Testcontainers.Firestore.Tests/Testcontainers.Firestore.Tests.csproj +++ b/tests/Testcontainers.Firestore.Tests/Testcontainers.Firestore.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Firestore.Tests/Usings.cs b/tests/Testcontainers.Firestore.Tests/Usings.cs index 7b77e86c3..1e2cc8793 100644 --- a/tests/Testcontainers.Firestore.Tests/Usings.cs +++ b/tests/Testcontainers.Firestore.Tests/Usings.cs @@ -5,4 +5,4 @@ global using DotNet.Testcontainers.Commons; global using Google.Cloud.Firestore; global using Grpc.Core; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.InfluxDb.Tests/InfluxDbContainerTest.cs b/tests/Testcontainers.InfluxDb.Tests/InfluxDbContainerTest.cs index 385ec707a..93b56aafc 100644 --- a/tests/Testcontainers.InfluxDb.Tests/InfluxDbContainerTest.cs +++ b/tests/Testcontainers.InfluxDb.Tests/InfluxDbContainerTest.cs @@ -4,12 +4,13 @@ public sealed class InfluxDbContainerTest : IAsyncLifetime { private const string AdminToken = "YOUR_API_TOKEN"; - private readonly InfluxDbContainer _influxDbContainer = new InfluxDbBuilder().WithAdminToken(AdminToken).Build(); + private readonly InfluxDbContainer _influxDbContainer = new InfluxDbBuilder() + .WithAdminToken(AdminToken) + .Build(); public async ValueTask InitializeAsync() { - await _influxDbContainer.StartAsync() - .ConfigureAwait(false); + await _influxDbContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -25,8 +26,7 @@ public async Task PingReturnsTrue() using var client = new InfluxDBClient(_influxDbContainer.GetAddress(), AdminToken); // When - var result = await client.PingAsync() - .ConfigureAwait(true); + var result = await client.PingAsync().ConfigureAwait(true); // Then Assert.True(result); @@ -37,7 +37,8 @@ public async Task PingReturnsTrue() public async Task PointQueryReturnsWrittenPoint() { // Given - const string query = "from(bucket:\"" + InfluxDbBuilder.DefaultBucket + "\") |> range(start: 0)"; + const string query = + "from(bucket:\"" + InfluxDbBuilder.DefaultBucket + "\") |> range(start: 0)"; const string regionTagName = "region"; @@ -56,10 +57,21 @@ public async Task PointQueryReturnsWrittenPoint() .Timestamp(DateTime.UtcNow, WritePrecision.Ns); // When - await writeApi.WritePointAsync(point, InfluxDbBuilder.DefaultBucket, InfluxDbBuilder.DefaultOrganization, TestContext.Current.CancellationToken) + await writeApi + .WritePointAsync( + point, + InfluxDbBuilder.DefaultBucket, + InfluxDbBuilder.DefaultOrganization, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - var fluxTables = await queryApi.QueryAsync(query, InfluxDbBuilder.DefaultOrganization, TestContext.Current.CancellationToken) + var fluxTables = await queryApi + .QueryAsync( + query, + InfluxDbBuilder.DefaultOrganization, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); var recordValues = fluxTables.Single().Records.Single().Values; @@ -68,4 +80,4 @@ await writeApi.WritePointAsync(point, InfluxDbBuilder.DefaultBucket, InfluxDbBui Assert.Equal(regionTagValue, recordValues[regionTagName]); Assert.Equal(temperature, recordValues["_value"]); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.InfluxDb.Tests/Testcontainers.InfluxDb.Tests.csproj b/tests/Testcontainers.InfluxDb.Tests/Testcontainers.InfluxDb.Tests.csproj index 284811662..5aabebfe8 100644 --- a/tests/Testcontainers.InfluxDb.Tests/Testcontainers.InfluxDb.Tests.csproj +++ b/tests/Testcontainers.InfluxDb.Tests/Testcontainers.InfluxDb.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.InfluxDb.Tests/Usings.cs b/tests/Testcontainers.InfluxDb.Tests/Usings.cs index ff2a6f81f..e9d616ec4 100644 --- a/tests/Testcontainers.InfluxDb.Tests/Usings.cs +++ b/tests/Testcontainers.InfluxDb.Tests/Usings.cs @@ -5,4 +5,4 @@ global using InfluxDB.Client; global using InfluxDB.Client.Api.Domain; global using InfluxDB.Client.Writes; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.JanusGraph.Tests/JanusGraphContainerTest.cs b/tests/Testcontainers.JanusGraph.Tests/JanusGraphContainerTest.cs index 924dfe7f8..9e1d67184 100644 --- a/tests/Testcontainers.JanusGraph.Tests/JanusGraphContainerTest.cs +++ b/tests/Testcontainers.JanusGraph.Tests/JanusGraphContainerTest.cs @@ -6,8 +6,7 @@ public sealed class JanusGraphContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _janusGraphContainer.StartAsync() - .ConfigureAwait(false); + await _janusGraphContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -22,20 +21,32 @@ public async Task InsertedVertexCanBeFound() // Given var label = Guid.NewGuid().ToString("D"); - using var client = new GremlinClient(new GremlinServer(_janusGraphContainer.Hostname, _janusGraphContainer.GetMappedPublicPort(JanusGraphBuilder.JanusGraphPort)), new JanusGraphGraphSONMessageSerializer()); + using var client = new GremlinClient( + new GremlinServer( + _janusGraphContainer.Hostname, + _janusGraphContainer.GetMappedPublicPort(JanusGraphBuilder.JanusGraphPort) + ), + new JanusGraphGraphSONMessageSerializer() + ); using var connection = new DriverRemoteConnection(client); var graphTraversalSource = AnonymousTraversalSource.Traversal().WithRemote(connection); // When - await graphTraversalSource.AddV(label).Promise(traversal => traversal.Iterate(), TestContext.Current.CancellationToken) + await graphTraversalSource + .AddV(label) + .Promise(traversal => traversal.Iterate(), TestContext.Current.CancellationToken) .ConfigureAwait(true); - var count = await graphTraversalSource.V().HasLabel(label).Count().Promise(traversal => traversal.Next(), TestContext.Current.CancellationToken) + var count = await graphTraversalSource + .V() + .HasLabel(label) + .Count() + .Promise(traversal => traversal.Next(), TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal(1, count); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.JanusGraph.Tests/Testcontainers.JanusGraph.Tests.csproj b/tests/Testcontainers.JanusGraph.Tests/Testcontainers.JanusGraph.Tests.csproj index f71958139..bcc5c0a12 100644 --- a/tests/Testcontainers.JanusGraph.Tests/Testcontainers.JanusGraph.Tests.csproj +++ b/tests/Testcontainers.JanusGraph.Tests/Testcontainers.JanusGraph.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.JanusGraph.Tests/Usings.cs b/tests/Testcontainers.JanusGraph.Tests/Usings.cs index 2199e60ae..613766223 100644 --- a/tests/Testcontainers.JanusGraph.Tests/Usings.cs +++ b/tests/Testcontainers.JanusGraph.Tests/Usings.cs @@ -5,4 +5,4 @@ global using Gremlin.Net.Driver.Remote; global using Gremlin.Net.Process.Traversal; global using JanusGraph.Net.IO.GraphSON; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.K3s.Tests/K3sContainerTest.cs b/tests/Testcontainers.K3s.Tests/K3sContainerTest.cs index ac0cf2b1d..a63e6c5e4 100644 --- a/tests/Testcontainers.K3s.Tests/K3sContainerTest.cs +++ b/tests/Testcontainers.K3s.Tests/K3sContainerTest.cs @@ -6,8 +6,7 @@ public sealed class K3sContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _k3sConainter.StartAsync() - .ConfigureAwait(false); + await _k3sConainter.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -22,22 +21,30 @@ public async Task CreateNamespaceReturnsHttpStatusCodeCreated() // Given using var kubeconfigStream = new MemoryStream(); - var kubeconfig = await _k3sConainter.GetKubeconfigAsync() - .ConfigureAwait(true); + var kubeconfig = await _k3sConainter.GetKubeconfigAsync().ConfigureAwait(true); - await kubeconfigStream.WriteAsync(Encoding.Default.GetBytes(kubeconfig), TestContext.Current.CancellationToken) + await kubeconfigStream + .WriteAsync( + Encoding.Default.GetBytes(kubeconfig), + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - var clientConfiguration = await KubernetesClientConfiguration.BuildConfigFromConfigFileAsync(kubeconfigStream) + var clientConfiguration = await KubernetesClientConfiguration + .BuildConfigFromConfigFileAsync(kubeconfigStream) .ConfigureAwait(true); using var client = new Kubernetes(clientConfiguration); // When - using var response = await client.CoreV1.CreateNamespaceWithHttpMessagesAsync(new V1Namespace(metadata: new V1ObjectMeta(name: Guid.NewGuid().ToString("D"))), cancellationToken: TestContext.Current.CancellationToken) + using var response = await client + .CoreV1.CreateNamespaceWithHttpMessagesAsync( + new V1Namespace(metadata: new V1ObjectMeta(name: Guid.NewGuid().ToString("D"))), + cancellationToken: TestContext.Current.CancellationToken + ) .ConfigureAwait(true); // Then Assert.Equal(HttpStatusCode.Created, response.Response.StatusCode); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.K3s.Tests/Testcontainers.K3s.Tests.csproj b/tests/Testcontainers.K3s.Tests/Testcontainers.K3s.Tests.csproj index 3cc4a3207..ed443069d 100644 --- a/tests/Testcontainers.K3s.Tests/Testcontainers.K3s.Tests.csproj +++ b/tests/Testcontainers.K3s.Tests/Testcontainers.K3s.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.K3s.Tests/Usings.cs b/tests/Testcontainers.K3s.Tests/Usings.cs index 11d7b5de8..ae3795a9d 100644 --- a/tests/Testcontainers.K3s.Tests/Usings.cs +++ b/tests/Testcontainers.K3s.Tests/Usings.cs @@ -6,4 +6,4 @@ global using DotNet.Testcontainers.Commons; global using k8s; global using k8s.Models; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Kafka.Tests/KafkaBuilderTest.cs b/tests/Testcontainers.Kafka.Tests/KafkaBuilderTest.cs index f5012fbb2..2e1c1e0fb 100644 --- a/tests/Testcontainers.Kafka.Tests/KafkaBuilderTest.cs +++ b/tests/Testcontainers.Kafka.Tests/KafkaBuilderTest.cs @@ -5,15 +5,23 @@ public sealed class KafkaBuilderTests [Fact] public void KRaftWithConfluentPre7ThrowsArgumentException() { - const string message = "KRaft is not supported for Confluent Platform images with versions earlier than 7.0.0."; - ExpectArgEx(message, () => new KafkaBuilder().WithImage("confluentinc/cp-kafka:6.1.9").WithKRaft().Build()); + const string message = + "KRaft is not supported for Confluent Platform images with versions earlier than 7.0.0."; + ExpectArgEx( + message, + () => new KafkaBuilder().WithImage("confluentinc/cp-kafka:6.1.9").WithKRaft().Build() + ); } [Fact] public void ZooKeeperWithApacheKafkaImageThrowsArgumentException() { - const string message = "Local ZooKeeper is not supported for Apache Kafka images. Configure an external ZooKeeper."; - ExpectArgEx(message, () => new KafkaBuilder().WithImage("apache/kafka:3.9.1").WithZooKeeper().Build()); + const string message = + "Local ZooKeeper is not supported for Apache Kafka images. Configure an external ZooKeeper."; + ExpectArgEx( + message, + () => new KafkaBuilder().WithImage("apache/kafka:3.9.1").WithZooKeeper().Build() + ); } private static void ExpectArgEx(string message, Action testCode) @@ -21,4 +29,4 @@ private static void ExpectArgEx(string message, Action testCode) var exception = Assert.Throws(testCode); Assert.StartsWith(message, exception.Message); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Kafka.Tests/KafkaContainerNetworkTest.cs b/tests/Testcontainers.Kafka.Tests/KafkaContainerNetworkTest.cs index 66db58bd7..a6a0490a9 100644 --- a/tests/Testcontainers.Kafka.Tests/KafkaContainerNetworkTest.cs +++ b/tests/Testcontainers.Kafka.Tests/KafkaContainerNetworkTest.cs @@ -16,8 +16,7 @@ public sealed class KafkaContainerNetworkTest : IAsyncLifetime public KafkaContainerNetworkTest() { - _network = new NetworkBuilder() - .Build(); + _network = new NetworkBuilder().Build(); _kafkaContainer = new KafkaBuilder() .WithImage("confluentinc/cp-kafka:6.1.9") @@ -35,35 +34,38 @@ public KafkaContainerNetworkTest() public async ValueTask InitializeAsync() { - await _kafkaContainer.StartAsync() - .ConfigureAwait(false); + await _kafkaContainer.StartAsync().ConfigureAwait(false); - await _kCatContainer.StartAsync() - .ConfigureAwait(false); + await _kCatContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await _kafkaContainer.StartAsync() - .ConfigureAwait(false); + await _kafkaContainer.StartAsync().ConfigureAwait(false); - await _kCatContainer.StartAsync() - .ConfigureAwait(false); + await _kCatContainer.StartAsync().ConfigureAwait(false); - await _network.DisposeAsync() - .ConfigureAwait(false); + await _network.DisposeAsync().ConfigureAwait(false); } [Fact] [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public async Task ConsumesProducedKafkaMessage() { - _ = await _kCatContainer.ExecAsync(new[] { "kafkacat", "-b", Listener, "-t", "msgs", "-P", "-l", DataFilePath }, TestContext.Current.CancellationToken) + _ = await _kCatContainer + .ExecAsync( + new[] { "kafkacat", "-b", Listener, "-t", "msgs", "-P", "-l", DataFilePath }, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - var execResult = await _kCatContainer.ExecAsync(new[] { "kafkacat", "-b", Listener, "-C", "-t", "msgs", "-c", "1" }, TestContext.Current.CancellationToken) + var execResult = await _kCatContainer + .ExecAsync( + new[] { "kafkacat", "-b", Listener, "-C", "-t", "msgs", "-c", "1" }, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); Assert.Equal(Message, execResult.Stdout.Trim()); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Kafka.Tests/KafkaContainerRegistryTest.cs b/tests/Testcontainers.Kafka.Tests/KafkaContainerRegistryTest.cs index 0598c7196..fdcf80e75 100644 --- a/tests/Testcontainers.Kafka.Tests/KafkaContainerRegistryTest.cs +++ b/tests/Testcontainers.Kafka.Tests/KafkaContainerRegistryTest.cs @@ -2,7 +2,8 @@ namespace Testcontainers.Kafka; public sealed class KafkaContainerRegistryTest : IAsyncLifetime { - private const string Schema = @" + private const string Schema = + @" { ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""title"": ""User"", @@ -32,8 +33,7 @@ public sealed class KafkaContainerRegistryTest : IAsyncLifetime public KafkaContainerRegistryTest() { - _network = new NetworkBuilder() - .Build(); + _network = new NetworkBuilder().Build(); _kafkaContainer = new KafkaBuilder() .WithImage("confluentinc/cp-kafka:6.1.9") @@ -48,32 +48,34 @@ public KafkaContainerRegistryTest() .WithNetworkAliases(SchemaRegistryNetworkAlias) .WithEnvironment("SCHEMA_REGISTRY_LISTENERS", "http://0.0.0.0:" + RestPort) .WithEnvironment("SCHEMA_REGISTRY_KAFKASTORE_SECURITY_PROTOCOL", "PLAINTEXT") - .WithEnvironment("SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS", "PLAINTEXT://" + Listener) + .WithEnvironment( + "SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS", + "PLAINTEXT://" + Listener + ) .WithEnvironment("SCHEMA_REGISTRY_HOST_NAME", SchemaRegistryNetworkAlias) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPort(RestPort).ForPath("/subjects"))) + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request.ForPort(RestPort).ForPath("/subjects") + ) + ) .Build(); } public async ValueTask InitializeAsync() { - await _kafkaContainer.StartAsync() - .ConfigureAwait(false); + await _kafkaContainer.StartAsync().ConfigureAwait(false); - await _schemaRegistryContainer.StartAsync() - .ConfigureAwait(false); + await _schemaRegistryContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await _kafkaContainer.StartAsync() - .ConfigureAwait(false); + await _kafkaContainer.StartAsync().ConfigureAwait(false); - await _schemaRegistryContainer.StartAsync() - .ConfigureAwait(false); + await _schemaRegistryContainer.StartAsync().ConfigureAwait(false); - await _network.DisposeAsync() - .ConfigureAwait(false); + await _network.DisposeAsync().ConfigureAwait(false); } [Fact] @@ -99,18 +101,24 @@ public async Task ConsumerReturnsProducerMessage() message.Value = new User("John", "Doe"); var schemaRegistryConfig = new SchemaRegistryConfig(); - schemaRegistryConfig.Url = new UriBuilder(Uri.UriSchemeHttp, _schemaRegistryContainer.Hostname, _schemaRegistryContainer.GetMappedPublicPort(RestPort)).ToString(); + schemaRegistryConfig.Url = new UriBuilder( + Uri.UriSchemeHttp, + _schemaRegistryContainer.Hostname, + _schemaRegistryContainer.GetMappedPublicPort(RestPort) + ).ToString(); // When using var schemaRegistry = new CachedSchemaRegistryClient(schemaRegistryConfig); - _ = await schemaRegistry.RegisterSchemaAsync(subject, new Schema(Schema, SchemaType.Json)) + _ = await schemaRegistry + .RegisterSchemaAsync(subject, new Schema(Schema, SchemaType.Json)) .ConfigureAwait(true); using var producer = new ProducerBuilder(producerConfig) .SetValueSerializer(new JsonSerializer(schemaRegistry)) .Build(); - _ = await producer.ProduceAsync(topic, message, TestContext.Current.CancellationToken) + _ = await producer + .ProduceAsync(topic, message, TestContext.Current.CancellationToken) .ConfigureAwait(true); using var consumer = new ConsumerBuilder(consumerConfig) @@ -128,4 +136,4 @@ public async Task ConsumerReturnsProducerMessage() [UsedImplicitly] private record User(string FirstName, string LastName); -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Kafka.Tests/KafkaContainerTest.cs b/tests/Testcontainers.Kafka.Tests/KafkaContainerTest.cs index 2618e8c4f..222c73518 100644 --- a/tests/Testcontainers.Kafka.Tests/KafkaContainerTest.cs +++ b/tests/Testcontainers.Kafka.Tests/KafkaContainerTest.cs @@ -11,14 +11,12 @@ private KafkaContainerTest(KafkaContainer kafkaContainer) public async ValueTask InitializeAsync() { - await _kafkaContainer.StartAsync() - .ConfigureAwait(false); + await _kafkaContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -45,7 +43,8 @@ public async Task ConsumerReturnsProducerMessage() // When using var producer = new ProducerBuilder(producerConfig).Build(); - _ = await producer.ProduceAsync(topic, message, TestContext.Current.CancellationToken) + _ = await producer + .ProduceAsync(topic, message, TestContext.Current.CancellationToken) .ConfigureAwait(true); using var consumer = new ConsumerBuilder(consumerConfig).Build(); @@ -67,52 +66,34 @@ protected virtual ValueTask DisposeAsyncCore() public sealed class KafkaDefaultConfiguration : KafkaContainerTest { public KafkaDefaultConfiguration() - : base(new KafkaBuilder().Build()) - { - } + : base(new KafkaBuilder().Build()) { } } [UsedImplicitly] public sealed class KafkaKRaftConfiguration : KafkaContainerTest { public KafkaKRaftConfiguration() - : base(new KafkaBuilder() - .WithKRaft() - .Build()) - { - } + : base(new KafkaBuilder().WithKRaft().Build()) { } } [UsedImplicitly] public sealed class KafkaZooKeeperConfiguration : KafkaContainerTest { public KafkaZooKeeperConfiguration() - : base(new KafkaBuilder() - .WithZooKeeper() - .Build()) - { - } + : base(new KafkaBuilder().WithZooKeeper().Build()) { } } [UsedImplicitly] public sealed class ApacheKafkaConfiguration : KafkaContainerTest { public ApacheKafkaConfiguration() - : base(new KafkaBuilder() - .WithImage("apache/kafka:3.9.1") - .Build()) - { - } + : base(new KafkaBuilder().WithImage("apache/kafka:3.9.1").Build()) { } } [UsedImplicitly] public sealed class ApacheKafkaNativeConfiguration : KafkaContainerTest { public ApacheKafkaNativeConfiguration() - : base(new KafkaBuilder() - .WithImage("apache/kafka-native:3.9.1") - .Build()) - { - } + : base(new KafkaBuilder().WithImage("apache/kafka-native:3.9.1").Build()) { } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Kafka.Tests/Testcontainers.Kafka.Tests.csproj b/tests/Testcontainers.Kafka.Tests/Testcontainers.Kafka.Tests.csproj index b7c297adf..1458179ec 100644 --- a/tests/Testcontainers.Kafka.Tests/Testcontainers.Kafka.Tests.csproj +++ b/tests/Testcontainers.Kafka.Tests/Testcontainers.Kafka.Tests.csproj @@ -1,21 +1,21 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Kafka.Tests/Usings.cs b/tests/Testcontainers.Kafka.Tests/Usings.cs index bb0fc9812..f92d6d3da 100644 --- a/tests/Testcontainers.Kafka.Tests/Usings.cs +++ b/tests/Testcontainers.Kafka.Tests/Usings.cs @@ -10,4 +10,4 @@ global using DotNet.Testcontainers.Containers; global using DotNet.Testcontainers.Networks; global using JetBrains.Annotations; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Keycloak.Tests/KeycloakContainerTest.cs b/tests/Testcontainers.Keycloak.Tests/KeycloakContainerTest.cs index 239412063..8b9e95d20 100644 --- a/tests/Testcontainers.Keycloak.Tests/KeycloakContainerTest.cs +++ b/tests/Testcontainers.Keycloak.Tests/KeycloakContainerTest.cs @@ -11,14 +11,12 @@ private KeycloakContainerTest(KeycloakContainer keycloakContainer) public async ValueTask InitializeAsync() { - await _keycloakContainer.StartAsync() - .ConfigureAwait(false); + await _keycloakContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -32,7 +30,11 @@ public async Task GetOpenIdEndpointReturnsHttpStatusCodeOk() httpClient.BaseAddress = new Uri(_keycloakContainer.GetBaseAddress()); // When - using var httpResponse = await httpClient.GetAsync("/realms/master/.well-known/openid-configuration", TestContext.Current.CancellationToken) + using var httpResponse = await httpClient + .GetAsync( + "/realms/master/.well-known/openid-configuration", + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); // Then @@ -44,10 +46,15 @@ public async Task GetOpenIdEndpointReturnsHttpStatusCodeOk() public async Task MasterRealmIsEnabled() { // Given - var keycloakClient = new KeycloakClient(_keycloakContainer.GetBaseAddress(), KeycloakBuilder.DefaultUsername, KeycloakBuilder.DefaultPassword); + var keycloakClient = new KeycloakClient( + _keycloakContainer.GetBaseAddress(), + KeycloakBuilder.DefaultUsername, + KeycloakBuilder.DefaultPassword + ); // When - var masterRealm = await keycloakClient.GetRealmAsync("master", TestContext.Current.CancellationToken) + var masterRealm = await keycloakClient + .GetRealmAsync("master", TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -63,26 +70,20 @@ protected virtual ValueTask DisposeAsyncCore() public sealed class KeycloakDefaultConfiguration : KeycloakContainerTest { public KeycloakDefaultConfiguration() - : base(new KeycloakBuilder().Build()) - { - } + : base(new KeycloakBuilder().Build()) { } } [UsedImplicitly] public sealed class KeycloakV25Configuration : KeycloakContainerTest { public KeycloakV25Configuration() - : base(new KeycloakBuilder().WithImage("quay.io/keycloak/keycloak:25.0").Build()) - { - } + : base(new KeycloakBuilder().WithImage("quay.io/keycloak/keycloak:25.0").Build()) { } } [UsedImplicitly] public sealed class KeycloakV26Configuration : KeycloakContainerTest { public KeycloakV26Configuration() - : base(new KeycloakBuilder().WithImage("quay.io/keycloak/keycloak:26.0").Build()) - { - } + : base(new KeycloakBuilder().WithImage("quay.io/keycloak/keycloak:26.0").Build()) { } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Keycloak.Tests/Testcontainers.Keycloak.Tests.csproj b/tests/Testcontainers.Keycloak.Tests/Testcontainers.Keycloak.Tests.csproj index b6314c639..90759ae0d 100644 --- a/tests/Testcontainers.Keycloak.Tests/Testcontainers.Keycloak.Tests.csproj +++ b/tests/Testcontainers.Keycloak.Tests/Testcontainers.Keycloak.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Keycloak.Tests/Usings.cs b/tests/Testcontainers.Keycloak.Tests/Usings.cs index 32947f5a9..98ba90e36 100644 --- a/tests/Testcontainers.Keycloak.Tests/Usings.cs +++ b/tests/Testcontainers.Keycloak.Tests/Usings.cs @@ -5,4 +5,4 @@ global using DotNet.Testcontainers.Commons; global using JetBrains.Annotations; global using Keycloak.Net; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Kusto.Tests/KustoContainerTest.cs b/tests/Testcontainers.Kusto.Tests/KustoContainerTest.cs index c003cdd3e..b67fd087c 100644 --- a/tests/Testcontainers.Kusto.Tests/KustoContainerTest.cs +++ b/tests/Testcontainers.Kusto.Tests/KustoContainerTest.cs @@ -6,8 +6,7 @@ public sealed class KustoContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _kustoContainer.StartAsync() - .ConfigureAwait(false); + await _kustoContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -20,10 +19,16 @@ public ValueTask DisposeAsync() public async Task ShowDatabaseReturnsDefaultDbInformation() { // Given - using var client = KustoClientFactory.CreateCslAdminProvider(_kustoContainer.GetConnectionString()); + using var client = KustoClientFactory.CreateCslAdminProvider( + _kustoContainer.GetConnectionString() + ); // When - using var dataReader = await client.ExecuteControlCommandAsync("NetDefaultDB", CslCommandGenerator.GenerateDatabaseShowCommand()) + using var dataReader = await client + .ExecuteControlCommandAsync( + "NetDefaultDB", + CslCommandGenerator.GenerateDatabaseShowCommand() + ) .ConfigureAwait(true); _ = dataReader.Read(); @@ -32,4 +37,4 @@ public async Task ShowDatabaseReturnsDefaultDbInformation() Assert.Equal("DatabaseName", dataReader.GetName(0)); Assert.Equal("NetDefaultDB", dataReader.GetString(0)); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Kusto.Tests/Testcontainers.Kusto.Tests.csproj b/tests/Testcontainers.Kusto.Tests/Testcontainers.Kusto.Tests.csproj index d24c53a0b..cf1e7e1a6 100644 --- a/tests/Testcontainers.Kusto.Tests/Testcontainers.Kusto.Tests.csproj +++ b/tests/Testcontainers.Kusto.Tests/Testcontainers.Kusto.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - + + net9.0 + false + false + Exe + + + + + + + - - + + - \ No newline at end of file + diff --git a/tests/Testcontainers.Kusto.Tests/Usings.cs b/tests/Testcontainers.Kusto.Tests/Usings.cs index b24f49d27..90383ccdf 100644 --- a/tests/Testcontainers.Kusto.Tests/Usings.cs +++ b/tests/Testcontainers.Kusto.Tests/Usings.cs @@ -2,4 +2,4 @@ global using DotNet.Testcontainers.Commons; global using Kusto.Data.Common; global using Kusto.Data.Net.Client; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.LocalStack.Tests/LocalStackContainerTest.cs b/tests/Testcontainers.LocalStack.Tests/LocalStackContainerTest.cs index 05d5f6513..015d1d57e 100644 --- a/tests/Testcontainers.LocalStack.Tests/LocalStackContainerTest.cs +++ b/tests/Testcontainers.LocalStack.Tests/LocalStackContainerTest.cs @@ -19,14 +19,12 @@ private LocalStackContainerTest(LocalStackContainer localStackContainer) public async ValueTask InitializeAsync() { - await _localStackContainer.StartAsync() - .ConfigureAwait(false); + await _localStackContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -45,7 +43,8 @@ public async Task CreateLogReturnsHttpStatusCodeOk() var logGroupRequest = new CreateLogGroupRequest(Guid.NewGuid().ToString("D")); // When - var logGroupResponse = await client.CreateLogGroupAsync(logGroupRequest, TestContext.Current.CancellationToken) + var logGroupResponse = await client + .CreateLogGroupAsync(logGroupRequest, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -69,26 +68,47 @@ public async Task GetItemReturnsPutItem() var tableRequest = new CreateTableRequest(); tableRequest.TableName = tableName; - tableRequest.AttributeDefinitions = new List { new AttributeDefinition("Id", ScalarAttributeType.S) }; - tableRequest.KeySchema = new List { new KeySchemaElement("Id", KeyType.HASH) }; + tableRequest.AttributeDefinitions = new List + { + new AttributeDefinition("Id", ScalarAttributeType.S), + }; + tableRequest.KeySchema = new List + { + new KeySchemaElement("Id", KeyType.HASH), + }; tableRequest.ProvisionedThroughput = new ProvisionedThroughput(10, 5); var putItemRequest = new PutItemRequest(); putItemRequest.TableName = tableName; - putItemRequest.Item = new Dictionary { { "Id", new AttributeValue { S = id } } }; + putItemRequest.Item = new Dictionary + { + { + "Id", + new AttributeValue { S = id } + }, + }; var getItemRequest = new GetItemRequest(); getItemRequest.TableName = tableName; - getItemRequest.Key = new Dictionary { { "Id", new AttributeValue { S = id } } }; + getItemRequest.Key = new Dictionary + { + { + "Id", + new AttributeValue { S = id } + }, + }; // When - _ = await client.CreateTableAsync(tableRequest, TestContext.Current.CancellationToken) + _ = await client + .CreateTableAsync(tableRequest, TestContext.Current.CancellationToken) .ConfigureAwait(true); - _ = await client.PutItemAsync(putItemRequest, TestContext.Current.CancellationToken) + _ = await client + .PutItemAsync(putItemRequest, TestContext.Current.CancellationToken) .ConfigureAwait(true); - var itemResponse = await client.GetItemAsync(getItemRequest, TestContext.Current.CancellationToken) + var itemResponse = await client + .GetItemAsync(getItemRequest, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -107,7 +127,8 @@ public async Task ListBucketsReturnsHttpStatusCodeOk() using var client = new AmazonS3Client(config); // When - var buckets = await client.ListBucketsAsync(TestContext.Current.CancellationToken) + var buckets = await client + .ListBucketsAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -126,7 +147,8 @@ public async Task CreateTopicReturnsHttpStatusCodeOk() using var client = new AmazonSimpleNotificationServiceClient(config); // When - var topicResponse = await client.CreateTopicAsync(Guid.NewGuid().ToString("D"), TestContext.Current.CancellationToken) + var topicResponse = await client + .CreateTopicAsync(Guid.NewGuid().ToString("D"), TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -145,7 +167,8 @@ public async Task CreateQueueReturnsHttpStatusCodeOk() using var client = new AmazonSQSClient(config); // When - var queueResponse = await client.CreateQueueAsync(Guid.NewGuid().ToString("D"), TestContext.Current.CancellationToken) + var queueResponse = await client + .CreateQueueAsync(Guid.NewGuid().ToString("D"), TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -161,17 +184,13 @@ protected virtual ValueTask DisposeAsyncCore() public sealed class LocalStackDefaultConfiguration : LocalStackContainerTest { public LocalStackDefaultConfiguration() - : base(new LocalStackBuilder().Build()) - { - } + : base(new LocalStackBuilder().Build()) { } } [UsedImplicitly] public sealed class LocalStackV1Configuration : LocalStackContainerTest { public LocalStackV1Configuration() - : base(new LocalStackBuilder().WithImage("localstack/localstack:1.4").Build()) - { - } + : base(new LocalStackBuilder().WithImage("localstack/localstack:1.4").Build()) { } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.LocalStack.Tests/Testcontainers.LocalStack.Tests.csproj b/tests/Testcontainers.LocalStack.Tests/Testcontainers.LocalStack.Tests.csproj index 30ca9476d..d637d40da 100644 --- a/tests/Testcontainers.LocalStack.Tests/Testcontainers.LocalStack.Tests.csproj +++ b/tests/Testcontainers.LocalStack.Tests/Testcontainers.LocalStack.Tests.csproj @@ -1,23 +1,23 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.LocalStack.Tests/Usings.cs b/tests/Testcontainers.LocalStack.Tests/Usings.cs index 81dc05551..0ed84f973 100644 --- a/tests/Testcontainers.LocalStack.Tests/Usings.cs +++ b/tests/Testcontainers.LocalStack.Tests/Usings.cs @@ -1,8 +1,8 @@ global using System; global using System.Collections.Generic; +global using System.Linq; global using System.Net; global using System.Threading.Tasks; -global using System.Linq; global using Amazon.CloudWatchLogs; global using Amazon.CloudWatchLogs.Model; global using Amazon.DynamoDBv2; @@ -12,4 +12,4 @@ global using Amazon.SQS; global using DotNet.Testcontainers.Commons; global using JetBrains.Annotations; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.LowkeyVault.Tests/LowkeyVaultContainerTest.cs b/tests/Testcontainers.LowkeyVault.Tests/LowkeyVaultContainerTest.cs index aebc537f8..0f3a51e26 100644 --- a/tests/Testcontainers.LowkeyVault.Tests/LowkeyVaultContainerTest.cs +++ b/tests/Testcontainers.LowkeyVault.Tests/LowkeyVaultContainerTest.cs @@ -8,14 +8,12 @@ public abstract class LowkeyVaultContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _lowkeyVaultContainer.StartAsync() - .ConfigureAwait(false); + await _lowkeyVaultContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -30,7 +28,8 @@ public async Task ServerCertificateValidationSucceedsWithTrustedCertificate() var certificates = await _lowkeyVaultContainer.GetCertificateAsync(); using var httpMessageHandler = new HttpClientHandler(); - httpMessageHandler.ServerCertificateCustomValidationCallback = (_, cert, _, _) => certificates.IndexOf(cert) > -1; + httpMessageHandler.ServerCertificateCustomValidationCallback = (_, cert, _, _) => + certificates.IndexOf(cert) > -1; using var httpClient = new HttpClient(httpMessageHandler); httpClient.BaseAddress = new Uri(baseAddress); @@ -38,7 +37,8 @@ public async Task ServerCertificateValidationSucceedsWithTrustedCertificate() // When using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "management/vault"); - using var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage, TestContext.Current.CancellationToken) + using var httpResponseMessage = await httpClient + .SendAsync(httpRequestMessage, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -56,13 +56,19 @@ public async Task GetSecretReturnsSetSecret() var baseAddress = _lowkeyVaultContainer.GetBaseAddress(); - var secretClient = new SecretClient(new Uri(baseAddress), GetTokenCredential(), GetSecretClientOptions()); + var secretClient = new SecretClient( + new Uri(baseAddress), + GetTokenCredential(), + GetSecretClientOptions() + ); - await secretClient.SetSecretAsync(secretName, secretValue, TestContext.Current.CancellationToken) + await secretClient + .SetSecretAsync(secretName, secretValue, TestContext.Current.CancellationToken) .ConfigureAwait(true); // When - var keyVaultSecret = await secretClient.GetSecretAsync(secretName, cancellationToken: TestContext.Current.CancellationToken) + var keyVaultSecret = await secretClient + .GetSecretAsync(secretName, cancellationToken: TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -82,7 +88,11 @@ public async Task DownloadCertificateReturnsCreatedCertificate() var baseAddress = _lowkeyVaultContainer.GetBaseAddress(); - var certificateClient = new CertificateClient(new Uri(baseAddress), GetTokenCredential(), GetCertificateClientOptions()); + var certificateClient = new CertificateClient( + new Uri(baseAddress), + GetTokenCredential(), + GetCertificateClientOptions() + ); var certificatePolicy = new CertificatePolicy("self", subject); certificatePolicy.KeyType = CertificateKeyType.Rsa; @@ -92,13 +102,23 @@ public async Task DownloadCertificateReturnsCreatedCertificate() certificatePolicy.ValidityInMonths = 12; // When - var certificateOperation = await certificateClient.StartCreateCertificateAsync(certificateName, certificatePolicy, cancellationToken: TestContext.Current.CancellationToken) + var certificateOperation = await certificateClient + .StartCreateCertificateAsync( + certificateName, + certificatePolicy, + cancellationToken: TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - await certificateOperation.WaitForCompletionAsync(TestContext.Current.CancellationToken) + await certificateOperation + .WaitForCompletionAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); - var response = await certificateClient.DownloadCertificateAsync(certificateName, cancellationToken: TestContext.Current.CancellationToken) + var response = await certificateClient + .DownloadCertificateAsync( + certificateName, + cancellationToken: TestContext.Current.CancellationToken + ) .ConfigureAwait(true); using var certificate = response!.Value; @@ -144,7 +164,11 @@ protected override TokenCredential GetTokenCredential() // This isn't a recommended approach. It stops you from running multiple containers // at the same time. const EnvironmentVariableTarget envVarTarget = EnvironmentVariableTarget.Process; - Environment.SetEnvironmentVariable("IDENTITY_ENDPOINT", _lowkeyVaultContainer.GetAuthTokenUrl(), envVarTarget); + Environment.SetEnvironmentVariable( + "IDENTITY_ENDPOINT", + _lowkeyVaultContainer.GetAuthTokenUrl(), + envVarTarget + ); Environment.SetEnvironmentVariable("IDENTITY_HEADER", "header", envVarTarget); return new DefaultAzureCredential(); } @@ -160,15 +184,21 @@ protected override TokenCredential GetTokenCredential() private sealed class NoopCredential : TokenCredential { - public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken) + public override AccessToken GetToken( + TokenRequestContext requestContext, + CancellationToken cancellationToken + ) { return new AccessToken("noop", DateTimeOffset.UtcNow.AddHours(1)); } - public override ValueTask GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken) + public override ValueTask GetTokenAsync( + TokenRequestContext requestContext, + CancellationToken cancellationToken + ) { return new ValueTask(GetToken(requestContext, cancellationToken)); } } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.LowkeyVault.Tests/Testcontainers.LowkeyVault.Tests.csproj b/tests/Testcontainers.LowkeyVault.Tests/Testcontainers.LowkeyVault.Tests.csproj index d48e8e5b8..d8a7277dc 100644 --- a/tests/Testcontainers.LowkeyVault.Tests/Testcontainers.LowkeyVault.Tests.csproj +++ b/tests/Testcontainers.LowkeyVault.Tests/Testcontainers.LowkeyVault.Tests.csproj @@ -1,21 +1,21 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.LowkeyVault.Tests/Usings.cs b/tests/Testcontainers.LowkeyVault.Tests/Usings.cs index fd554ccb8..8a1c8d477 100644 --- a/tests/Testcontainers.LowkeyVault.Tests/Usings.cs +++ b/tests/Testcontainers.LowkeyVault.Tests/Usings.cs @@ -11,4 +11,4 @@ global using Azure.Security.KeyVault.Secrets; global using DotNet.Testcontainers.Commons; global using JetBrains.Annotations; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.MariaDb.Tests/MariaDbContainerTest.cs b/tests/Testcontainers.MariaDb.Tests/MariaDbContainerTest.cs index f2999cf2c..c55b345b3 100644 --- a/tests/Testcontainers.MariaDb.Tests/MariaDbContainerTest.cs +++ b/tests/Testcontainers.MariaDb.Tests/MariaDbContainerTest.cs @@ -24,7 +24,8 @@ public async Task ExecScriptReturnsSuccessful() const string scriptContent = "SELECT 1;"; // When - var execResult = await fixture.Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) + var execResult = await fixture + .Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -35,23 +36,26 @@ public async Task ExecScriptReturnsSuccessful() public class MariaDbDefaultFixture(IMessageSink messageSink) : DbContainerFixture(messageSink) { - public override DbProviderFactory DbProviderFactory - => MySqlConnectorFactory.Instance; + public override DbProviderFactory DbProviderFactory => MySqlConnectorFactory.Instance; } [UsedImplicitly] public class MariaDbWaitForDatabaseFixture(IMessageSink messageSink) : MariaDbDefaultFixture(messageSink) { - protected override MariaDbBuilder Configure(MariaDbBuilder builder) - => builder.WithWaitStrategy(Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory)); + protected override MariaDbBuilder Configure(MariaDbBuilder builder) => + builder.WithWaitStrategy( + Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory) + ); } [UsedImplicitly] public sealed class MariaDbDefaultConfiguration(MariaDbDefaultFixture fixture) - : MariaDbContainerTest(fixture), IClassFixture; + : MariaDbContainerTest(fixture), + IClassFixture; [UsedImplicitly] public sealed class MariaDbWaitForDatabaseConfiguration(MariaDbWaitForDatabaseFixture fixture) - : MariaDbContainerTest(fixture), IClassFixture; -} \ No newline at end of file + : MariaDbContainerTest(fixture), + IClassFixture; +} diff --git a/tests/Testcontainers.MariaDb.Tests/Testcontainers.MariaDb.Tests.csproj b/tests/Testcontainers.MariaDb.Tests/Testcontainers.MariaDb.Tests.csproj index 8a35f125b..a08cb85f5 100644 --- a/tests/Testcontainers.MariaDb.Tests/Testcontainers.MariaDb.Tests.csproj +++ b/tests/Testcontainers.MariaDb.Tests/Testcontainers.MariaDb.Tests.csproj @@ -1,20 +1,20 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.MariaDb.Tests/Usings.cs b/tests/Testcontainers.MariaDb.Tests/Usings.cs index 34433ebc1..86f14ba1a 100644 --- a/tests/Testcontainers.MariaDb.Tests/Usings.cs +++ b/tests/Testcontainers.MariaDb.Tests/Usings.cs @@ -7,4 +7,4 @@ global using MySqlConnector; global using Testcontainers.Xunit; global using Xunit; -global using Xunit.Sdk; \ No newline at end of file +global using Xunit.Sdk; diff --git a/tests/Testcontainers.Milvus.Tests/MilvusContainerTest.cs b/tests/Testcontainers.Milvus.Tests/MilvusContainerTest.cs index f855fe9d5..af0cd3f9c 100644 --- a/tests/Testcontainers.Milvus.Tests/MilvusContainerTest.cs +++ b/tests/Testcontainers.Milvus.Tests/MilvusContainerTest.cs @@ -13,14 +13,12 @@ private MilvusContainerTest(MilvusContainer milvusContainer) public async ValueTask InitializeAsync() { - await _milvusContainer.StartAsync() - .ConfigureAwait(false); + await _milvusContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -33,7 +31,8 @@ public async Task GetVersionReturnsExpectedVersion() using var client = new MilvusClient(_milvusContainer.GetEndpoint()); // When - var version = await client.GetVersionAsync(TestContext.Current.CancellationToken) + var version = await client + .GetVersionAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -49,40 +48,41 @@ protected virtual ValueTask DisposeAsyncCore() public sealed class MilvusDefaultConfiguration : MilvusContainerTest { public MilvusDefaultConfiguration() - : base(new MilvusBuilder().WithImage("milvusdb/milvus:" + MilvusVersion).Build()) - { - } + : base(new MilvusBuilder().WithImage("milvusdb/milvus:" + MilvusVersion).Build()) { } } [UsedImplicitly] public sealed class MilvusSidecarConfiguration : MilvusContainerTest { public MilvusSidecarConfiguration() - : this(new NetworkBuilder().Build()) - { - } + : this(new NetworkBuilder().Build()) { } private MilvusSidecarConfiguration(INetwork network) - : base(new MilvusBuilder() - .WithImage("milvusdb/milvus:" + MilvusVersion) - .WithEtcdEndpoint("etcd:2379") - .DependsOn(new ContainerBuilder() - .WithImage("quay.io/coreos/etcd:v3.5.5") - .WithNetworkAliases("etcd") - .WithCommand("etcd") - .WithCommand("-advertise-client-urls=http://127.0.0.1:2379") - .WithCommand("-listen-client-urls=http://0.0.0.0:2379") - .WithCommand("-data-dir=/etcd") - .WithEnvironment("ETCD_AUTO_COMPACTION_MODE", "periodic") - .WithEnvironment("ETCD_AUTO_COMPACTION_RETENTION", "0") - .WithEnvironment("ETCD_QUOTA_BACKEND_BYTES", "0") - .WithEnvironment("ETCD_SNAPSHOT_COUNT", "100000") - .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("ready to serve client requests")) + : base( + new MilvusBuilder() + .WithImage("milvusdb/milvus:" + MilvusVersion) + .WithEtcdEndpoint("etcd:2379") + .DependsOn( + new ContainerBuilder() + .WithImage("quay.io/coreos/etcd:v3.5.5") + .WithNetworkAliases("etcd") + .WithCommand("etcd") + .WithCommand("-advertise-client-urls=http://127.0.0.1:2379") + .WithCommand("-listen-client-urls=http://0.0.0.0:2379") + .WithCommand("-data-dir=/etcd") + .WithEnvironment("ETCD_AUTO_COMPACTION_MODE", "periodic") + .WithEnvironment("ETCD_AUTO_COMPACTION_RETENTION", "0") + .WithEnvironment("ETCD_QUOTA_BACKEND_BYTES", "0") + .WithEnvironment("ETCD_SNAPSHOT_COUNT", "100000") + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilMessageIsLogged("ready to serve client requests") + ) + .DependsOn(network) + .Build() + ) .DependsOn(network) - .Build()) - .DependsOn(network) - .Build()) - { - } + .Build() + ) { } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Milvus.Tests/Testcontainers.Milvus.Tests.csproj b/tests/Testcontainers.Milvus.Tests/Testcontainers.Milvus.Tests.csproj index bcda6a193..e4d6eb3c1 100644 --- a/tests/Testcontainers.Milvus.Tests/Testcontainers.Milvus.Tests.csproj +++ b/tests/Testcontainers.Milvus.Tests/Testcontainers.Milvus.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Milvus.Tests/Usings.cs b/tests/Testcontainers.Milvus.Tests/Usings.cs index 0df5bdaaf..b4ce6bf29 100644 --- a/tests/Testcontainers.Milvus.Tests/Usings.cs +++ b/tests/Testcontainers.Milvus.Tests/Usings.cs @@ -5,4 +5,4 @@ global using DotNet.Testcontainers.Networks; global using JetBrains.Annotations; global using Milvus.Client; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Minio.Tests/MinioContainerTest.cs b/tests/Testcontainers.Minio.Tests/MinioContainerTest.cs index 86c490e9d..dd5b13381 100644 --- a/tests/Testcontainers.Minio.Tests/MinioContainerTest.cs +++ b/tests/Testcontainers.Minio.Tests/MinioContainerTest.cs @@ -6,8 +6,7 @@ public sealed class MinioContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _minioContainer.StartAsync() - .ConfigureAwait(false); + await _minioContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -23,10 +22,15 @@ public async Task ListBucketsReturnsHttpStatusCodeOk() var config = new AmazonS3Config(); config.ServiceURL = _minioContainer.GetConnectionString(); - using var client = new AmazonS3Client(_minioContainer.GetAccessKey(), _minioContainer.GetSecretKey(), config); + using var client = new AmazonS3Client( + _minioContainer.GetAccessKey(), + _minioContainer.GetSecretKey(), + config + ); // When - var buckets = await client.ListBucketsAsync(TestContext.Current.CancellationToken) + var buckets = await client + .ListBucketsAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -43,7 +47,11 @@ public async Task GetObjectReturnsPutObject() var config = new AmazonS3Config(); config.ServiceURL = _minioContainer.GetConnectionString(); - using var client = new AmazonS3Client(_minioContainer.GetAccessKey(), _minioContainer.GetSecretKey(), config); + using var client = new AmazonS3Client( + _minioContainer.GetAccessKey(), + _minioContainer.GetSecretKey(), + config + ); var objectRequest = new PutObjectRequest(); objectRequest.BucketName = Guid.NewGuid().ToString("D"); @@ -51,16 +59,23 @@ public async Task GetObjectReturnsPutObject() objectRequest.InputStream = inputStream; // When - _ = await client.PutBucketAsync(objectRequest.BucketName, TestContext.Current.CancellationToken) + _ = await client + .PutBucketAsync(objectRequest.BucketName, TestContext.Current.CancellationToken) .ConfigureAwait(true); - _ = await client.PutObjectAsync(objectRequest, TestContext.Current.CancellationToken) + _ = await client + .PutObjectAsync(objectRequest, TestContext.Current.CancellationToken) .ConfigureAwait(true); - var objectResponse = await client.GetObjectAsync(objectRequest.BucketName, objectRequest.Key, TestContext.Current.CancellationToken) + var objectResponse = await client + .GetObjectAsync( + objectRequest.BucketName, + objectRequest.Key, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); // Then Assert.Equal(byte.MaxValue, objectResponse.ContentLength); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Minio.Tests/Testcontainers.Minio.Tests.csproj b/tests/Testcontainers.Minio.Tests/Testcontainers.Minio.Tests.csproj index 99fa60a5c..48ed6168d 100644 --- a/tests/Testcontainers.Minio.Tests/Testcontainers.Minio.Tests.csproj +++ b/tests/Testcontainers.Minio.Tests/Testcontainers.Minio.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Minio.Tests/Usings.cs b/tests/Testcontainers.Minio.Tests/Usings.cs index d469b39a3..e13ba1edb 100644 --- a/tests/Testcontainers.Minio.Tests/Usings.cs +++ b/tests/Testcontainers.Minio.Tests/Usings.cs @@ -5,4 +5,4 @@ global using Amazon.S3; global using Amazon.S3.Model; global using DotNet.Testcontainers.Commons; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.MongoDb.Tests/MongoDbContainerTest.cs b/tests/Testcontainers.MongoDb.Tests/MongoDbContainerTest.cs index b83f13618..aab3b5118 100644 --- a/tests/Testcontainers.MongoDb.Tests/MongoDbContainerTest.cs +++ b/tests/Testcontainers.MongoDb.Tests/MongoDbContainerTest.cs @@ -15,14 +15,12 @@ private MongoDbContainerTest(MongoDbContainer mongoDbContainer, bool replicaSetE // # --8<-- [start:UseMongoDbContainer] public async ValueTask InitializeAsync() { - await _mongoDbContainer.StartAsync() - .ConfigureAwait(false); + await _mongoDbContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -38,7 +36,10 @@ public void ConnectionStateReturnsOpen() using var databases = client.ListDatabases(TestContext.Current.CancellationToken); // Then - Assert.Contains(databases.ToEnumerable(TestContext.Current.CancellationToken), database => database.TryGetValue("name", out var name) && "admin".Equals(name.AsString)); + Assert.Contains( + databases.ToEnumerable(TestContext.Current.CancellationToken), + database => database.TryGetValue("name", out var name) && "admin".Equals(name.AsString) + ); } [Fact] @@ -46,16 +47,19 @@ public void ConnectionStateReturnsOpen() public async Task ExecScriptReturnsSuccessful() { // Given - const string scriptContent = "printjson(db.adminCommand({listDatabases:1,nameOnly:true,filter:{\"name\":/^admin/}}));"; + const string scriptContent = + "printjson(db.adminCommand({listDatabases:1,nameOnly:true,filter:{\"name\":/^admin/}}));"; // When - var execResult = await _mongoDbContainer.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) + var execResult = await _mongoDbContainer + .ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.True(0L.Equals(execResult.ExitCode), execResult.Stderr); Assert.Empty(execResult.Stderr); } + // # --8<-- [end:UseMongoDbContainer] [Fact] @@ -66,7 +70,8 @@ public async Task ReplicaSetStatus() const string scriptContent = "rs.status().ok;"; // When - var execResult = await _mongoDbContainer.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) + var execResult = await _mongoDbContainer + .ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -92,46 +97,42 @@ protected virtual ValueTask DisposeAsyncCore() public sealed class MongoDbDefaultConfiguration : MongoDbContainerTest { public MongoDbDefaultConfiguration() - : base(new MongoDbBuilder().Build()) - { - } + : base(new MongoDbBuilder().Build()) { } } [UsedImplicitly] public sealed class MongoDbNoAuthConfiguration : MongoDbContainerTest { public MongoDbNoAuthConfiguration() - : base(new MongoDbBuilder().WithUsername(string.Empty).WithPassword(string.Empty).Build()) - { - } + : base( + new MongoDbBuilder().WithUsername(string.Empty).WithPassword(string.Empty).Build() + ) { } } + // # --8<-- [end:CreateMongoDbContainer] [UsedImplicitly] public sealed class MongoDbV5Configuration : MongoDbContainerTest { public MongoDbV5Configuration() - : base(new MongoDbBuilder().WithImage("mongo:5.0").Build()) - { - } + : base(new MongoDbBuilder().WithImage("mongo:5.0").Build()) { } } [UsedImplicitly] public sealed class MongoDbV4Configuration : MongoDbContainerTest { public MongoDbV4Configuration() - : base(new MongoDbBuilder().WithImage("mongo:4.4").Build(), true /* Replica set status returns "ok" in MongoDB 4.4 without initialization. */) - { - } + : base( + new MongoDbBuilder().WithImage("mongo:4.4").Build(), + true /* Replica set status returns "ok" in MongoDB 4.4 without initialization. */ + ) { } } [UsedImplicitly] public sealed class MongoDbReplicaSetDefaultConfiguration : MongoDbContainerTest { public MongoDbReplicaSetDefaultConfiguration() - : base(new MongoDbBuilder().WithReplicaSet().Build(), true) - { - } + : base(new MongoDbBuilder().WithReplicaSet().Build(), true) { } } // # --8<-- [start:ReplicaSetContainerConfiguration] @@ -139,9 +140,7 @@ public MongoDbReplicaSetDefaultConfiguration() public sealed class MongoDbNamedReplicaSetConfiguration : MongoDbContainerTest { public MongoDbNamedReplicaSetConfiguration() - : base(new MongoDbBuilder().WithReplicaSet("rs1").Build(), true) - { - } + : base(new MongoDbBuilder().WithReplicaSet("rs1").Build(), true) { } } // # --8<-- [end:ReplicaSetContainerConfiguration] -} \ 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 dd6f0444c..468fe2195 100644 --- a/tests/Testcontainers.MongoDb.Tests/Testcontainers.MongoDb.Tests.csproj +++ b/tests/Testcontainers.MongoDb.Tests/Testcontainers.MongoDb.Tests.csproj @@ -1,21 +1,21 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.MongoDb.Tests/Usings.cs b/tests/Testcontainers.MongoDb.Tests/Usings.cs index 6d2e03725..c5818bcc7 100644 --- a/tests/Testcontainers.MongoDb.Tests/Usings.cs +++ b/tests/Testcontainers.MongoDb.Tests/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Commons; global using JetBrains.Annotations; global using MongoDB.Driver; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.MsSql.Tests/MsSqlContainerTest.cs b/tests/Testcontainers.MsSql.Tests/MsSqlContainerTest.cs index c8e7e7abb..fe3ce3c04 100644 --- a/tests/Testcontainers.MsSql.Tests/MsSqlContainerTest.cs +++ b/tests/Testcontainers.MsSql.Tests/MsSqlContainerTest.cs @@ -25,35 +25,40 @@ public async Task ExecScriptReturnsSuccessful() const string scriptContent = "SELECT 1;"; // When - var execResult = await fixture.Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) + var execResult = await fixture + .Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.True(0L.Equals(execResult.ExitCode), execResult.Stderr); Assert.Empty(execResult.Stderr); } + // # --8<-- [end:UseMsSqlContainer] public class MsSqlDefaultFixture(IMessageSink messageSink) : DbContainerFixture(messageSink) { - public override DbProviderFactory DbProviderFactory - => SqlClientFactory.Instance; + public override DbProviderFactory DbProviderFactory => SqlClientFactory.Instance; } [UsedImplicitly] public class MsSqlWaitForDatabaseFixture(IMessageSink messageSink) : MsSqlDefaultFixture(messageSink) { - protected override MsSqlBuilder Configure(MsSqlBuilder builder) - => builder.WithWaitStrategy(Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory)); + protected override MsSqlBuilder Configure(MsSqlBuilder builder) => + builder.WithWaitStrategy( + Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory) + ); } [UsedImplicitly] public sealed class MsSqlDefaultConfiguration(MsSqlDefaultFixture fixture) - : MsSqlContainerTest(fixture), IClassFixture; + : MsSqlContainerTest(fixture), + IClassFixture; [UsedImplicitly] public sealed class MsSqlWaitForDatabaseConfiguration(MsSqlWaitForDatabaseFixture fixture) - : MsSqlContainerTest(fixture), IClassFixture; -} \ No newline at end of file + : MsSqlContainerTest(fixture), + IClassFixture; +} diff --git a/tests/Testcontainers.MsSql.Tests/Testcontainers.MsSql.Tests.csproj b/tests/Testcontainers.MsSql.Tests/Testcontainers.MsSql.Tests.csproj index 85a2d5aab..cf208a8fd 100644 --- a/tests/Testcontainers.MsSql.Tests/Testcontainers.MsSql.Tests.csproj +++ b/tests/Testcontainers.MsSql.Tests/Testcontainers.MsSql.Tests.csproj @@ -1,22 +1,22 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.MsSql.Tests/Usings.cs b/tests/Testcontainers.MsSql.Tests/Usings.cs index debde9e33..9227d9633 100644 --- a/tests/Testcontainers.MsSql.Tests/Usings.cs +++ b/tests/Testcontainers.MsSql.Tests/Usings.cs @@ -7,4 +7,4 @@ global using Microsoft.Data.SqlClient; global using Testcontainers.Xunit; global using Xunit; -global using Xunit.Sdk; \ No newline at end of file +global using Xunit.Sdk; diff --git a/tests/Testcontainers.MySql.Tests/MySqlContainerTest.cs b/tests/Testcontainers.MySql.Tests/MySqlContainerTest.cs index 9d87da403..2361e23a5 100644 --- a/tests/Testcontainers.MySql.Tests/MySqlContainerTest.cs +++ b/tests/Testcontainers.MySql.Tests/MySqlContainerTest.cs @@ -24,7 +24,8 @@ public async Task ExecScriptReturnsSuccessful() const string scriptContent = "SELECT 1;"; // When - var execResult = await fixture.Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) + var execResult = await fixture + .Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -35,24 +36,24 @@ public async Task ExecScriptReturnsSuccessful() public class MySqlDefaultFixture(IMessageSink messageSink) : DbContainerFixture(messageSink) { - public override DbProviderFactory DbProviderFactory - => MySqlConnectorFactory.Instance; + public override DbProviderFactory DbProviderFactory => MySqlConnectorFactory.Instance; } [UsedImplicitly] public class MySqlWaitForDatabaseFixture(IMessageSink messageSink) : MySqlDefaultFixture(messageSink) { - protected override MySqlBuilder Configure(MySqlBuilder builder) - => builder.WithWaitStrategy(Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory)); + protected override MySqlBuilder Configure(MySqlBuilder builder) => + builder.WithWaitStrategy( + Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory) + ); } [UsedImplicitly] - public class MySqlRootFixture(IMessageSink messageSink) - : MySqlDefaultFixture(messageSink) + public class MySqlRootFixture(IMessageSink messageSink) : MySqlDefaultFixture(messageSink) { - protected override MySqlBuilder Configure(MySqlBuilder builder) - => builder.WithUsername("root"); + protected override MySqlBuilder Configure(MySqlBuilder builder) => + builder.WithUsername("root"); } [UsedImplicitly] @@ -60,23 +61,27 @@ public class MySqlGitHubIssue1142Fixture(IMessageSink messageSink) : MySqlDefaultFixture(messageSink) { // https://github.com/testcontainers/testcontainers-dotnet/issues/1142. - protected override MySqlBuilder Configure(MySqlBuilder builder) - => builder.WithImage("mysql:8.0.28"); + protected override MySqlBuilder Configure(MySqlBuilder builder) => + builder.WithImage("mysql:8.0.28"); } [UsedImplicitly] public sealed class MySqlDefaultConfiguration(MySqlDefaultFixture fixture) - : MySqlContainerTest(fixture), IClassFixture; + : MySqlContainerTest(fixture), + IClassFixture; [UsedImplicitly] public sealed class MySqlWaitForDatabaseConfiguration(MySqlWaitForDatabaseFixture fixture) - : MySqlContainerTest(fixture), IClassFixture; + : MySqlContainerTest(fixture), + IClassFixture; [UsedImplicitly] public sealed class MySqlRootConfiguration(MySqlRootFixture fixture) - : MySqlContainerTest(fixture), IClassFixture; + : MySqlContainerTest(fixture), + IClassFixture; [UsedImplicitly] public sealed class MySqlGitHubIssue1142Configuration(MySqlGitHubIssue1142Fixture fixture) - : MySqlContainerTest(fixture), IClassFixture; -} \ No newline at end of file + : MySqlContainerTest(fixture), + IClassFixture; +} diff --git a/tests/Testcontainers.MySql.Tests/Testcontainers.MySql.Tests.csproj b/tests/Testcontainers.MySql.Tests/Testcontainers.MySql.Tests.csproj index ce26a4b8a..a159a324f 100644 --- a/tests/Testcontainers.MySql.Tests/Testcontainers.MySql.Tests.csproj +++ b/tests/Testcontainers.MySql.Tests/Testcontainers.MySql.Tests.csproj @@ -1,20 +1,20 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.MySql.Tests/Usings.cs b/tests/Testcontainers.MySql.Tests/Usings.cs index 34433ebc1..86f14ba1a 100644 --- a/tests/Testcontainers.MySql.Tests/Usings.cs +++ b/tests/Testcontainers.MySql.Tests/Usings.cs @@ -7,4 +7,4 @@ global using MySqlConnector; global using Testcontainers.Xunit; global using Xunit; -global using Xunit.Sdk; \ No newline at end of file +global using Xunit.Sdk; diff --git a/tests/Testcontainers.Nats.Tests/NatsContainerTest.cs b/tests/Testcontainers.Nats.Tests/NatsContainerTest.cs index 89481fa28..d2c2a0509 100644 --- a/tests/Testcontainers.Nats.Tests/NatsContainerTest.cs +++ b/tests/Testcontainers.Nats.Tests/NatsContainerTest.cs @@ -11,14 +11,12 @@ private NatsContainerTest(NatsContainer natsContainer) public async ValueTask InitializeAsync() { - await _natsContainer.StartAsync() - .ConfigureAwait(false); + await _natsContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -32,10 +30,12 @@ public async Task HealthcheckReturnsHttpStatusCodeOk() httpClient.BaseAddress = new Uri(_natsContainer.GetManagementEndpoint()); // When - using var httpResponse = await httpClient.GetAsync("/healthz", TestContext.Current.CancellationToken) + using var httpResponse = await httpClient + .GetAsync("/healthz", TestContext.Current.CancellationToken) .ConfigureAwait(true); - var jsonStatusString = await httpResponse.Content.ReadAsStringAsync(TestContext.Current.CancellationToken) + var jsonStatusString = await httpResponse + .Content.ReadAsStringAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -52,7 +52,9 @@ public void GetStringReturnsPublishString() var message = Guid.NewGuid().ToString("D"); - using var client = new ConnectionFactory().CreateConnection(_natsContainer.GetConnectionString()); + using var client = new ConnectionFactory().CreateConnection( + _natsContainer.GetConnectionString() + ); using var subscription = client.SubscribeSync(subject); @@ -74,9 +76,7 @@ protected virtual ValueTask DisposeAsyncCore() public sealed class NatsDefaultConfiguration : NatsContainerTest { public NatsDefaultConfiguration() - : base(new NatsBuilder().Build()) - { - } + : base(new NatsBuilder().Build()) { } } [UsedImplicitly] @@ -84,21 +84,24 @@ public sealed class NatsAuthConfiguration : NatsContainerTest { public NatsAuthConfiguration() : base(new NatsBuilder().WithUsername("%username!").WithPassword("?password&").Build()) - { - } + { } [Fact] [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public void ThrowsExceptionIfUsernameIsMissing() { - Assert.Throws(() => new NatsBuilder().WithPassword("password").Build()); + Assert.Throws(() => + new NatsBuilder().WithPassword("password").Build() + ); } [Fact] [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public void ThrowsExceptionIfPasswordIsMissing() { - Assert.Throws(() => new NatsBuilder().WithUsername("username").Build()); + Assert.Throws(() => + new NatsBuilder().WithUsername("username").Build() + ); } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Nats.Tests/Testcontainers.Nats.Tests.csproj b/tests/Testcontainers.Nats.Tests/Testcontainers.Nats.Tests.csproj index 7d8517f36..100ac2095 100644 --- a/tests/Testcontainers.Nats.Tests/Testcontainers.Nats.Tests.csproj +++ b/tests/Testcontainers.Nats.Tests/Testcontainers.Nats.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Nats.Tests/Usings.cs b/tests/Testcontainers.Nats.Tests/Usings.cs index 49a70954e..73c837042 100644 --- a/tests/Testcontainers.Nats.Tests/Usings.cs +++ b/tests/Testcontainers.Nats.Tests/Usings.cs @@ -6,4 +6,4 @@ global using DotNet.Testcontainers.Commons; global using JetBrains.Annotations; global using NATS.Client; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Neo4j.Tests/Neo4jBuilderTest.cs b/tests/Testcontainers.Neo4j.Tests/Neo4jBuilderTest.cs index fc8b15b1e..b637a214b 100644 --- a/tests/Testcontainers.Neo4j.Tests/Neo4jBuilderTest.cs +++ b/tests/Testcontainers.Neo4j.Tests/Neo4jBuilderTest.cs @@ -24,17 +24,28 @@ public sealed class Neo4jBuilderTest [InlineData("neo4j:5-enterprise", "5-enterprise")] [InlineData("neo4j:enterprise", "enterprise")] [InlineData("neo4j", "enterprise")] - [InlineData("neo4j@sha256:20eb19e3d60f9f07c12c89eac8d8722e393be7e45c6d7e56004a2c493b8e2032", null)] - public void AppendsEnterpriseSuffixWhenEnterpriseEditionLicenseAgreementIsAccepted(string image, string expected) + [InlineData( + "neo4j@sha256:20eb19e3d60f9f07c12c89eac8d8722e393be7e45c6d7e56004a2c493b8e2032", + null + )] + public void AppendsEnterpriseSuffixWhenEnterpriseEditionLicenseAgreementIsAccepted( + string image, + string expected + ) { - var neo4jContainer = new Neo4jBuilder().WithImage(image).WithEnterpriseEdition(true).Build(); + var neo4jContainer = new Neo4jBuilder() + .WithImage(image) + .WithEnterpriseEdition(true) + .Build(); Assert.Equal(expected, neo4jContainer.Image.Tag); } [Theory] [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] [ClassData(typeof(Neo4jBuilderConfigurations))] - public void ThrowsArgumentExceptionWhenEnterpriseEditionLicenseAgreementIsNotAccepted(Neo4jBuilder neo4jBuilder) + public void ThrowsArgumentExceptionWhenEnterpriseEditionLicenseAgreementIsNotAccepted( + Neo4jBuilder neo4jBuilder + ) { Assert.Throws(neo4jBuilder.Build); } @@ -47,4 +58,4 @@ public Neo4jBuilderConfigurations() Add(new Neo4jBuilder().WithEnterpriseEdition(false)); } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Neo4j.Tests/Neo4jContainerTest.cs b/tests/Testcontainers.Neo4j.Tests/Neo4jContainerTest.cs index 0ce752b12..b2cbeae82 100644 --- a/tests/Testcontainers.Neo4j.Tests/Neo4jContainerTest.cs +++ b/tests/Testcontainers.Neo4j.Tests/Neo4jContainerTest.cs @@ -14,14 +14,12 @@ private Neo4jContainerTest(Neo4jContainer neo4jContainer) // # --8<-- [start:UseNeo4jContainer] public async ValueTask InitializeAsync() { - await _neo4jContainer.StartAsync() - .ConfigureAwait(false); + await _neo4jContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -36,13 +34,15 @@ public async Task SessionReturnsDatabase() using var driver = GraphDatabase.Driver(_neo4jContainer.GetConnectionString()); // When - using var session = driver.AsyncSession(sessionConfigBuilder => sessionConfigBuilder.WithDatabase(neo4jDatabase)); + using var session = driver.AsyncSession(sessionConfigBuilder => + sessionConfigBuilder.WithDatabase(neo4jDatabase) + ); - var result = await session.RunAsync("CALL dbms.components() YIELD edition RETURN edition") + var result = await session + .RunAsync("CALL dbms.components() YIELD edition RETURN edition") .ConfigureAwait(true); - var record = await result.SingleAsync() - .ConfigureAwait(true); + var record = await result.SingleAsync().ConfigureAwait(true); var edition = record["edition"].As(); @@ -50,6 +50,7 @@ public async Task SessionReturnsDatabase() Assert.Equal(neo4jDatabase, session.SessionConfig.Database); Assert.Equal(Edition, edition); } + // # --8<-- [end:UseNeo4jContainer] protected virtual ValueTask DisposeAsyncCore() @@ -62,9 +63,7 @@ protected virtual ValueTask DisposeAsyncCore() public sealed class Neo4jDefaultConfiguration : Neo4jContainerTest { public Neo4jDefaultConfiguration() - : base(new Neo4jBuilder().Build()) - { - } + : base(new Neo4jBuilder().Build()) { } public override string Edition => "community"; } @@ -73,11 +72,9 @@ public Neo4jDefaultConfiguration() public sealed class Neo4jEnterpriseEditionConfiguration : Neo4jContainerTest { public Neo4jEnterpriseEditionConfiguration() - : base(new Neo4jBuilder().WithEnterpriseEdition(true).Build()) - { - } + : base(new Neo4jBuilder().WithEnterpriseEdition(true).Build()) { } public override string Edition => "enterprise"; } // # --8<-- [end:CreateNeo4jContainer] -} \ 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 96f795a3d..aaadb2883 100644 --- a/tests/Testcontainers.Neo4j.Tests/Testcontainers.Neo4j.Tests.csproj +++ b/tests/Testcontainers.Neo4j.Tests/Testcontainers.Neo4j.Tests.csproj @@ -1,21 +1,21 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Neo4j.Tests/Usings.cs b/tests/Testcontainers.Neo4j.Tests/Usings.cs index b7288ff63..cc390df2d 100644 --- a/tests/Testcontainers.Neo4j.Tests/Usings.cs +++ b/tests/Testcontainers.Neo4j.Tests/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Commons; global using JetBrains.Annotations; global using Neo4j.Driver; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Ollama.Tests/OllamaContainerTest.cs b/tests/Testcontainers.Ollama.Tests/OllamaContainerTest.cs index ce97b40e6..75ea996ad 100644 --- a/tests/Testcontainers.Ollama.Tests/OllamaContainerTest.cs +++ b/tests/Testcontainers.Ollama.Tests/OllamaContainerTest.cs @@ -6,8 +6,7 @@ public sealed class OllamaContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _ollamaContainer.StartAsync() - .ConfigureAwait(false); + await _ollamaContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -29,14 +28,19 @@ public async Task GenerateEmbeddingsReturnsEmbeddings() embedRequest.Input = new List { "Hello, World!" }; // When - await foreach (var _ in ollamaClient.PullModelAsync(model, TestContext.Current.CancellationToken) - .ConfigureAwait(true)); - - var embedResponse = await ollamaClient.EmbedAsync(embedRequest, TestContext.Current.CancellationToken) + await foreach ( + var _ in ollamaClient + .PullModelAsync(model, TestContext.Current.CancellationToken) + .ConfigureAwait(true) + ) + ; + + var embedResponse = await ollamaClient + .EmbedAsync(embedRequest, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.NotNull(embedResponse); Assert.NotEmpty(embedResponse.Embeddings); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Ollama.Tests/Testcontainers.Ollama.Tests.csproj b/tests/Testcontainers.Ollama.Tests/Testcontainers.Ollama.Tests.csproj index 0a9d2252c..4eae5d7b6 100644 --- a/tests/Testcontainers.Ollama.Tests/Testcontainers.Ollama.Tests.csproj +++ b/tests/Testcontainers.Ollama.Tests/Testcontainers.Ollama.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Ollama.Tests/Usings.cs b/tests/Testcontainers.Ollama.Tests/Usings.cs index 69a12ecca..b2897db10 100644 --- a/tests/Testcontainers.Ollama.Tests/Usings.cs +++ b/tests/Testcontainers.Ollama.Tests/Usings.cs @@ -3,4 +3,4 @@ global using DotNet.Testcontainers.Commons; global using OllamaSharp; global using OllamaSharp.Models; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.OpenSearch.Tests/OpenSearchBuilderTest.cs b/tests/Testcontainers.OpenSearch.Tests/OpenSearchBuilderTest.cs index 6b6093a5d..36f2beca7 100644 --- a/tests/Testcontainers.OpenSearch.Tests/OpenSearchBuilderTest.cs +++ b/tests/Testcontainers.OpenSearch.Tests/OpenSearchBuilderTest.cs @@ -19,4 +19,4 @@ public void ShouldUseHardcodedDefaultPassword(string image) // Then Assert.Equal("admin", credentials.Password); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.OpenSearch.Tests/OpenSearchContainerTest.cs b/tests/Testcontainers.OpenSearch.Tests/OpenSearchContainerTest.cs index d7c41b432..7c3313cf2 100644 --- a/tests/Testcontainers.OpenSearch.Tests/OpenSearchContainerTest.cs +++ b/tests/Testcontainers.OpenSearch.Tests/OpenSearchContainerTest.cs @@ -14,17 +14,16 @@ private OpenSearchContainerTest(OpenSearchContainer openSearchContainer) public async ValueTask InitializeAsync() { - await _openSearchContainer.StartAsync() - .ConfigureAwait(false); + await _openSearchContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } + // // @@ -36,12 +35,14 @@ public async Task PingReturnsValidResponse() var client = CreateClient(); // When - var response = await client.PingAsync(ct: TestContext.Current.CancellationToken) + var response = await client + .PingAsync(ct: TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.True(response.IsValid); } + // // @@ -57,16 +58,17 @@ public async Task ShouldCreateIndexAndAlias() var alias = new Name(IndexName + "-alias"); // When - var createIndexResponse = await CreateIndexAsync(client) - .ConfigureAwait(true); + var createIndexResponse = await CreateIndexAsync(client).ConfigureAwait(true); - var createAliasResponse = await client.Indices.PutAliasAsync(index, alias, ct: TestContext.Current.CancellationToken) + var createAliasResponse = await client + .Indices.PutAliasAsync(index, alias, ct: TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.True(createIndexResponse.IsValid); Assert.True(createAliasResponse.IsValid); } + // // @@ -86,13 +88,14 @@ public async Task ShouldIndexAndSearchForDocument() Func, ISearchRequest> searchRequest = s => s.Index(IndexName).Query(q => q.Match(m => m.Field("title").Query(document.Title))); - var createIndexResponse = await CreateIndexAsync(client) - .ConfigureAwait(true); + var createIndexResponse = await CreateIndexAsync(client).ConfigureAwait(true); - var indexResponse = await client.IndexAsync(document, indexRequest, TestContext.Current.CancellationToken) + var indexResponse = await client + .IndexAsync(document, indexRequest, TestContext.Current.CancellationToken) .ConfigureAwait(true); - var searchResponse = await client.SearchAsync(searchRequest, TestContext.Current.CancellationToken) + var searchResponse = await client + .SearchAsync(searchRequest, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -104,16 +107,23 @@ public async Task ShouldIndexAndSearchForDocument() Assert.True(searchResponse.IsValid); Assert.Single(searchResponse.Documents, item => document.Id.Equals(item.Id)); } + // // private static Task CreateIndexAsync(OpenSearchClient client) { Func createIndexRequest = c => - c.Settings(s => s.NumberOfReplicas(0).NumberOfShards(1)).Map(m => m.AutoMap()); - - return client.Indices.CreateAsync(Indices.Index(IndexName), createIndexRequest, TestContext.Current.CancellationToken); + c.Settings(s => s.NumberOfReplicas(0).NumberOfShards(1)) + .Map(m => m.AutoMap()); + + return client.Indices.CreateAsync( + Indices.Index(IndexName), + createIndexRequest, + TestContext.Current.CancellationToken + ); } + // protected virtual ValueTask DisposeAsyncCore() @@ -140,11 +150,7 @@ protected virtual OpenSearchClient CreateClient() public sealed class InsecureNoAuthConfiguration : OpenSearchContainerTest { public InsecureNoAuthConfiguration() - : base(new OpenSearchBuilder() - .WithSecurityEnabled(false) - .Build()) - { - } + : base(new OpenSearchBuilder().WithSecurityEnabled(false).Build()) { } protected override OpenSearchClient CreateClient() { @@ -153,6 +159,7 @@ protected override OpenSearchClient CreateClient() return new OpenSearchClient(connectionString); } } + // // @@ -160,11 +167,9 @@ protected override OpenSearchClient CreateClient() public sealed class SslBasicAuthDefaultCredentialsConfiguration : OpenSearchContainerTest { public SslBasicAuthDefaultCredentialsConfiguration() - : base(new OpenSearchBuilder() - .Build()) - { - } + : base(new OpenSearchBuilder().Build()) { } } + // // @@ -172,14 +177,15 @@ public SslBasicAuthDefaultCredentialsConfiguration() public sealed class SslBasicAuthCustomCredentialsConfiguration : OpenSearchContainerTest { public SslBasicAuthCustomCredentialsConfiguration() - : base(new OpenSearchBuilder() - .WithPassword(new string(OpenSearchBuilder.DefaultPassword.Reverse().ToArray())) - .Build()) - { - } + : base( + new OpenSearchBuilder() + .WithPassword(new string(OpenSearchBuilder.DefaultPassword.Reverse().ToArray())) + .Build() + ) { } } + // [UsedImplicitly] private record Document(string Id, string Title); -} \ No newline at end of file +} diff --git a/tests/Testcontainers.OpenSearch.Tests/Testcontainers.OpenSearch.Tests.csproj b/tests/Testcontainers.OpenSearch.Tests/Testcontainers.OpenSearch.Tests.csproj index e5a910e8e..31220eaa3 100644 --- a/tests/Testcontainers.OpenSearch.Tests/Testcontainers.OpenSearch.Tests.csproj +++ b/tests/Testcontainers.OpenSearch.Tests/Testcontainers.OpenSearch.Tests.csproj @@ -1,21 +1,21 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.OpenSearch.Tests/Usings.cs b/tests/Testcontainers.OpenSearch.Tests/Usings.cs index e99d10a3d..bbc244591 100644 --- a/tests/Testcontainers.OpenSearch.Tests/Usings.cs +++ b/tests/Testcontainers.OpenSearch.Tests/Usings.cs @@ -5,4 +5,4 @@ global using JetBrains.Annotations; global using OpenSearch.Client; global using OpenSearch.Net; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Oracle.Tests/OracleContainerTest.cs b/tests/Testcontainers.Oracle.Tests/OracleContainerTest.cs index 5f00d5302..f3fe690a0 100644 --- a/tests/Testcontainers.Oracle.Tests/OracleContainerTest.cs +++ b/tests/Testcontainers.Oracle.Tests/OracleContainerTest.cs @@ -24,7 +24,8 @@ public async Task ExecScriptReturnsSuccessful() const string scriptContent = "SELECT 1 FROM DUAL;"; // When - var execResult = await fixture.Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) + var execResult = await fixture + .Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -32,7 +33,13 @@ public async Task ExecScriptReturnsSuccessful() Assert.Empty(execResult.Stderr); } - public abstract class OracleFixture(IMessageSink messageSink, string edition, int? version, string database = null, bool waitForDatabase = false) : DbContainerFixture(messageSink) + public abstract class OracleFixture( + IMessageSink messageSink, + string edition, + int? version, + string database = null, + bool waitForDatabase = false + ) : DbContainerFixture(messageSink) { public override DbProviderFactory DbProviderFactory => OracleClientFactory.Instance; @@ -44,50 +51,136 @@ protected override OracleBuilder Configure(OracleBuilder builder) } var image = $"gvenzl/oracle-{edition}:{version}-slim-faststart"; - return database == null ? Apply(builder, oracle => oracle.WithImage(image)) : Apply(builder, oracle => oracle.WithImage(image).WithDatabase(database)); + return database == null + ? Apply(builder, oracle => oracle.WithImage(image)) + : Apply(builder, oracle => oracle.WithImage(image).WithDatabase(database)); } - private OracleBuilder Apply(OracleBuilder builder, Func configure) + private OracleBuilder Apply( + OracleBuilder builder, + Func configure + ) { - return waitForDatabase ? configure(builder.WithWaitStrategy(Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory))) : configure(builder); + return waitForDatabase + ? configure( + builder.WithWaitStrategy( + Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory) + ) + ) + : configure(builder); } } #if ORACLE_DEFAULT - [UsedImplicitly] public sealed class OracleDefault(OracleDefaultFixture fixture) : OracleContainerTest(fixture), IClassFixture; - [UsedImplicitly] public sealed class OracleDefaultFixture(IMessageSink messageSink) : OracleFixture(messageSink, null, null); + [UsedImplicitly] + public sealed class OracleDefault(OracleDefaultFixture fixture) + : OracleContainerTest(fixture), + IClassFixture; + + [UsedImplicitly] + public sealed class OracleDefaultFixture(IMessageSink messageSink) + : OracleFixture(messageSink, null, null); #endif #if ORACLE_11 - [UsedImplicitly] public sealed class Oracle11(Oracle11Fixture fixture) : OracleContainerTest(fixture), IClassFixture; - [UsedImplicitly] public sealed class Oracle11Fixture(IMessageSink messageSink) : OracleFixture(messageSink, "xe", 11); - [UsedImplicitly] public sealed class Oracle11FixtureWaitForDatabase(IMessageSink messageSink) : OracleFixture(messageSink, "xe", 11, waitForDatabase: true); + [UsedImplicitly] + public sealed class Oracle11(Oracle11Fixture fixture) + : OracleContainerTest(fixture), + IClassFixture; + + [UsedImplicitly] + public sealed class Oracle11Fixture(IMessageSink messageSink) + : OracleFixture(messageSink, "xe", 11); + + [UsedImplicitly] + public sealed class Oracle11FixtureWaitForDatabase(IMessageSink messageSink) + : OracleFixture(messageSink, "xe", 11, waitForDatabase: true); #endif #if ORACLE_18 - [UsedImplicitly] public sealed class Oracle18(Oracle18Fixture fixture) : OracleContainerTest(fixture), IClassFixture; - [UsedImplicitly] public sealed class Oracle18Default(Oracle18FixtureDefault fixture) : OracleContainerTest(fixture), IClassFixture; - [UsedImplicitly] public sealed class Oracle18Scott(Oracle18FixtureScott fixture) : OracleContainerTest(fixture), IClassFixture; - [UsedImplicitly] public sealed class Oracle18Fixture(IMessageSink messageSink) : OracleFixture(messageSink, "xe", 18); - [UsedImplicitly] public sealed class Oracle18FixtureDefault(IMessageSink messageSink) : OracleFixture(messageSink, "xe", 18, "XEPDB1", waitForDatabase: true); - [UsedImplicitly] public sealed class Oracle18FixtureScott(IMessageSink messageSink) : OracleFixture(messageSink, "xe", 18, "SCOTT"); + [UsedImplicitly] + public sealed class Oracle18(Oracle18Fixture fixture) + : OracleContainerTest(fixture), + IClassFixture; + + [UsedImplicitly] + public sealed class Oracle18Default(Oracle18FixtureDefault fixture) + : OracleContainerTest(fixture), + IClassFixture; + + [UsedImplicitly] + public sealed class Oracle18Scott(Oracle18FixtureScott fixture) + : OracleContainerTest(fixture), + IClassFixture; + + [UsedImplicitly] + public sealed class Oracle18Fixture(IMessageSink messageSink) + : OracleFixture(messageSink, "xe", 18); + + [UsedImplicitly] + public sealed class Oracle18FixtureDefault(IMessageSink messageSink) + : OracleFixture(messageSink, "xe", 18, "XEPDB1", waitForDatabase: true); + + [UsedImplicitly] + public sealed class Oracle18FixtureScott(IMessageSink messageSink) + : OracleFixture(messageSink, "xe", 18, "SCOTT"); #endif #if ORACLE_21 - [UsedImplicitly] public sealed class Oracle21(Oracle21Fixture fixture) : OracleContainerTest(fixture), IClassFixture; - [UsedImplicitly] public sealed class Oracle21Default(Oracle21FixtureDefault fixture) : OracleContainerTest(fixture), IClassFixture; - [UsedImplicitly] public sealed class Oracle21Scott(Oracle21FixtureScott fixture) : OracleContainerTest(fixture), IClassFixture; - [UsedImplicitly] public sealed class Oracle21Fixture(IMessageSink messageSink) : OracleFixture(messageSink, "xe", 21); - [UsedImplicitly] public sealed class Oracle21FixtureDefault(IMessageSink messageSink) : OracleFixture(messageSink, "xe", 21, "XEPDB1", waitForDatabase: true); - [UsedImplicitly] public sealed class Oracle21FixtureScott(IMessageSink messageSink) : OracleFixture(messageSink, "xe", 21, "SCOTT"); + [UsedImplicitly] + public sealed class Oracle21(Oracle21Fixture fixture) + : OracleContainerTest(fixture), + IClassFixture; + + [UsedImplicitly] + public sealed class Oracle21Default(Oracle21FixtureDefault fixture) + : OracleContainerTest(fixture), + IClassFixture; + + [UsedImplicitly] + public sealed class Oracle21Scott(Oracle21FixtureScott fixture) + : OracleContainerTest(fixture), + IClassFixture; + + [UsedImplicitly] + public sealed class Oracle21Fixture(IMessageSink messageSink) + : OracleFixture(messageSink, "xe", 21); + + [UsedImplicitly] + public sealed class Oracle21FixtureDefault(IMessageSink messageSink) + : OracleFixture(messageSink, "xe", 21, "XEPDB1", waitForDatabase: true); + + [UsedImplicitly] + public sealed class Oracle21FixtureScott(IMessageSink messageSink) + : OracleFixture(messageSink, "xe", 21, "SCOTT"); #endif #if ORACLE_23 - [UsedImplicitly] public sealed class Oracle23(Oracle23Fixture fixture) : OracleContainerTest(fixture), IClassFixture; - [UsedImplicitly] public sealed class Oracle23Default(Oracle23FixtureDefault fixture) : OracleContainerTest(fixture), IClassFixture; - [UsedImplicitly] public sealed class Oracle23Scott(Oracle23FixtureScott fixture) : OracleContainerTest(fixture), IClassFixture; - [UsedImplicitly] public sealed class Oracle23Fixture(IMessageSink messageSink) : OracleFixture(messageSink, "free", 23); - [UsedImplicitly] public sealed class Oracle23FixtureDefault(IMessageSink messageSink) : OracleFixture(messageSink, "free", 23, "FREEPDB1", waitForDatabase: true); - [UsedImplicitly] public sealed class Oracle23FixtureScott(IMessageSink messageSink) : OracleFixture(messageSink, "free", 23, "SCOTT"); + [UsedImplicitly] + public sealed class Oracle23(Oracle23Fixture fixture) + : OracleContainerTest(fixture), + IClassFixture; + + [UsedImplicitly] + public sealed class Oracle23Default(Oracle23FixtureDefault fixture) + : OracleContainerTest(fixture), + IClassFixture; + + [UsedImplicitly] + public sealed class Oracle23Scott(Oracle23FixtureScott fixture) + : OracleContainerTest(fixture), + IClassFixture; + + [UsedImplicitly] + public sealed class Oracle23Fixture(IMessageSink messageSink) + : OracleFixture(messageSink, "free", 23); + + [UsedImplicitly] + public sealed class Oracle23FixtureDefault(IMessageSink messageSink) + : OracleFixture(messageSink, "free", 23, "FREEPDB1", waitForDatabase: true); + + [UsedImplicitly] + public sealed class Oracle23FixtureScott(IMessageSink messageSink) + : OracleFixture(messageSink, "free", 23, "SCOTT"); #endif -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Oracle.Tests/Testcontainers.Oracle.Tests.csproj b/tests/Testcontainers.Oracle.Tests/Testcontainers.Oracle.Tests.csproj index 592c11387..69b462a24 100644 --- a/tests/Testcontainers.Oracle.Tests/Testcontainers.Oracle.Tests.csproj +++ b/tests/Testcontainers.Oracle.Tests/Testcontainers.Oracle.Tests.csproj @@ -1,21 +1,21 @@ - - net9.0 - false - false - Exe - $(DefineConstants);ORACLE_DEFAULT - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + $(DefineConstants);ORACLE_DEFAULT + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Oracle.Tests/Usings.cs b/tests/Testcontainers.Oracle.Tests/Usings.cs index 0c2c150f0..fb5ab69e3 100644 --- a/tests/Testcontainers.Oracle.Tests/Usings.cs +++ b/tests/Testcontainers.Oracle.Tests/Usings.cs @@ -8,4 +8,4 @@ global using Oracle.ManagedDataAccess.Client; global using Testcontainers.Xunit; global using Xunit; -global using Xunit.Sdk; \ No newline at end of file +global using Xunit.Sdk; diff --git a/tests/Testcontainers.Oracle11.Tests/Testcontainers.Oracle11.Tests.csproj b/tests/Testcontainers.Oracle11.Tests/Testcontainers.Oracle11.Tests.csproj index 6f721214f..03d8eef68 100644 --- a/tests/Testcontainers.Oracle11.Tests/Testcontainers.Oracle11.Tests.csproj +++ b/tests/Testcontainers.Oracle11.Tests/Testcontainers.Oracle11.Tests.csproj @@ -1,24 +1,24 @@ - - net9.0 - false - false - Exe - $(DefineConstants);ORACLE_11 - - - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + $(DefineConstants);ORACLE_11 + + + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Oracle18.Tests/Testcontainers.Oracle18.Tests.csproj b/tests/Testcontainers.Oracle18.Tests/Testcontainers.Oracle18.Tests.csproj index 0fcf048e5..1ae903cff 100644 --- a/tests/Testcontainers.Oracle18.Tests/Testcontainers.Oracle18.Tests.csproj +++ b/tests/Testcontainers.Oracle18.Tests/Testcontainers.Oracle18.Tests.csproj @@ -1,24 +1,24 @@ - - net9.0 - false - false - Exe - $(DefineConstants);ORACLE_18 - - - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + $(DefineConstants);ORACLE_18 + + + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Oracle21.Tests/Testcontainers.Oracle21.Tests.csproj b/tests/Testcontainers.Oracle21.Tests/Testcontainers.Oracle21.Tests.csproj index c11605ba2..29d7e57e3 100644 --- a/tests/Testcontainers.Oracle21.Tests/Testcontainers.Oracle21.Tests.csproj +++ b/tests/Testcontainers.Oracle21.Tests/Testcontainers.Oracle21.Tests.csproj @@ -1,24 +1,24 @@ - - net9.0 - false - false - Exe - $(DefineConstants);ORACLE_21 - - - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + $(DefineConstants);ORACLE_21 + + + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Oracle23.Tests/Testcontainers.Oracle23.Tests.csproj b/tests/Testcontainers.Oracle23.Tests/Testcontainers.Oracle23.Tests.csproj index 40ca200c3..1ca604369 100644 --- a/tests/Testcontainers.Oracle23.Tests/Testcontainers.Oracle23.Tests.csproj +++ b/tests/Testcontainers.Oracle23.Tests/Testcontainers.Oracle23.Tests.csproj @@ -1,24 +1,24 @@ - - net9.0 - false - false - Exe - $(DefineConstants);ORACLE_23 - - - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + $(DefineConstants);ORACLE_23 + + + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Papercut.Tests/PapercutContainerTest.cs b/tests/Testcontainers.Papercut.Tests/PapercutContainerTest.cs index 6ad43b706..d6a85f8fb 100644 --- a/tests/Testcontainers.Papercut.Tests/PapercutContainerTest.cs +++ b/tests/Testcontainers.Papercut.Tests/PapercutContainerTest.cs @@ -6,8 +6,7 @@ public sealed class PapercutContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _papercutContainer.StartAsync() - .ConfigureAwait(false); + await _papercutContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -22,7 +21,10 @@ public async Task ReceivesSentMessage() // Given const string subject = "Test"; - using var smtpClient = new SmtpClient(_papercutContainer.Hostname, _papercutContainer.SmtpPort); + using var smtpClient = new SmtpClient( + _papercutContainer.Hostname, + _papercutContainer.SmtpPort + ); using var httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(_papercutContainer.GetBaseAddress()); @@ -30,7 +32,8 @@ public async Task ReceivesSentMessage() // When smtpClient.Send("from@example.com", "to@example.com", subject, "A test message"); - var messagesJson = await httpClient.GetStringAsync("/api/messages", TestContext.Current.CancellationToken) + var messagesJson = await httpClient + .GetStringAsync("/api/messages", TestContext.Current.CancellationToken) .ConfigureAwait(true); var jsonDocument = JsonDocument.Parse(messagesJson); @@ -63,4 +66,4 @@ public Message(string id, string subject, string size, DateTime createdAt) [JsonPropertyName("createdAt")] public DateTime CreatedAt { get; } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Papercut.Tests/Testcontainers.Papercut.Tests.csproj b/tests/Testcontainers.Papercut.Tests/Testcontainers.Papercut.Tests.csproj index 75195a5bf..6f82b9362 100644 --- a/tests/Testcontainers.Papercut.Tests/Testcontainers.Papercut.Tests.csproj +++ b/tests/Testcontainers.Papercut.Tests/Testcontainers.Papercut.Tests.csproj @@ -1,18 +1,18 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + diff --git a/tests/Testcontainers.Papercut.Tests/Usings.cs b/tests/Testcontainers.Papercut.Tests/Usings.cs index 763582fff..fd8f22f9b 100644 --- a/tests/Testcontainers.Papercut.Tests/Usings.cs +++ b/tests/Testcontainers.Papercut.Tests/Usings.cs @@ -5,4 +5,4 @@ global using System.Text.Json.Serialization; global using System.Threading.Tasks; global using DotNet.Testcontainers.Commons; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Platform.Linux.Tests/AcceptLicenseAgreementTest.cs b/tests/Testcontainers.Platform.Linux.Tests/AcceptLicenseAgreementTest.cs index a63cda9ed..040424e47 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/AcceptLicenseAgreementTest.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/AcceptLicenseAgreementTest.cs @@ -6,7 +6,12 @@ public sealed class AcceptLicenseAgreementTest [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public void WithLicenseAgreementAcceptedThrowsArgumentException() { - var exception = Assert.Throws(() => new ContainerBuilder().WithAcceptLicenseAgreement(true).Build()); - Assert.Equal("The module does not require you to accept a license agreement.", exception.Message); + var exception = Assert.Throws(() => + new ContainerBuilder().WithAcceptLicenseAgreement(true).Build() + ); + Assert.Equal( + "The module does not require you to accept a license agreement.", + exception.Message + ); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Platform.Linux.Tests/ComposableTest.cs b/tests/Testcontainers.Platform.Linux.Tests/ComposableTest.cs index 638e8001c..98be651f8 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/ComposableTest.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/ComposableTest.cs @@ -42,29 +42,33 @@ public void OverwritesThenAppendsFlag() Assert.Equal(new[] { "pattern", "*.log", "-l" }, command); } - private sealed class ComposableContainerBuilder : ContainerBuilder + private sealed class ComposableContainerBuilder + : ContainerBuilder { - public ComposableContainerBuilder() : this(new ContainerConfiguration()) - => DockerResourceConfiguration = Init().DockerResourceConfiguration; + public ComposableContainerBuilder() + : this(new ContainerConfiguration()) => + DockerResourceConfiguration = Init().DockerResourceConfiguration; - private ComposableContainerBuilder(ContainerConfiguration configuration) : base(configuration) - => DockerResourceConfiguration = configuration; + private ComposableContainerBuilder(ContainerConfiguration configuration) + : base(configuration) => DockerResourceConfiguration = configuration; protected override ContainerConfiguration DockerResourceConfiguration { get; } - public IEnumerable GetCommand() - => DockerResourceConfiguration.Command; + public IEnumerable GetCommand() => DockerResourceConfiguration.Command; - public override DockerContainer Build() - => new(DockerResourceConfiguration); + public override DockerContainer Build() => new(DockerResourceConfiguration); - protected override ComposableContainerBuilder Clone(IResourceConfiguration resourceConfiguration) - => Merge(DockerResourceConfiguration, new ContainerConfiguration(resourceConfiguration)); + protected override ComposableContainerBuilder Clone( + IResourceConfiguration resourceConfiguration + ) => Merge(DockerResourceConfiguration, new ContainerConfiguration(resourceConfiguration)); - protected override ComposableContainerBuilder Clone(IContainerConfiguration resourceConfiguration) - => Merge(DockerResourceConfiguration, new ContainerConfiguration(resourceConfiguration)); + protected override ComposableContainerBuilder Clone( + IContainerConfiguration resourceConfiguration + ) => Merge(DockerResourceConfiguration, new ContainerConfiguration(resourceConfiguration)); - protected override ComposableContainerBuilder Merge(ContainerConfiguration oldValue, ContainerConfiguration newValue) - => new(new ContainerConfiguration(oldValue, newValue)); + protected override ComposableContainerBuilder Merge( + ContainerConfiguration oldValue, + ContainerConfiguration newValue + ) => new(new ContainerConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Platform.Linux.Tests/DependsOnTest.cs b/tests/Testcontainers.Platform.Linux.Tests/DependsOnTest.cs index b712becb0..574fb5570 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/DependsOnTest.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/DependsOnTest.cs @@ -27,13 +27,9 @@ public async ValueTask InitializeAsync() .WithLabel(_labelKey, _labelValue) .Build(); - var network = new NetworkBuilder() - .WithLabel(_labelKey, _labelValue) - .Build(); + var network = new NetworkBuilder().WithLabel(_labelKey, _labelValue).Build(); - var volume = new VolumeBuilder() - .WithLabel(_labelKey, _labelValue) - .Build(); + var volume = new VolumeBuilder().WithLabel(_labelKey, _labelValue).Build(); var parentContainer = new ContainerBuilder() .DependsOn(childContainer1) @@ -44,8 +40,7 @@ public async ValueTask InitializeAsync() .WithLabel(_labelKey, _labelValue) .Build(); - await parentContainer.StartAsync() - .ConfigureAwait(false); + await parentContainer.StartAsync().ConfigureAwait(false); _disposables.Add(parentContainer); _disposables.Add(childContainer1); @@ -65,24 +60,40 @@ await Task.WhenAll(_disposables.Select(disposable => disposable.DisposeAsync().A public async Task DependsOnCreatesDependentResources() { // Given - using var clientConfiguration = TestcontainersSettings.OS.DockerEndpointAuthConfig.GetDockerClientConfiguration(Guid.NewGuid()); + using var clientConfiguration = + TestcontainersSettings.OS.DockerEndpointAuthConfig.GetDockerClientConfiguration( + Guid.NewGuid() + ); using var client = clientConfiguration.CreateClient(); - var containersListParameters = new ContainersListParameters { All = true, Filters = _filters }; + var containersListParameters = new ContainersListParameters + { + All = true, + Filters = _filters, + }; var networksListParameters = new NetworksListParameters { Filters = _filters }; var volumesListParameters = new VolumesListParameters { Filters = _filters }; // When - var containers = await client.Containers.ListContainersAsync(containersListParameters, TestContext.Current.CancellationToken) + var containers = await client + .Containers.ListContainersAsync( + containersListParameters, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - var networks = await client.Networks.ListNetworksAsync(networksListParameters, TestContext.Current.CancellationToken) + var networks = await client + .Networks.ListNetworksAsync( + networksListParameters, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - var response = await client.Volumes.ListAsync(volumesListParameters, TestContext.Current.CancellationToken) + var response = await client + .Volumes.ListAsync(volumesListParameters, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -90,4 +101,4 @@ public async Task DependsOnCreatesDependentResources() Assert.Single(networks); Assert.Single(response.Volumes); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Platform.Linux.Tests/ExecFailedExceptionTest.cs b/tests/Testcontainers.Platform.Linux.Tests/ExecFailedExceptionTest.cs index 7d0a5185f..34420f99e 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/ExecFailedExceptionTest.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/ExecFailedExceptionTest.cs @@ -2,32 +2,44 @@ namespace Testcontainers.Tests; public sealed class ExecFailedExceptionTest { - public static TheoryData ExecResultTestData { get; } - = new TheoryData + public static TheoryData ExecResultTestData { get; } = + new TheoryData { { new ExecResultSerializable("Stdout\nStdout", "Stderr\nStderr", 1), - "Process exited with code 1." + Environment.NewLine + - " Stdout: " + Environment.NewLine + - " Stdout" + Environment.NewLine + - " Stdout" + Environment.NewLine + - " Stderr: " + Environment.NewLine + - " Stderr" + Environment.NewLine + - " Stderr" + "Process exited with code 1." + + Environment.NewLine + + " Stdout: " + + Environment.NewLine + + " Stdout" + + Environment.NewLine + + " Stdout" + + Environment.NewLine + + " Stderr: " + + Environment.NewLine + + " Stderr" + + Environment.NewLine + + " Stderr" }, { new ExecResultSerializable("Stdout\nStdout", string.Empty, 1), - "Process exited with code 1." + Environment.NewLine + - " Stdout: " + Environment.NewLine + - " Stdout" + Environment.NewLine + - " Stdout" + "Process exited with code 1." + + Environment.NewLine + + " Stdout: " + + Environment.NewLine + + " Stdout" + + Environment.NewLine + + " Stdout" }, { new ExecResultSerializable(string.Empty, "Stderr\nStderr", 1), - "Process exited with code 1." + Environment.NewLine + - " Stderr: " + Environment.NewLine + - " Stderr" + Environment.NewLine + - " Stderr" + "Process exited with code 1." + + Environment.NewLine + + " Stderr: " + + Environment.NewLine + + " Stderr" + + Environment.NewLine + + " Stderr" }, { new ExecResultSerializable(string.Empty, string.Empty, 1), @@ -37,7 +49,10 @@ public sealed class ExecFailedExceptionTest [Theory] [MemberData(nameof(ExecResultTestData))] - public void ExecFailedExceptionCreatesExpectedMessage(ExecResultSerializable serializable, string message) + public void ExecFailedExceptionCreatesExpectedMessage( + ExecResultSerializable serializable, + string message + ) { // Given var execResult = serializable.ToExecResult(); @@ -59,9 +74,7 @@ public sealed class ExecResultSerializable : IXunitSerializable private int _exitCode; - public ExecResultSerializable() - { - } + public ExecResultSerializable() { } public ExecResultSerializable(string stdout, string stderr, int exitCode) { @@ -89,4 +102,4 @@ public void Serialize(IXunitSerializationInfo info) info.AddValue(nameof(_exitCode), _exitCode); } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Platform.Linux.Tests/ExecResultExtensionsTest.cs b/tests/Testcontainers.Platform.Linux.Tests/ExecResultExtensionsTest.cs index 7efcadb62..cd31804b9 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/ExecResultExtensionsTest.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/ExecResultExtensionsTest.cs @@ -9,8 +9,7 @@ public sealed class ExecResultExtensionsTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _container.StartAsync() - .ConfigureAwait(false); + await _container.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -26,7 +25,12 @@ public async Task ExecAsyncShouldSucceedWhenCommandReturnsZeroExitCode() var command = new[] { "true" }; // When - var exception = await Record.ExceptionAsync(() => _container.ExecAsync(command, TestContext.Current.CancellationToken).ThrowOnFailure()) + var exception = await Record + .ExceptionAsync(() => + _container + .ExecAsync(command, TestContext.Current.CancellationToken) + .ThrowOnFailure() + ) .ConfigureAwait(true); // Then @@ -41,7 +45,12 @@ public async Task ExecAsyncShouldThrowExecFailedExceptionWhenCommandFails() var command = new[] { "/bin/sh", "-c", "echo out; echo err >&2; exit 1" }; // When - var exception = await Assert.ThrowsAsync(() => _container.ExecAsync(command, TestContext.Current.CancellationToken).ThrowOnFailure()) + var exception = await Assert + .ThrowsAsync(() => + _container + .ExecAsync(command, TestContext.Current.CancellationToken) + .ThrowOnFailure() + ) .ConfigureAwait(true); // Then @@ -49,4 +58,4 @@ public async Task ExecAsyncShouldThrowExecFailedExceptionWhenCommandFails() Assert.Equal("out", exception.ExecResult.Stdout.Trim()); Assert.Equal("err", exception.ExecResult.Stderr.Trim()); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Platform.Linux.Tests/LoggerTest.cs b/tests/Testcontainers.Platform.Linux.Tests/LoggerTest.cs index 4398ec6eb..4ab781e6c 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/LoggerTest.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/LoggerTest.cs @@ -22,8 +22,7 @@ public async ValueTask InitializeAsync() public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -46,18 +45,14 @@ protected virtual ValueTask DisposeAsyncCore() public sealed class SingleInstanceTest : LoggerTest { public SingleInstanceTest() - : base(new SingleInstance()) - { - } + : base(new SingleInstance()) { } } [UsedImplicitly] public sealed class SharedInstanceTest : LoggerTest, IClassFixture { public SharedInstanceTest(SharedInstance sharedInstance) - : base(sharedInstance) - { - } + : base(sharedInstance) { } } [UsedImplicitly] @@ -65,9 +60,7 @@ public SharedInstanceTest(SharedInstance sharedInstance) public sealed class SharedCollectionTest1 : LoggerTest { public SharedCollectionTest1(SharedInstance sharedInstance) - : base(sharedInstance) - { - } + : base(sharedInstance) { } } [UsedImplicitly] @@ -75,9 +68,7 @@ public SharedCollectionTest1(SharedInstance sharedInstance) public sealed class SharedCollectionTest2 : LoggerTest { public SharedCollectionTest2(SharedInstance sharedInstance) - : base(sharedInstance) - { - } + : base(sharedInstance) { } } public sealed class SingleInstance : FakeLogger @@ -95,4 +86,4 @@ public sealed class SharedCollection : ICollectionFixture { // Ctor IMessageSink } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Platform.Linux.Tests/PauseUnpauseTest.cs b/tests/Testcontainers.Platform.Linux.Tests/PauseUnpauseTest.cs index 87d575402..6e00e802f 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/PauseUnpauseTest.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/PauseUnpauseTest.cs @@ -9,8 +9,7 @@ public sealed class PauseUnpauseTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _container.StartAsync() - .ConfigureAwait(false); + await _container.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -22,12 +21,10 @@ public ValueTask DisposeAsync() [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public async Task PausesAndUnpausesContainerSuccessfully() { - await _container.PauseAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await _container.PauseAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); Assert.Equal(TestcontainersStates.Paused, _container.State); - await _container.UnpauseAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await _container.UnpauseAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); Assert.Equal(TestcontainersStates.Running, _container.State); } @@ -35,6 +32,8 @@ await _container.UnpauseAsync(TestContext.Current.CancellationToken) [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public Task UnpausingRunningContainerThrowsDockerApiException() { - return Assert.ThrowsAsync(() => _container.UnpauseAsync(TestContext.Current.CancellationToken)); + return Assert.ThrowsAsync(() => + _container.UnpauseAsync(TestContext.Current.CancellationToken) + ); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Platform.Linux.Tests/PortBindingTest.cs b/tests/Testcontainers.Platform.Linux.Tests/PortBindingTest.cs index 66db1fb1e..eb76a772c 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/PortBindingTest.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/PortBindingTest.cs @@ -6,20 +6,22 @@ public abstract class PortBindingTest : IAsyncLifetime private PortBindingTest(ushort[] expectedPorts) { - var containerBuilder = new ContainerBuilder().WithImage(CommonImages.Alpine).WithEntrypoint(CommonCommands.SleepInfinity); - _container = expectedPorts.Aggregate(containerBuilder, (builder, port) => builder.WithPortBinding(port, true)).Build(); + var containerBuilder = new ContainerBuilder() + .WithImage(CommonImages.Alpine) + .WithEntrypoint(CommonCommands.SleepInfinity); + _container = expectedPorts + .Aggregate(containerBuilder, (builder, port) => builder.WithPortBinding(port, true)) + .Build(); } public async ValueTask InitializeAsync() { - await _container.StartAsync() - .ConfigureAwait(false); + await _container.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -54,12 +56,9 @@ public void ShouldThrowWhenNoPortsExist() } } - public sealed class NoPortBindingTest() - : MappedPublicPorts(Array.Empty()); + public sealed class NoPortBindingTest() : MappedPublicPorts(Array.Empty()); - public sealed class SinglePortBindingTest() - : MappedPublicPorts(new ushort[] { 8080 }); + public sealed class SinglePortBindingTest() : MappedPublicPorts(new ushort[] { 8080 }); - public sealed class MultiplePortBindingTest() - : MappedPublicPorts(new ushort[] { 8080, 8081 }); -} \ No newline at end of file + public sealed class MultiplePortBindingTest() : MappedPublicPorts(new ushort[] { 8080, 8081 }); +} diff --git a/tests/Testcontainers.Platform.Linux.Tests/PortForwardingTest.cs b/tests/Testcontainers.Platform.Linux.Tests/PortForwardingTest.cs index 795ab4431..a02c86080 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/PortForwardingTest.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/PortForwardingTest.cs @@ -11,14 +11,12 @@ private PortForwardingTest(IContainer container) public async ValueTask InitializeAsync() { - await _container.StartAsync() - .ConfigureAwait(false); + await _container.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -27,10 +25,12 @@ await DisposeAsyncCore() [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public async Task EstablishesHostConnection() { - var exitCode = await _container.GetExitCodeAsync(TestContext.Current.CancellationToken) + var exitCode = await _container + .GetExitCodeAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); - var (stdout, _) = await _container.GetLogsAsync(timestampsEnabled: false, ct: TestContext.Current.CancellationToken) + var (stdout, _) = await _container + .GetLogsAsync(timestampsEnabled: false, ct: TestContext.Current.CancellationToken) .ConfigureAwait(true); Assert.Equal(0, exitCode); @@ -43,42 +43,59 @@ protected virtual ValueTask DisposeAsyncCore() } [UsedImplicitly] - public sealed class PortForwardingDefaultConfiguration : PortForwardingTest, IClassFixture + public sealed class PortForwardingDefaultConfiguration + : PortForwardingTest, + IClassFixture { public PortForwardingDefaultConfiguration(HostedService fixture) - : base(new ContainerBuilder() - .WithImage(CommonImages.Alpine) - .WithAutoRemove(false) - .WithEntrypoint("nc") - .WithCommand(HostedService.Host, fixture.Port.ToString(CultureInfo.InvariantCulture)) - .WithWaitStrategy(Wait.ForUnixContainer().AddCustomWaitStrategy(new WaitUntil())) - .Build()) - { - } + : base( + new ContainerBuilder() + .WithImage(CommonImages.Alpine) + .WithAutoRemove(false) + .WithEntrypoint("nc") + .WithCommand( + HostedService.Host, + fixture.Port.ToString(CultureInfo.InvariantCulture) + ) + .WithWaitStrategy( + Wait.ForUnixContainer().AddCustomWaitStrategy(new WaitUntil()) + ) + .Build() + ) { } } [UsedImplicitly] - public sealed class PortForwardingNetworkConfiguration : PortForwardingTest, IClassFixture + public sealed class PortForwardingNetworkConfiguration + : PortForwardingTest, + IClassFixture { public PortForwardingNetworkConfiguration(HostedService fixture) - : base(new ContainerBuilder() - .WithImage(CommonImages.Alpine) - .WithAutoRemove(false) - .WithEntrypoint("nc") - .WithCommand(HostedService.Host, fixture.Port.ToString(CultureInfo.InvariantCulture)) - .WithNetwork(new NetworkBuilder().Build()) - .WithWaitStrategy(Wait.ForUnixContainer().AddCustomWaitStrategy(new WaitUntil())) - .Build()) - { - } + : base( + new ContainerBuilder() + .WithImage(CommonImages.Alpine) + .WithAutoRemove(false) + .WithEntrypoint("nc") + .WithCommand( + HostedService.Host, + fixture.Port.ToString(CultureInfo.InvariantCulture) + ) + .WithNetwork(new NetworkBuilder().Build()) + .WithWaitStrategy( + Wait.ForUnixContainer().AddCustomWaitStrategy(new WaitUntil()) + ) + .Build() + ) { } } [UsedImplicitly] public sealed class HostedService : IAsyncLifetime { - private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + private readonly CancellationTokenSource _cancellationTokenSource = + new CancellationTokenSource(); - private readonly TcpListener _tcpListener = new TcpListener(new IPEndPoint(IPAddress.Any, 0)); + private readonly TcpListener _tcpListener = new TcpListener( + new IPEndPoint(IPAddress.Any, 0) + ); public HostedService() { @@ -91,7 +108,10 @@ public HostedService() public async ValueTask InitializeAsync() { - await Task.WhenAny(TestcontainersSettings.ExposeHostPortsAsync(Port), AcceptSocketAsync()) + await Task.WhenAny( + TestcontainersSettings.ExposeHostPortsAsync(Port), + AcceptSocketAsync() + ) .ConfigureAwait(false); } @@ -108,10 +128,12 @@ private async Task AcceptSocketAsync() { var sendBytes = Encoding.Default.GetBytes(bool.TrueString); - using var socket = await _tcpListener.AcceptSocketAsync(_cancellationTokenSource.Token) + using var socket = await _tcpListener + .AcceptSocketAsync(_cancellationTokenSource.Token) .ConfigureAwait(false); - _ = await socket.SendAsync(sendBytes, SocketFlags.None, _cancellationTokenSource.Token) + _ = await socket + .SendAsync(sendBytes, SocketFlags.None, _cancellationTokenSource.Token) .ConfigureAwait(false); } } @@ -123,4 +145,4 @@ public Task UntilAsync(IContainer container) return Task.FromResult(TestcontainersStates.Exited.Equals(container.State)); } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Platform.Linux.Tests/ReusableResourceTest.cs b/tests/Testcontainers.Platform.Linux.Tests/ReusableResourceTest.cs index 457761ba5..f9eb0548e 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/ReusableResourceTest.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/ReusableResourceTest.cs @@ -58,39 +58,58 @@ await Task.WhenAll(container.StartAsync(), network.CreateAsync(), volume.CreateA public async ValueTask DisposeAsync() { - await Task.WhenAll(_disposables - .Take(3) - .Select(disposable => - { - // We do not want to leak resources, but `WithCleanUp(true)` cannot be used - // alongside `WithReuse(true)`. As a workaround, we set the `SessionId` using - // reflection afterward to delete the container, network, and volume. - disposable.AsDynamic()._configuration.SessionId = ResourceReaper.DefaultSessionId; - return disposable.DisposeAsync().AsTask(); - })); + await Task.WhenAll( + _disposables + .Take(3) + .Select(disposable => + { + // We do not want to leak resources, but `WithCleanUp(true)` cannot be used + // alongside `WithReuse(true)`. As a workaround, we set the `SessionId` using + // reflection afterward to delete the container, network, and volume. + disposable.AsDynamic()._configuration.SessionId = + ResourceReaper.DefaultSessionId; + return disposable.DisposeAsync().AsTask(); + }) + ); } [Fact] [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public async Task ShouldReuseExistingResource() { - using var clientConfiguration = TestcontainersSettings.OS.DockerEndpointAuthConfig.GetDockerClientConfiguration(Guid.NewGuid()); + using var clientConfiguration = + TestcontainersSettings.OS.DockerEndpointAuthConfig.GetDockerClientConfiguration( + Guid.NewGuid() + ); using var client = clientConfiguration.CreateClient(); - var containersListParameters = new ContainersListParameters { All = true, Filters = _filters }; + var containersListParameters = new ContainersListParameters + { + All = true, + Filters = _filters, + }; var networksListParameters = new NetworksListParameters { Filters = _filters }; var volumesListParameters = new VolumesListParameters { Filters = _filters }; - var containers = await client.Containers.ListContainersAsync(containersListParameters, TestContext.Current.CancellationToken) + var containers = await client + .Containers.ListContainersAsync( + containersListParameters, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - var networks = await client.Networks.ListNetworksAsync(networksListParameters, TestContext.Current.CancellationToken) + var networks = await client + .Networks.ListNetworksAsync( + networksListParameters, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - var response = await client.Volumes.ListAsync(volumesListParameters, TestContext.Current.CancellationToken) + var response = await client + .Volumes.ListAsync(volumesListParameters, TestContext.Current.CancellationToken) .ConfigureAwait(true); Assert.Single(containers); @@ -115,9 +134,11 @@ public void ForDifferentNames() public static class UnsupportedBuilderConfigurationTest { - private const string EnabledCleanUpExceptionMessage = "Reuse cannot be used in conjunction with WithCleanUp(true). (Parameter 'Reuse')"; + private const string EnabledCleanUpExceptionMessage = + "Reuse cannot be used in conjunction with WithCleanUp(true). (Parameter 'Reuse')"; - private const string EnabledAutoRemoveExceptionMessage = "Reuse cannot be used in conjunction with WithAutoRemove(true). (Parameter 'Reuse')"; + private const string EnabledAutoRemoveExceptionMessage = + "Reuse cannot be used in conjunction with WithAutoRemove(true). (Parameter 'Reuse')"; public sealed class ContainerBuilderTest { @@ -185,29 +206,33 @@ public void EnabledCleanUpThrowsException() } } - private sealed class ReuseHashContainerBuilder : ContainerBuilder + private sealed class ReuseHashContainerBuilder + : ContainerBuilder { - public ReuseHashContainerBuilder() : this(new ContainerConfiguration()) - => DockerResourceConfiguration = Init().DockerResourceConfiguration; + public ReuseHashContainerBuilder() + : this(new ContainerConfiguration()) => + DockerResourceConfiguration = Init().DockerResourceConfiguration; - private ReuseHashContainerBuilder(ContainerConfiguration configuration) : base(configuration) - => DockerResourceConfiguration = configuration; + private ReuseHashContainerBuilder(ContainerConfiguration configuration) + : base(configuration) => DockerResourceConfiguration = configuration; protected override ContainerConfiguration DockerResourceConfiguration { get; } - public string GetReuseHash() - => DockerResourceConfiguration.GetReuseHash(); + public string GetReuseHash() => DockerResourceConfiguration.GetReuseHash(); - public override DockerContainer Build() - => new(DockerResourceConfiguration); + public override DockerContainer Build() => new(DockerResourceConfiguration); - protected override ReuseHashContainerBuilder Clone(IResourceConfiguration resourceConfiguration) - => Merge(DockerResourceConfiguration, new ContainerConfiguration(resourceConfiguration)); + protected override ReuseHashContainerBuilder Clone( + IResourceConfiguration resourceConfiguration + ) => Merge(DockerResourceConfiguration, new ContainerConfiguration(resourceConfiguration)); - protected override ReuseHashContainerBuilder Clone(IContainerConfiguration resourceConfiguration) - => Merge(DockerResourceConfiguration, new ContainerConfiguration(resourceConfiguration)); + protected override ReuseHashContainerBuilder Clone( + IContainerConfiguration resourceConfiguration + ) => Merge(DockerResourceConfiguration, new ContainerConfiguration(resourceConfiguration)); - protected override ReuseHashContainerBuilder Merge(ContainerConfiguration oldValue, ContainerConfiguration newValue) - => new(new ContainerConfiguration(oldValue, newValue)); + protected override ReuseHashContainerBuilder Merge( + ContainerConfiguration oldValue, + ContainerConfiguration newValue + ) => new(new ContainerConfiguration(oldValue, newValue)); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Platform.Linux.Tests/SocatContainerTest.cs b/tests/Testcontainers.Platform.Linux.Tests/SocatContainerTest.cs index d9d0da535..61e7165ca 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/SocatContainerTest.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/SocatContainerTest.cs @@ -12,8 +12,7 @@ public sealed class SocatContainerTest : IAsyncLifetime public SocatContainerTest() { - _network = new NetworkBuilder() - .Build(); + _network = new NetworkBuilder().Build(); _helloWorldContainer = new ContainerBuilder() .WithImage(CommonImages.HelloWorld) @@ -30,23 +29,18 @@ public SocatContainerTest() public async ValueTask InitializeAsync() { - await _helloWorldContainer.StartAsync() - .ConfigureAwait(false); + await _helloWorldContainer.StartAsync().ConfigureAwait(false); - await _socatContainer.StartAsync() - .ConfigureAwait(false); + await _socatContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await _socatContainer.DisposeAsync() - .ConfigureAwait(false); + await _socatContainer.DisposeAsync().ConfigureAwait(false); - await _helloWorldContainer.DisposeAsync() - .ConfigureAwait(false); + await _helloWorldContainer.DisposeAsync().ConfigureAwait(false); - await _network.DisposeAsync() - .ConfigureAwait(false); + await _network.DisposeAsync().ConfigureAwait(false); } [Theory] @@ -56,16 +50,22 @@ public async Task RequestTargetContainer(int containerPort) { // Given using var httpClient = new HttpClient(); - httpClient.BaseAddress = new UriBuilder(Uri.UriSchemeHttp, _socatContainer.Hostname, _socatContainer.GetMappedPublicPort(containerPort)).Uri; + httpClient.BaseAddress = new UriBuilder( + Uri.UriSchemeHttp, + _socatContainer.Hostname, + _socatContainer.GetMappedPublicPort(containerPort) + ).Uri; // When - using var httpResponse = await httpClient.GetAsync("/ping", TestContext.Current.CancellationToken) + using var httpResponse = await httpClient + .GetAsync("/ping", TestContext.Current.CancellationToken) .ConfigureAwait(true); - var response = await httpResponse.Content.ReadAsStringAsync(TestContext.Current.CancellationToken) + var response = await httpResponse + .Content.ReadAsStringAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal("PONG", response); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Platform.Linux.Tests/TarOutputMemoryStreamTest.cs b/tests/Testcontainers.Platform.Linux.Tests/TarOutputMemoryStreamTest.cs index 36d329e6b..7e9488b16 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/TarOutputMemoryStreamTest.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/TarOutputMemoryStreamTest.cs @@ -4,9 +4,18 @@ public abstract class TarOutputMemoryStreamTest : IDisposable { private const string TargetDirectoryPath = "/tmp"; - private readonly TarOutputMemoryStream _tarOutputMemoryStream = new TarOutputMemoryStream(TargetDirectoryPath, NullLogger.Instance); - - private readonly FileInfo _testFile = new FileInfo(Path.Combine(TestSession.TempDirectoryPath, Guid.NewGuid().ToString("D"), Path.GetRandomFileName())); + private readonly TarOutputMemoryStream _tarOutputMemoryStream = new TarOutputMemoryStream( + TargetDirectoryPath, + NullLogger.Instance + ); + + private readonly FileInfo _testFile = new FileInfo( + Path.Combine( + TestSession.TempDirectoryPath, + Guid.NewGuid().ToString("D"), + Path.GetRandomFileName() + ) + ); private bool _disposed; @@ -14,7 +23,11 @@ protected TarOutputMemoryStreamTest() { _ = Directory.CreateDirectory(_testFile.Directory!.FullName); - using var fileStream = _testFile.Open(FileMode.Create, FileAccess.Write, FileShare.ReadWrite); + using var fileStream = _testFile.Open( + FileMode.Create, + FileAccess.Write, + FileShare.ReadWrite + ); fileStream.WriteByte(13); } @@ -51,7 +64,10 @@ public void TestFileExistsInTarFile() _tarOutputMemoryStream.Seek(0, SeekOrigin.Begin); // When - using var tarIn = TarArchive.CreateInputTarArchive(_tarOutputMemoryStream, Encoding.Default); + using var tarIn = TarArchive.CreateInputTarArchive( + _tarOutputMemoryStream, + Encoding.Default + ); tarIn.ProgressMessageEvent += (_, entry, _) => actual.Add(entry.Name); tarIn.ListContents(); @@ -60,7 +76,11 @@ public void TestFileExistsInTarFile() } [UsedImplicitly] - public sealed class FromResourceMapping : TarOutputMemoryStreamTest, IResourceMapping, IClassFixture, IAsyncLifetime + public sealed class FromResourceMapping + : TarOutputMemoryStreamTest, + IResourceMapping, + IClassFixture, + IAsyncLifetime { private readonly string _testHttpUri; @@ -72,25 +92,19 @@ public FromResourceMapping(HttpFixture httpFixture) _testFileUri = new Uri(_testFile.FullName).ToString(); } - public MountType Type - => MountType.Bind; + public MountType Type => MountType.Bind; - public AccessMode AccessMode - => AccessMode.ReadOnly; + public AccessMode AccessMode => AccessMode.ReadOnly; - public string Source - => string.Empty; + public string Source => string.Empty; - public string Target - => string.Join("/", TargetDirectoryPath, _testFile.Name); + public string Target => string.Join("/", TargetDirectoryPath, _testFile.Name); - public UnixFileModes FileMode - => Unix.FileMode644; + public UnixFileModes FileMode => Unix.FileMode644; public async ValueTask InitializeAsync() { - await _tarOutputMemoryStream.AddAsync(this) - .ConfigureAwait(false); + await _tarOutputMemoryStream.AddAsync(this).ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -118,9 +132,27 @@ public Task GetAllBytesAsync(CancellationToken ct = default) public async Task TestFileExistsInContainer() { // Given - var targetFilePath1 = string.Join("/", string.Empty, "tmp", Guid.NewGuid(), _testFile.Name); - var targetFilePath2 = string.Join("/", string.Empty, "tmp", Guid.NewGuid(), _testFile.Name); - var targetFilePath3 = string.Join("/", string.Empty, "tmp", Guid.NewGuid(), _testFile.Name); + var targetFilePath1 = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid(), + _testFile.Name + ); + var targetFilePath2 = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid(), + _testFile.Name + ); + var targetFilePath3 = string.Join( + "/", + string.Empty, + "tmp", + Guid.NewGuid(), + _testFile.Name + ); var targetDirectoryPath1 = string.Join("/", string.Empty, "tmp", Guid.NewGuid()); var targetDirectoryPath2 = string.Join("/", string.Empty, "tmp", Guid.NewGuid()); var targetDirectoryPath3 = string.Join("/", string.Empty, "tmp", Guid.NewGuid()); @@ -151,20 +183,37 @@ public async Task TestFileExistsInContainer() var fileContent = await GetAllBytesAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); - await container.CopyAsync(fileContent, targetFilePath3, ct: TestContext.Current.CancellationToken) + await container + .CopyAsync(fileContent, targetFilePath3, ct: TestContext.Current.CancellationToken) .ConfigureAwait(true); - await container.CopyAsync(_testFile.FullName, targetDirectoryPath4, ct: TestContext.Current.CancellationToken) + await container + .CopyAsync( + _testFile.FullName, + targetDirectoryPath4, + ct: TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - await container.CopyAsync(_testFile.Directory!.FullName, targetDirectoryPath5, ct: TestContext.Current.CancellationToken) + await container + .CopyAsync( + _testFile.Directory!.FullName, + targetDirectoryPath5, + ct: TestContext.Current.CancellationToken + ) .ConfigureAwait(true); // Then - var execResults = await Task.WhenAll(targetFilePaths.Select(containerFilePath => container.ExecAsync(new[] { "test", "-f", containerFilePath }, TestContext.Current.CancellationToken))) + var execResults = await Task.WhenAll( + targetFilePaths.Select(containerFilePath => + container.ExecAsync( + new[] { "test", "-f", containerFilePath }, + TestContext.Current.CancellationToken + ) + ) + ) .ConfigureAwait(true); Assert.All(execResults, result => Assert.Equal(0, result.ExitCode)); @@ -181,11 +230,17 @@ public sealed class HttpFixture : IAsyncLifetime .WithCommand($"TCP-LISTEN:{HttpPort},crlf,reuseaddr,fork") .WithCommand("SYSTEM:'echo -e \"HTTP/1.1 200 OK\\nContent-Length: 0\\n\\n\"'") .WithPortBinding(HttpPort, true) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => request)) + .WithWaitStrategy( + Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => request) + ) .Build(); - public string BaseAddress - => new UriBuilder(Uri.UriSchemeHttp, _container.Hostname, _container.GetMappedPublicPort(HttpPort)).ToString(); + public string BaseAddress => + new UriBuilder( + Uri.UriSchemeHttp, + _container.Hostname, + _container.GetMappedPublicPort(HttpPort) + ).ToString(); public ValueTask InitializeAsync() { @@ -204,7 +259,8 @@ public sealed class FromFile : TarOutputMemoryStreamTest, IAsyncLifetime { public async ValueTask InitializeAsync() { - await _tarOutputMemoryStream.AddAsync(_testFile, Unix.FileMode644) + await _tarOutputMemoryStream + .AddAsync(_testFile, Unix.FileMode644) .ConfigureAwait(false); } @@ -219,7 +275,8 @@ public sealed class FromDirectory : TarOutputMemoryStreamTest, IAsyncLifetime { public async ValueTask InitializeAsync() { - await _tarOutputMemoryStream.AddAsync(_testFile.Directory, true, Unix.FileMode644) + await _tarOutputMemoryStream + .AddAsync(_testFile.Directory, true, Unix.FileMode644) .ConfigureAwait(false); } @@ -237,9 +294,12 @@ public sealed class UnixFileModeTest [InlineData(Unix.FileMode700, "700")] [InlineData(Unix.FileMode755, "755")] [InlineData(Unix.FileMode777, "777")] - public void UnixFileModeResolvesToPosixFilePermission(UnixFileModes fileMode, string posixFilePermission) + public void UnixFileModeResolvesToPosixFilePermission( + UnixFileModes fileMode, + string posixFilePermission + ) { Assert.Equal(Convert.ToInt32(posixFilePermission, 8), Convert.ToInt32(fileMode)); } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Platform.Linux.Tests/Testcontainers.Platform.Linux.Tests.csproj b/tests/Testcontainers.Platform.Linux.Tests/Testcontainers.Platform.Linux.Tests.csproj index 3d69ef8fa..c2c9be55b 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/Testcontainers.Platform.Linux.Tests.csproj +++ b/tests/Testcontainers.Platform.Linux.Tests/Testcontainers.Platform.Linux.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Platform.Linux.Tests/Usings.cs b/tests/Testcontainers.Platform.Linux.Tests/Usings.cs index 7ee62e7fc..be41a9706 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/Usings.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/Usings.cs @@ -24,4 +24,4 @@ global using Microsoft.Extensions.Logging.Testing; global using ReflectionMagic; global using Xunit; -global using Xunit.Sdk; \ No newline at end of file +global using Xunit.Sdk; diff --git a/tests/Testcontainers.Platform.Linux.Tests/WaitStrategyTest.cs b/tests/Testcontainers.Platform.Linux.Tests/WaitStrategyTest.cs index 11352cc16..03ba5c635 100644 --- a/tests/Testcontainers.Platform.Linux.Tests/WaitStrategyTest.cs +++ b/tests/Testcontainers.Platform.Linux.Tests/WaitStrategyTest.cs @@ -6,42 +6,50 @@ public sealed class WaitStrategyTest [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public Task WithTimeout() { - return Assert.ThrowsAsync(() => new ContainerBuilder() - .WithImage(CommonImages.Alpine) - .WithEntrypoint(CommonCommands.SleepInfinity) - .WithWaitStrategy(Wait.ForUnixContainer().AddCustomWaitStrategy(FailingWaitStrategy.Instance, o => o.WithTimeout(TimeSpan.FromSeconds(1)))) - .Build() - .StartAsync(TestContext.Current.CancellationToken)); + return Assert.ThrowsAsync(() => + new ContainerBuilder() + .WithImage(CommonImages.Alpine) + .WithEntrypoint(CommonCommands.SleepInfinity) + .WithWaitStrategy( + Wait.ForUnixContainer() + .AddCustomWaitStrategy( + FailingWaitStrategy.Instance, + o => o.WithTimeout(TimeSpan.FromSeconds(1)) + ) + ) + .Build() + .StartAsync(TestContext.Current.CancellationToken) + ); } [Fact] [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public Task WithRetries() { - return Assert.ThrowsAsync(() => new ContainerBuilder() - .WithImage(CommonImages.Alpine) - .WithEntrypoint(CommonCommands.SleepInfinity) - .WithWaitStrategy(Wait.ForUnixContainer().AddCustomWaitStrategy(FailingWaitStrategy.Instance, o => o.WithRetries(1))) - .Build() - .StartAsync(TestContext.Current.CancellationToken)); + return Assert.ThrowsAsync(() => + new ContainerBuilder() + .WithImage(CommonImages.Alpine) + .WithEntrypoint(CommonCommands.SleepInfinity) + .WithWaitStrategy( + Wait.ForUnixContainer() + .AddCustomWaitStrategy(FailingWaitStrategy.Instance, o => o.WithRetries(1)) + ) + .Build() + .StartAsync(TestContext.Current.CancellationToken) + ); } private sealed class FailingWaitStrategy : IWaitUntil { - static FailingWaitStrategy() - { - } + static FailingWaitStrategy() { } - private FailingWaitStrategy() - { - } + private FailingWaitStrategy() { } - public static IWaitUntil Instance { get; } - = new FailingWaitStrategy(); + public static IWaitUntil Instance { get; } = new FailingWaitStrategy(); public Task UntilAsync(IContainer container) { return Task.FromResult(false); } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Platform.Windows.Tests/SkipOnLinuxEngineAttribute.cs b/tests/Testcontainers.Platform.Windows.Tests/SkipOnLinuxEngineAttribute.cs index f2fbb08a1..0399d398b 100644 --- a/tests/Testcontainers.Platform.Windows.Tests/SkipOnLinuxEngineAttribute.cs +++ b/tests/Testcontainers.Platform.Windows.Tests/SkipOnLinuxEngineAttribute.cs @@ -3,7 +3,9 @@ namespace Testcontainers.Tests; [PublicAPI] public sealed class SkipOnLinuxEngineAttribute : FactAttribute { - private static readonly bool IsLinuxEngineEnabled = DockerCli.PlatformIsEnabled(DockerCli.DockerPlatform.Linux); + private static readonly bool IsLinuxEngineEnabled = DockerCli.PlatformIsEnabled( + DockerCli.DockerPlatform.Linux + ); public SkipOnLinuxEngineAttribute() { @@ -12,4 +14,4 @@ public SkipOnLinuxEngineAttribute() Skip = "Docker Windows engine is not available."; } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Platform.Windows.Tests/Testcontainers.Platform.Windows.Tests.csproj b/tests/Testcontainers.Platform.Windows.Tests/Testcontainers.Platform.Windows.Tests.csproj index 82a619df8..bd517a8c0 100644 --- a/tests/Testcontainers.Platform.Windows.Tests/Testcontainers.Platform.Windows.Tests.csproj +++ b/tests/Testcontainers.Platform.Windows.Tests/Testcontainers.Platform.Windows.Tests.csproj @@ -1,17 +1,17 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + diff --git a/tests/Testcontainers.Platform.Windows.Tests/Usings.cs b/tests/Testcontainers.Platform.Windows.Tests/Usings.cs index 30832d99e..accbc75e9 100644 --- a/tests/Testcontainers.Platform.Windows.Tests/Usings.cs +++ b/tests/Testcontainers.Platform.Windows.Tests/Usings.cs @@ -4,4 +4,4 @@ global using DotNet.Testcontainers.Commons; global using DotNet.Testcontainers.Containers; global using JetBrains.Annotations; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Platform.Windows.Tests/WindowsContainerTest.cs b/tests/Testcontainers.Platform.Windows.Tests/WindowsContainerTest.cs index 4e8300975..998b820d4 100644 --- a/tests/Testcontainers.Platform.Windows.Tests/WindowsContainerTest.cs +++ b/tests/Testcontainers.Platform.Windows.Tests/WindowsContainerTest.cs @@ -11,14 +11,12 @@ private WindowsContainerTest(IContainer container) public async ValueTask InitializeAsync() { - await _container.StartAsync() - .ConfigureAwait(false); + await _container.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -39,42 +37,53 @@ protected virtual ValueTask DisposeAsyncCore() public sealed class UntilCommandIsCompleted : WindowsContainerTest { public UntilCommandIsCompleted() - : base(new ContainerBuilder() - .WithImage(CommonImages.ServerCore) - .WithEntrypoint("PowerShell", "-NoLogo", "-Command") - .WithCommand("Start-Sleep -Seconds 120") - .WithWaitStrategy(Wait.ForWindowsContainer().UntilCommandIsCompleted("Exit(-Not(Test-Path -Path 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'))")) - .Build()) - { - } + : base( + new ContainerBuilder() + .WithImage(CommonImages.ServerCore) + .WithEntrypoint("PowerShell", "-NoLogo", "-Command") + .WithCommand("Start-Sleep -Seconds 120") + .WithWaitStrategy( + Wait.ForWindowsContainer() + .UntilCommandIsCompleted( + "Exit(-Not(Test-Path -Path 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'))" + ) + ) + .Build() + ) { } } [UsedImplicitly] public sealed class UntilInternalTcpPortIsAvailable : WindowsContainerTest { public UntilInternalTcpPortIsAvailable() - : base(new ContainerBuilder() - .WithImage(CommonImages.ServerCore) - .WithEntrypoint("PowerShell", "-NoLogo", "-Command") - .WithCommand("$tcpListener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Any, 8080); $tcpListener.Start(); Start-Sleep -Seconds 120") - .WithWaitStrategy(Wait.ForWindowsContainer().UntilPortIsAvailable(8080)) - .Build()) - { - } + : base( + new ContainerBuilder() + .WithImage(CommonImages.ServerCore) + .WithEntrypoint("PowerShell", "-NoLogo", "-Command") + .WithCommand( + "$tcpListener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Any, 8080); $tcpListener.Start(); Start-Sleep -Seconds 120" + ) + .WithWaitStrategy(Wait.ForWindowsContainer().UntilPortIsAvailable(8080)) + .Build() + ) { } } [UsedImplicitly] public sealed class UntilExternalTcpPortIsAvailable : WindowsContainerTest { public UntilExternalTcpPortIsAvailable() - : base(new ContainerBuilder() - .WithImage(CommonImages.ServerCore) - .WithPortBinding(8080, true) - .WithEntrypoint("PowerShell", "-NoLogo", "-Command") - .WithCommand("$tcpListener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Any, 8080); $tcpListener.Start(); Start-Sleep -Seconds 120") - .WithWaitStrategy(Wait.ForWindowsContainer().UntilExternalTcpPortIsAvailable(8080)) - .Build()) - { - } + : base( + new ContainerBuilder() + .WithImage(CommonImages.ServerCore) + .WithPortBinding(8080, true) + .WithEntrypoint("PowerShell", "-NoLogo", "-Command") + .WithCommand( + "$tcpListener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Any, 8080); $tcpListener.Start(); Start-Sleep -Seconds 120" + ) + .WithWaitStrategy( + Wait.ForWindowsContainer().UntilExternalTcpPortIsAvailable(8080) + ) + .Build() + ) { } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.PostgreSql.Tests/PostgreSqlContainerTest.cs b/tests/Testcontainers.PostgreSql.Tests/PostgreSqlContainerTest.cs index 78cd90ab7..691768521 100644 --- a/tests/Testcontainers.PostgreSql.Tests/PostgreSqlContainerTest.cs +++ b/tests/Testcontainers.PostgreSql.Tests/PostgreSqlContainerTest.cs @@ -1,6 +1,8 @@ namespace Testcontainers.PostgreSql; -public abstract class PostgreSqlContainerTest(PostgreSqlContainerTest.PostgreSqlDefaultFixture fixture) +public abstract class PostgreSqlContainerTest( + PostgreSqlContainerTest.PostgreSqlDefaultFixture fixture +) { // # --8<-- [start:UsePostgreSqlContainer] [Fact] @@ -25,18 +27,22 @@ public async Task ExecScriptReturnsSuccessful() const string scriptContent = "SELECT 1;"; // When - var execResult = await fixture.Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) + var execResult = await fixture + .Container.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.True(0L.Equals(execResult.ExitCode), execResult.Stderr); Assert.Empty(execResult.Stderr); } + // # --8<-- [end:UsePostgreSqlContainer] public sealed class ReuseContainerTest : IClassFixture, IDisposable { - private readonly CancellationTokenSource _cts = new CancellationTokenSource(TimeSpan.FromMinutes(1)); + private readonly CancellationTokenSource _cts = new CancellationTokenSource( + TimeSpan.FromMinutes(1) + ); private readonly PostgreSqlDefaultFixture _fixture; @@ -56,11 +62,9 @@ public void Dispose() [InlineData(2)] public async Task StopsAndStartsContainerSuccessful(int _) { - await _fixture.Container.StopAsync(_cts.Token) - .ConfigureAwait(true); + await _fixture.Container.StopAsync(_cts.Token).ConfigureAwait(true); - await _fixture.Container.StartAsync(_cts.Token) - .ConfigureAwait(true); + await _fixture.Container.StartAsync(_cts.Token).ConfigureAwait(true); Assert.False(_cts.IsCancellationRequested); } @@ -69,23 +73,26 @@ await _fixture.Container.StartAsync(_cts.Token) public class PostgreSqlDefaultFixture(IMessageSink messageSink) : DbContainerFixture(messageSink) { - public override DbProviderFactory DbProviderFactory - => NpgsqlFactory.Instance; + public override DbProviderFactory DbProviderFactory => NpgsqlFactory.Instance; } [UsedImplicitly] public class PostgreSqlWaitForDatabaseFixture(IMessageSink messageSink) : PostgreSqlDefaultFixture(messageSink) { - protected override PostgreSqlBuilder Configure(PostgreSqlBuilder builder) - => builder.WithWaitStrategy(Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory)); + protected override PostgreSqlBuilder Configure(PostgreSqlBuilder builder) => + builder.WithWaitStrategy( + Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory) + ); } [UsedImplicitly] public sealed class PostgreSqlDefaultConfiguration(PostgreSqlDefaultFixture fixture) - : PostgreSqlContainerTest(fixture), IClassFixture; + : PostgreSqlContainerTest(fixture), + IClassFixture; [UsedImplicitly] - public sealed class PostgreSqlWaitForDatabaseConfiguration(PostgreSqlWaitForDatabaseFixture fixture) - : PostgreSqlContainerTest(fixture), IClassFixture; -} \ No newline at end of file + public sealed class PostgreSqlWaitForDatabaseConfiguration( + PostgreSqlWaitForDatabaseFixture fixture + ) : PostgreSqlContainerTest(fixture), IClassFixture; +} diff --git a/tests/Testcontainers.PostgreSql.Tests/Testcontainers.PostgreSql.Tests.csproj b/tests/Testcontainers.PostgreSql.Tests/Testcontainers.PostgreSql.Tests.csproj index 80d6b8100..c871c3023 100644 --- a/tests/Testcontainers.PostgreSql.Tests/Testcontainers.PostgreSql.Tests.csproj +++ b/tests/Testcontainers.PostgreSql.Tests/Testcontainers.PostgreSql.Tests.csproj @@ -1,22 +1,22 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.PostgreSql.Tests/Usings.cs b/tests/Testcontainers.PostgreSql.Tests/Usings.cs index 1da39ede9..d49e100ed 100644 --- a/tests/Testcontainers.PostgreSql.Tests/Usings.cs +++ b/tests/Testcontainers.PostgreSql.Tests/Usings.cs @@ -9,4 +9,4 @@ global using Npgsql; global using Testcontainers.Xunit; global using Xunit; -global using Xunit.Sdk; \ No newline at end of file +global using Xunit.Sdk; diff --git a/tests/Testcontainers.PubSub.Tests/PubSubContainerTest.cs b/tests/Testcontainers.PubSub.Tests/PubSubContainerTest.cs index 37e4911af..fd8a99a71 100644 --- a/tests/Testcontainers.PubSub.Tests/PubSubContainerTest.cs +++ b/tests/Testcontainers.PubSub.Tests/PubSubContainerTest.cs @@ -6,8 +6,7 @@ public sealed class PubSubContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _pubSubContainer.StartAsync() - .ConfigureAwait(false); + await _pubSubContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -44,28 +43,32 @@ public async Task SubTopicReturnsPubMessage() subscriberClientBuilder.ChannelCredentials = ChannelCredentials.Insecure; // When - var publisher = await publisherClientBuilder.BuildAsync(TestContext.Current.CancellationToken) + var publisher = await publisherClientBuilder + .BuildAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); - _ = await publisher.CreateTopicAsync(topicName) - .ConfigureAwait(true); + _ = await publisher.CreateTopicAsync(topicName).ConfigureAwait(true); - var subscriber = await subscriberClientBuilder.BuildAsync(TestContext.Current.CancellationToken) + var subscriber = await subscriberClientBuilder + .BuildAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); - _ = await subscriber.CreateSubscriptionAsync(subscriptionName, topicName, null, 60) + _ = await subscriber + .CreateSubscriptionAsync(subscriptionName, topicName, null, 60) .ConfigureAwait(true); - _ = await publisher.PublishAsync(topicName, new[] { message }) - .ConfigureAwait(true); + _ = await publisher.PublishAsync(topicName, new[] { message }).ConfigureAwait(true); - var response = await subscriber.PullAsync(subscriptionName, 1) - .ConfigureAwait(true); + var response = await subscriber.PullAsync(subscriptionName, 1).ConfigureAwait(true); - await subscriber.AcknowledgeAsync(subscriptionName, response.ReceivedMessages.Select(receivedMessage => receivedMessage.AckId)) + await subscriber + .AcknowledgeAsync( + subscriptionName, + response.ReceivedMessages.Select(receivedMessage => receivedMessage.AckId) + ) .ConfigureAwait(true); // Then Assert.Equal(helloPubSub, response.ReceivedMessages.Single().Message.Data.ToStringUtf8()); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.PubSub.Tests/Testcontainers.PubSub.Tests.csproj b/tests/Testcontainers.PubSub.Tests/Testcontainers.PubSub.Tests.csproj index 40cad9fef..120d91d10 100644 --- a/tests/Testcontainers.PubSub.Tests/Testcontainers.PubSub.Tests.csproj +++ b/tests/Testcontainers.PubSub.Tests/Testcontainers.PubSub.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.PubSub.Tests/Usings.cs b/tests/Testcontainers.PubSub.Tests/Usings.cs index c6e804fe3..807b9c7ca 100644 --- a/tests/Testcontainers.PubSub.Tests/Usings.cs +++ b/tests/Testcontainers.PubSub.Tests/Usings.cs @@ -4,4 +4,4 @@ global using Google.Cloud.PubSub.V1; global using Google.Protobuf; global using Grpc.Core; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Pulsar.Tests/PulsarContainerTest.cs b/tests/Testcontainers.Pulsar.Tests/PulsarContainerTest.cs index e2b845d7a..642562ae0 100644 --- a/tests/Testcontainers.Pulsar.Tests/PulsarContainerTest.cs +++ b/tests/Testcontainers.Pulsar.Tests/PulsarContainerTest.cs @@ -2,7 +2,13 @@ namespace Testcontainers.Pulsar; public abstract class PulsarContainerTest : IAsyncLifetime { - private static readonly IReadOnlyDictionary MemorySettings = new Dictionary { { "PULSAR_MEM", "-Xms256m -Xmx512m" } }; + private static readonly IReadOnlyDictionary MemorySettings = new Dictionary< + string, + string + > + { + { "PULSAR_MEM", "-Xms256m -Xmx512m" }, + }; private readonly PulsarContainer _pulsarContainer; @@ -17,14 +23,12 @@ private PulsarContainerTest(PulsarContainer pulsarContainer, bool authentication // # --8<-- [start:UsePulsarContainer] public async ValueTask InitializeAsync() { - await _pulsarContainer.StartAsync() - .ConfigureAwait(false); + await _pulsarContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -40,41 +44,58 @@ public async Task ConsumerReceivesSendMessage() var name = Guid.NewGuid().ToString("D"); - var clientBuilder = PulsarClient.Builder().ServiceUrl(new Uri(_pulsarContainer.GetBrokerAddress())); + var clientBuilder = PulsarClient + .Builder() + .ServiceUrl(new Uri(_pulsarContainer.GetBrokerAddress())); if (_authenticationEnabled) { - var authToken = await _pulsarContainer.CreateAuthenticationTokenAsync(Timeout.InfiniteTimeSpan, TestContext.Current.CancellationToken); + var authToken = await _pulsarContainer.CreateAuthenticationTokenAsync( + Timeout.InfiniteTimeSpan, + TestContext.Current.CancellationToken + ); _ = clientBuilder.Authentication(new TokenAuthentication(authToken)); } await using var client = clientBuilder.Build(); - await using var producer = client.NewProducer(Schema.String) - .Topic(topic) - .Create(); + await using var producer = client.NewProducer(Schema.String).Topic(topic).Create(); - await using var consumer = client.NewConsumer(Schema.String) + await using var consumer = client + .NewConsumer(Schema.String) .Topic(topic) .SubscriptionName(name) .Create(); // When - _ = await consumer.OnStateChangeTo(ConsumerState.Active, TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken) + _ = await consumer + .OnStateChangeTo( + ConsumerState.Active, + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - _ = await producer.OnStateChangeTo(ProducerState.Connected, TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken) + _ = await producer + .OnStateChangeTo( + ProducerState.Connected, + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - _ = await producer.Send(helloPulsar, cancellationToken: TestContext.Current.CancellationToken) + _ = await producer + .Send(helloPulsar, cancellationToken: TestContext.Current.CancellationToken) .ConfigureAwait(true); - var message = await consumer.Receive(TestContext.Current.CancellationToken) + var message = await consumer + .Receive(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal(helloPulsar, Encoding.Default.GetString(message.Data)); } + // # --8<-- [end:UsePulsarContainer] protected virtual ValueTask DisposeAsyncCore() @@ -87,48 +108,45 @@ protected virtual ValueTask DisposeAsyncCore() public sealed class PulsarDefaultConfiguration : PulsarContainerTest { public PulsarDefaultConfiguration() - : base(new PulsarBuilder() - .WithEnvironment(MemorySettings) - .Build(), false) - { - } + : base(new PulsarBuilder().WithEnvironment(MemorySettings).Build(), false) { } } + // # --8<-- [end:CreatePulsarContainer] [UsedImplicitly] public sealed class PulsarAuthConfiguration : PulsarContainerTest { public PulsarAuthConfiguration() - : base(new PulsarBuilder() - .WithAuthentication() - .WithEnvironment(MemorySettings) - .Build(), true) - { - } + : base( + new PulsarBuilder().WithAuthentication().WithEnvironment(MemorySettings).Build(), + true + ) { } } [UsedImplicitly] public sealed class PulsarV4Configuration : PulsarContainerTest { public PulsarV4Configuration() - : base(new PulsarBuilder() - .WithImage("apachepulsar/pulsar:4.0.2") - .WithEnvironment(MemorySettings) - .Build(), false) - { - } + : base( + new PulsarBuilder() + .WithImage("apachepulsar/pulsar:4.0.2") + .WithEnvironment(MemorySettings) + .Build(), + false + ) { } } [UsedImplicitly] public sealed class PulsarV4AuthConfiguration : PulsarContainerTest { public PulsarV4AuthConfiguration() - : base(new PulsarBuilder() - .WithImage("apachepulsar/pulsar:4.0.2") - .WithAuthentication() - .WithEnvironment(MemorySettings) - .Build(), true) - { - } + : base( + new PulsarBuilder() + .WithImage("apachepulsar/pulsar:4.0.2") + .WithAuthentication() + .WithEnvironment(MemorySettings) + .Build(), + true + ) { } } -} \ 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 85e66ab89..d88c21ba6 100644 --- a/tests/Testcontainers.Pulsar.Tests/Testcontainers.Pulsar.Tests.csproj +++ b/tests/Testcontainers.Pulsar.Tests/Testcontainers.Pulsar.Tests.csproj @@ -1,21 +1,21 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Pulsar.Tests/Usings.cs b/tests/Testcontainers.Pulsar.Tests/Usings.cs index 237e01c9b..51100bd6c 100644 --- a/tests/Testcontainers.Pulsar.Tests/Usings.cs +++ b/tests/Testcontainers.Pulsar.Tests/Usings.cs @@ -8,4 +8,4 @@ global using DotPulsar.Extensions; global using DotPulsar.Internal; global using JetBrains.Annotations; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Qdrant.Tests/PemCertificate.cs b/tests/Testcontainers.Qdrant.Tests/PemCertificate.cs index 49ee96a43..b219baaa0 100644 --- a/tests/Testcontainers.Qdrant.Tests/PemCertificate.cs +++ b/tests/Testcontainers.Qdrant.Tests/PemCertificate.cs @@ -2,9 +2,7 @@ namespace Testcontainers.Qdrant; public sealed class PemCertificate { - static PemCertificate() - { - } + static PemCertificate() { } private PemCertificate(string commonName) { @@ -12,9 +10,17 @@ private PemCertificate(string commonName) var subjectName = new X500DistinguishedName($"CN={commonName}"); - var request = new CertificateRequest(subjectName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + var request = new CertificateRequest( + subjectName, + rsa, + HashAlgorithmName.SHA256, + RSASignaturePadding.Pkcs1 + ); - using var certificate = request.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(1)); + using var certificate = request.CreateSelfSigned( + DateTimeOffset.Now, + DateTimeOffset.Now.AddYears(1) + ); CommonName = commonName; Thumbprint = certificate.GetCertHashString(HashAlgorithmName.SHA256); @@ -22,8 +28,7 @@ private PemCertificate(string commonName) CertificateKey = rsa.ExportPkcs8PrivateKeyPem(); } - public static PemCertificate Instance { get; } - = new PemCertificate("localhost"); + public static PemCertificate Instance { get; } = new PemCertificate("localhost"); public string CommonName { get; } @@ -32,4 +37,4 @@ private PemCertificate(string commonName) public string Certificate { get; } public string CertificateKey { get; } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Qdrant.Tests/QdrantDefaultContainerTest.cs b/tests/Testcontainers.Qdrant.Tests/QdrantDefaultContainerTest.cs index 98358b399..6e5c099c9 100644 --- a/tests/Testcontainers.Qdrant.Tests/QdrantDefaultContainerTest.cs +++ b/tests/Testcontainers.Qdrant.Tests/QdrantDefaultContainerTest.cs @@ -7,8 +7,7 @@ public sealed class QdrantDefaultContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _qdrantContainer.StartAsync() - .ConfigureAwait(false); + await _qdrantContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -24,12 +23,14 @@ public async Task HealthReturnsValidResponse() using var client = new QdrantClient(new Uri(_qdrantContainer.GetGrpcConnectionString())); // When - var response = await client.HealthAsync(TestContext.Current.CancellationToken) + var response = await client + .HealthAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.NotEmpty(response.Title); } + // # --8<-- [end:UseQdrantContainer] [Fact] @@ -41,10 +42,11 @@ public async Task GetRootEndpointReturnsHttpStatusCodeOk() httpClient.BaseAddress = new Uri(_qdrantContainer.GetHttpConnectionString()); // When - using var httpResponse = await httpClient.GetAsync("/", TestContext.Current.CancellationToken) + using var httpResponse = await httpClient + .GetAsync("/", TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Qdrant.Tests/QdrantSecureContainerTest.cs b/tests/Testcontainers.Qdrant.Tests/QdrantSecureContainerTest.cs index b25c7f62a..adbdf9422 100644 --- a/tests/Testcontainers.Qdrant.Tests/QdrantSecureContainerTest.cs +++ b/tests/Testcontainers.Qdrant.Tests/QdrantSecureContainerTest.cs @@ -24,8 +24,7 @@ public sealed class QdrantSecureContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _qdrantContainer.StartAsync() - .ConfigureAwait(false); + await _qdrantContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -40,7 +39,8 @@ public async Task HealthReturnsValidResponse() // Given // # --8<-- [start:ConfigureQdrantClientCertificate-1] using var httpMessageHandler = new HttpClientHandler(); - httpMessageHandler.ServerCertificateCustomValidationCallback = CertificateValidation.Thumbprint(Thumbprint); + httpMessageHandler.ServerCertificateCustomValidationCallback = + CertificateValidation.Thumbprint(Thumbprint); using var httpClient = new HttpClient(httpMessageHandler); httpClient.DefaultRequestHeaders.Host = CommonName; @@ -54,7 +54,10 @@ public async Task HealthReturnsValidResponse() var grpcChannelOptions = new GrpcChannelOptions(); grpcChannelOptions.HttpClient = httpClient; - using var grpcChannel = GrpcChannel.ForAddress(_qdrantContainer.GetGrpcConnectionString(), grpcChannelOptions); + using var grpcChannel = GrpcChannel.ForAddress( + _qdrantContainer.GetGrpcConnectionString(), + grpcChannelOptions + ); using var grpcClient = new QdrantGrpcClient(grpcChannel); @@ -62,7 +65,8 @@ public async Task HealthReturnsValidResponse() // # --8<-- [end:ConfigureQdrantClientCertificate-2] // When - var response = await client.HealthAsync(TestContext.Current.CancellationToken) + var response = await client + .HealthAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -75,7 +79,8 @@ public async Task HealthWithoutApiKeyReturnsUnauthenticated() { // Given using var httpMessageHandler = new HttpClientHandler(); - httpMessageHandler.ServerCertificateCustomValidationCallback = CertificateValidation.Thumbprint(Thumbprint); + httpMessageHandler.ServerCertificateCustomValidationCallback = + CertificateValidation.Thumbprint(Thumbprint); using var httpClient = new HttpClient(httpMessageHandler); httpClient.DefaultRequestHeaders.Host = CommonName; @@ -83,14 +88,20 @@ public async Task HealthWithoutApiKeyReturnsUnauthenticated() var grpcChannelOptions = new GrpcChannelOptions(); grpcChannelOptions.HttpClient = httpClient; - using var grpcChannel = GrpcChannel.ForAddress(_qdrantContainer.GetGrpcConnectionString(), grpcChannelOptions); + using var grpcChannel = GrpcChannel.ForAddress( + _qdrantContainer.GetGrpcConnectionString(), + grpcChannelOptions + ); using var grpcClient = new QdrantGrpcClient(grpcChannel); using var client = new QdrantClient(grpcClient); // When - var exception = await Assert.ThrowsAsync(() => client.HealthAsync(TestContext.Current.CancellationToken)) + var exception = await Assert + .ThrowsAsync(() => + client.HealthAsync(TestContext.Current.CancellationToken) + ) .ConfigureAwait(true); // Then @@ -108,10 +119,13 @@ public async Task HealthWithoutCertificateValidationReturnsSecureConnectionError httpClient.DefaultRequestHeaders.Add("api-key", ApiKey); // When - var exception = await Assert.ThrowsAsync(() => httpClient.GetAsync("/", TestContext.Current.CancellationToken)) + var exception = await Assert + .ThrowsAsync(() => + httpClient.GetAsync("/", TestContext.Current.CancellationToken) + ) .ConfigureAwait(true); // Then Assert.Equal(HttpRequestError.SecureConnectionError, exception.HttpRequestError); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Qdrant.Tests/Testcontainers.Qdrant.Tests.csproj b/tests/Testcontainers.Qdrant.Tests/Testcontainers.Qdrant.Tests.csproj index c79acca3b..fd0bf8563 100644 --- a/tests/Testcontainers.Qdrant.Tests/Testcontainers.Qdrant.Tests.csproj +++ b/tests/Testcontainers.Qdrant.Tests/Testcontainers.Qdrant.Tests.csproj @@ -1,21 +1,21 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Qdrant.Tests/Usings.cs b/tests/Testcontainers.Qdrant.Tests/Usings.cs index ff80cf90b..5fcc5ab43 100644 --- a/tests/Testcontainers.Qdrant.Tests/Usings.cs +++ b/tests/Testcontainers.Qdrant.Tests/Usings.cs @@ -9,4 +9,4 @@ global using Grpc.Net.Client; global using Qdrant.Client; global using Qdrant.Client.Grpc; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.RabbitMq.Tests/RabbitMqContainerTest.cs b/tests/Testcontainers.RabbitMq.Tests/RabbitMqContainerTest.cs index 3dfd28db4..e2d92090d 100644 --- a/tests/Testcontainers.RabbitMq.Tests/RabbitMqContainerTest.cs +++ b/tests/Testcontainers.RabbitMq.Tests/RabbitMqContainerTest.cs @@ -7,8 +7,7 @@ public sealed class RabbitMqContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _rabbitMqContainer.StartAsync() - .ConfigureAwait(false); + await _rabbitMqContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -31,4 +30,4 @@ public void IsOpenReturnsTrue() Assert.True(connection.IsOpen); } // # --8<-- [end:UseRabbitMqContainer] -} \ 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 86751134d..f285290d1 100644 --- a/tests/Testcontainers.RabbitMq.Tests/Testcontainers.RabbitMq.Tests.csproj +++ b/tests/Testcontainers.RabbitMq.Tests/Testcontainers.RabbitMq.Tests.csproj @@ -1,21 +1,21 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + diff --git a/tests/Testcontainers.RabbitMq.Tests/Usings.cs b/tests/Testcontainers.RabbitMq.Tests/Usings.cs index b624b7af6..1d2eb01c8 100644 --- a/tests/Testcontainers.RabbitMq.Tests/Usings.cs +++ b/tests/Testcontainers.RabbitMq.Tests/Usings.cs @@ -2,4 +2,4 @@ global using System.Threading.Tasks; global using DotNet.Testcontainers.Commons; global using RabbitMQ.Client; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.RavenDb.Tests/RavenDbContainerTest.cs b/tests/Testcontainers.RavenDb.Tests/RavenDbContainerTest.cs index 8c9aa469c..d24598721 100644 --- a/tests/Testcontainers.RavenDb.Tests/RavenDbContainerTest.cs +++ b/tests/Testcontainers.RavenDb.Tests/RavenDbContainerTest.cs @@ -6,8 +6,7 @@ public sealed class RavenDbContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _ravenDbContainer.StartAsync() - .ConfigureAwait(false); + await _ravenDbContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -30,4 +29,4 @@ public void GetBuildNumberOperationReturnsBuildNumber() // Then Assert.Equal("5.4", buildNumber.ProductVersion); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.RavenDb.Tests/Testcontainers.RavenDb.Tests.csproj b/tests/Testcontainers.RavenDb.Tests/Testcontainers.RavenDb.Tests.csproj index 14be078f1..14e8bc245 100644 --- a/tests/Testcontainers.RavenDb.Tests/Testcontainers.RavenDb.Tests.csproj +++ b/tests/Testcontainers.RavenDb.Tests/Testcontainers.RavenDb.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.RavenDb.Tests/Usings.cs b/tests/Testcontainers.RavenDb.Tests/Usings.cs index efe37ee56..eb297dca4 100644 --- a/tests/Testcontainers.RavenDb.Tests/Usings.cs +++ b/tests/Testcontainers.RavenDb.Tests/Usings.cs @@ -2,4 +2,4 @@ global using DotNet.Testcontainers.Commons; global using Raven.Client.Documents; global using Raven.Client.ServerWide.Operations; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Redis.Tests/RedisContainerTest.cs b/tests/Testcontainers.Redis.Tests/RedisContainerTest.cs index 6b780fb06..be5ef4b6f 100644 --- a/tests/Testcontainers.Redis.Tests/RedisContainerTest.cs +++ b/tests/Testcontainers.Redis.Tests/RedisContainerTest.cs @@ -6,8 +6,7 @@ public sealed class RedisContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _redisContainer.StartAsync() - .ConfigureAwait(false); + await _redisContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -31,7 +30,8 @@ public async Task ExecScriptReturnsSuccessful() const string scriptContent = "return 'Hello, scripting!'"; // When - var execResult = await _redisContainer.ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) + var execResult = await _redisContainer + .ExecScriptAsync(scriptContent, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -39,4 +39,4 @@ public async Task ExecScriptReturnsSuccessful() Assert.True("Hello, scripting!\n".Equals(execResult.Stdout), execResult.Stdout); Assert.Empty(execResult.Stderr); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Redis.Tests/Testcontainers.Redis.Tests.csproj b/tests/Testcontainers.Redis.Tests/Testcontainers.Redis.Tests.csproj index af894494e..2d63b96d3 100644 --- a/tests/Testcontainers.Redis.Tests/Testcontainers.Redis.Tests.csproj +++ b/tests/Testcontainers.Redis.Tests/Testcontainers.Redis.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Redis.Tests/Usings.cs b/tests/Testcontainers.Redis.Tests/Usings.cs index 4e7182108..d97ddd327 100644 --- a/tests/Testcontainers.Redis.Tests/Usings.cs +++ b/tests/Testcontainers.Redis.Tests/Usings.cs @@ -1,4 +1,4 @@ global using System.Threading.Tasks; global using DotNet.Testcontainers.Commons; global using StackExchange.Redis; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Redpanda.Tests/RedpandaContainerTest.cs b/tests/Testcontainers.Redpanda.Tests/RedpandaContainerTest.cs index d3ee15572..24f169e25 100644 --- a/tests/Testcontainers.Redpanda.Tests/RedpandaContainerTest.cs +++ b/tests/Testcontainers.Redpanda.Tests/RedpandaContainerTest.cs @@ -6,8 +6,7 @@ public sealed class RedpandaContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _redpandaContainer.StartAsync() - .ConfigureAwait(false); + await _redpandaContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -37,7 +36,8 @@ public async Task ConsumerReturnsProducerMessage() // When using var producer = new ProducerBuilder(producerConfig).Build(); - _ = await producer.ProduceAsync(topic, message, TestContext.Current.CancellationToken) + _ = await producer + .ProduceAsync(topic, message, TestContext.Current.CancellationToken) .ConfigureAwait(true); using var consumer = new ConsumerBuilder(consumerConfig).Build(); @@ -49,4 +49,4 @@ public async Task ConsumerReturnsProducerMessage() Assert.NotNull(result); Assert.Equal(message.Value, result.Message.Value); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Redpanda.Tests/Testcontainers.Redpanda.Tests.csproj b/tests/Testcontainers.Redpanda.Tests/Testcontainers.Redpanda.Tests.csproj index ae28de5ac..4ee416f12 100644 --- a/tests/Testcontainers.Redpanda.Tests/Testcontainers.Redpanda.Tests.csproj +++ b/tests/Testcontainers.Redpanda.Tests/Testcontainers.Redpanda.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.Redpanda.Tests/Usings.cs b/tests/Testcontainers.Redpanda.Tests/Usings.cs index a7fcce194..f42457e57 100644 --- a/tests/Testcontainers.Redpanda.Tests/Usings.cs +++ b/tests/Testcontainers.Redpanda.Tests/Usings.cs @@ -2,4 +2,4 @@ global using System.Threading.Tasks; global using Confluent.Kafka; global using DotNet.Testcontainers.Commons; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.ResourceReaper.Tests/DefaultResourceReaperTest.cs b/tests/Testcontainers.ResourceReaper.Tests/DefaultResourceReaperTest.cs index c7947b137..e6bbd9aca 100644 --- a/tests/Testcontainers.ResourceReaper.Tests/DefaultResourceReaperTest.cs +++ b/tests/Testcontainers.ResourceReaper.Tests/DefaultResourceReaperTest.cs @@ -11,11 +11,14 @@ public sealed class DefaultResourceReaperTest : IAsyncLifetime { public async ValueTask InitializeAsync() { - var resourceReaper = await ResourceReaper.GetAndStartDefaultAsync(TestcontainersSettings.OS.DockerEndpointAuthConfig, ConsoleLogger.Instance) + var resourceReaper = await ResourceReaper + .GetAndStartDefaultAsync( + TestcontainersSettings.OS.DockerEndpointAuthConfig, + ConsoleLogger.Instance + ) .ConfigureAwait(false); - await resourceReaper.DisposeAsync() - .ConfigureAwait(false); + await resourceReaper.DisposeAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -38,14 +41,18 @@ public async Task ContainerCleanUpStartsDefaultResourceReaper(bool resourceReape .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); - await container.StopAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StopAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); // Then - Assert.Equal(resourceReaperEnabled, DockerCli.ResourceExists(DockerCli.DockerResource.Container, "testcontainers-ryuk-" + ResourceReaper.DefaultSessionId.ToString("D"))); + Assert.Equal( + resourceReaperEnabled, + DockerCli.ResourceExists( + DockerCli.DockerResource.Container, + "testcontainers-ryuk-" + ResourceReaper.DefaultSessionId.ToString("D") + ) + ); } } } diff --git a/tests/Testcontainers.ResourceReaper.Tests/Testcontainers.ResourceReaper.Tests.csproj b/tests/Testcontainers.ResourceReaper.Tests/Testcontainers.ResourceReaper.Tests.csproj index a9e46c327..3ec213603 100644 --- a/tests/Testcontainers.ResourceReaper.Tests/Testcontainers.ResourceReaper.Tests.csproj +++ b/tests/Testcontainers.ResourceReaper.Tests/Testcontainers.ResourceReaper.Tests.csproj @@ -8,12 +8,12 @@ DotNet.Testcontainers.ResourceReaper.Tests - - - - + + + + - + diff --git a/tests/Testcontainers.ServiceBus.Tests/DeclineLicenseAgreementTest.cs b/tests/Testcontainers.ServiceBus.Tests/DeclineLicenseAgreementTest.cs index 523dac1dc..6dbb74194 100644 --- a/tests/Testcontainers.ServiceBus.Tests/DeclineLicenseAgreementTest.cs +++ b/tests/Testcontainers.ServiceBus.Tests/DeclineLicenseAgreementTest.cs @@ -17,7 +17,9 @@ public void WithoutAcceptingLicenseAgreementThrowsArgumentException() [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public void WithLicenseAgreementDeclinedThrowsArgumentException() { - var exception = Assert.Throws(() => new ServiceBusBuilder().WithAcceptLicenseAgreement(false).Build()); + var exception = Assert.Throws(() => + new ServiceBusBuilder().WithAcceptLicenseAgreement(false).Build() + ); Assert.Matches(LicenseAgreementNotAccepted(), exception.Message); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.ServiceBus.Tests/ServiceBusContainerTest.cs b/tests/Testcontainers.ServiceBus.Tests/ServiceBusContainerTest.cs index 670117b67..c05ff5387 100644 --- a/tests/Testcontainers.ServiceBus.Tests/ServiceBusContainerTest.cs +++ b/tests/Testcontainers.ServiceBus.Tests/ServiceBusContainerTest.cs @@ -14,14 +14,12 @@ private ServiceBusContainerTest(ServiceBusContainer serviceBusContainer) // # --8<-- [start:UseServiceBusContainer] public async ValueTask InitializeAsync() { - await _serviceBusContainer.StartAsync() - .ConfigureAwait(false); + await _serviceBusContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -49,15 +47,18 @@ public async Task ReceiveMessageReturnsSentMessage() var receiver = client.CreateReceiver(QueueName); // When - await sender.SendMessageAsync(message, TestContext.Current.CancellationToken) + await sender + .SendMessageAsync(message, TestContext.Current.CancellationToken) .ConfigureAwait(true); - var receivedMessage = await receiver.ReceiveMessageAsync(cancellationToken: TestContext.Current.CancellationToken) + var receivedMessage = await receiver + .ReceiveMessageAsync(cancellationToken: TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal(helloServiceBus, receivedMessage.Body.ToString()); } + // # --8<-- [end:UseServiceBusContainer] protected virtual ValueTask DisposeAsyncCore() @@ -70,40 +71,45 @@ protected virtual ValueTask DisposeAsyncCore() public sealed class ServiceBusDefaultMsSqlConfiguration : ServiceBusContainerTest { public ServiceBusDefaultMsSqlConfiguration() - : base(new ServiceBusBuilder() - .WithAcceptLicenseAgreement(true) - .Build()) - { - } + : base(new ServiceBusBuilder().WithAcceptLicenseAgreement(true).Build()) { } } + // # --8<-- [end:CreateServiceBusContainer] [UsedImplicitly] - public sealed class ServiceBusCustomMsSqlConfiguration : ServiceBusContainerTest, IClassFixture + public sealed class ServiceBusCustomMsSqlConfiguration + : ServiceBusContainerTest, + IClassFixture { public ServiceBusCustomMsSqlConfiguration(DatabaseFixture fixture) - : base(new ServiceBusBuilder() - .WithAcceptLicenseAgreement(true) - // # --8<-- [start:ReuseExistingMsSqlContainer] - .WithMsSqlContainer(fixture.Network, fixture.Container, DatabaseFixture.DatabaseNetworkAlias) - // # --8<-- [end:ReuseExistingMsSqlContainer] - .Build()) - { - } + : base( + new ServiceBusBuilder() + .WithAcceptLicenseAgreement(true) + // # --8<-- [start:ReuseExistingMsSqlContainer] + .WithMsSqlContainer( + fixture.Network, + fixture.Container, + DatabaseFixture.DatabaseNetworkAlias + ) + // # --8<-- [end:ReuseExistingMsSqlContainer] + .Build() + ) { } } [UsedImplicitly] - public sealed class ServiceBusCustomQueueConfiguration : ServiceBusContainerTest, IClassFixture + public sealed class ServiceBusCustomQueueConfiguration + : ServiceBusContainerTest, + IClassFixture { public ServiceBusCustomQueueConfiguration() - : base(new ServiceBusBuilder() - .WithAcceptLicenseAgreement(true) - // # --8<-- [start:UseCustomConfiguration] - .WithConfig("custom-queue-config.json") - // # --8<-- [end:UseCustomConfiguration] - .Build()) - { - } + : base( + new ServiceBusBuilder() + .WithAcceptLicenseAgreement(true) + // # --8<-- [start:UseCustomConfiguration] + .WithConfig("custom-queue-config.json") + // # --8<-- [end:UseCustomConfiguration] + .Build() + ) { } protected override string QueueName => "custom-queue.1"; } @@ -113,8 +119,7 @@ public sealed class DatabaseFixture { public DatabaseFixture() { - Network = new NetworkBuilder() - .Build(); + Network = new NetworkBuilder().Build(); Container = new MsSqlBuilder() .WithNetwork(Network) @@ -128,4 +133,4 @@ public DatabaseFixture() public MsSqlContainer Container { get; } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.ServiceBus.Tests/Testcontainers.ServiceBus.Tests.csproj b/tests/Testcontainers.ServiceBus.Tests/Testcontainers.ServiceBus.Tests.csproj index 162ab19c3..2a96e6997 100644 --- a/tests/Testcontainers.ServiceBus.Tests/Testcontainers.ServiceBus.Tests.csproj +++ b/tests/Testcontainers.ServiceBus.Tests/Testcontainers.ServiceBus.Tests.csproj @@ -1,26 +1,26 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - - - - - PreserveNewest - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + + + + + PreserveNewest + + + diff --git a/tests/Testcontainers.ServiceBus.Tests/Usings.cs b/tests/Testcontainers.ServiceBus.Tests/Usings.cs index 8fb60a0cc..95c4640a7 100644 --- a/tests/Testcontainers.ServiceBus.Tests/Usings.cs +++ b/tests/Testcontainers.ServiceBus.Tests/Usings.cs @@ -7,4 +7,4 @@ global using DotNet.Testcontainers.Networks; global using JetBrains.Annotations; global using Testcontainers.MsSql; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Sftp.Tests/SftpContainerTest.cs b/tests/Testcontainers.Sftp.Tests/SftpContainerTest.cs index d3d18d49a..f667cfb3c 100644 --- a/tests/Testcontainers.Sftp.Tests/SftpContainerTest.cs +++ b/tests/Testcontainers.Sftp.Tests/SftpContainerTest.cs @@ -6,8 +6,7 @@ public sealed class SftpContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _sftpContainer.StartAsync() - .ConfigureAwait(false); + await _sftpContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -24,13 +23,17 @@ public async Task IsConnectedReturnsTrue() var port = _sftpContainer.GetMappedPublicPort(SftpBuilder.SftpPort); - using var sftpClient = new SftpClient(host, port, SftpBuilder.DefaultUsername, SftpBuilder.DefaultPassword); + using var sftpClient = new SftpClient( + host, + port, + SftpBuilder.DefaultUsername, + SftpBuilder.DefaultPassword + ); // When - await sftpClient.ConnectAsync(CancellationToken.None) - .ConfigureAwait(true); + await sftpClient.ConnectAsync(CancellationToken.None).ConfigureAwait(true); // Then Assert.True(sftpClient.IsConnected); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Sftp.Tests/Testcontainers.Sftp.Tests.csproj b/tests/Testcontainers.Sftp.Tests/Testcontainers.Sftp.Tests.csproj index dc3e49334..b73aed2d1 100644 --- a/tests/Testcontainers.Sftp.Tests/Testcontainers.Sftp.Tests.csproj +++ b/tests/Testcontainers.Sftp.Tests/Testcontainers.Sftp.Tests.csproj @@ -1,18 +1,18 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + diff --git a/tests/Testcontainers.Sftp.Tests/Usings.cs b/tests/Testcontainers.Sftp.Tests/Usings.cs index 9e93730ce..52647ba81 100644 --- a/tests/Testcontainers.Sftp.Tests/Usings.cs +++ b/tests/Testcontainers.Sftp.Tests/Usings.cs @@ -2,4 +2,4 @@ global using System.Threading.Tasks; global using DotNet.Testcontainers.Commons; global using Renci.SshNet; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Tests/ContinuousIntegration/JobsTest.cs b/tests/Testcontainers.Tests/ContinuousIntegration/JobsTest.cs index 8ec9fb10b..7b5378abd 100644 --- a/tests/Testcontainers.Tests/ContinuousIntegration/JobsTest.cs +++ b/tests/Testcontainers.Tests/ContinuousIntegration/JobsTest.cs @@ -16,20 +16,32 @@ public void AllTestProjectsShouldBeConfiguredForContinuousIntegration() { var ciCdFilePath = GetCiCdFilePath(); - var expectedProjects = File.ReadAllLines(ciCdFilePath).Select(line => ProjectNameRegex().Match(line).Groups[1].Value).Where(line => line.Length > 0).ToList(); + var expectedProjects = File.ReadAllLines(ciCdFilePath) + .Select(line => ProjectNameRegex().Match(line).Groups[1].Value) + .Where(line => line.Length > 0) + .ToList(); Assert.NotEmpty(expectedProjects); - var actualProjects = Directory.GetFiles(GetTestsDirectoryPath(), "*.Tests.csproj", SearchOption.AllDirectories).Select(name => Path.GetFileName(name)[..^13]).ToList(); + var actualProjects = Directory + .GetFiles(GetTestsDirectoryPath(), "*.Tests.csproj", SearchOption.AllDirectories) + .Select(name => Path.GetFileName(name)[..^13]) + .ToList(); Assert.NotEmpty(actualProjects); var missingConfiguredProjects = actualProjects.Except(expectedProjects).ToList(); - Assert.True(missingConfiguredProjects.Count == 0, $"{string.Join(", ", missingConfiguredProjects)} must be configured in '{ciCdFilePath}'."); + Assert.True( + missingConfiguredProjects.Count == 0, + $"{string.Join(", ", missingConfiguredProjects)} must be configured in '{ciCdFilePath}'." + ); } - private static string GetCiCdFilePath() => Path.Combine(GetRepositoryDirectoryPath(), ".github", "workflows", "cicd.yml"); + private static string GetCiCdFilePath() => + Path.Combine(GetRepositoryDirectoryPath(), ".github", "workflows", "cicd.yml"); - private static string GetTestsDirectoryPath() => Path.Combine(GetRepositoryDirectoryPath(), "tests"); + private static string GetTestsDirectoryPath() => + Path.Combine(GetRepositoryDirectoryPath(), "tests"); - private static string GetRepositoryDirectoryPath() => CommonDirectoryPath.GetSolutionDirectory().DirectoryPath; + private static string GetRepositoryDirectoryPath() => + CommonDirectoryPath.GetSolutionDirectory().DirectoryPath; } } diff --git a/tests/Testcontainers.Tests/Fixtures/Configurations/WaitUntilFiveSecondsPassedFixture.cs b/tests/Testcontainers.Tests/Fixtures/Configurations/WaitUntilFiveSecondsPassedFixture.cs index 08cfa2689..c4d03a84b 100644 --- a/tests/Testcontainers.Tests/Fixtures/Configurations/WaitUntilFiveSecondsPassedFixture.cs +++ b/tests/Testcontainers.Tests/Fixtures/Configurations/WaitUntilFiveSecondsPassedFixture.cs @@ -11,7 +11,9 @@ public sealed class WaitUntilFiveSecondsPassedFixture : IWaitUntil public Task UntilAsync(IContainer container) { - return Task.FromResult(new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds() > _timestamp + 5); + return Task.FromResult( + new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds() > _timestamp + 5 + ); } } } diff --git a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/AlpineFixture.cs b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/AlpineFixture.cs index cdc7598fa..aa327a745 100644 --- a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/AlpineFixture.cs +++ b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/AlpineFixture.cs @@ -11,8 +11,8 @@ namespace DotNet.Testcontainers.Tests.Fixtures [UsedImplicitly] public sealed class AlpineFixture : IAsyncLifetime { - public IContainer Container { get; } - = new ContainerBuilder() + public IContainer Container { get; } = + new ContainerBuilder() .WithImage(CommonImages.Alpine) .WithCommand(CommonCommands.SleepInfinity) .WithStartupCallback((_, ct) => Task.Delay(TimeSpan.FromMinutes(1), ct)) diff --git a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/DockerMTls.cs b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/DockerMTls.cs index 84265df0f..8eef64b35 100644 --- a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/DockerMTls.cs +++ b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/DockerMTls.cs @@ -6,9 +6,7 @@ namespace DotNet.Testcontainers.Tests.Fixtures public abstract class DockerMTls : ProtectDockerDaemonSocket { public DockerMTls(string dockerImageVersion) - : base(new ContainerBuilder(), dockerImageVersion) - { - } + : base(new ContainerBuilder(), dockerImageVersion) { } public override IList CustomProperties { diff --git a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/DockerTlsFixture.cs b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/DockerTlsFixture.cs index 1ed591185..e07ccb1f5 100644 --- a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/DockerTlsFixture.cs +++ b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/DockerTlsFixture.cs @@ -8,10 +8,7 @@ namespace DotNet.Testcontainers.Tests.Fixtures public sealed class DockerTlsFixture : ProtectDockerDaemonSocket { public DockerTlsFixture() - : base(new ContainerBuilder() - .WithCommand("--tlsverify=false"), "20.10.18") - { - } + : base(new ContainerBuilder().WithCommand("--tlsverify=false"), "20.10.18") { } public override IList CustomProperties { diff --git a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/NetworkFixture.cs b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/NetworkFixture.cs index a14ed6707..c28426132 100644 --- a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/NetworkFixture.cs +++ b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/NetworkFixture.cs @@ -11,22 +11,20 @@ namespace DotNet.Testcontainers.Tests.Fixtures [UsedImplicitly] public sealed class NetworkFixture : IAsyncLifetime { - public INetwork Network { get; } - = new NetworkBuilder() + public INetwork Network { get; } = + new NetworkBuilder() .WithDriver(NetworkDriver.Bridge) .WithName(Guid.NewGuid().ToString("D")) .Build(); public async ValueTask InitializeAsync() { - await Network.CreateAsync() - .ConfigureAwait(false); + await Network.CreateAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await Network.DeleteAsync() - .ConfigureAwait(false); + await Network.DeleteAsync().ConfigureAwait(false); } } } diff --git a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/OpenSsl1_1_1Fixture.cs b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/OpenSsl1_1_1Fixture.cs index 37705ec29..b53a643ea 100644 --- a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/OpenSsl1_1_1Fixture.cs +++ b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/OpenSsl1_1_1Fixture.cs @@ -5,8 +5,7 @@ namespace DotNet.Testcontainers.Tests.Fixtures [UsedImplicitly] public sealed class OpenSsl1_1_1Fixture : DockerMTls { - public OpenSsl1_1_1Fixture() : base("20.10.18") - { - } + public OpenSsl1_1_1Fixture() + : base("20.10.18") { } } } diff --git a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/OpenSsl3_1Fixture.cs b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/OpenSsl3_1Fixture.cs index 0a4768b96..a756eacd3 100644 --- a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/OpenSsl3_1Fixture.cs +++ b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/OpenSsl3_1Fixture.cs @@ -5,8 +5,7 @@ namespace DotNet.Testcontainers.Tests.Fixtures [UsedImplicitly] public sealed class OpenSsl3_1Fixture : DockerMTls { - public OpenSsl3_1Fixture() : base("24.0.5") - { - } + public OpenSsl3_1Fixture() + : base("24.0.5") { } } } diff --git a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/ProtectDockerDaemonSocket.cs b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/ProtectDockerDaemonSocket.cs index a07dc124d..5a68ffd32 100644 --- a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/ProtectDockerDaemonSocket.cs +++ b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/ProtectDockerDaemonSocket.cs @@ -17,13 +17,20 @@ public abstract class ProtectDockerDaemonSocket : IAsyncLifetime private const ushort TlsPort = 2376; - private readonly string _hostCertsDirectoryPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("D"), CertsDirectoryName); + private readonly string _hostCertsDirectoryPath = Path.Combine( + Path.GetTempPath(), + Guid.NewGuid().ToString("D"), + CertsDirectoryName + ); private readonly string _containerCertsDirectoryPath = Path.Combine("/", CertsDirectoryName); private readonly IContainer _container; - protected ProtectDockerDaemonSocket(ContainerBuilder containerConfiguration, string dockerImageVersion) + protected ProtectDockerDaemonSocket( + ContainerBuilder containerConfiguration, + string dockerImageVersion + ) { _container = containerConfiguration .WithImage(new DockerImage("docker", null, dockerImageVersion + "-dind")) @@ -39,7 +46,9 @@ public virtual IList CustomProperties get { var customProperties = new List(); - customProperties.Add($"docker.host={new UriBuilder("tcp", _container.Hostname, _container.GetMappedPublicPort(TlsPort))}"); + customProperties.Add( + $"docker.host={new UriBuilder("tcp", _container.Hostname, _container.GetMappedPublicPort(TlsPort))}" + ); customProperties.Add($"docker.cert.path={Path.Combine(_hostCertsDirectoryPath, "client")}"); return customProperties; } @@ -47,17 +56,18 @@ public virtual IList CustomProperties public IImage Image { - get - { - return _container.Image; - } + get { return _container.Image; } } public object TlsKey { get { - using (var tlsKeyStream = new StreamReader(Path.Combine(_hostCertsDirectoryPath, "client", "key.pem"))) + using ( + var tlsKeyStream = new StreamReader( + Path.Combine(_hostCertsDirectoryPath, "client", "key.pem") + ) + ) { return new PemReader(tlsKeyStream).ReadObject(); } @@ -68,30 +78,26 @@ public async ValueTask InitializeAsync() { _ = Directory.CreateDirectory(_hostCertsDirectoryPath); - await _container.StartAsync() - .ConfigureAwait(false); + await _container.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } protected virtual async ValueTask DisposeAsyncCore() { - await _container.DisposeAsync() - .ConfigureAwait(false); + await _container.DisposeAsync().ConfigureAwait(false); } private sealed class UntilListenOn : IWaitUntil { public async Task UntilAsync(IContainer container) { - var (_, stderr) = await container.GetLogsAsync() - .ConfigureAwait(false); + var (_, stderr) = await container.GetLogsAsync().ConfigureAwait(false); return stderr != null && stderr.Contains("API listen on [::]:2376"); } diff --git a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/VolumeFixture.cs b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/VolumeFixture.cs index 60aaffe78..f9ba92d6a 100644 --- a/tests/Testcontainers.Tests/Fixtures/Containers/Unix/VolumeFixture.cs +++ b/tests/Testcontainers.Tests/Fixtures/Containers/Unix/VolumeFixture.cs @@ -10,21 +10,17 @@ namespace DotNet.Testcontainers.Tests.Fixtures [UsedImplicitly] public sealed class VolumeFixture : IAsyncLifetime { - public IVolume Volume { get; } - = new VolumeBuilder() - .WithName(Guid.NewGuid().ToString("D")) - .Build(); + public IVolume Volume { get; } = + new VolumeBuilder().WithName(Guid.NewGuid().ToString("D")).Build(); public async ValueTask InitializeAsync() { - await Volume.CreateAsync() - .ConfigureAwait(false); + await Volume.CreateAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await Volume.DeleteAsync() - .ConfigureAwait(false); + await Volume.DeleteAsync().ConfigureAwait(false); } } } diff --git a/tests/Testcontainers.Tests/Fixtures/Images/DockerImageFixture.cs b/tests/Testcontainers.Tests/Fixtures/Images/DockerImageFixture.cs index 4497fd8fd..bad4c1f46 100644 --- a/tests/Testcontainers.Tests/Fixtures/Images/DockerImageFixture.cs +++ b/tests/Testcontainers.Tests/Fixtures/Images/DockerImageFixture.cs @@ -3,7 +3,8 @@ namespace DotNet.Testcontainers.Tests.Fixtures using DotNet.Testcontainers.Images; using Xunit; - public sealed class DockerImageFixture : TheoryData + public sealed class DockerImageFixture + : TheoryData { private const string FooBarBaz = "foo/bar/baz"; private const string BarBaz = "bar/baz"; @@ -15,30 +16,119 @@ public sealed class DockerImageFixture : TheoryData _image.Repository; @@ -47,14 +49,12 @@ public bool MatchVersion(Predicate predicate) public async ValueTask InitializeAsync() { - await _image.CreateAsync() - .ConfigureAwait(false); + await _image.CreateAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await _image.DeleteAsync() - .ConfigureAwait(false); + await _image.DeleteAsync().ConfigureAwait(false); } } } diff --git a/tests/Testcontainers.Tests/Fixtures/Images/IgnoreFileFixture.cs b/tests/Testcontainers.Tests/Fixtures/Images/IgnoreFileFixture.cs index 48ca59d4b..61e34d807 100644 --- a/tests/Testcontainers.Tests/Fixtures/Images/IgnoreFileFixture.cs +++ b/tests/Testcontainers.Tests/Fixtures/Images/IgnoreFileFixture.cs @@ -13,9 +13,25 @@ public IgnoreFileFixture() var ignoreAllFilesAndDirectories = new IgnoreFile(new[] { "*", "!README*.md" }, logger); var ignoreNonRecursiveFiles = new IgnoreFile(new[] { "*/temp*" }, logger); var ignoreNonRecursiveNestedFiles = new IgnoreFile(new[] { "*/*/temp*" }, logger); - var ignoreRecursiveFiles = new IgnoreFile(new[] { "**/*.txt", "**/.idea", "**/.vs", "**/.git", "!**/.gitignore", "!.git/HEAD", "!.git/refs/heads/**", "src/**/lipsum.config" }, logger); + var ignoreRecursiveFiles = new IgnoreFile( + new[] + { + "**/*.txt", + "**/.idea", + "**/.vs", + "**/.git", + "!**/.gitignore", + "!.git/HEAD", + "!.git/refs/heads/**", + "src/**/lipsum.config", + }, + logger + ); var ignoreSingleCharacterFiles = new IgnoreFile(new[] { "temp?" }, logger); - var ignoreExceptionFiles = new IgnoreFile(new[] { "*.md", "!README*.md", "README-secret.md" }, logger); + var ignoreExceptionFiles = new IgnoreFile( + new[] { "*.md", "!README*.md", "README-secret.md" }, + logger + ); Add(ignoreFilesAndDirectories, "bin/Debug", false); Add(ignoreFilesAndDirectories, "obj/Debug", false); Add(ignoreFilesAndDirectories, "README.md", true); diff --git a/tests/Testcontainers.Tests/Testcontainers.Tests.csproj b/tests/Testcontainers.Tests/Testcontainers.Tests.csproj index e55ea193f..7b7e9a99a 100644 --- a/tests/Testcontainers.Tests/Testcontainers.Tests.csproj +++ b/tests/Testcontainers.Tests/Testcontainers.Tests.csproj @@ -11,14 +11,14 @@ true - - - - - + + + + + - + diff --git a/tests/Testcontainers.Tests/Unit/Builders/BuildConfigurationTest.cs b/tests/Testcontainers.Tests/Unit/Builders/BuildConfigurationTest.cs index 09b776285..91ce344a2 100644 --- a/tests/Testcontainers.Tests/Unit/Builders/BuildConfigurationTest.cs +++ b/tests/Testcontainers.Tests/Unit/Builders/BuildConfigurationTest.cs @@ -14,10 +14,7 @@ public sealed class BuildConfigurationTest [InlineData(null, "B", "B")] [InlineData("A", null, "A")] [InlineData("A", "B", "B")] - public void CombineReferenceTypes( - string oldValue, - string newValue, - string expected) + public void CombineReferenceTypes(string oldValue, string newValue, string expected) { var actual = BuildConfiguration.Combine(oldValue, newValue); Assert.Equal(expected, actual); @@ -28,7 +25,8 @@ public void CombineReferenceTypes( public void CombineEnumerables( IEnumerable oldValue, IEnumerable newValue, - IEnumerable expected) + IEnumerable expected + ) { var actual = BuildConfiguration.Combine(oldValue, newValue); Assert.Equal(expected?.OrderBy(item => item), actual?.OrderBy(item => item)); @@ -39,7 +37,8 @@ public void CombineEnumerables( public void CombineReadOnlyLists( IReadOnlyList oldValue, IReadOnlyList newValue, - IReadOnlyList expected) + IReadOnlyList expected + ) { var actual = BuildConfiguration.Combine(oldValue, newValue); Assert.Equal(expected, actual); @@ -50,7 +49,8 @@ public void CombineReadOnlyLists( public void CombineReadOnlyDictionaries( IReadOnlyDictionary oldValue, IReadOnlyDictionary newValue, - IReadOnlyDictionary expected) + IReadOnlyDictionary expected + ) { var actual = BuildConfiguration.Combine(oldValue, newValue); Assert.Equal(expected, actual); @@ -61,7 +61,8 @@ public void CombineReadOnlyDictionaries( public void CombineComposableEnumerables( ComposableEnumerable oldValue, ComposableEnumerable newValue, - IEnumerable expected) + IEnumerable expected + ) { var actual = BuildConfiguration.Combine(oldValue, newValue); Assert.Equal(expected, actual); @@ -72,7 +73,8 @@ public void CombineComposableEnumerables( public void AppendEnumerableCompose( IEnumerable oldValue, IEnumerable newValue, - IEnumerable expected) + IEnumerable expected + ) { var append = new AppendEnumerable(newValue); var result = append.Compose(oldValue); @@ -84,7 +86,8 @@ public void AppendEnumerableCompose( public void OverwriteEnumerableCompose( IEnumerable oldValue, IEnumerable newValue, - IEnumerable expected) + IEnumerable expected + ) { var overwrite = new OverwriteEnumerable(newValue); var result = overwrite.Compose(oldValue); @@ -96,7 +99,8 @@ public void OverwriteEnumerableCompose( public void AppendDictionaryCompose( IReadOnlyDictionary oldValue, IReadOnlyDictionary newValue, - IReadOnlyDictionary expected) + IReadOnlyDictionary expected + ) { var append = new AppendDictionary(newValue); var result = append.Compose(oldValue); @@ -108,7 +112,8 @@ public void AppendDictionaryCompose( public void OverwriteDictionaryCompose( IReadOnlyDictionary oldValue, IReadOnlyDictionary newValue, - IReadOnlyDictionary expected) + IReadOnlyDictionary expected + ) { var overwrite = new OverwriteDictionary(newValue); var result = overwrite.Compose(oldValue); @@ -136,258 +141,226 @@ public void ComposableDictionaryHandlesNullDictionary() } private sealed class EnumerableCombinationTestData - : TheoryData< - IEnumerable, - IEnumerable, - IEnumerable - > + : TheoryData, IEnumerable, IEnumerable> { public EnumerableCombinationTestData() { - Add(null, - null, - Array.Empty()); + Add(null, null, Array.Empty()); - Add(null, - new[] { "2" }, - new[] { "2" }); + Add(null, new[] { "2" }, new[] { "2" }); - Add(new[] { "1" }, - null, - new[] { "1" }); + Add(new[] { "1" }, null, new[] { "1" }); - Add(new[] { "1" }, - new[] { "2" }, - new[] { "1", "2" }); + Add(new[] { "1" }, new[] { "2" }, new[] { "1", "2" }); - Add(new[] { "1", "2", "3" }, - new[] { "2", "3", "4" }, - new[] { "1", "2", "2", "3", "3", "4" }); + Add( + new[] { "1", "2", "3" }, + new[] { "2", "3", "4" }, + new[] { "1", "2", "2", "3", "3", "4" } + ); } } private sealed class ReadOnlyListCombinationTestData - : TheoryData< - IReadOnlyList, - IReadOnlyList, - IReadOnlyList - > + : TheoryData, IReadOnlyList, IReadOnlyList> { public ReadOnlyListCombinationTestData() { - Add(null, - null, - Array.Empty()); + Add(null, null, Array.Empty()); - Add(null, - new[] { "2" }, - new[] { "2" }); + Add(null, new[] { "2" }, new[] { "2" }); - Add(new[] { "1" }, - null, - new[] { "1" }); + Add(new[] { "1" }, null, new[] { "1" }); - Add(new[] { "1" }, - new[] { "2" }, - new[] { "1", "2" }); + Add(new[] { "1" }, new[] { "2" }, new[] { "1", "2" }); - Add(new[] { "1", "2", "3" }, - new[] { "2", "3", "4" }, - new[] { "1", "2", "3", "2", "3", "4" }); + Add( + new[] { "1", "2", "3" }, + new[] { "2", "3", "4" }, + new[] { "1", "2", "3", "2", "3", "4" } + ); } } private sealed class DictionaryCombinationTestData : TheoryData< - IReadOnlyDictionary, - IReadOnlyDictionary, - IReadOnlyDictionary - > + IReadOnlyDictionary, + IReadOnlyDictionary, + IReadOnlyDictionary + > { public DictionaryCombinationTestData() { - Add(null, - null, - new Dictionary()); - - Add(new Dictionary { ["A"] = "A" }, - null, - new Dictionary { ["A"] = "A" }); - - Add(null, - new Dictionary { ["B"] = "B" }, - new Dictionary { ["B"] = "B" }); - - Add(new Dictionary { ["A"] = "old", ["B"] = "B" }, - new Dictionary { ["A"] = "new" }, - new Dictionary { ["A"] = "new", ["B"] = "B" }); + Add(null, null, new Dictionary()); + + Add( + new Dictionary { ["A"] = "A" }, + null, + new Dictionary { ["A"] = "A" } + ); + + Add( + null, + new Dictionary { ["B"] = "B" }, + new Dictionary { ["B"] = "B" } + ); + + Add( + new Dictionary { ["A"] = "old", ["B"] = "B" }, + new Dictionary { ["A"] = "new" }, + new Dictionary { ["A"] = "new", ["B"] = "B" } + ); } } private sealed class ComposableEnumerableCombinationTestData - : TheoryData< - ComposableEnumerable, - ComposableEnumerable, - IEnumerable - > + : TheoryData, ComposableEnumerable, IEnumerable> { public ComposableEnumerableCombinationTestData() { - Add(null, - null, - Array.Empty()); + Add(null, null, Array.Empty()); - Add(null, - new AppendEnumerable(new[] { "2" }), - new[] { "2" }); + Add(null, new AppendEnumerable(new[] { "2" }), new[] { "2" }); - Add(new AppendEnumerable(new[] { "1" }), - null, - new[] { "1" }); + Add(new AppendEnumerable(new[] { "1" }), null, new[] { "1" }); - Add(new AppendEnumerable(new[] { "1" }), - new AppendEnumerable(new[] { "2" }), - new[] { "1", "2" }); + Add( + new AppendEnumerable(new[] { "1" }), + new AppendEnumerable(new[] { "2" }), + new[] { "1", "2" } + ); - Add(new AppendEnumerable(new[] { "1", "2" }), - new OverwriteEnumerable(new[] { "3", "4" }), - new[] { "3", "4" }); + Add( + new AppendEnumerable(new[] { "1", "2" }), + new OverwriteEnumerable(new[] { "3", "4" }), + new[] { "3", "4" } + ); - Add(new AppendEnumerable(new[] { "1", "2", "3" }), - new AppendEnumerable(new[] { "4", "5" }), - new[] { "1", "2", "3", "4", "5" }); + Add( + new AppendEnumerable(new[] { "1", "2", "3" }), + new AppendEnumerable(new[] { "4", "5" }), + new[] { "1", "2", "3", "4", "5" } + ); } } private sealed class AppendEnumerableTestData - : TheoryData< - IEnumerable, - IEnumerable, - IEnumerable - > + : TheoryData, IEnumerable, IEnumerable> { public AppendEnumerableTestData() { - Add(Array.Empty(), - Array.Empty(), - Array.Empty()); + Add(Array.Empty(), Array.Empty(), Array.Empty()); - Add(new[] { "old" }, - Array.Empty(), - new[] { "old" }); + Add(new[] { "old" }, Array.Empty(), new[] { "old" }); - Add(Array.Empty(), - new[] { "new" }, - new[] { "new" }); + Add(Array.Empty(), new[] { "new" }, new[] { "new" }); - Add(new[] { "old" }, - new[] { "new" }, - new[] { "old", "new" }); + Add(new[] { "old" }, new[] { "new" }, new[] { "old", "new" }); - Add(new[] { "1", "2" }, - new[] { "3", "4" }, - new[] { "1", "2", "3", "4" }); + Add(new[] { "1", "2" }, new[] { "3", "4" }, new[] { "1", "2", "3", "4" }); - Add(new[] { "A", "B", "C" }, - new[] { "X", "Y" }, - new[] { "A", "B", "C", "X", "Y" }); + Add(new[] { "A", "B", "C" }, new[] { "X", "Y" }, new[] { "A", "B", "C", "X", "Y" }); } } private sealed class OverwriteEnumerableTestData - : TheoryData< - IEnumerable, - IEnumerable, - IEnumerable - > + : TheoryData, IEnumerable, IEnumerable> { public OverwriteEnumerableTestData() { - Add(Array.Empty(), - Array.Empty(), - Array.Empty()); + Add(Array.Empty(), Array.Empty(), Array.Empty()); - Add(new[] { "old" }, - Array.Empty(), - Array.Empty()); + Add(new[] { "old" }, Array.Empty(), Array.Empty()); - Add(Array.Empty(), - new[] { "new" }, - new[] { "new" }); + Add(Array.Empty(), new[] { "new" }, new[] { "new" }); - Add(new[] { "old" }, - new[] { "new" }, - new[] { "new" }); + Add(new[] { "old" }, new[] { "new" }, new[] { "new" }); - Add(new[] { "1", "2" }, - new[] { "3", "4" }, - new[] { "3", "4" }); + Add(new[] { "1", "2" }, new[] { "3", "4" }, new[] { "3", "4" }); - Add(new[] { "A", "B", "C" }, - new[] { "X", "Y", "Z" }, - new[] { "X", "Y", "Z" }); + Add(new[] { "A", "B", "C" }, new[] { "X", "Y", "Z" }, new[] { "X", "Y", "Z" }); } } private sealed class AppendDictionaryTestData : TheoryData< - IReadOnlyDictionary, - IReadOnlyDictionary, - IReadOnlyDictionary - > + IReadOnlyDictionary, + IReadOnlyDictionary, + IReadOnlyDictionary + > { public AppendDictionaryTestData() { - Add(new Dictionary(), - new Dictionary(), - new Dictionary()); - - Add(new Dictionary { ["A"] = "old" }, - new Dictionary(), - new Dictionary { ["A"] = "old" }); - - Add(new Dictionary(), - new Dictionary { ["B"] = "new" }, - new Dictionary { ["B"] = "new" }); - - Add(new Dictionary { ["A"] = "old" }, - new Dictionary { ["B"] = "new" }, - new Dictionary { ["A"] = "old", ["B"] = "new" }); - - Add(new Dictionary { ["A"] = "old", ["B"] = "keep" }, - new Dictionary { ["A"] = "new" }, - new Dictionary { ["A"] = "new", ["B"] = "keep" }); + Add( + new Dictionary(), + new Dictionary(), + new Dictionary() + ); + + Add( + new Dictionary { ["A"] = "old" }, + new Dictionary(), + new Dictionary { ["A"] = "old" } + ); + + Add( + new Dictionary(), + new Dictionary { ["B"] = "new" }, + new Dictionary { ["B"] = "new" } + ); + + Add( + new Dictionary { ["A"] = "old" }, + new Dictionary { ["B"] = "new" }, + new Dictionary { ["A"] = "old", ["B"] = "new" } + ); + + Add( + new Dictionary { ["A"] = "old", ["B"] = "keep" }, + new Dictionary { ["A"] = "new" }, + new Dictionary { ["A"] = "new", ["B"] = "keep" } + ); } } private sealed class OverwriteDictionaryTestData : TheoryData< - IReadOnlyDictionary, - IReadOnlyDictionary, - IReadOnlyDictionary - > + IReadOnlyDictionary, + IReadOnlyDictionary, + IReadOnlyDictionary + > { public OverwriteDictionaryTestData() { - Add(new Dictionary(), - new Dictionary(), - new Dictionary()); - - Add(new Dictionary { ["A"] = "old" }, - new Dictionary(), - new Dictionary()); - - Add(new Dictionary(), - new Dictionary { ["B"] = "new" }, - new Dictionary { ["B"] = "new" }); - - Add(new Dictionary { ["A"] = "old" }, - new Dictionary { ["B"] = "new" }, - new Dictionary { ["B"] = "new" }); - - Add(new Dictionary { ["A"] = "old", ["B"] = "ignore" }, - new Dictionary { ["A"] = "new", ["C"] = "keep" }, - new Dictionary { ["A"] = "new", ["C"] = "keep" }); + Add( + new Dictionary(), + new Dictionary(), + new Dictionary() + ); + + Add( + new Dictionary { ["A"] = "old" }, + new Dictionary(), + new Dictionary() + ); + + Add( + new Dictionary(), + new Dictionary { ["B"] = "new" }, + new Dictionary { ["B"] = "new" } + ); + + Add( + new Dictionary { ["A"] = "old" }, + new Dictionary { ["B"] = "new" }, + new Dictionary { ["B"] = "new" } + ); + + Add( + new Dictionary { ["A"] = "old", ["B"] = "ignore" }, + new Dictionary { ["A"] = "new", ["C"] = "keep" }, + new Dictionary { ["A"] = "new", ["C"] = "keep" } + ); } } } diff --git a/tests/Testcontainers.Tests/Unit/Builders/CommonDirectoryPathTest.cs b/tests/Testcontainers.Tests/Unit/Builders/CommonDirectoryPathTest.cs index 14e4e5ea7..6832ccff9 100644 --- a/tests/Testcontainers.Tests/Unit/Builders/CommonDirectoryPathTest.cs +++ b/tests/Testcontainers.Tests/Unit/Builders/CommonDirectoryPathTest.cs @@ -1,16 +1,20 @@ namespace DotNet.Testcontainers.Tests.Unit { using System.IO; - using DotNet.Testcontainers.Commons; using DotNet.Testcontainers.Builders; + using DotNet.Testcontainers.Commons; using Xunit; public sealed class CommonDirectoryPathTest { public static TheoryData CommonDirectoryPaths() { - using var fsprojFileStream = File.Create(Path.Combine(TestSession.TempDirectoryPath, "Testcontainers.fsproj")); - using var vbprojFileStream = File.Create(Path.Combine(TestSession.TempDirectoryPath, "Testcontainers.vbproj")); + using var fsprojFileStream = File.Create( + Path.Combine(TestSession.TempDirectoryPath, "Testcontainers.fsproj") + ); + using var vbprojFileStream = File.Create( + Path.Combine(TestSession.TempDirectoryPath, "Testcontainers.vbproj") + ); var theoryData = new TheoryData(); theoryData.Add(CommonDirectoryPath.GetBinDirectory()); theoryData.Add(CommonDirectoryPath.GetGitDirectory()); @@ -33,7 +37,9 @@ public void CommonDirectoryPathExists(CommonDirectoryPath commonDirectoryPath) public void CommonDirectoryPathNotExists() { var callerFilePath = Path.GetPathRoot(Directory.GetCurrentDirectory()); - Assert.Throws(() => CommonDirectoryPath.GetGitDirectory(callerFilePath!)); + Assert.Throws(() => + CommonDirectoryPath.GetGitDirectory(callerFilePath!) + ); } } } diff --git a/tests/Testcontainers.Tests/Unit/Builders/DockerConfigTest.cs b/tests/Testcontainers.Tests/Unit/Builders/DockerConfigTest.cs index 7584dd3fe..a3e228308 100644 --- a/tests/Testcontainers.Tests/Unit/Builders/DockerConfigTest.cs +++ b/tests/Testcontainers.Tests/Unit/Builders/DockerConfigTest.cs @@ -18,7 +18,9 @@ public sealed class DockerContextConfigurationTests public void ReturnsActiveEndpointWhenDockerContextIsEmpty() { // Given - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { "docker.context=" }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { "docker.context=" } + ); var dockerConfig = new DockerConfig(customConfiguration); // When @@ -32,7 +34,9 @@ public void ReturnsActiveEndpointWhenDockerContextIsEmpty() public void ReturnsDefaultEndpointWhenDockerContextIsDefault() { // Given - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { "docker.context=default" }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { "docker.context=default" } + ); var dockerConfig = new DockerConfig(customConfiguration); // When @@ -48,7 +52,9 @@ public void ReturnsConfiguredEndpointWhenDockerContextIsCustomFromPropertiesFile // Given using var context = new ConfigMetaFile("custom", new Uri("tcp://127.0.0.1:2375/")); - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { "docker.context=custom", $"docker.config={context.DockerConfigDirectoryPath}" }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { "docker.context=custom", $"docker.config={context.DockerConfigDirectoryPath}" } + ); var dockerConfig = new DockerConfig(customConfiguration); // When @@ -65,7 +71,9 @@ public void ReturnsConfiguredEndpointWhenDockerContextIsCustomFromConfigFile() using var context = new ConfigMetaFile("custom", new Uri("tcp://127.0.0.1:2375/")); // This test reads the current context JSON node from the Docker config file. - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { $"docker.config={context.DockerConfigDirectoryPath}" }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { $"docker.config={context.DockerConfigDirectoryPath}" } + ); var dockerConfig = new DockerConfig(customConfiguration); // When @@ -86,11 +94,15 @@ public void ReturnsActiveEndpointWhenDockerContextIsUnset() public void ThrowsWhenDockerContextNotFound() { // Given - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { "docker.context=missing" }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { "docker.context=missing" } + ); var dockerConfig = new DockerConfig(customConfiguration); // When - var exception = Assert.Throws(() => dockerConfig.GetCurrentEndpoint()); + var exception = Assert.Throws(() => + dockerConfig.GetCurrentEndpoint() + ); // Then Assert.Equal("The Docker context 'missing' does not exist.", exception.Message); @@ -103,11 +115,15 @@ public void ThrowsWhenDockerHostNotFound() // Given using var context = new ConfigMetaFile("custom", null); - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { "docker.context=custom", $"docker.config={context.DockerConfigDirectoryPath}" }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { "docker.context=custom", $"docker.config={context.DockerConfigDirectoryPath}" } + ); var dockerConfig = new DockerConfig(customConfiguration); // When - var exception = Assert.Throws(() => dockerConfig.GetCurrentEndpoint()); + var exception = Assert.Throws(() => + dockerConfig.GetCurrentEndpoint() + ); // Then Assert.StartsWith("The Docker host is null or empty in ", exception.Message); @@ -123,7 +139,9 @@ public sealed class DockerHostConfigurationTests public void ReturnsActiveEndpointWhenDockerHostIsEmpty() { // Given - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { "docker.host=" }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { "docker.host=" } + ); var dockerConfig = new DockerConfig(customConfiguration); // When @@ -139,7 +157,13 @@ public void ReturnsConfiguredEndpointWhenDockerHostIsSet() // Given using var context = new ConfigMetaFile("custom", null); - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { "docker.host=tcp://127.0.0.1:2375/", $"docker.config={context.DockerConfigDirectoryPath}" }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] + { + "docker.host=tcp://127.0.0.1:2375/", + $"docker.config={context.DockerConfigDirectoryPath}", + } + ); var dockerConfig = new DockerConfig(customConfiguration); // When @@ -154,7 +178,8 @@ private sealed class SkipIfHostOrContextIsSet : FactAttribute { public SkipIfHostOrContextIsSet() { - const string reason = "The Docker CLI doesn't know about ~/.testcontainers.properties file."; + const string reason = + "The Docker CLI doesn't know about ~/.testcontainers.properties file."; var dockerHost = PropertiesFileConfiguration.Instance.GetDockerHost(); var dockerContext = PropertiesFileConfiguration.Instance.GetDockerContext(); Skip = dockerHost != null || dockerContext != null ? reason : string.Empty; @@ -165,16 +190,30 @@ private sealed class ConfigMetaFile : IDisposable { private const string ConfigFileJson = "{{\"currentContext\":\"{0}\"}}"; - private const string MetaFileJson = "{{\"Name\":\"{0}\",\"Metadata\":{{}},\"Endpoints\":{{\"docker\":{{\"Host\":\"{1}\",\"SkipTLSVerify\":false}}}}}}"; + private const string MetaFileJson = + "{{\"Name\":\"{0}\",\"Metadata\":{{}},\"Endpoints\":{{\"docker\":{{\"Host\":\"{1}\",\"SkipTLSVerify\":false}}}}}}"; public ConfigMetaFile(string context, Uri endpoint, [CallerMemberName] string caller = "") { DockerConfigDirectoryPath = Path.Combine(TestSession.TempDirectoryPath, caller); - var dockerContextHash = Convert.ToHexString(SHA256.HashData(Encoding.Default.GetBytes(context))).ToLowerInvariant(); - var dockerContextMetaDirectoryPath = Path.Combine(DockerConfigDirectoryPath, "contexts", "meta", dockerContextHash); + var dockerContextHash = Convert + .ToHexString(SHA256.HashData(Encoding.Default.GetBytes(context))) + .ToLowerInvariant(); + var dockerContextMetaDirectoryPath = Path.Combine( + DockerConfigDirectoryPath, + "contexts", + "meta", + dockerContextHash + ); _ = Directory.CreateDirectory(dockerContextMetaDirectoryPath); - File.WriteAllText(Path.Combine(DockerConfigDirectoryPath, "config.json"), string.Format(ConfigFileJson, context)); - File.WriteAllText(Path.Combine(dockerContextMetaDirectoryPath, "meta.json"), endpoint == null ? "{}" : string.Format(MetaFileJson, context, endpoint.AbsoluteUri)); + File.WriteAllText( + Path.Combine(DockerConfigDirectoryPath, "config.json"), + string.Format(ConfigFileJson, context) + ); + File.WriteAllText( + Path.Combine(dockerContextMetaDirectoryPath, "meta.json"), + endpoint == null ? "{}" : string.Format(MetaFileJson, context, endpoint.AbsoluteUri) + ); } public string DockerConfigDirectoryPath { get; } diff --git a/tests/Testcontainers.Tests/Unit/Clients/ContainerConfigurationConverterTest.cs b/tests/Testcontainers.Tests/Unit/Clients/ContainerConfigurationConverterTest.cs index 61c6b8e6f..47b2a182f 100644 --- a/tests/Testcontainers.Tests/Unit/Clients/ContainerConfigurationConverterTest.cs +++ b/tests/Testcontainers.Tests/Unit/Clients/ContainerConfigurationConverterTest.cs @@ -16,10 +16,14 @@ public sealed class ExposedPorts public void ShouldAddTcpPortSuffix() { // Given - var containerConfiguration = new ContainerConfiguration(exposedPorts: new Dictionary { { Port, null } }); + var containerConfiguration = new ContainerConfiguration( + exposedPorts: new Dictionary { { Port, null } } + ); // When - var exposedPort = new ContainerConfigurationConverter(containerConfiguration).ExposedPorts.Single().Key; + var exposedPort = new ContainerConfigurationConverter(containerConfiguration) + .ExposedPorts.Single() + .Key; // Then Assert.Equal($"{Port}/tcp", exposedPort); @@ -34,10 +38,14 @@ public void ShouldKeepPortSuffix(string portSuffix) // Given var qualifiedPort = $"{Port}/{portSuffix}"; - var containerConfiguration = new ContainerConfiguration(exposedPorts: new Dictionary { { qualifiedPort, null } }); + var containerConfiguration = new ContainerConfiguration( + exposedPorts: new Dictionary { { qualifiedPort, null } } + ); // When - var exposedPort = new ContainerConfigurationConverter(containerConfiguration).ExposedPorts.Single().Key; + var exposedPort = new ContainerConfigurationConverter(containerConfiguration) + .ExposedPorts.Single() + .Key; // Then Assert.Equal($"{Port}/{portSuffix}".ToLowerInvariant(), exposedPort); @@ -50,10 +58,14 @@ public sealed class PortBindings public void ShouldAddTcpPortSuffix() { // Given - var containerConfiguration = new ContainerConfiguration(portBindings: new Dictionary { { Port, Port } }); + var containerConfiguration = new ContainerConfiguration( + portBindings: new Dictionary { { Port, Port } } + ); // When - var portBinding = new ContainerConfigurationConverter(containerConfiguration).PortBindings.Single().Key; + var portBinding = new ContainerConfigurationConverter(containerConfiguration) + .PortBindings.Single() + .Key; // Then Assert.Equal($"{Port}/tcp", portBinding); @@ -68,10 +80,14 @@ public void ShouldKeepPortSuffix(string portSuffix) // Given var qualifiedPort = $"{Port}/{portSuffix}"; - var containerConfiguration = new ContainerConfiguration(portBindings: new Dictionary { { qualifiedPort, Port } }); + var containerConfiguration = new ContainerConfiguration( + portBindings: new Dictionary { { qualifiedPort, Port } } + ); // When - var portBinding = new ContainerConfigurationConverter(containerConfiguration).PortBindings.Single().Key; + var portBinding = new ContainerConfigurationConverter(containerConfiguration) + .PortBindings.Single() + .Key; // Then Assert.Equal($"{Port}/{portSuffix}".ToLowerInvariant(), portBinding); diff --git a/tests/Testcontainers.Tests/Unit/Configurations/CustomConfigurationTest.cs b/tests/Testcontainers.Tests/Unit/Configurations/CustomConfigurationTest.cs index 1d123dea5..266b5aaa2 100644 --- a/tests/Testcontainers.Tests/Unit/Configurations/CustomConfigurationTest.cs +++ b/tests/Testcontainers.Tests/Unit/Configurations/CustomConfigurationTest.cs @@ -38,7 +38,11 @@ static EnvironmentConfigurationTest() [InlineData("", "", null)] [InlineData("DOCKER_CONFIG", "", null)] [InlineData("DOCKER_CONFIG", "~/.docker/", "~/.docker/")] - public void GetDockerConfigCustomConfiguration(string propertyName, string propertyValue, string expected) + public void GetDockerConfigCustomConfiguration( + string propertyName, + string propertyValue, + string expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -49,7 +53,11 @@ public void GetDockerConfigCustomConfiguration(string propertyName, string prope [InlineData("", "", null)] [InlineData("DOCKER_HOST", "", null)] [InlineData("DOCKER_HOST", "tcp://127.0.0.1:2375/", "tcp://127.0.0.1:2375/")] - public void GetDockerHostCustomConfiguration(string propertyName, string propertyValue, string expected) + public void GetDockerHostCustomConfiguration( + string propertyName, + string propertyValue, + string expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -60,7 +68,11 @@ public void GetDockerHostCustomConfiguration(string propertyName, string propert [InlineData("", "", null)] [InlineData("DOCKER_CONTEXT", "", null)] [InlineData("DOCKER_CONTEXT", "default", "default")] - public void GetDockerContextCustomConfiguration(string propertyName, string propertyValue, string expected) + public void GetDockerContextCustomConfiguration( + string propertyName, + string propertyValue, + string expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -71,7 +83,11 @@ public void GetDockerContextCustomConfiguration(string propertyName, string prop [InlineData("", "", null)] [InlineData("TESTCONTAINERS_HOST_OVERRIDE", "", null)] [InlineData("TESTCONTAINERS_HOST_OVERRIDE", "docker.svc.local", "docker.svc.local")] - public void GetDockerHostOverrideCustomConfiguration(string propertyName, string propertyValue, string expected) + public void GetDockerHostOverrideCustomConfiguration( + string propertyName, + string propertyValue, + string expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -81,8 +97,16 @@ public void GetDockerHostOverrideCustomConfiguration(string propertyName, string [Theory] [InlineData("", "", null)] [InlineData("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE", "", null)] - [InlineData("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE", "/var/run/docker.sock", "/var/run/docker.sock")] - public void GetDockerSocketOverrideCustomConfiguration(string propertyName, string propertyValue, string expected) + [InlineData( + "TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE", + "/var/run/docker.sock", + "/var/run/docker.sock" + )] + public void GetDockerSocketOverrideCustomConfiguration( + string propertyName, + string propertyValue, + string expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -96,8 +120,16 @@ public void GetDockerSocketOverrideCustomConfiguration(string propertyName, stri [InlineData("DOCKER_AUTH_CONFIG", "{}", "{}")] [InlineData("DOCKER_AUTH_CONFIG", "{\"auths\":null}", "{\"auths\":null}")] [InlineData("DOCKER_AUTH_CONFIG", "{\"auths\":{}}", "{\"auths\":{}}")] - [InlineData("DOCKER_AUTH_CONFIG", "{\"auths\":{\"ghcr.io\":{}}}", "{\"auths\":{\"ghcr.io\":{}}}")] - public void GetDockerAuthConfigCustomConfiguration(string propertyName, string propertyValue, string expected) + [InlineData( + "DOCKER_AUTH_CONFIG", + "{\"auths\":{\"ghcr.io\":{}}}", + "{\"auths\":{\"ghcr.io\":{}}}" + )] + public void GetDockerAuthConfigCustomConfiguration( + string propertyName, + string propertyValue, + string expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -108,7 +140,11 @@ public void GetDockerAuthConfigCustomConfiguration(string propertyName, string p [InlineData("", "", null)] [InlineData("DOCKER_CERT_PATH", "", null)] [InlineData("DOCKER_CERT_PATH", "/home/docker/.docker/certs", "/home/docker/.docker/certs")] - public void GetDockerCertPathCustomConfiguration(string propertyName, string propertyValue, string expected) + public void GetDockerCertPathCustomConfiguration( + string propertyName, + string propertyValue, + string expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -124,7 +160,11 @@ public void GetDockerCertPathCustomConfiguration(string propertyName, string pro [InlineData("DOCKER_TLS", "1", true)] [InlineData("DOCKER_TLS", "TRUE", true)] [InlineData("DOCKER_TLS", "true", true)] - public void GetDockerTlsCustomConfiguration(string propertyName, string propertyValue, bool expected) + public void GetDockerTlsCustomConfiguration( + string propertyName, + string propertyValue, + bool expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -140,7 +180,11 @@ public void GetDockerTlsCustomConfiguration(string propertyName, string property [InlineData("DOCKER_TLS_VERIFY", "1", true)] [InlineData("DOCKER_TLS_VERIFY", "TRUE", true)] [InlineData("DOCKER_TLS_VERIFY", "true", true)] - public void GetDockerTlsVerifyCustomConfiguration(string propertyName, string propertyValue, bool expected) + public void GetDockerTlsVerifyCustomConfiguration( + string propertyName, + string propertyValue, + bool expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -152,7 +196,11 @@ public void GetDockerTlsVerifyCustomConfiguration(string propertyName, string pr [InlineData("TESTCONTAINERS_RYUK_DISABLED", "", false)] [InlineData("TESTCONTAINERS_RYUK_DISABLED", "false", false)] [InlineData("TESTCONTAINERS_RYUK_DISABLED", "true", true)] - public void GetRyukDisabledCustomConfiguration(string propertyName, string propertyValue, bool expected) + public void GetRyukDisabledCustomConfiguration( + string propertyName, + string propertyValue, + bool expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -164,7 +212,11 @@ public void GetRyukDisabledCustomConfiguration(string propertyName, string prope [InlineData("TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED", "", null)] [InlineData("TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED", "false", false)] [InlineData("TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED", "true", true)] - public void GetRyukContainerPrivilegedCustomConfiguration(string propertyName, string propertyValue, bool? expected) + public void GetRyukContainerPrivilegedCustomConfiguration( + string propertyName, + string propertyValue, + bool? expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -175,7 +227,11 @@ public void GetRyukContainerPrivilegedCustomConfiguration(string propertyName, s [InlineData("", "", null)] [InlineData("TESTCONTAINERS_RYUK_CONTAINER_IMAGE", "", null)] [InlineData("TESTCONTAINERS_RYUK_CONTAINER_IMAGE", "alpine:latest", "alpine:latest")] - public void GetRyukContainerImageCustomConfiguration(string propertyName, string propertyValue, string expected) + public void GetRyukContainerImageCustomConfiguration( + string propertyName, + string propertyValue, + string expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -186,7 +242,11 @@ public void GetRyukContainerImageCustomConfiguration(string propertyName, string [InlineData("", "", null)] [InlineData("TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX", "", null)] [InlineData("TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX", "my.proxy.com", "my.proxy.com")] - public void GetHubImageNamePrefixCustomConfiguration(string propertyName, string propertyValue, string expected) + public void GetHubImageNamePrefixCustomConfiguration( + string propertyName, + string propertyValue, + string expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -197,7 +257,11 @@ public void GetHubImageNamePrefixCustomConfiguration(string propertyName, string [InlineData("", "", null)] [InlineData("TESTCONTAINERS_WAIT_STRATEGY_RETRIES", "", null)] [InlineData("TESTCONTAINERS_WAIT_STRATEGY_RETRIES", "1", 1)] - public void GetWaitStrategyRetriesCustomConfiguration(string propertyName, string propertyValue, int? expected) + public void GetWaitStrategyRetriesCustomConfiguration( + string propertyName, + string propertyValue, + int? expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -209,7 +273,11 @@ public void GetWaitStrategyRetriesCustomConfiguration(string propertyName, strin [InlineData("TESTCONTAINERS_WAIT_STRATEGY_INTERVAL", "", null)] [InlineData("TESTCONTAINERS_WAIT_STRATEGY_INTERVAL", "-00:00:00.001", null)] [InlineData("TESTCONTAINERS_WAIT_STRATEGY_INTERVAL", "00:00:01", "00:00:01")] - public void GetWaitStrategyIntervalCustomConfiguration(string propertyName, string propertyValue, string expected) + public void GetWaitStrategyIntervalCustomConfiguration( + string propertyName, + string propertyValue, + string expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -221,7 +289,11 @@ public void GetWaitStrategyIntervalCustomConfiguration(string propertyName, stri [InlineData("TESTCONTAINERS_WAIT_STRATEGY_TIMEOUT", "", null)] [InlineData("TESTCONTAINERS_WAIT_STRATEGY_TIMEOUT", "-00:00:00.001", null)] [InlineData("TESTCONTAINERS_WAIT_STRATEGY_TIMEOUT", "00:00:01", "00:00:01")] - public void GetWaitStrategyTimeoutCustomConfiguration(string propertyName, string propertyValue, string expected) + public void GetWaitStrategyTimeoutCustomConfiguration( + string propertyName, + string propertyValue, + string expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -233,7 +305,11 @@ public void GetWaitStrategyTimeoutCustomConfiguration(string propertyName, strin [InlineData("TESTCONTAINERS_NAMED_PIPE_CONNECTION_TIMEOUT", "", null)] [InlineData("TESTCONTAINERS_NAMED_PIPE_CONNECTION_TIMEOUT", "-00:00:00.001", null)] [InlineData("TESTCONTAINERS_NAMED_PIPE_CONNECTION_TIMEOUT", "00:00:01", "00:00:01")] - public void GetNamedPipeConnectionTimeoutCustomConfiguration(string propertyName, string propertyValue, string expected) + public void GetNamedPipeConnectionTimeoutCustomConfiguration( + string propertyName, + string propertyValue, + string expected + ) { SetEnvironmentVariable(propertyName, propertyValue); ICustomConfiguration customConfiguration = new EnvironmentConfiguration(); @@ -265,7 +341,9 @@ public sealed class PropertiesFileConfigurationTest [InlineData("docker.config=~/.docker/", "~/.docker/")] public void GetDockerConfigCustomConfiguration(string configuration, string expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetDockerConfig()); } @@ -275,7 +353,9 @@ public void GetDockerConfigCustomConfiguration(string configuration, string expe [InlineData("docker.host=tcp://127.0.0.1:2375/", "tcp://127.0.0.1:2375/")] public void GetDockerHostCustomConfiguration(string configuration, string expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetDockerHost()?.ToString()); } @@ -285,7 +365,9 @@ public void GetDockerHostCustomConfiguration(string configuration, string expect [InlineData("docker.context=default", "default")] public void GetDockerContextCustomConfiguration(string configuration, string expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetDockerContext()); } @@ -295,7 +377,9 @@ public void GetDockerContextCustomConfiguration(string configuration, string exp [InlineData("host.override=docker.svc.local", "docker.svc.local")] public void GetDockerHostOverrideCustomConfiguration(string configuration, string expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetDockerHostOverride()); } @@ -305,7 +389,9 @@ public void GetDockerHostOverrideCustomConfiguration(string configuration, strin [InlineData("docker.socket.override=/var/run/docker.sock", "/var/run/docker.sock")] public void GetDockerSocketOverrideCustomConfiguration(string configuration, string expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetDockerSocketOverride()); } @@ -316,10 +402,15 @@ public void GetDockerSocketOverrideCustomConfiguration(string configuration, str [InlineData("docker.auth.config={}", "{}")] [InlineData("docker.auth.config={\"auths\":null}", "{\"auths\":null}")] [InlineData("docker.auth.config={\"auths\":{}}", "{\"auths\":{}}")] - [InlineData("docker.auth.config={\"auths\":{\"ghcr.io\":{}}}", "{\"auths\":{\"ghcr.io\":{}}}")] + [InlineData( + "docker.auth.config={\"auths\":{\"ghcr.io\":{}}}", + "{\"auths\":{\"ghcr.io\":{}}}" + )] public void GetDockerAuthConfigCustomConfiguration(string configuration, string expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetDockerAuthConfig()?.RootElement.ToString()); } @@ -329,7 +420,9 @@ public void GetDockerAuthConfigCustomConfiguration(string configuration, string [InlineData("docker.cert.path=/home/docker/.docker/certs", "/home/docker/.docker/certs")] public void GetDockerCertPathCustomConfiguration(string configuration, string expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetDockerCertPath()); } @@ -344,7 +437,9 @@ public void GetDockerCertPathCustomConfiguration(string configuration, string ex [InlineData("docker.tls=true", true)] public void GetDockerTlsCustomConfiguration(string configuration, bool expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetDockerTls()); } @@ -359,7 +454,9 @@ public void GetDockerTlsCustomConfiguration(string configuration, bool expected) [InlineData("docker.tls.verify=true", true)] public void GetDockerTlsVerifyCustomConfiguration(string configuration, bool expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetDockerTlsVerify()); } @@ -370,7 +467,9 @@ public void GetDockerTlsVerifyCustomConfiguration(string configuration, bool exp [InlineData("ryuk.disabled=true", true)] public void GetRyukDisabledCustomConfiguration(string configuration, bool expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetRyukDisabled()); } @@ -379,9 +478,14 @@ public void GetRyukDisabledCustomConfiguration(string configuration, bool expect [InlineData("ryuk.container.privileged=", null)] [InlineData("ryuk.container.privileged=false", false)] [InlineData("ryuk.container.privileged=true", true)] - public void GetRyukContainerPrivilegedCustomConfiguration(string configuration, bool? expected) - { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + public void GetRyukContainerPrivilegedCustomConfiguration( + string configuration, + bool? expected + ) + { + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetRyukContainerPrivileged()); } @@ -391,7 +495,9 @@ public void GetRyukContainerPrivilegedCustomConfiguration(string configuration, [InlineData("ryuk.container.image=alpine:latest", "alpine:latest")] public void GetRyukContainerImageCustomConfiguration(string configuration, string expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetRyukContainerImage()?.FullName); } @@ -401,7 +507,9 @@ public void GetRyukContainerImageCustomConfiguration(string configuration, strin [InlineData("hub.image.name.prefix=my.proxy.com", "my.proxy.com")] public void GetHubImageNamePrefixCustomConfiguration(string configuration, string expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetHubImageNamePrefix()); } @@ -411,7 +519,9 @@ public void GetHubImageNamePrefixCustomConfiguration(string configuration, strin [InlineData("wait.strategy.retries=1", 1)] public void GetWaitStrategyRetriesCustomConfiguration(string configuration, int? expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetWaitStrategyRetries()); } @@ -422,7 +532,9 @@ public void GetWaitStrategyRetriesCustomConfiguration(string configuration, int? [InlineData("wait.strategy.interval=00:00:01", "00:00:01")] public void GetWaitStrategyIntervalCustomConfiguration(string configuration, string expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetWaitStrategyInterval()?.ToString()); } @@ -433,7 +545,9 @@ public void GetWaitStrategyIntervalCustomConfiguration(string configuration, str [InlineData("wait.strategy.timeout=00:00:01", "00:00:01")] public void GetWaitStrategyTimeoutCustomConfiguration(string configuration, string expected) { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetWaitStrategyTimeout()?.ToString()); } @@ -442,9 +556,14 @@ public void GetWaitStrategyTimeoutCustomConfiguration(string configuration, stri [InlineData("named.pipe.connection.timeout=", null)] [InlineData("named.pipe.connection.timeout=-00:00:00.001", null)] [InlineData("named.pipe.connection.timeout=00:00:01", "00:00:01")] - public void GetNamedPipeConnectionTimeoutCustomConfiguration(string configuration, string expected) - { - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { configuration }); + public void GetNamedPipeConnectionTimeoutCustomConfiguration( + string configuration, + string expected + ) + { + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { configuration } + ); Assert.Equal(expected, customConfiguration.GetNamedPipeConnectionTimeout()?.ToString()); } } diff --git a/tests/Testcontainers.Tests/Unit/Configurations/DockerEndpointAuthenticationProviderTest.cs b/tests/Testcontainers.Tests/Unit/Configurations/DockerEndpointAuthenticationProviderTest.cs index 2ba73314f..f52702650 100644 --- a/tests/Testcontainers.Tests/Unit/Configurations/DockerEndpointAuthenticationProviderTest.cs +++ b/tests/Testcontainers.Tests/Unit/Configurations/DockerEndpointAuthenticationProviderTest.cs @@ -14,11 +14,16 @@ public sealed class DockerEndpointAuthenticationProviderTest private const string DockerTlsHost = "tcp://127.0.0.1:2376"; - private static readonly string CertificatesDirectoryPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("D")); + private static readonly string CertificatesDirectoryPath = Path.Combine( + Path.GetTempPath(), + Guid.NewGuid().ToString("D") + ); - private static readonly ICustomConfiguration DockerHostConfiguration = new PropertiesFileConfiguration(new[] { "docker.host=" + DockerHost }); + private static readonly ICustomConfiguration DockerHostConfiguration = + new PropertiesFileConfiguration(new[] { "docker.host=" + DockerHost }); - private static readonly ICustomConfiguration DockerTlsHostConfiguration = new PropertiesFileConfiguration(new[] { "docker.host=" + DockerTlsHost }); + private static readonly ICustomConfiguration DockerTlsHostConfiguration = + new PropertiesFileConfiguration(new[] { "docker.host=" + DockerTlsHost }); static DockerEndpointAuthenticationProviderTest() { @@ -30,14 +35,20 @@ static DockerEndpointAuthenticationProviderTest() [Theory] [ClassData(typeof(AuthProviderTestData))] - internal void AuthProviderShouldBeApplicable(IDockerEndpointAuthenticationProvider authProvider, bool isApplicable) + internal void AuthProviderShouldBeApplicable( + IDockerEndpointAuthenticationProvider authProvider, + bool isApplicable + ) { Assert.Equal(isApplicable, authProvider.IsApplicable()); } [Theory] [ClassData(typeof(AuthConfigTestData))] - internal void AuthConfigShouldGetDockerClientEndpoint(IDockerEndpointAuthenticationConfiguration authConfig, Uri dockerClientEndpoint) + internal void AuthConfigShouldGetDockerClientEndpoint( + IDockerEndpointAuthenticationConfiguration authConfig, + Uri dockerClientEndpoint + ) { using (var dockerClientConfiguration = authConfig.GetDockerClientConfiguration()) { @@ -51,14 +62,18 @@ public sealed class TestcontainersHostEndpointAuthenticationProviderTest [Fact] public void GetDockerHostOverrideReturnsNull() { - ICustomConfiguration customConfiguration = new TestcontainersEndpointAuthenticationProvider("host.override=host.docker.internal"); + ICustomConfiguration customConfiguration = new TestcontainersEndpointAuthenticationProvider( + "host.override=host.docker.internal" + ); Assert.Null(customConfiguration.GetDockerHostOverride()); } [Fact] public void GetDockerSocketOverrideReturnsNull() { - ICustomConfiguration customConfiguration = new TestcontainersEndpointAuthenticationProvider("docker.socket.override=/var/run/docker.sock"); + ICustomConfiguration customConfiguration = new TestcontainersEndpointAuthenticationProvider( + "docker.socket.override=/var/run/docker.sock" + ); Assert.Null(customConfiguration.GetDockerSocketOverride()); } } @@ -68,24 +83,99 @@ private sealed class AuthProviderTestData : List public AuthProviderTestData() { var defaultConfiguration = new PropertiesFileConfiguration(Array.Empty()); - var dockerTlsConfiguration = new PropertiesFileConfiguration("docker.tls=true", "docker.cert.path=" + CertificatesDirectoryPath); - var dockerMTlsConfiguration = new PropertiesFileConfiguration("docker.tls.verify=true", "docker.cert.path=" + CertificatesDirectoryPath); + var dockerTlsConfiguration = new PropertiesFileConfiguration( + "docker.tls=true", + "docker.cert.path=" + CertificatesDirectoryPath + ); + var dockerMTlsConfiguration = new PropertiesFileConfiguration( + "docker.tls.verify=true", + "docker.cert.path=" + CertificatesDirectoryPath + ); Add(new object[] { new MTlsEndpointAuthenticationProvider(defaultConfiguration), false }); Add(new object[] { new MTlsEndpointAuthenticationProvider(dockerMTlsConfiguration), true }); - Add(new object[] { new MTlsEndpointAuthenticationProvider(Array.Empty()), false }); - Add(new object[] { new MTlsEndpointAuthenticationProvider(defaultConfiguration, dockerMTlsConfiguration), true }); + Add( + new object[] + { + new MTlsEndpointAuthenticationProvider(Array.Empty()), + false, + } + ); + Add( + new object[] + { + new MTlsEndpointAuthenticationProvider(defaultConfiguration, dockerMTlsConfiguration), + true, + } + ); Add(new object[] { new TlsEndpointAuthenticationProvider(defaultConfiguration), false }); Add(new object[] { new TlsEndpointAuthenticationProvider(dockerTlsConfiguration), true }); - Add(new object[] { new TlsEndpointAuthenticationProvider(Array.Empty()), false }); - Add(new object[] { new TlsEndpointAuthenticationProvider(defaultConfiguration, dockerTlsConfiguration), true }); - Add(new object[] { new EnvironmentEndpointAuthenticationProvider(defaultConfiguration), false }); - Add(new object[] { new EnvironmentEndpointAuthenticationProvider(DockerHostConfiguration), true }); - Add(new object[] { new EnvironmentEndpointAuthenticationProvider(Array.Empty()), false }); - Add(new object[] { new EnvironmentEndpointAuthenticationProvider(defaultConfiguration, DockerHostConfiguration), true }); - Add(new object[] { new NpipeEndpointAuthenticationProvider(), RuntimeInformation.IsOSPlatform(OSPlatform.Windows) }); - Add(new object[] { new UnixEndpointAuthenticationProvider(), !RuntimeInformation.IsOSPlatform(OSPlatform.Windows) }); + Add( + new object[] + { + new TlsEndpointAuthenticationProvider(Array.Empty()), + false, + } + ); + Add( + new object[] + { + new TlsEndpointAuthenticationProvider(defaultConfiguration, dockerTlsConfiguration), + true, + } + ); + Add( + new object[] + { + new EnvironmentEndpointAuthenticationProvider(defaultConfiguration), + false, + } + ); + Add( + new object[] + { + new EnvironmentEndpointAuthenticationProvider(DockerHostConfiguration), + true, + } + ); + Add( + new object[] + { + new EnvironmentEndpointAuthenticationProvider(Array.Empty()), + false, + } + ); + Add( + new object[] + { + new EnvironmentEndpointAuthenticationProvider( + defaultConfiguration, + DockerHostConfiguration + ), + true, + } + ); + Add( + new object[] + { + new NpipeEndpointAuthenticationProvider(), + RuntimeInformation.IsOSPlatform(OSPlatform.Windows), + } + ); + Add( + new object[] + { + new UnixEndpointAuthenticationProvider(), + !RuntimeInformation.IsOSPlatform(OSPlatform.Windows), + } + ); Add(new object[] { new TestcontainersEndpointAuthenticationProvider(string.Empty), false }); - Add(new object[] { new TestcontainersEndpointAuthenticationProvider("tc.host=" + DockerHost), true }); + Add( + new object[] + { + new TestcontainersEndpointAuthenticationProvider("tc.host=" + DockerHost), + true, + } + ); } } @@ -93,11 +183,43 @@ private sealed class AuthConfigTestData : List { public AuthConfigTestData() { - Add(new object[] { new TlsEndpointAuthenticationProvider(DockerTlsHostConfiguration).GetAuthConfig(), new Uri(DockerTlsHost) }); - Add(new object[] { new EnvironmentEndpointAuthenticationProvider(DockerHostConfiguration).GetAuthConfig(), new Uri(DockerHost) }); - Add(new object[] { new NpipeEndpointAuthenticationProvider().GetAuthConfig(), new Uri("npipe://./pipe/docker_engine") }); - Add(new object[] { new UnixEndpointAuthenticationProvider().GetAuthConfig(), new Uri("unix:///var/run/docker.sock") }); - Add(new object[] { new TestcontainersEndpointAuthenticationProvider("tc.host=" + DockerHost).GetAuthConfig(), new Uri(DockerHost) }); + Add( + new object[] + { + new TlsEndpointAuthenticationProvider(DockerTlsHostConfiguration).GetAuthConfig(), + new Uri(DockerTlsHost), + } + ); + Add( + new object[] + { + new EnvironmentEndpointAuthenticationProvider(DockerHostConfiguration).GetAuthConfig(), + new Uri(DockerHost), + } + ); + Add( + new object[] + { + new NpipeEndpointAuthenticationProvider().GetAuthConfig(), + new Uri("npipe://./pipe/docker_engine"), + } + ); + Add( + new object[] + { + new UnixEndpointAuthenticationProvider().GetAuthConfig(), + new Uri("unix:///var/run/docker.sock"), + } + ); + Add( + new object[] + { + new TestcontainersEndpointAuthenticationProvider( + "tc.host=" + DockerHost + ).GetAuthConfig(), + new Uri(DockerHost), + } + ); } } } diff --git a/tests/Testcontainers.Tests/Unit/Configurations/DockerImageNameSubstitutionTest.cs b/tests/Testcontainers.Tests/Unit/Configurations/DockerImageNameSubstitutionTest.cs index e316dfb55..a0cb49875 100644 --- a/tests/Testcontainers.Tests/Unit/Configurations/DockerImageNameSubstitutionTest.cs +++ b/tests/Testcontainers.Tests/Unit/Configurations/DockerImageNameSubstitutionTest.cs @@ -13,8 +13,8 @@ public static class DockerImageNameSubstitutionTest [Collection(nameof(DockerImageNameSubstitutionTest))] public sealed class HubImageNamePrefixIsSet : IDisposable { - public static TheoryData Substitutions { get; } - = new TheoryData + public static TheoryData Substitutions { get; } = + new TheoryData { { "my.proxy.com", "bar", "my.proxy.com/bar:latest" }, { "my.proxy.com", "bar:latest", "my.proxy.com/bar:latest" }, @@ -25,21 +25,31 @@ public sealed class HubImageNamePrefixIsSet : IDisposable { "my.proxy.com/my-path", "foo/bar:1.0.0", "my.proxy.com/my-path/foo/bar:1.0.0" }, { "my.proxy.com:443", "foo/bar:1.0.0", "my.proxy.com:443/foo/bar:1.0.0" }, { "my.proxy.com:443/my-path", "foo/bar:1.0.0", "my.proxy.com:443/my-path/foo/bar:1.0.0" }, - { "my.proxy.com", "myregistry.azurecr.io/foo/bar:1.0.0", "myregistry.azurecr.io/foo/bar:1.0.0" }, - { "my.proxy.com", "myregistry.azurecr.io:443/foo/bar:1.0.0", "myregistry.azurecr.io:443/foo/bar:1.0.0" }, + { + "my.proxy.com", + "myregistry.azurecr.io/foo/bar:1.0.0", + "myregistry.azurecr.io/foo/bar:1.0.0" + }, + { + "my.proxy.com", + "myregistry.azurecr.io:443/foo/bar:1.0.0", + "myregistry.azurecr.io:443/foo/bar:1.0.0" + }, }; [Theory] [MemberData(nameof(Substitutions))] - public void PrependForStringConfiguration(string hubImageNamePrefix, string imageName, string expectedFullName) + public void PrependForStringConfiguration( + string hubImageNamePrefix, + string imageName, + string expectedFullName + ) { // Given TestcontainersSettings.HubImageNamePrefix = hubImageNamePrefix; // When - IContainer container = new ContainerBuilder() - .WithImage(imageName) - .Build(); + IContainer container = new ContainerBuilder().WithImage(imageName).Build(); // Then Assert.Equal(expectedFullName, container.Image.FullName); @@ -47,7 +57,11 @@ public void PrependForStringConfiguration(string hubImageNamePrefix, string imag [Theory] [MemberData(nameof(Substitutions))] - public void PrependForObjectConfiguration(string hubImageNamePrefix, string imageName, string expectedFullName) + public void PrependForObjectConfiguration( + string hubImageNamePrefix, + string imageName, + string expectedFullName + ) { // Given TestcontainersSettings.HubImageNamePrefix = hubImageNamePrefix; @@ -55,9 +69,7 @@ public void PrependForObjectConfiguration(string hubImageNamePrefix, string imag IImage image = new DockerImage(imageName); // When - IContainer container = new ContainerBuilder() - .WithImage(image) - .Build(); + IContainer container = new ContainerBuilder().WithImage(image).Build(); // Then Assert.Equal(expectedFullName, container.Image.FullName); @@ -84,9 +96,7 @@ public void DoNotPrependForStringConfiguration() const string imageName = "bar:latest"; // When - IContainer container = new ContainerBuilder() - .WithImage(imageName) - .Build(); + IContainer container = new ContainerBuilder().WithImage(imageName).Build(); // Then Assert.Equal(imageName, container.Image.FullName); @@ -101,9 +111,7 @@ public void DoNotPrependForObjectConfiguration() IImage image = new DockerImage(imageName); // When - IContainer container = new ContainerBuilder() - .WithImage(image) - .Build(); + IContainer container = new ContainerBuilder().WithImage(image).Build(); // Then Assert.Equal(imageName, container.Image.FullName); diff --git a/tests/Testcontainers.Tests/Unit/Configurations/DockerRegistryAuthenticationProviderTest.cs b/tests/Testcontainers.Tests/Unit/Configurations/DockerRegistryAuthenticationProviderTest.cs index 855d190c0..6424cde7f 100644 --- a/tests/Testcontainers.Tests/Unit/Configurations/DockerRegistryAuthenticationProviderTest.cs +++ b/tests/Testcontainers.Tests/Unit/Configurations/DockerRegistryAuthenticationProviderTest.cs @@ -56,9 +56,17 @@ public void GetHostnameFromHubImageNamePrefix(string repository, string tag) public void ShouldGetDefaultDockerRegistryAuthenticationConfiguration() { // Make sure the auth provider does not accidentally read the user's `config.json` file. - ICustomConfiguration customConfiguration = new PropertiesFileConfiguration(new[] { "docker.config=" + Path.Combine("C:", "CON") }); - var authenticationProvider = new DockerRegistryAuthenticationProvider(new DockerConfig(customConfiguration), NullLogger.Instance); - Assert.Equal(default(DockerRegistryAuthenticationConfiguration), authenticationProvider.GetAuthConfig("index.docker.io")); + ICustomConfiguration customConfiguration = new PropertiesFileConfiguration( + new[] { "docker.config=" + Path.Combine("C:", "CON") } + ); + var authenticationProvider = new DockerRegistryAuthenticationProvider( + new DockerConfig(customConfiguration), + NullLogger.Instance + ); + Assert.Equal( + default(DockerRegistryAuthenticationConfiguration), + authenticationProvider.GetAuthConfig("index.docker.io") + ); } public sealed class Base64ProviderTest @@ -70,11 +78,19 @@ public sealed class Base64ProviderTest [InlineData("{\"auths\":{\"ghcr.io\":{}}}", "ghcr", false)] [InlineData("{\"auths\":{\"http://ghcr.io\":{}}}", "ghcr.io", true)] [InlineData("{\"auths\":{\"https://ghcr.io\":{}}}", "ghcr.io", true)] - [InlineData("{\"auths\":{\"registry.example.com:5000\":{}}}", "registry.example.com:5000", true)] + [InlineData( + "{\"auths\":{\"registry.example.com:5000\":{}}}", + "registry.example.com:5000", + true + )] [InlineData("{\"auths\":{\"localhost:5000\":{}}}", "localhost:5000", true)] [InlineData("{\"auths\":{\"registry.example.com:5000\":{}}}", "registry.example.com", false)] [InlineData("{\"auths\":{\"localhost:5000\":{}}}", "localhost", false)] - [InlineData("{\"auths\":{\"https://registry.example.com:5000\":{}}}", "registry.example.com:5000", true)] + [InlineData( + "{\"auths\":{\"https://registry.example.com:5000\":{}}}", + "registry.example.com:5000", + true + )] [InlineData("{\"auths\":{\"http://localhost:8080\":{}}}", "localhost:8080", true)] [InlineData("{\"auths\":{\"docker.io\":{}}}", "docker.io", true)] [InlineData("{\"auths\":{\"docker.io\":{}}}", "index.docker.io", false)] @@ -87,8 +103,16 @@ public sealed class Base64ProviderTest [InlineData("{\"auths\":{\"localhost\":{}}}", "localhost", true)] [InlineData("{\"auths\":{\"127.0.0.1:5000\":{}}}", "127.0.0.1:5000", true)] [InlineData("{\"auths\":{\"[::1]:5000\":{}}}", "[::1]:5000", true)] - [InlineData("{\"auths\":{\"https://registry.example.com/v2\":{}}}", "registry.example.com", true)] - public void ResolvePartialDockerRegistry(string jsonDocument, string hostname, bool expectedResult) + [InlineData( + "{\"auths\":{\"https://registry.example.com/v2\":{}}}", + "registry.example.com", + true + )] + public void ResolvePartialDockerRegistry( + string jsonDocument, + string hostname, + bool expectedResult + ) { // Given var jsonElement = JsonDocument.Parse(jsonDocument).RootElement; @@ -106,11 +130,31 @@ public void ResolvePartialDockerRegistry(string jsonDocument, string hostname, b [InlineData("{\"auths\":{}}", false, null)] [InlineData("{\"auths\":{\"ghcr.io\":{}}}", false, null)] [InlineData("{\"auths\":{\"" + DockerRegistry + "\":{}}}", true, null)] - [InlineData("{\"auths\":{\"" + DockerRegistry + "\":{\"auth\":null}}}", true, "The \"auth\" property value for https://index.docker.io/v1/ not found")] - [InlineData("{\"auths\":{\"" + DockerRegistry + "\":{\"auth\":\"\"}}}", true, "The \"auth\" property value for https://index.docker.io/v1/ not found")] - [InlineData("{\"auths\":{\"" + DockerRegistry + "\":{\"auth\":{}}}}", true, "The \"auth\" property value kind for https://index.docker.io/v1/ is invalid: Object")] - [InlineData("{\"auths\":{\"" + DockerRegistry + "\":{\"auth\":\"Not_Base64_encoded\"}}}", true, "The \"auth\" property value for https://index.docker.io/v1/ is not a valid Base64 string")] - [InlineData("{\"auths\":{\"" + DockerRegistry + "\":{\"auth\":\"dXNlcm5hbWU=\"}}}", true, "The \"auth\" property value for https://index.docker.io/v1/ should contain one colon separating the username and the password (basic authentication)")] + [InlineData( + "{\"auths\":{\"" + DockerRegistry + "\":{\"auth\":null}}}", + true, + "The \"auth\" property value for https://index.docker.io/v1/ not found" + )] + [InlineData( + "{\"auths\":{\"" + DockerRegistry + "\":{\"auth\":\"\"}}}", + true, + "The \"auth\" property value for https://index.docker.io/v1/ not found" + )] + [InlineData( + "{\"auths\":{\"" + DockerRegistry + "\":{\"auth\":{}}}}", + true, + "The \"auth\" property value kind for https://index.docker.io/v1/ is invalid: Object" + )] + [InlineData( + "{\"auths\":{\"" + DockerRegistry + "\":{\"auth\":\"Not_Base64_encoded\"}}}", + true, + "The \"auth\" property value for https://index.docker.io/v1/ is not a valid Base64 string" + )] + [InlineData( + "{\"auths\":{\"" + DockerRegistry + "\":{\"auth\":\"dXNlcm5hbWU=\"}}}", + true, + "The \"auth\" property value for https://index.docker.io/v1/ should contain one colon separating the username and the password (basic authentication)" + )] [InlineData("{\"auths\":{\"" + DockerRegistry + "\":{\"identitytoken\":null}}}", true, null)] [InlineData("{\"auths\":{\"" + DockerRegistry + "\":{\"identitytoken\":\"\"}}}", true, null)] [InlineData("{\"auths\":{\"" + DockerRegistry + "\":{\"identitytoken\":{}}}}", true, null)] @@ -138,9 +182,24 @@ public void ShouldGetNull(string jsonDocument, bool isApplicable, string logMess } [Theory] - [InlineData("{\"auths\":{\"" + DockerRegistry + "\":{\"auth\":\"dXNlcm5hbWU6cGFzc3dvcmQ=\"}}}", "username", "password", null)] - [InlineData("{\"auths\":{\"" + DockerRegistry + "\":{\"identitytoken\":\"identitytoken\"}}}", null, null, "identitytoken")] - public void ShouldGetAuthConfig(string jsonDocument, string expectedUsername, string expectedPassword, string expectedIdentityToken) + [InlineData( + "{\"auths\":{\"" + DockerRegistry + "\":{\"auth\":\"dXNlcm5hbWU6cGFzc3dvcmQ=\"}}}", + "username", + "password", + null + )] + [InlineData( + "{\"auths\":{\"" + DockerRegistry + "\":{\"identitytoken\":\"identitytoken\"}}}", + null, + null, + "identitytoken" + )] + public void ShouldGetAuthConfig( + string jsonDocument, + string expectedUsername, + string expectedPassword, + string expectedIdentityToken + ) { // Given var jsonElement = JsonDocument.Parse(jsonDocument).RootElement; @@ -184,7 +243,10 @@ public void ShouldGetNull(string jsonDocument, bool isApplicable) public void ShouldGetAuthConfig() { // Given - var credsStoreScriptName = Path.ChangeExtension("desktop", RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "bat" : "sh"); + var credsStoreScriptName = Path.ChangeExtension( + "desktop", + RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "bat" : "sh" + ); var jsonDocument = "{\"credsStore\":\"" + credsStoreScriptName + "\"}"; var jsonElement = JsonDocument.Parse(jsonDocument).RootElement; @@ -229,11 +291,20 @@ public void ShouldGetNull(string jsonDocument, bool isApplicable) [Theory] [InlineData("password", "username", "password", null)] [InlineData("token", null, null, "identitytoken")] - public void ShouldGetAuthConfig(string credHelperName, string expectedUsername, string expectedPassword, string expectedIdentityToken) + public void ShouldGetAuthConfig( + string credHelperName, + string expectedUsername, + string expectedPassword, + string expectedIdentityToken + ) { // Given - var credHelpersScriptName = Path.ChangeExtension(credHelperName, RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "bat" : "sh"); - var jsonDocument = "{\"credHelpers\":{\"" + DockerRegistry + "\":\"" + credHelpersScriptName + "\"}}"; + var credHelpersScriptName = Path.ChangeExtension( + credHelperName, + RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "bat" : "sh" + ); + var jsonDocument = + "{\"credHelpers\":{\"" + DockerRegistry + "\":\"" + credHelpersScriptName + "\"}}"; var jsonElement = JsonDocument.Parse(jsonDocument).RootElement; // When @@ -254,39 +325,45 @@ public abstract class SetEnvVarPath { static SetEnvVarPath() { - Environment.SetEnvironmentVariable("PATH", string.Join(Path.PathSeparator, (Environment.GetEnvironmentVariable("PATH") ?? string.Empty) - .Split(Path.PathSeparator) - .Prepend(Path.Combine(Environment.CurrentDirectory, "Assets", "credHelpers")) - .Prepend(Path.Combine(Environment.CurrentDirectory, "Assets", "credsStore")) - .Distinct())); + Environment.SetEnvironmentVariable( + "PATH", + string.Join( + Path.PathSeparator, + (Environment.GetEnvironmentVariable("PATH") ?? string.Empty) + .Split(Path.PathSeparator) + .Prepend(Path.Combine(Environment.CurrentDirectory, "Assets", "credHelpers")) + .Prepend(Path.Combine(Environment.CurrentDirectory, "Assets", "credsStore")) + .Distinct() + ) + ); } } private sealed class Disposable : IDisposable { - static Disposable() - { - } + static Disposable() { } - private Disposable() - { - } + private Disposable() { } - public static IDisposable Empty { get; } - = new Disposable(); + public static IDisposable Empty { get; } = new Disposable(); - public void Dispose() - { - } + public void Dispose() { } } private sealed class WarnLogger : ILogger { - private readonly IList> _logMessages = new List>(); + private readonly IList> _logMessages = + new List>(); public IEnumerable> LogMessages => _logMessages; - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception exception, + Func formatter + ) { if (IsEnabled(logLevel)) { diff --git a/tests/Testcontainers.Tests/Unit/Configurations/ResourcePropertiesTest.cs b/tests/Testcontainers.Tests/Unit/Configurations/ResourcePropertiesTest.cs index e5235b892..11843ebea 100644 --- a/tests/Testcontainers.Tests/Unit/Configurations/ResourcePropertiesTest.cs +++ b/tests/Testcontainers.Tests/Unit/Configurations/ResourcePropertiesTest.cs @@ -14,47 +14,60 @@ public sealed class ResourcePropertiesTest { private static readonly string ResourceIdOrName = Guid.NewGuid().ToString("D"); - private static readonly ITestcontainersClient Client = new TestcontainersClient(Guid.Empty, TestcontainersSettings.OS.DockerEndpointAuthConfig, NullLogger.Instance); + private static readonly ITestcontainersClient Client = new TestcontainersClient( + Guid.Empty, + TestcontainersSettings.OS.DockerEndpointAuthConfig, + NullLogger.Instance + ); [Fact] public async Task QueryNotExistingDockerContainerById() { - Assert.False(await Client.Container.ExistsWithIdAsync(ResourceIdOrName, TestContext.Current.CancellationToken) - .ConfigureAwait(true)); + Assert.False( + await Client + .Container.ExistsWithIdAsync(ResourceIdOrName, TestContext.Current.CancellationToken) + .ConfigureAwait(true) + ); } [Fact] public async Task QueryNotExistingDockerImageById() { - Assert.False(await Client.Image.ExistsWithIdAsync(ResourceIdOrName, TestContext.Current.CancellationToken) - .ConfigureAwait(true)); + Assert.False( + await Client + .Image.ExistsWithIdAsync(ResourceIdOrName, TestContext.Current.CancellationToken) + .ConfigureAwait(true) + ); } [Fact] public async Task QueryNotExistingDockerNetworkById() { - Assert.False(await Client.Network.ExistsWithIdAsync(ResourceIdOrName, TestContext.Current.CancellationToken) - .ConfigureAwait(true)); + Assert.False( + await Client + .Network.ExistsWithIdAsync(ResourceIdOrName, TestContext.Current.CancellationToken) + .ConfigureAwait(true) + ); } [Fact] public async Task QueryNotExistingDockerVolumeById() { - Assert.False(await Client.Volume.ExistsWithIdAsync(ResourceIdOrName, TestContext.Current.CancellationToken) - .ConfigureAwait(true)); + Assert.False( + await Client + .Volume.ExistsWithIdAsync(ResourceIdOrName, TestContext.Current.CancellationToken) + .ConfigureAwait(true) + ); } [Fact] public async Task QueryContainerInformationOfCreatedContainer() { // Given - var container = new ContainerBuilder() - .WithImage(CommonImages.Nginx) - .Build(); + var container = new ContainerBuilder().WithImage(CommonImages.Nginx).Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); // Then Assert.NotEmpty(container.Id); @@ -68,13 +81,10 @@ await container.StartAsync(TestContext.Current.CancellationToken) public async Task QueryContainerInformationOfNotCreatedContainer() { // Given - var container = new ContainerBuilder() - .WithImage(CommonImages.Nginx) - .Build(); + var container = new ContainerBuilder().WithImage(CommonImages.Nginx).Build(); // When - await Task.CompletedTask - .ConfigureAwait(true); + await Task.CompletedTask.ConfigureAwait(true); // Then Assert.Throws(() => container.Id); @@ -90,12 +100,10 @@ await Task.CompletedTask public async Task QueryImageInformationOfNotCreatedImage() { // Given - var image = new ImageFromDockerfileBuilder() - .Build(); + var image = new ImageFromDockerfileBuilder().Build(); // When - await Task.CompletedTask - .ConfigureAwait(true); + await Task.CompletedTask.ConfigureAwait(true); // Then Assert.Throws(() => image.Repository); @@ -113,8 +121,7 @@ public async Task QueryNetworkInformationOfNotCreatedNetwork() var network = new NetworkBuilder().Build(); // When - await Task.CompletedTask - .ConfigureAwait(true); + await Task.CompletedTask.ConfigureAwait(true); // Then Assert.Throws(() => network.Name); @@ -127,8 +134,7 @@ public async Task QueryVolumeInformationOfNotCreatedVolume() var volume = new VolumeBuilder().Build(); // When - await Task.CompletedTask - .ConfigureAwait(true); + await Task.CompletedTask.ConfigureAwait(true); // Then Assert.Throws(() => volume.Name); diff --git a/tests/Testcontainers.Tests/Unit/Configurations/TestcontainersWaitStrategyTest.cs b/tests/Testcontainers.Tests/Unit/Configurations/TestcontainersWaitStrategyTest.cs index 08c32e684..eb8ff2eb0 100644 --- a/tests/Testcontainers.Tests/Unit/Configurations/TestcontainersWaitStrategyTest.cs +++ b/tests/Testcontainers.Tests/Unit/Configurations/TestcontainersWaitStrategyTest.cs @@ -13,7 +13,15 @@ public sealed class Finish : IWaitUntil, IWaitWhile [Fact] public async Task ImmediatelyUntil() { - var exception = await Record.ExceptionAsync(() => WaitStrategy.WaitUntilAsync(() => UntilAsync(null), TimeSpan.FromMilliseconds(25), TimeSpan.FromMilliseconds(100), ct: TestContext.Current.CancellationToken)) + var exception = await Record + .ExceptionAsync(() => + WaitStrategy.WaitUntilAsync( + () => UntilAsync(null), + TimeSpan.FromMilliseconds(25), + TimeSpan.FromMilliseconds(100), + ct: TestContext.Current.CancellationToken + ) + ) .ConfigureAwait(true); Assert.Null(exception); @@ -22,7 +30,15 @@ public async Task ImmediatelyUntil() [Fact] public async Task ImmediatelyWhile() { - var exception = await Record.ExceptionAsync(() => WaitStrategy.WaitWhileAsync(() => WhileAsync(null), TimeSpan.FromMilliseconds(25), TimeSpan.FromMilliseconds(100), ct: TestContext.Current.CancellationToken)) + var exception = await Record + .ExceptionAsync(() => + WaitStrategy.WaitWhileAsync( + () => WhileAsync(null), + TimeSpan.FromMilliseconds(25), + TimeSpan.FromMilliseconds(100), + ct: TestContext.Current.CancellationToken + ) + ) .ConfigureAwait(true); Assert.Null(exception); @@ -44,13 +60,27 @@ public sealed class Timeout : IWaitUntil, IWaitWhile [Fact] public Task After100MsUntil() { - return Assert.ThrowsAsync(() => WaitStrategy.WaitUntilAsync(() => UntilAsync(null), TimeSpan.FromMilliseconds(25), TimeSpan.FromMilliseconds(100), ct: TestContext.Current.CancellationToken)); + return Assert.ThrowsAsync(() => + WaitStrategy.WaitUntilAsync( + () => UntilAsync(null), + TimeSpan.FromMilliseconds(25), + TimeSpan.FromMilliseconds(100), + ct: TestContext.Current.CancellationToken + ) + ); } [Fact] public Task After100MsWhile() { - return Assert.ThrowsAsync(() => WaitStrategy.WaitWhileAsync(() => WhileAsync(null), TimeSpan.FromMilliseconds(25), TimeSpan.FromMilliseconds(100), ct: TestContext.Current.CancellationToken)); + return Assert.ThrowsAsync(() => + WaitStrategy.WaitWhileAsync( + () => WhileAsync(null), + TimeSpan.FromMilliseconds(25), + TimeSpan.FromMilliseconds(100), + ct: TestContext.Current.CancellationToken + ) + ); } public Task UntilAsync(IContainer container) @@ -69,13 +99,27 @@ public sealed class Rethrow : IWaitUntil, IWaitWhile [Fact] public Task RethrowUntil() { - return Assert.ThrowsAsync(() => WaitStrategy.WaitUntilAsync(() => UntilAsync(null), TimeSpan.FromMilliseconds(25), TimeSpan.FromMilliseconds(100), ct: TestContext.Current.CancellationToken)); + return Assert.ThrowsAsync(() => + WaitStrategy.WaitUntilAsync( + () => UntilAsync(null), + TimeSpan.FromMilliseconds(25), + TimeSpan.FromMilliseconds(100), + ct: TestContext.Current.CancellationToken + ) + ); } [Fact] public Task RethrowWhile() { - return Assert.ThrowsAsync(() => WaitStrategy.WaitWhileAsync(() => WhileAsync(null), TimeSpan.FromMilliseconds(25), TimeSpan.FromMilliseconds(100), ct: TestContext.Current.CancellationToken)); + return Assert.ThrowsAsync(() => + WaitStrategy.WaitWhileAsync( + () => WhileAsync(null), + TimeSpan.FromMilliseconds(25), + TimeSpan.FromMilliseconds(100), + ct: TestContext.Current.CancellationToken + ) + ); } public Task UntilAsync(IContainer container) diff --git a/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilContainerIsHealthyTest.cs b/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilContainerIsHealthyTest.cs index d4585007e..afae2426f 100644 --- a/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilContainerIsHealthyTest.cs +++ b/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilContainerIsHealthyTest.cs @@ -27,8 +27,7 @@ public async Task ContainerHealthCheckShouldBeHealthy() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); // Then Assert.Equal(TestcontainersHealthStatus.Healthy, container.Health); @@ -45,7 +44,8 @@ public async Task ContainerHealthCheckShouldBeUnhealthy() .Build(); // When - _ = await Record.ExceptionAsync(() => container.StartAsync(TestContext.Current.CancellationToken)) + _ = await Record + .ExceptionAsync(() => container.StartAsync(TestContext.Current.CancellationToken)) .ConfigureAwait(true); // Then diff --git a/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilExternalTcpPortIsAvailable.cs b/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilExternalTcpPortIsAvailable.cs index f43c52c39..408833951 100644 --- a/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilExternalTcpPortIsAvailable.cs +++ b/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilExternalTcpPortIsAvailable.cs @@ -28,8 +28,7 @@ public sealed class WaitUntilExternalTcpPortIsAvailable : IAsyncLifetime public async ValueTask InitializeAsync() { - await _container.StartAsync() - .ConfigureAwait(false); + await _container.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -44,8 +43,7 @@ public async Task SucceedsWhenPortIsMappedAndListening() var waitStrategy = new UntilExternalTcpPortIsAvailable(ListeningPort); // When - var success = await waitStrategy.UntilAsync(_container) - .ConfigureAwait(true); + var success = await waitStrategy.UntilAsync(_container).ConfigureAwait(true); // Then Assert.True(success); @@ -58,8 +56,7 @@ public async Task SucceedsWhenPortIsMappedButNotListening() var waitStrategy = new UntilExternalTcpPortIsAvailable(MappedPort); // When - var success = await waitStrategy.UntilAsync(_container) - .ConfigureAwait(true); + var success = await waitStrategy.UntilAsync(_container).ConfigureAwait(true); // Then Assert.True(success); @@ -69,7 +66,9 @@ public async Task SucceedsWhenPortIsMappedButNotListening() public Task ThrowsWhenPortIsNotMapped() { var waitStrategy = new UntilExternalTcpPortIsAvailable(UnmappedPort); - return Assert.ThrowsAsync(() => waitStrategy.UntilAsync(_container)); + return Assert.ThrowsAsync(() => + waitStrategy.UntilAsync(_container) + ); } } } diff --git a/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilFileExistsInContainerTest.cs b/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilFileExistsInContainerTest.cs index eb0105c19..dd1177913 100644 --- a/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilFileExistsInContainerTest.cs +++ b/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilFileExistsInContainerTest.cs @@ -14,19 +14,22 @@ public sealed class WaitUntilFileExistsInContainerTest : IAsyncLifetime, IDispos { private const string ContainerFilePath = "/tmp/hostname"; - private readonly CancellationTokenSource _cts = new CancellationTokenSource(TimeSpan.FromMinutes(1)); + private readonly CancellationTokenSource _cts = new CancellationTokenSource( + TimeSpan.FromMinutes(1) + ); private readonly IContainer _container = new ContainerBuilder() .WithImage(CommonImages.Alpine) .WithEntrypoint("/bin/sh", "-c") .WithCommand("hostname > " + ContainerFilePath + "; trap : TERM INT; sleep infinity & wait") - .WithWaitStrategy(Wait.ForUnixContainer().UntilFileExists(ContainerFilePath, FileSystem.Container)) + .WithWaitStrategy( + Wait.ForUnixContainer().UntilFileExists(ContainerFilePath, FileSystem.Container) + ) .Build(); public async ValueTask InitializeAsync() { - await _container.StartAsync(_cts.Token) - .ConfigureAwait(false); + await _container.StartAsync(_cts.Token).ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -42,7 +45,11 @@ public void Dispose() [Fact] public async Task ContainerIsRunning() { - var execResult = await _container.ExecAsync(new List { "test", "-f", ContainerFilePath }, TestContext.Current.CancellationToken) + var execResult = await _container + .ExecAsync( + new List { "test", "-f", ContainerFilePath }, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); Assert.Equal(0, execResult.ExitCode); diff --git a/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilHttpRequestIsSucceededTest.cs b/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilHttpRequestIsSucceededTest.cs index 4317f9b96..abe637f04 100644 --- a/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilHttpRequestIsSucceededTest.cs +++ b/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilHttpRequestIsSucceededTest.cs @@ -13,7 +13,8 @@ namespace DotNet.Testcontainers.Tests.Unit using JetBrains.Annotations; using Xunit; - public sealed class WaitUntilHttpRequestIsSucceededTest : IClassFixture + public sealed class WaitUntilHttpRequestIsSucceededTest + : IClassFixture { private const ushort HttpPort = 80; @@ -24,23 +25,28 @@ public WaitUntilHttpRequestIsSucceededTest(HttpFixture httpFixture) _container = httpFixture.Container; } - public static TheoryData HttpWaitStrategies { get; } - = new TheoryData + public static TheoryData HttpWaitStrategies { get; } = + new TheoryData { new HttpWaitStrategy(), new HttpWaitStrategy().ForPort(HttpPort), new HttpWaitStrategy().ForStatusCode(HttpStatusCode.OK), - new HttpWaitStrategy().ForStatusCodeMatching(statusCode => HttpStatusCode.OK.Equals(statusCode)), - new HttpWaitStrategy().ForResponseMessageMatching(response => Task.FromResult(response.IsSuccessStatusCode)), - new HttpWaitStrategy().ForStatusCode(HttpStatusCode.MovedPermanently).ForStatusCodeMatching(statusCode => HttpStatusCode.OK.Equals(statusCode)), + new HttpWaitStrategy().ForStatusCodeMatching(statusCode => + HttpStatusCode.OK.Equals(statusCode) + ), + new HttpWaitStrategy().ForResponseMessageMatching(response => + Task.FromResult(response.IsSuccessStatusCode) + ), + new HttpWaitStrategy() + .ForStatusCode(HttpStatusCode.MovedPermanently) + .ForStatusCodeMatching(statusCode => HttpStatusCode.OK.Equals(statusCode)), }; [Theory] [MemberData(nameof(HttpWaitStrategies))] public async Task HttpWaitStrategyReceivesStatusCode(HttpWaitStrategy httpWaitStrategy) { - var succeeded = await httpWaitStrategy.UntilAsync(_container) - .ConfigureAwait(true); + var succeeded = await httpWaitStrategy.UntilAsync(_container).ConfigureAwait(true); Assert.True(succeeded); } @@ -55,16 +61,18 @@ public async Task HttpWaitStrategySendsHeaders() var httpHeaders = new Dictionary { { "Connection", "keep-alive" } }; - var httpWaitStrategy = new HttpWaitStrategy().WithBasicAuthentication(username, password).WithHeaders(httpHeaders); + var httpWaitStrategy = new HttpWaitStrategy() + .WithBasicAuthentication(username, password) + .WithHeaders(httpHeaders); // When - var succeeded = await httpWaitStrategy.UntilAsync(_container) - .ConfigureAwait(true); + var succeeded = await httpWaitStrategy.UntilAsync(_container).ConfigureAwait(true); await Task.Delay(TimeSpan.FromSeconds(1), TestContext.Current.CancellationToken) .ConfigureAwait(true); - var (_, stderr) = await _container.GetLogsAsync(ct: TestContext.Current.CancellationToken) + var (_, stderr) = await _container + .GetLogsAsync(ct: TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -88,13 +96,13 @@ public async Task HttpWaitStrategyUsesCustomHttpClientHandler() var httpWaitStrategy = new HttpWaitStrategy().UsingHttpMessageHandler(httpMessageHandler); // When - var succeeded = await httpWaitStrategy.UntilAsync(_container) - .ConfigureAwait(true); + var succeeded = await httpWaitStrategy.UntilAsync(_container).ConfigureAwait(true); await Task.Delay(TimeSpan.FromSeconds(1), TestContext.Current.CancellationToken) .ConfigureAwait(true); - var (_, stderr) = await _container.GetLogsAsync(ct: TestContext.Current.CancellationToken) + var (_, stderr) = await _container + .GetLogsAsync(ct: TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -112,10 +120,10 @@ public async Task HttpWaitStrategyReusesCustomHttpClientHandler() var httpWaitStrategy = new HttpWaitStrategy().UsingHttpMessageHandler(httpMessageHandler); // When - await httpWaitStrategy.UntilAsync(_container) - .ConfigureAwait(true); + await httpWaitStrategy.UntilAsync(_container).ConfigureAwait(true); - var exceptionOnSubsequentCall = await Record.ExceptionAsync(() => httpWaitStrategy.UntilAsync(_container)) + var exceptionOnSubsequentCall = await Record + .ExceptionAsync(() => httpWaitStrategy.UntilAsync(_container)) .ConfigureAwait(true); // Then @@ -125,14 +133,15 @@ await httpWaitStrategy.UntilAsync(_container) [UsedImplicitly] public sealed class HttpFixture : IAsyncLifetime { - public IContainer Container { get; } = new ContainerBuilder() - .WithImage(CommonImages.Socat) - .WithCommand("-v") - .WithCommand($"TCP-LISTEN:{HttpPort},crlf,reuseaddr,fork") - .WithCommand("SYSTEM:'echo -e \"HTTP/1.1 200 OK\\nContent-Length: 0\\n\\n\"'") - .WithPortBinding(HttpPort, true) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => request)) - .Build(); + public IContainer Container { get; } = + new ContainerBuilder() + .WithImage(CommonImages.Socat) + .WithCommand("-v") + .WithCommand($"TCP-LISTEN:{HttpPort},crlf,reuseaddr,fork") + .WithCommand("SYSTEM:'echo -e \"HTTP/1.1 200 OK\\nContent-Length: 0\\n\\n\"'") + .WithPortBinding(HttpPort, true) + .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => request)) + .Build(); public ValueTask InitializeAsync() { diff --git a/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilMessageIsLoggedTest.cs b/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilMessageIsLoggedTest.cs index 0661ef425..63c16184f 100644 --- a/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilMessageIsLoggedTest.cs +++ b/tests/Testcontainers.Tests/Unit/Configurations/WaitUntilMessageIsLoggedTest.cs @@ -10,7 +10,9 @@ namespace DotNet.Testcontainers.Tests.Unit public sealed class WaitUntilMessageIsLoggedTest : IAsyncLifetime, IDisposable { - private readonly CancellationTokenSource _cts = new CancellationTokenSource(TimeSpan.FromMinutes(1)); + private readonly CancellationTokenSource _cts = new CancellationTokenSource( + TimeSpan.FromMinutes(1) + ); private readonly IContainer _container; @@ -26,8 +28,7 @@ public WaitUntilMessageIsLoggedTest() public async ValueTask InitializeAsync() { - await _container.StartAsync(_cts.Token) - .ConfigureAwait(false); + await _container.StartAsync(_cts.Token).ConfigureAwait(false); } public ValueTask DisposeAsync() diff --git a/tests/Testcontainers.Tests/Unit/Containers/Unix/GetContainerLogsTest.cs b/tests/Testcontainers.Tests/Unit/Containers/Unix/GetContainerLogsTest.cs index 960878350..31989bbff 100644 --- a/tests/Testcontainers.Tests/Unit/Containers/Unix/GetContainerLogsTest.cs +++ b/tests/Testcontainers.Tests/Unit/Containers/Unix/GetContainerLogsTest.cs @@ -10,14 +10,14 @@ public sealed class GetContainerLogsTest : IAsyncLifetime { private readonly IContainer _container = new ContainerBuilder() .WithImage("amazon/dynamodb-local:1.20.0") - .WithWaitStrategy(Wait.ForUnixContainer() - .UntilPortIsAvailable(8000)) + .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(8000)) .Build(); [Fact] public async Task GetLogsShouldNotBeEmpty() { - var (stdout, _) = await _container.GetLogsAsync(ct: TestContext.Current.CancellationToken) + var (stdout, _) = await _container + .GetLogsAsync(ct: TestContext.Current.CancellationToken) .ConfigureAwait(true); Assert.NotEmpty(stdout); @@ -26,7 +26,8 @@ public async Task GetLogsShouldNotBeEmpty() [Fact] public async Task GetLogsShouldBeEmptyWhenSinceIsOutOfDateRage() { - var (stdout, stderr) = await _container.GetLogsAsync(since: DateTime.Now.AddDays(1), ct: TestContext.Current.CancellationToken) + var (stdout, stderr) = await _container + .GetLogsAsync(since: DateTime.Now.AddDays(1), ct: TestContext.Current.CancellationToken) .ConfigureAwait(true); Assert.Empty(stdout); @@ -36,7 +37,8 @@ public async Task GetLogsShouldBeEmptyWhenSinceIsOutOfDateRage() [Fact] public async Task GetLogsShouldBeEmptyWhenUntilIsOutOfDateRage() { - var (stdout, stderr) = await _container.GetLogsAsync(until: DateTime.Now.AddDays(-1), ct: TestContext.Current.CancellationToken) + var (stdout, stderr) = await _container + .GetLogsAsync(until: DateTime.Now.AddDays(-1), ct: TestContext.Current.CancellationToken) .ConfigureAwait(true); Assert.Empty(stdout); @@ -45,8 +47,7 @@ public async Task GetLogsShouldBeEmptyWhenUntilIsOutOfDateRage() public async ValueTask InitializeAsync() { - await _container.StartAsync() - .ConfigureAwait(false); + await _container.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() diff --git a/tests/Testcontainers.Tests/Unit/Containers/Unix/ProtectDockerDaemonSocketTest.cs b/tests/Testcontainers.Tests/Unit/Containers/Unix/ProtectDockerDaemonSocketTest.cs index e73f7367a..300205c28 100644 --- a/tests/Testcontainers.Tests/Unit/Containers/Unix/ProtectDockerDaemonSocketTest.cs +++ b/tests/Testcontainers.Tests/Unit/Containers/Unix/ProtectDockerDaemonSocketTest.cs @@ -14,10 +14,20 @@ namespace DotNet.Testcontainers.Tests.Unit public static class ProtectDockerDaemonSocketTest { - private static IDockerEndpointAuthenticationConfiguration GetAuthConfig(ProtectDockerDaemonSocket protectDockerDaemonSocket) + private static IDockerEndpointAuthenticationConfiguration GetAuthConfig( + ProtectDockerDaemonSocket protectDockerDaemonSocket + ) { - var customConfiguration = new PropertiesFileConfiguration(protectDockerDaemonSocket.CustomProperties.ToArray()); - return new IDockerEndpointAuthenticationProvider[] { new MTlsEndpointAuthenticationProvider(customConfiguration), new TlsEndpointAuthenticationProvider(customConfiguration) }.First(authProvider => authProvider.IsApplicable()).GetAuthConfig(); + var customConfiguration = new PropertiesFileConfiguration( + protectDockerDaemonSocket.CustomProperties.ToArray() + ); + return new IDockerEndpointAuthenticationProvider[] + { + new MTlsEndpointAuthenticationProvider(customConfiguration), + new TlsEndpointAuthenticationProvider(customConfiguration), + } + .First(authProvider => authProvider.IsApplicable()) + .GetAuthConfig(); } public sealed class MTlsOpenSsl1_1_1 : IClassFixture @@ -39,7 +49,8 @@ public async Task GetVersionReturnsVersion() var client = new TestcontainersClient(Guid.Empty, _authConfig, NullLogger.Instance); // When - var version = await client.System.GetVersionAsync(TestContext.Current.CancellationToken) + var version = await client + .System.GetVersionAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -67,7 +78,8 @@ public async Task GetVersionReturnsVersion() var client = new TestcontainersClient(Guid.Empty, _authConfig, NullLogger.Instance); // When - var version = await client.System.GetVersionAsync(TestContext.Current.CancellationToken) + var version = await client + .System.GetVersionAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -95,7 +107,8 @@ public async Task GetVersionReturnsVersion() var client = new TestcontainersClient(Guid.Empty, _authConfig, NullLogger.Instance); // When - var version = await client.System.GetVersionAsync(TestContext.Current.CancellationToken) + var version = await client + .System.GetVersionAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then diff --git a/tests/Testcontainers.Tests/Unit/Containers/Unix/ReadFileFromContainerTest.cs b/tests/Testcontainers.Tests/Unit/Containers/Unix/ReadFileFromContainerTest.cs index 2fabb1e0d..858742114 100644 --- a/tests/Testcontainers.Tests/Unit/Containers/Unix/ReadFileFromContainerTest.cs +++ b/tests/Testcontainers.Tests/Unit/Containers/Unix/ReadFileFromContainerTest.cs @@ -25,10 +25,15 @@ public async Task ReadExistingFile() var dayOfWeek = DateTime.UtcNow.DayOfWeek.ToString(); // When - _ = await _container.ExecAsync(new[] { "/bin/sh", "-c", $"echo {dayOfWeek} > {dayOfWeekFilePath}" }, TestContext.Current.CancellationToken) + _ = await _container + .ExecAsync( + new[] { "/bin/sh", "-c", $"echo {dayOfWeek} > {dayOfWeekFilePath}" }, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - var fileContent = await _container.ReadFileAsync(dayOfWeekFilePath, TestContext.Current.CancellationToken) + var fileContent = await _container + .ReadFileAsync(dayOfWeekFilePath, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -38,19 +43,22 @@ public async Task ReadExistingFile() [Fact] public Task AccessNotExistingFileThrowsFileNotFoundException() { - return Assert.ThrowsAsync(() => _container.ReadFileAsync("/tmp/fileNotFound", TestContext.Current.CancellationToken)); + return Assert.ThrowsAsync(() => + _container.ReadFileAsync("/tmp/fileNotFound", TestContext.Current.CancellationToken) + ); } [Fact] public Task AccessDirectoryThrowsInvalidOperationException() { - return Assert.ThrowsAsync(() => _container.ReadFileAsync("/tmp", TestContext.Current.CancellationToken)); + return Assert.ThrowsAsync(() => + _container.ReadFileAsync("/tmp", TestContext.Current.CancellationToken) + ); } public async ValueTask InitializeAsync() { - await _container.StartAsync() - .ConfigureAwait(false); + await _container.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() diff --git a/tests/Testcontainers.Tests/Unit/Containers/Unix/TestcontainersContainerCancellationTest.cs b/tests/Testcontainers.Tests/Unit/Containers/Unix/TestcontainersContainerCancellationTest.cs index d1a715fbe..ec3e59896 100644 --- a/tests/Testcontainers.Tests/Unit/Containers/Unix/TestcontainersContainerCancellationTest.cs +++ b/tests/Testcontainers.Tests/Unit/Containers/Unix/TestcontainersContainerCancellationTest.cs @@ -24,10 +24,17 @@ public async Task Start() // Given using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); - var expectedExceptions = new[] { typeof(TaskCanceledException), typeof(OperationCanceledException), typeof(TimeoutException), typeof(IOException) }; + var expectedExceptions = new[] + { + typeof(TaskCanceledException), + typeof(OperationCanceledException), + typeof(TimeoutException), + typeof(IOException), + }; // When - var exception = await Assert.ThrowsAnyAsync(() => _alpineFixture.Container.StartAsync(cts.Token)) + var exception = await Assert + .ThrowsAnyAsync(() => _alpineFixture.Container.StartAsync(cts.Token)) .ConfigureAwait(true); // Then diff --git a/tests/Testcontainers.Tests/Unit/Containers/Unix/TestcontainersContainerTest.cs b/tests/Testcontainers.Tests/Unit/Containers/Unix/TestcontainersContainerTest.cs index 0d7710fed..067bc2a3b 100644 --- a/tests/Testcontainers.Tests/Unit/Containers/Unix/TestcontainersContainerTest.cs +++ b/tests/Testcontainers.Tests/Unit/Containers/Unix/TestcontainersContainerTest.cs @@ -34,8 +34,7 @@ public async Task GeneratedContainerName() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); // Then Assert.NotEmpty(container.Name); @@ -54,8 +53,7 @@ public async Task SpecifiedContainerName() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); // Then Assert.EndsWith(name, container.Name); @@ -74,10 +72,10 @@ public async Task Hostname() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); - var exitCode = await container.GetExitCodeAsync(TestContext.Current.CancellationToken) + var exitCode = await container + .GetExitCodeAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -97,8 +95,7 @@ public async Task MacAddress() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); // Then Assert.Equal(macAddress, container.MacAddress); @@ -115,10 +112,10 @@ public async Task WorkingDirectory() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); - var exitCode = await container.GetExitCodeAsync(TestContext.Current.CancellationToken) + var exitCode = await container + .GetExitCodeAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -135,10 +132,10 @@ public async Task Entrypoint() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); - var exitCode = await container.GetExitCodeAsync(TestContext.Current.CancellationToken) + var exitCode = await container + .GetExitCodeAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -151,20 +148,25 @@ public async Task StaticPortBinding() // Given const ushort containerPort = 80; - using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + using var socket = new Socket( + AddressFamily.InterNetwork, + SocketType.Stream, + ProtocolType.Tcp + ); socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); var hostPort = ((IPEndPoint)socket.LocalEndPoint).Port; await using var container = new ContainerBuilder() .WithImage(CommonImages.Nginx) .WithPortBinding(hostPort, containerPort) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPort(containerPort))) + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => request.ForPort(containerPort)) + ) .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); // Then Assert.Equal(hostPort, container.GetMappedPublicPort(containerPort)); @@ -185,8 +187,7 @@ public async Task RandomUdpPortBinding() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); // Then Assert.NotEqual(containerPort, container.GetMappedPublicPort(qualifiedContainerPort)); @@ -201,13 +202,14 @@ public async Task RandomTcpPortBinding() await using var container = new ContainerBuilder() .WithImage(CommonImages.Nginx) .WithPortBinding(containerPort, true) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPort(containerPort))) + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => request.ForPort(containerPort)) + ) .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); // Then Assert.NotEqual(containerPort, container.GetMappedPublicPort(containerPort)); @@ -224,8 +226,7 @@ public async Task UnboundPortBindingThrowsException() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); // Then Assert.Throws(() => container.GetMappedPublicPort(443)); @@ -244,12 +245,14 @@ public async Task BindMountAndCommand() .WithEntrypoint("/bin/sh", "-c") .WithCommand($"hostname > /{target}/{file}") .WithBindMount(TestSession.TempDirectoryPath, $"/{target}") - .WithWaitStrategy(Wait.ForUnixContainer().UntilFileExists(Path.Combine(TestSession.TempDirectoryPath, file))) + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilFileExists(Path.Combine(TestSession.TempDirectoryPath, file)) + ) .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); // Then var fileInfo = new FileInfo(Path.Combine(TestSession.TempDirectoryPath, file)); @@ -273,12 +276,14 @@ public async Task BindMountAndEnvironment() .WithEntrypoint("/bin/sh", "-c") .WithCommand($"printf $DAY_OF_WEEK > /{target}/{file}") .WithBindMount(TestSession.TempDirectoryPath, $"/{target}") - .WithWaitStrategy(Wait.ForUnixContainer().UntilFileExists(Path.Combine(TestSession.TempDirectoryPath, file))) + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilFileExists(Path.Combine(TestSession.TempDirectoryPath, file)) + ) .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); // Then var fileInfo = new FileInfo(Path.Combine(TestSession.TempDirectoryPath, file)); @@ -296,7 +301,8 @@ public async Task DockerEndpoint() .Build(); // When - var exception = await Record.ExceptionAsync(() => container.StartAsync(TestContext.Current.CancellationToken)) + var exception = await Record + .ExceptionAsync(() => container.StartAsync(TestContext.Current.CancellationToken)) .ConfigureAwait(true); // Then @@ -312,7 +318,10 @@ public async Task DockerEndpoint() [InlineData("1.1.1.1", "http://1.1.1.1")] [InlineData("1.1.1.1", "https://1.1.1.1")] [InlineData("1.1.1.1", "tcp://1.1.1.1")] - public async Task HostnameShouldMatchDockerGatewayAddress(string expectedHostname, string endpoint) + public async Task HostnameShouldMatchDockerGatewayAddress( + string expectedHostname, + string endpoint + ) { await using var container = new ContainerBuilder() .WithDockerEndpoint(endpoint) @@ -326,9 +335,14 @@ public async Task HostnameShouldMatchDockerGatewayAddress(string expectedHostnam public async Task OutputConsumer() { // Given - using var consumer = Consume.RedirectStdoutAndStderrToStream(new MemoryStream(), new MemoryStream()); + using var consumer = Consume.RedirectStdoutAndStderrToStream( + new MemoryStream(), + new MemoryStream() + ); - var unixTimeInMilliseconds = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture); + var unixTimeInMilliseconds = DateTimeOffset + .UtcNow.ToUnixTimeMilliseconds() + .ToString(CultureInfo.InvariantCulture); // When await using var container = new ContainerBuilder() @@ -339,18 +353,19 @@ public async Task OutputConsumer() .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged(unixTimeInMilliseconds)) .Build(); - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); consumer.Stdout.Seek(0, SeekOrigin.Begin); consumer.Stderr.Seek(0, SeekOrigin.Begin); using var stdoutReader = new StreamReader(consumer.Stdout, leaveOpen: true); - var stdout = await stdoutReader.ReadToEndAsync(TestContext.Current.CancellationToken) + var stdout = await stdoutReader + .ReadToEndAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); using var stderrReader = new StreamReader(consumer.Stderr, leaveOpen: true); - var stderr = await stderrReader.ReadToEndAsync(TestContext.Current.CancellationToken) + var stderr = await stderrReader + .ReadToEndAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -365,11 +380,14 @@ public async Task WaitStrategy() await using var container = new ContainerBuilder() .WithImage(CommonImages.Alpine) .WithEntrypoint(CommonCommands.SleepInfinity) - .WithWaitStrategy(Wait.ForUnixContainer().AddCustomWaitStrategy(new WaitUntilFiveSecondsPassedFixture())) + .WithWaitStrategy( + Wait.ForUnixContainer().AddCustomWaitStrategy(new WaitUntilFiveSecondsPassedFixture()) + ) .Build(); // When - var exception = await Record.ExceptionAsync(() => container.StartAsync(TestContext.Current.CancellationToken)) + var exception = await Record + .ExceptionAsync(() => container.StartAsync(TestContext.Current.CancellationToken)) .ConfigureAwait(true); // Then @@ -386,10 +404,10 @@ public async Task ExecCommandInRunningContainer() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); - var execResult = await container.ExecAsync(new[] { "/bin/sh", "-c", "exit 255" }, TestContext.Current.CancellationToken) + var execResult = await container + .ExecAsync(new[] { "/bin/sh", "-c", "exit 255" }, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -406,10 +424,13 @@ public async Task ExecCommandInRunningContainerWithStdout() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); - var execResult = await container.ExecAsync(new[] { "ping", "-c", "1", "google.com" }, TestContext.Current.CancellationToken) + var execResult = await container + .ExecAsync( + new[] { "ping", "-c", "1", "google.com" }, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); // Then @@ -426,10 +447,13 @@ public async Task ExecCommandInRunningContainerWithStderr() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); - var execResult = await container.ExecAsync(new[] { "ping", "-c", "1", "google.invalid" }, TestContext.Current.CancellationToken) + var execResult = await container + .ExecAsync( + new[] { "ping", "-c", "1", "google.invalid" }, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); // Then @@ -450,13 +474,21 @@ public async Task CopyFileToRunningContainer() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); - await container.CopyAsync(Encoding.Default.GetBytes(dayOfWeek), dayOfWeekFilePath, ct: TestContext.Current.CancellationToken) + await container + .CopyAsync( + Encoding.Default.GetBytes(dayOfWeek), + dayOfWeekFilePath, + ct: TestContext.Current.CancellationToken + ) .ConfigureAwait(true); - var execResult = await container.ExecAsync(new[] { "test", "-f", dayOfWeekFilePath }, TestContext.Current.CancellationToken) + var execResult = await container + .ExecAsync( + new[] { "test", "-f", dayOfWeekFilePath }, + TestContext.Current.CancellationToken + ) .ConfigureAwait(true); // Then @@ -475,8 +507,7 @@ public async Task AutoRemoveFalseShouldNotRemoveContainer() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); var id = container.Id; @@ -499,13 +530,11 @@ public async Task AutoRemoveTrueShouldRemoveContainer() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); var id = container.Id; - await container.StopAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StopAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); await Task.Delay(TimeSpan.FromSeconds(1), TestContext.Current.CancellationToken) .ConfigureAwait(true); @@ -528,8 +557,7 @@ public async Task ParameterModifiers() .Build(); // When - await container.StartAsync(TestContext.Current.CancellationToken) - .ConfigureAwait(true); + await container.StartAsync(TestContext.Current.CancellationToken).ConfigureAwait(true); // Then Assert.EndsWith(name, container.Name); @@ -540,12 +568,15 @@ public async Task PullDigest() { // Given await using var container = new ContainerBuilder() - .WithImage("alpine@sha256:3451da08fc6ef554a100da3e2df5ac6d598c82f2a774d5f6ed465c3d80cd163a") + .WithImage( + "alpine@sha256:3451da08fc6ef554a100da3e2df5ac6d598c82f2a774d5f6ed465c3d80cd163a" + ) .WithEntrypoint(CommonCommands.SleepInfinity) .Build(); // When - var exception = await Record.ExceptionAsync(() => container.StartAsync(TestContext.Current.CancellationToken)) + var exception = await Record + .ExceptionAsync(() => container.StartAsync(TestContext.Current.CancellationToken)) .ConfigureAwait(true); // Then @@ -561,7 +592,10 @@ public async Task PullPolicyNever() .WithImagePullPolicy(PullPolicy.Never) .Build(); - await Assert.ThrowsAnyAsync(() => container.StartAsync(TestContext.Current.CancellationToken)) + await Assert + .ThrowsAnyAsync(() => + container.StartAsync(TestContext.Current.CancellationToken) + ) .ConfigureAwait(true); } } diff --git a/tests/Testcontainers.Tests/Unit/GuardTest.cs b/tests/Testcontainers.Tests/Unit/GuardTest.cs index e13ef47b3..d028aaa44 100644 --- a/tests/Testcontainers.Tests/Unit/GuardTest.cs +++ b/tests/Testcontainers.Tests/Unit/GuardTest.cs @@ -12,21 +12,29 @@ public sealed class DoNotThrowException [Fact] public void IfNull() { - var exception = Record.Exception(() => Guard.Argument(null, nameof(IfNull)).Null()); + var exception = Record.Exception(() => + Guard.Argument(null, nameof(IfNull)).Null() + ); Assert.Null(exception); } [Fact] public void IfNotNull() { - var exception = Record.Exception(() => Guard.Argument(new object(), nameof(IfNotNull)).NotNull()); + var exception = Record.Exception(() => + Guard.Argument(new object(), nameof(IfNotNull)).NotNull() + ); Assert.Null(exception); } [Fact] public void ThrowIf() { - var exception = Record.Exception(() => Guard.Argument(new object(), nameof(ThrowIf)).ThrowIf(_ => false, _ => new ArgumentException())); + var exception = Record.Exception(() => + Guard + .Argument(new object(), nameof(ThrowIf)) + .ThrowIf(_ => false, _ => new ArgumentException()) + ); Assert.Null(exception); } } @@ -36,19 +44,27 @@ public sealed class ThrowArgumentException [Fact] public void IfNull() { - Assert.Throws(() => Guard.Argument(null, nameof(IfNull)).NotNull()); + Assert.Throws(() => + Guard.Argument(null, nameof(IfNull)).NotNull() + ); } [Fact] public void IfNotNull() { - Assert.Throws(() => Guard.Argument(new object(), nameof(IfNotNull)).Null()); + Assert.Throws(() => + Guard.Argument(new object(), nameof(IfNotNull)).Null() + ); } [Fact] public void ThrowIf() { - Assert.Throws(() => Guard.Argument(new object(), nameof(ThrowIf)).ThrowIf(_ => true, _ => new ArgumentException())); + Assert.Throws(() => + Guard + .Argument(new object(), nameof(ThrowIf)) + .ThrowIf(_ => true, _ => new ArgumentException()) + ); } } } @@ -60,14 +76,18 @@ public sealed class DoNotThrowException [Fact] public void IfEmpty() { - var exception = Record.Exception(() => Guard.Argument(string.Empty, nameof(IfEmpty)).Empty()); + var exception = Record.Exception(() => + Guard.Argument(string.Empty, nameof(IfEmpty)).Empty() + ); Assert.Null(exception); } [Fact] public void IfNotEmpty() { - var exception = Record.Exception(() => Guard.Argument("Not Empty", nameof(IfNotEmpty)).NotEmpty()); + var exception = Record.Exception(() => + Guard.Argument("Not Empty", nameof(IfNotEmpty)).NotEmpty() + ); Assert.Null(exception); } } @@ -77,13 +97,17 @@ public sealed class ThrowArgumentException [Fact] public void IfEmpty() { - Assert.Throws(() => Guard.Argument(string.Empty, nameof(IfEmpty)).NotEmpty()); + Assert.Throws(() => + Guard.Argument(string.Empty, nameof(IfEmpty)).NotEmpty() + ); } [Fact] public void IfNotEmpty() { - Assert.Throws(() => Guard.Argument("Not Empty", nameof(IfNotEmpty)).Empty()); + Assert.Throws(() => + Guard.Argument("Not Empty", nameof(IfNotEmpty)).Empty() + ); } } } diff --git a/tests/Testcontainers.Tests/Unit/Images/ImageFromDockerfileTest.cs b/tests/Testcontainers.Tests/Unit/Images/ImageFromDockerfileTest.cs index 7e8b7f494..5ac9cd70a 100644 --- a/tests/Testcontainers.Tests/Unit/Images/ImageFromDockerfileTest.cs +++ b/tests/Testcontainers.Tests/Unit/Images/ImageFromDockerfileTest.cs @@ -19,9 +19,18 @@ public sealed class ImageFromDockerfileTest public void DockerfileArchiveGetBaseImages() { // Given - IImage image = new DockerImage("localhost/testcontainers", Guid.NewGuid().ToString("D"), string.Empty); - - var dockerfileArchive = new DockerfileArchive("Assets/pullBaseImages/", "Dockerfile", image, NullLogger.Instance); + IImage image = new DockerImage( + "localhost/testcontainers", + Guid.NewGuid().ToString("D"), + string.Empty + ); + + var dockerfileArchive = new DockerfileArchive( + "Assets/pullBaseImages/", + "Dockerfile", + image, + NullLogger.Instance + ); // When var baseImages = dockerfileArchive.GetBaseImages().ToArray(); @@ -29,24 +38,43 @@ public void DockerfileArchiveGetBaseImages() // Then Assert.Equal(4, baseImages.Length); Assert.Contains(baseImages, item => "mcr.microsoft.com/dotnet/sdk:6.0".Equals(item.FullName)); - Assert.Contains(baseImages, item => "mcr.microsoft.com/dotnet/runtime:6.0".Equals(item.FullName)); - Assert.Contains(baseImages, item => "mcr.microsoft.com/dotnet/aspnet:6.0.22-jammy-amd64".Equals(item.FullName)); - Assert.Contains(baseImages, item => "mcr.microsoft.com/dotnet/aspnet:6.0.23-jammy-amd64".Equals(item.FullName)); + Assert.Contains( + baseImages, + item => "mcr.microsoft.com/dotnet/runtime:6.0".Equals(item.FullName) + ); + Assert.Contains( + baseImages, + item => "mcr.microsoft.com/dotnet/aspnet:6.0.22-jammy-amd64".Equals(item.FullName) + ); + Assert.Contains( + baseImages, + item => "mcr.microsoft.com/dotnet/aspnet:6.0.23-jammy-amd64".Equals(item.FullName) + ); } [Fact] public async Task DockerfileArchiveTar() { // Given - IImage image = new DockerImage("localhost/testcontainers", Guid.NewGuid().ToString("D"), string.Empty); + IImage image = new DockerImage( + "localhost/testcontainers", + Guid.NewGuid().ToString("D"), + string.Empty + ); var expected = new SortedSet { ".dockerignore", "Dockerfile", "setup/setup.sh" }; var actual = new SortedSet(); - var dockerfileArchive = new DockerfileArchive("Assets/", "Dockerfile", image, NullLogger.Instance); + var dockerfileArchive = new DockerfileArchive( + "Assets/", + "Dockerfile", + image, + NullLogger.Instance + ); - var dockerfileArchiveFilePath = await dockerfileArchive.Tar(TestContext.Current.CancellationToken) + var dockerfileArchiveFilePath = await dockerfileArchive + .Tar(TestContext.Current.CancellationToken) .ConfigureAwait(true); // When @@ -75,11 +103,17 @@ public async Task ThrowsDockerfileDoesNotExist() .Build(); // When - var exception = await Assert.ThrowsAsync(() => imageFromDockerfileBuilder.CreateAsync(TestContext.Current.CancellationToken)) + var exception = await Assert + .ThrowsAsync(() => + imageFromDockerfileBuilder.CreateAsync(TestContext.Current.CancellationToken) + ) .ConfigureAwait(true); // Then - Assert.Equal($"Dockerfile does not exist in '{Path.GetFullPath(dockerfileDirectory)}'.", exception.Message); + Assert.Equal( + $"Dockerfile does not exist in '{Path.GetFullPath(dockerfileDirectory)}'.", + exception.Message + ); } [Fact] @@ -93,11 +127,17 @@ public async Task ThrowsDockerfileDirectoryDoesNotExist() .Build(); // When - var exception = await Assert.ThrowsAsync(() => imageFromDockerfileBuilder.CreateAsync(TestContext.Current.CancellationToken)) + var exception = await Assert + .ThrowsAsync(() => + imageFromDockerfileBuilder.CreateAsync(TestContext.Current.CancellationToken) + ) .ConfigureAwait(true); // Then - Assert.Equal($"Directory '{Path.GetFullPath(dockerfileDirectory)}' does not exist.", exception.Message); + Assert.Equal( + $"Directory '{Path.GetFullPath(dockerfileDirectory)}' does not exist.", + exception.Message + ); } [Fact] @@ -109,7 +149,10 @@ public async Task BuildsDockerScratchImage() .Build(); // When - var exception = await Record.ExceptionAsync(() => imageFromDockerfileBuilder.CreateAsync(TestContext.Current.CancellationToken)) + var exception = await Record + .ExceptionAsync(() => + imageFromDockerfileBuilder.CreateAsync(TestContext.Current.CancellationToken) + ) .ConfigureAwait(true); // Then @@ -127,9 +170,17 @@ public async Task BuildsDockerScratchImage() public async Task BuildsDockerAlpineImage(string dockerfile) { // Given - IImage tag1 = new DockerImage(new DockerImage(string.Join("/", "localhost", "testcontainers", Guid.NewGuid().ToString("D")))); - - IImage tag2 = new DockerImage(new DockerImage(string.Join("/", "localhost", "testcontainers", Guid.NewGuid().ToString("D")))); + IImage tag1 = new DockerImage( + new DockerImage( + string.Join("/", "localhost", "testcontainers", Guid.NewGuid().ToString("D")) + ) + ); + + IImage tag2 = new DockerImage( + new DockerImage( + string.Join("/", "localhost", "testcontainers", Guid.NewGuid().ToString("D")) + ) + ); var imageFromDockerfileBuilder = new ImageFromDockerfileBuilder() .WithName(tag1) @@ -140,10 +191,12 @@ public async Task BuildsDockerAlpineImage(string dockerfile) .Build(); // When - await imageFromDockerfileBuilder.CreateAsync(TestContext.Current.CancellationToken) + await imageFromDockerfileBuilder + .CreateAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); - await imageFromDockerfileBuilder.CreateAsync(TestContext.Current.CancellationToken) + await imageFromDockerfileBuilder + .CreateAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then diff --git a/tests/Testcontainers.Tests/Unit/Images/TestcontainersImageTest.cs b/tests/Testcontainers.Tests/Unit/Images/TestcontainersImageTest.cs index 4dc349470..8d3993e2f 100644 --- a/tests/Testcontainers.Tests/Unit/Images/TestcontainersImageTest.cs +++ b/tests/Testcontainers.Tests/Unit/Images/TestcontainersImageTest.cs @@ -18,7 +18,9 @@ public void ShouldThrowArgumentNullExceptionWhenInstantiateDockerImage() public void ShouldThrowArgumentExceptionWhenInstantiateDockerImage() { Assert.Throws(() => new DockerImage(string.Empty)); - Assert.Throws(() => new DockerImage(string.Empty, string.Empty, string.Empty)); + Assert.Throws(() => + new DockerImage(string.Empty, string.Empty, string.Empty) + ); } [Theory] @@ -52,7 +54,11 @@ public void ShouldNotThrowArgumentExceptionIfImageTagHasUppercaseCharacters(stri [Theory] [ClassData(typeof(DockerImageFixture))] - public void WhenImageNameGetsAssigned(DockerImageFixtureSerializable serializable, string image, string fullName) + public void WhenImageNameGetsAssigned( + DockerImageFixtureSerializable serializable, + string image, + string fullName + ) { // Given var expected = serializable.Image; @@ -115,10 +121,17 @@ public void MatchLatestOrNightly_TagIsNeither_ReturnsFalse() [InlineData("foo:2.3-variant", 2, 3, -1, -1)] [InlineData("foo:2.3.4", 2, 3, 4, -1)] [InlineData("foo:2.3.4-variant", 2, 3, 4, -1)] - public void MatchVersion_ReturnsTrue_WhenVersionMatchesPredicate(string image, int major, int minor, int build, int revision) + public void MatchVersion_ReturnsTrue_WhenVersionMatchesPredicate( + string image, + int major, + int minor, + int build, + int revision + ) { // Given - Predicate predicate = v => v.Major == major && v.Minor == minor && v.Build == build && v.Revision == revision; + Predicate predicate = v => + v.Major == major && v.Minor == minor && v.Build == build && v.Revision == revision; IImage dockerImage = new DockerImage(image); // When diff --git a/tests/Testcontainers.Tests/Unit/Networks/TestcontainerNetworkBuilderTest.cs b/tests/Testcontainers.Tests/Unit/Networks/TestcontainerNetworkBuilderTest.cs index df5662777..a1ef2f686 100644 --- a/tests/Testcontainers.Tests/Unit/Networks/TestcontainerNetworkBuilderTest.cs +++ b/tests/Testcontainers.Tests/Unit/Networks/TestcontainerNetworkBuilderTest.cs @@ -13,15 +13,28 @@ namespace DotNet.Testcontainers.Tests.Unit using Microsoft.Extensions.Logging.Abstractions; using Xunit; - public sealed class TestcontainerNetworkBuilderTest : IClassFixture + public sealed class TestcontainerNetworkBuilderTest + : IClassFixture { private static readonly string NetworkName = Guid.NewGuid().ToString("D"); - private static readonly KeyValuePair Option = new KeyValuePair("mtu", "1350"); + private static readonly KeyValuePair Option = new KeyValuePair( + "mtu", + "1350" + ); - private static readonly KeyValuePair Label = new KeyValuePair(TestcontainersClient.TestcontainersLabel + ".network.test", Guid.NewGuid().ToString("D")); + private static readonly KeyValuePair Label = new KeyValuePair( + TestcontainersClient.TestcontainersLabel + ".network.test", + Guid.NewGuid().ToString("D") + ); - private static readonly KeyValuePair ParameterModifier = new KeyValuePair(TestcontainersClient.TestcontainersLabel + ".parameter.modifier", Guid.NewGuid().ToString("D")); + private static readonly KeyValuePair ParameterModifier = new KeyValuePair< + string, + string + >( + TestcontainersClient.TestcontainersLabel + ".parameter.modifier", + Guid.NewGuid().ToString("D") + ); private readonly INetwork _network; @@ -33,10 +46,9 @@ public TestcontainerNetworkBuilderTest(DockerNetwork network) [Fact] public void GetNameThrowsInvalidOperationException() { - _ = Assert.Throws(() => new NetworkBuilder() - .WithName(NetworkName) - .Build() - .Name); + _ = Assert.Throws(() => + new NetworkBuilder().WithName(NetworkName).Build().Name + ); } [Fact] @@ -49,10 +61,15 @@ public void GetNameReturnsNetworkName() public async Task CreateNetworkAssignsOptions() { // Given - var client = new TestcontainersClient(ResourceReaper.DefaultSessionId, TestcontainersSettings.OS.DockerEndpointAuthConfig, NullLogger.Instance); + var client = new TestcontainersClient( + ResourceReaper.DefaultSessionId, + TestcontainersSettings.OS.DockerEndpointAuthConfig, + NullLogger.Instance + ); // When - var networkResponse = await client.Network.ByIdAsync(_network.Name, TestContext.Current.CancellationToken) + var networkResponse = await client + .Network.ByIdAsync(_network.Name, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -63,15 +80,23 @@ public async Task CreateNetworkAssignsOptions() public async Task CreateNetworkAssignsLabels() { // Given - var client = new TestcontainersClient(ResourceReaper.DefaultSessionId, TestcontainersSettings.OS.DockerEndpointAuthConfig, NullLogger.Instance); + var client = new TestcontainersClient( + ResourceReaper.DefaultSessionId, + TestcontainersSettings.OS.DockerEndpointAuthConfig, + NullLogger.Instance + ); // When - var networkResponse = await client.Network.ByIdAsync(_network.Name, TestContext.Current.CancellationToken) + var networkResponse = await client + .Network.ByIdAsync(_network.Name, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal(Label.Value, Assert.Contains(Label.Key, networkResponse.Labels)); - Assert.Equal(ParameterModifier.Value, Assert.Contains(ParameterModifier.Key, networkResponse.Labels)); + Assert.Equal( + ParameterModifier.Value, + Assert.Contains(ParameterModifier.Key, networkResponse.Labels) + ); } [UsedImplicitly] @@ -81,15 +106,16 @@ public sealed class DockerNetwork : INetwork, IAsyncLifetime .WithName(NetworkName) .WithOption(Option.Key, Option.Value) .WithLabel(Label.Key, Label.Value) - .WithCreateParameterModifier(parameterModifier => parameterModifier.Labels.Add(ParameterModifier.Key, ParameterModifier.Value)) + .WithCreateParameterModifier(parameterModifier => + parameterModifier.Labels.Add(ParameterModifier.Key, ParameterModifier.Value) + ) .Build(); public string Name => _network.Name; public async ValueTask InitializeAsync() { - await CreateAsync() - .ConfigureAwait(false); + await CreateAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() diff --git a/tests/Testcontainers.Tests/Unit/Networks/TestcontainersNetworkTest.cs b/tests/Testcontainers.Tests/Unit/Networks/TestcontainersNetworkTest.cs index f224036bf..b50f2333b 100644 --- a/tests/Testcontainers.Tests/Unit/Networks/TestcontainersNetworkTest.cs +++ b/tests/Testcontainers.Tests/Unit/Networks/TestcontainersNetworkTest.cs @@ -22,19 +22,14 @@ public TestcontainersNetworkTest(NetworkFixture networkFixture) .WithEntrypoint(CommonCommands.SleepInfinity) .WithNetwork(networkFixture.Network.Name); - _container1 = containerBuilder - .WithNetworkAliases(nameof(_container1) + AliasSuffix) - .Build(); + _container1 = containerBuilder.WithNetworkAliases(nameof(_container1) + AliasSuffix).Build(); - _container2 = containerBuilder - .WithNetworkAliases(nameof(_container2) + AliasSuffix) - .Build(); + _container2 = containerBuilder.WithNetworkAliases(nameof(_container2) + AliasSuffix).Build(); } public async ValueTask InitializeAsync() { - await Task.WhenAll(_container1.StartAsync(), _container2.StartAsync()) - .ConfigureAwait(false); + await Task.WhenAll(_container1.StartAsync(), _container2.StartAsync()).ConfigureAwait(false); } public async ValueTask DisposeAsync() @@ -50,7 +45,8 @@ public async Task PingContainer() const string destination = nameof(_container2) + AliasSuffix; // When - var execResult = await _container1.ExecAsync(new[] { "ping", "-c", "1", destination }, TestContext.Current.CancellationToken) + var execResult = await _container1 + .ExecAsync(new[] { "ping", "-c", "1", destination }, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then diff --git a/tests/Testcontainers.Tests/Unit/Volumes/TestcontainersVolumeBuilderTest.cs b/tests/Testcontainers.Tests/Unit/Volumes/TestcontainersVolumeBuilderTest.cs index 0f27729c8..827bb5c11 100644 --- a/tests/Testcontainers.Tests/Unit/Volumes/TestcontainersVolumeBuilderTest.cs +++ b/tests/Testcontainers.Tests/Unit/Volumes/TestcontainersVolumeBuilderTest.cs @@ -13,13 +13,23 @@ namespace DotNet.Testcontainers.Tests.Unit using Microsoft.Extensions.Logging.Abstractions; using Xunit; - public sealed class TestcontainersVolumeBuilderTest : IClassFixture + public sealed class TestcontainersVolumeBuilderTest + : IClassFixture { private static readonly string VolumeName = Guid.NewGuid().ToString("D"); - private static readonly KeyValuePair Label = new KeyValuePair(TestcontainersClient.TestcontainersLabel + ".volume.test", Guid.NewGuid().ToString("D")); + private static readonly KeyValuePair Label = new KeyValuePair( + TestcontainersClient.TestcontainersLabel + ".volume.test", + Guid.NewGuid().ToString("D") + ); - private static readonly KeyValuePair ParameterModifier = new KeyValuePair(TestcontainersClient.TestcontainersLabel + ".parameter.modifier", Guid.NewGuid().ToString("D")); + private static readonly KeyValuePair ParameterModifier = new KeyValuePair< + string, + string + >( + TestcontainersClient.TestcontainersLabel + ".parameter.modifier", + Guid.NewGuid().ToString("D") + ); private readonly IVolume _volume; @@ -31,10 +41,9 @@ public TestcontainersVolumeBuilderTest(DockerVolume volume) [Fact] public void GetNameThrowsInvalidOperationException() { - _ = Assert.Throws(() => new VolumeBuilder() - .WithName(VolumeName) - .Build() - .Name); + _ = Assert.Throws(() => + new VolumeBuilder().WithName(VolumeName).Build().Name + ); } [Fact] @@ -47,15 +56,23 @@ public void GetNameReturnsVolumeName() public async Task CreateVolumeAssignsLabels() { // Given - var client = new TestcontainersClient(ResourceReaper.DefaultSessionId, TestcontainersSettings.OS.DockerEndpointAuthConfig, NullLogger.Instance); + var client = new TestcontainersClient( + ResourceReaper.DefaultSessionId, + TestcontainersSettings.OS.DockerEndpointAuthConfig, + NullLogger.Instance + ); // When - var volumeResponse = await client.Volume.ByIdAsync(_volume.Name, TestContext.Current.CancellationToken) + var volumeResponse = await client + .Volume.ByIdAsync(_volume.Name, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal(Label.Value, Assert.Contains(Label.Key, volumeResponse.Labels)); - Assert.Equal(ParameterModifier.Value, Assert.Contains(ParameterModifier.Key, volumeResponse.Labels)); + Assert.Equal( + ParameterModifier.Value, + Assert.Contains(ParameterModifier.Key, volumeResponse.Labels) + ); } [UsedImplicitly] @@ -64,15 +81,16 @@ public sealed class DockerVolume : IVolume, IAsyncLifetime private readonly IVolume _volume = new VolumeBuilder() .WithName(VolumeName) .WithLabel(Label.Key, Label.Value) - .WithCreateParameterModifier(parameterModifier => parameterModifier.Labels.Add(ParameterModifier.Key, ParameterModifier.Value)) + .WithCreateParameterModifier(parameterModifier => + parameterModifier.Labels.Add(ParameterModifier.Key, ParameterModifier.Value) + ) .Build(); public string Name => _volume.Name; public async ValueTask InitializeAsync() { - await CreateAsync() - .ConfigureAwait(false); + await CreateAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() diff --git a/tests/Testcontainers.Tests/Unit/Volumes/TestcontainersVolumeTest.cs b/tests/Testcontainers.Tests/Unit/Volumes/TestcontainersVolumeTest.cs index d0d3ce938..f6f448072 100644 --- a/tests/Testcontainers.Tests/Unit/Volumes/TestcontainersVolumeTest.cs +++ b/tests/Testcontainers.Tests/Unit/Volumes/TestcontainersVolumeTest.cs @@ -27,13 +27,9 @@ public TestcontainersVolumeTest(VolumeFixture volumeFixture) .WithVolumeMount(volumeFixture.Volume.Name, Destination) .WithTmpfsMount(TmpfsDestination); - _testcontainer1 = testcontainersBuilder - .WithHostname(nameof(_testcontainer1)) - .Build(); + _testcontainer1 = testcontainersBuilder.WithHostname(nameof(_testcontainer1)).Build(); - _testcontainer2 = testcontainersBuilder - .WithHostname(nameof(_testcontainer2)) - .Build(); + _testcontainer2 = testcontainersBuilder.WithHostname(nameof(_testcontainer2)).Build(); } public async ValueTask InitializeAsync() @@ -44,22 +40,57 @@ await Task.WhenAll(_testcontainer1.StartAsync(), _testcontainer2.StartAsync()) public async ValueTask DisposeAsync() { - await Task.WhenAll(_testcontainer1.DisposeAsync().AsTask(), _testcontainer2.DisposeAsync().AsTask()) + await Task.WhenAll( + _testcontainer1.DisposeAsync().AsTask(), + _testcontainer2.DisposeAsync().AsTask() + ) .ConfigureAwait(false); } [Fact] public async Task WithVolumeMount() { - Assert.Equal(0, (await _testcontainer1.ExecAsync(new[] { "test", "-f", Path.Combine(Destination, nameof(_testcontainer2)) }, TestContext.Current.CancellationToken)).ExitCode); - Assert.Equal(0, (await _testcontainer2.ExecAsync(new[] { "test", "-f", Path.Combine(Destination, nameof(_testcontainer1)) }, TestContext.Current.CancellationToken)).ExitCode); + Assert.Equal( + 0, + ( + await _testcontainer1.ExecAsync( + new[] { "test", "-f", Path.Combine(Destination, nameof(_testcontainer2)) }, + TestContext.Current.CancellationToken + ) + ).ExitCode + ); + Assert.Equal( + 0, + ( + await _testcontainer2.ExecAsync( + new[] { "test", "-f", Path.Combine(Destination, nameof(_testcontainer1)) }, + TestContext.Current.CancellationToken + ) + ).ExitCode + ); } [Fact] public async Task WithTmpfsVolumeMount() { - Assert.Equal(0, (await _testcontainer1.ExecAsync(new[] { "test", "-d", TmpfsDestination }, TestContext.Current.CancellationToken)).ExitCode); - Assert.Equal(0, (await _testcontainer2.ExecAsync(new[] { "test", "-d", TmpfsDestination }, TestContext.Current.CancellationToken)).ExitCode); + Assert.Equal( + 0, + ( + await _testcontainer1.ExecAsync( + new[] { "test", "-d", TmpfsDestination }, + TestContext.Current.CancellationToken + ) + ).ExitCode + ); + Assert.Equal( + 0, + ( + await _testcontainer2.ExecAsync( + new[] { "test", "-d", TmpfsDestination }, + TestContext.Current.CancellationToken + ) + ).ExitCode + ); } } } diff --git a/tests/Testcontainers.Typesense.Tests/Testcontainers.Typesense.Tests.csproj b/tests/Testcontainers.Typesense.Tests/Testcontainers.Typesense.Tests.csproj index a227dd0a5..a3871396f 100644 --- a/tests/Testcontainers.Typesense.Tests/Testcontainers.Typesense.Tests.csproj +++ b/tests/Testcontainers.Typesense.Tests/Testcontainers.Typesense.Tests.csproj @@ -1,18 +1,18 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + diff --git a/tests/Testcontainers.Typesense.Tests/TypesenseContainerTest.cs b/tests/Testcontainers.Typesense.Tests/TypesenseContainerTest.cs index b98a3fc41..1c5d63f48 100644 --- a/tests/Testcontainers.Typesense.Tests/TypesenseContainerTest.cs +++ b/tests/Testcontainers.Typesense.Tests/TypesenseContainerTest.cs @@ -6,8 +6,7 @@ public sealed class TypesenseContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _typesenseContainer.StartAsync() - .ConfigureAwait(false); + await _typesenseContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -25,13 +24,15 @@ public async Task GetCollectionsReturnsEmptyArray() httpClient.BaseAddress = new Uri(_typesenseContainer.GetBaseAddress()); // When - using var httpResponse = await httpClient.GetAsync("/collections", TestContext.Current.CancellationToken) + using var httpResponse = await httpClient + .GetAsync("/collections", TestContext.Current.CancellationToken) .ConfigureAwait(true); - var response = await httpResponse.Content.ReadAsStringAsync(TestContext.Current.CancellationToken) + var response = await httpResponse + .Content.ReadAsStringAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal("[]", response); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Typesense.Tests/Usings.cs b/tests/Testcontainers.Typesense.Tests/Usings.cs index a558bb8d1..01a48fbb2 100644 --- a/tests/Testcontainers.Typesense.Tests/Usings.cs +++ b/tests/Testcontainers.Typesense.Tests/Usings.cs @@ -2,4 +2,4 @@ global using System.Net.Http; global using System.Threading.Tasks; global using DotNet.Testcontainers.Commons; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Weaviate.Tests/Testcontainers.Weaviate.Tests.csproj b/tests/Testcontainers.Weaviate.Tests/Testcontainers.Weaviate.Tests.csproj index ef238447e..b955afbfd 100644 --- a/tests/Testcontainers.Weaviate.Tests/Testcontainers.Weaviate.Tests.csproj +++ b/tests/Testcontainers.Weaviate.Tests/Testcontainers.Weaviate.Tests.csproj @@ -1,18 +1,18 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + diff --git a/tests/Testcontainers.Weaviate.Tests/Usings.cs b/tests/Testcontainers.Weaviate.Tests/Usings.cs index dc15b5753..424f90a8b 100644 --- a/tests/Testcontainers.Weaviate.Tests/Usings.cs +++ b/tests/Testcontainers.Weaviate.Tests/Usings.cs @@ -3,4 +3,4 @@ global using System.Net.Http; global using System.Threading.Tasks; global using DotNet.Testcontainers.Commons; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.Weaviate.Tests/WeaviateContainerTest.cs b/tests/Testcontainers.Weaviate.Tests/WeaviateContainerTest.cs index 572baa0e6..efa24a65b 100644 --- a/tests/Testcontainers.Weaviate.Tests/WeaviateContainerTest.cs +++ b/tests/Testcontainers.Weaviate.Tests/WeaviateContainerTest.cs @@ -6,8 +6,7 @@ public sealed class WeaviateContainerTest : IAsyncLifetime public async ValueTask InitializeAsync() { - await _weaviateContainer.StartAsync() - .ConfigureAwait(false); + await _weaviateContainer.StartAsync().ConfigureAwait(false); } public ValueTask DisposeAsync() @@ -24,10 +23,11 @@ public async Task GetSchemaReturnsHttpStatusCodeOk() httpClient.BaseAddress = new Uri(_weaviateContainer.GetBaseAddress()); // When - using var httpResponse = await httpClient.GetAsync("v1/schema", TestContext.Current.CancellationToken) + using var httpResponse = await httpClient + .GetAsync("v1/schema", TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.WebDriver.Tests/Testcontainers.WebDriver.Tests.csproj b/tests/Testcontainers.WebDriver.Tests/Testcontainers.WebDriver.Tests.csproj index a525805c2..7f60e0872 100644 --- a/tests/Testcontainers.WebDriver.Tests/Testcontainers.WebDriver.Tests.csproj +++ b/tests/Testcontainers.WebDriver.Tests/Testcontainers.WebDriver.Tests.csproj @@ -1,19 +1,19 @@ - - net9.0 - false - false - Exe - - - - - - - - - - - - - \ No newline at end of file + + net9.0 + false + false + Exe + + + + + + + + + + + + + diff --git a/tests/Testcontainers.WebDriver.Tests/Usings.cs b/tests/Testcontainers.WebDriver.Tests/Usings.cs index e490f22c2..cd988e560 100644 --- a/tests/Testcontainers.WebDriver.Tests/Usings.cs +++ b/tests/Testcontainers.WebDriver.Tests/Usings.cs @@ -7,4 +7,4 @@ global using JetBrains.Annotations; global using OpenQA.Selenium.Chrome; global using OpenQA.Selenium.Remote; -global using Xunit; \ No newline at end of file +global using Xunit; diff --git a/tests/Testcontainers.WebDriver.Tests/WebDriverContainerTest.cs b/tests/Testcontainers.WebDriver.Tests/WebDriverContainerTest.cs index 8debc769e..2aeec062f 100644 --- a/tests/Testcontainers.WebDriver.Tests/WebDriverContainerTest.cs +++ b/tests/Testcontainers.WebDriver.Tests/WebDriverContainerTest.cs @@ -2,7 +2,11 @@ namespace Testcontainers.WebDriver; public abstract class WebDriverContainerTest : IAsyncLifetime { - private readonly Uri _helloWorldBaseAddress = new UriBuilder(Uri.UriSchemeHttp, "hello-world-container", 8080).Uri; + private readonly Uri _helloWorldBaseAddress = new UriBuilder( + Uri.UriSchemeHttp, + "hello-world-container", + 8080 + ).Uri; private readonly IContainer _helloWorldContainer; @@ -15,8 +19,12 @@ private WebDriverContainerTest(WebDriverContainer webDriverContainer) .WithNetwork(webDriverContainer.GetNetwork()) .WithNetworkAliases(_helloWorldBaseAddress.Host) .WithPortBinding(_helloWorldBaseAddress.Port, true) - .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(request => - request.ForPath("/").ForPort(Convert.ToUInt16(_helloWorldBaseAddress.Port)))) + .WithWaitStrategy( + Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(request => + request.ForPath("/").ForPort(Convert.ToUInt16(_helloWorldBaseAddress.Port)) + ) + ) .Build(); _webDriverContainer = webDriverContainer; @@ -24,17 +32,14 @@ private WebDriverContainerTest(WebDriverContainer webDriverContainer) public async ValueTask InitializeAsync() { - await _webDriverContainer.StartAsync() - .ConfigureAwait(false); + await _webDriverContainer.StartAsync().ConfigureAwait(false); - await _helloWorldContainer.StartAsync() - .ConfigureAwait(false); + await _helloWorldContainer.StartAsync().ConfigureAwait(false); } public async ValueTask DisposeAsync() { - await DisposeAsyncCore() - .ConfigureAwait(false); + await DisposeAsyncCore().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -44,7 +49,10 @@ await DisposeAsyncCore() public void HeadingElementReturnsHelloWorld() { // Given - using var driver = new RemoteWebDriver(new Uri(_webDriverContainer.GetConnectionString()), new ChromeOptions()); + using var driver = new RemoteWebDriver( + new Uri(_webDriverContainer.GetConnectionString()), + new ChromeOptions() + ); // When driver.Navigate().GoToUrl(_helloWorldBaseAddress.ToString()); @@ -56,35 +64,36 @@ public void HeadingElementReturnsHelloWorld() protected virtual async ValueTask DisposeAsyncCore() { - await _helloWorldContainer.DisposeAsync() - .ConfigureAwait(false); + await _helloWorldContainer.DisposeAsync().ConfigureAwait(false); - await _webDriverContainer.DisposeAsync() - .ConfigureAwait(false); + await _webDriverContainer.DisposeAsync().ConfigureAwait(false); } [UsedImplicitly] public sealed class RecordingEnabled : WebDriverContainerTest { public RecordingEnabled() - : base(new WebDriverBuilder().WithRecording().Build()) - { - } + : base(new WebDriverBuilder().WithRecording().Build()) { } [Fact] [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public async Task ExportVideoWritesFile() { // Given - var videoFilePath = Path.Combine(TestSession.TempDirectoryPath, Path.GetRandomFileName()); + var videoFilePath = Path.Combine( + TestSession.TempDirectoryPath, + Path.GetRandomFileName() + ); // When HeadingElementReturnsHelloWorld(); - await _webDriverContainer.StopAsync(TestContext.Current.CancellationToken) + await _webDriverContainer + .StopAsync(TestContext.Current.CancellationToken) .ConfigureAwait(true); - await _webDriverContainer.ExportVideoAsync(videoFilePath, TestContext.Current.CancellationToken) + await _webDriverContainer + .ExportVideoAsync(videoFilePath, TestContext.Current.CancellationToken) .ConfigureAwait(true); // Then @@ -95,8 +104,12 @@ await _webDriverContainer.ExportVideoAsync(videoFilePath, TestContext.Current.Ca [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public Task ExportVideoThrowsInvalidOperationException() { - return Assert.ThrowsAsync(() - => _webDriverContainer.ExportVideoAsync(string.Empty, TestContext.Current.CancellationToken)); + return Assert.ThrowsAsync(() => + _webDriverContainer.ExportVideoAsync( + string.Empty, + TestContext.Current.CancellationToken + ) + ); } } @@ -104,16 +117,18 @@ public Task ExportVideoThrowsInvalidOperationException() public sealed class RecordingDisabled : WebDriverContainerTest { public RecordingDisabled() - : base(new WebDriverBuilder().Build()) - { - } + : base(new WebDriverBuilder().Build()) { } [Fact] [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public Task ExportVideoThrowsInvalidOperationException() { - return Assert.ThrowsAsync(() - => _webDriverContainer.ExportVideoAsync(string.Empty, TestContext.Current.CancellationToken)); + return Assert.ThrowsAsync(() => + _webDriverContainer.ExportVideoAsync( + string.Empty, + TestContext.Current.CancellationToken + ) + ); } } -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Xunit.Tests/AlphabeticalTestCaseOrderer.cs b/tests/Testcontainers.Xunit.Tests/AlphabeticalTestCaseOrderer.cs index 51b2a3870..4faa5f70a 100644 --- a/tests/Testcontainers.Xunit.Tests/AlphabeticalTestCaseOrderer.cs +++ b/tests/Testcontainers.Xunit.Tests/AlphabeticalTestCaseOrderer.cs @@ -3,7 +3,9 @@ namespace Testcontainers.Xunit.Tests; public class AlphabeticalTestCaseOrderer : ITestCaseOrderer { #if XUNIT_V3 - public IReadOnlyCollection OrderTestCases(IReadOnlyCollection testCases) + public IReadOnlyCollection OrderTestCases( + IReadOnlyCollection testCases + ) where TTestCase : notnull, ITestCase { return testCases.OrderBy(testCase => testCase.TestMethod?.MethodName).ToImmutableList(); @@ -15,4 +17,4 @@ public IEnumerable OrderTestCases(IEnumerable t return testCases.OrderBy(testCase => testCase.TestMethod.Method.Name); } #endif -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Xunit.Tests/PostgreSqlContainer.cs b/tests/Testcontainers.Xunit.Tests/PostgreSqlContainer.cs index 917c7b3a3..db1156839 100644 --- a/tests/Testcontainers.Xunit.Tests/PostgreSqlContainer.cs +++ b/tests/Testcontainers.Xunit.Tests/PostgreSqlContainer.cs @@ -8,16 +8,19 @@ protected override PostgreSqlBuilder Configure(PostgreSqlBuilder builder) { return builder .WithImage("postgres:15.1") - .WithResourceMapping("Chinook_PostgreSql_AutoIncrementPKs.sql", "/docker-entrypoint-initdb.d/"); + .WithResourceMapping( + "Chinook_PostgreSql_AutoIncrementPKs.sql", + "/docker-entrypoint-initdb.d/" + ); } } + // # --8<-- [end:ConfigurePostgreSqlContainer] public sealed partial class PostgreSqlContainerTest { // # --8<-- [start:ConfigureDbProviderFactory] - public override DbProviderFactory DbProviderFactory - => NpgsqlFactory.Instance; + public override DbProviderFactory DbProviderFactory => NpgsqlFactory.Instance; // # --8<-- [end:ConfigureDbProviderFactory] } @@ -58,4 +61,4 @@ public async Task Test1() Assert.Equal("For Those About To Rock We Salute You", title); } // # --8<-- [end:RunTests] -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Xunit.Tests/RedisContainerTest`1.cs b/tests/Testcontainers.Xunit.Tests/RedisContainerTest`1.cs index 8d1aa2ef5..30d0ea036 100644 --- a/tests/Testcontainers.Xunit.Tests/RedisContainerTest`1.cs +++ b/tests/Testcontainers.Xunit.Tests/RedisContainerTest`1.cs @@ -15,7 +15,10 @@ protected override RedisBuilder Configure(RedisBuilder builder) #if XUNIT_V3 [TestCaseOrderer(ordererType: typeof(Testcontainers.Xunit.Tests.AlphabeticalTestCaseOrderer))] #else -[TestCaseOrderer(ordererTypeName: "Testcontainers.Xunit.Tests.AlphabeticalTestCaseOrderer", ordererAssemblyName: "Testcontainers.Xunit.Tests")] +[TestCaseOrderer( + ordererTypeName: "Testcontainers.Xunit.Tests.AlphabeticalTestCaseOrderer", + ordererAssemblyName: "Testcontainers.Xunit.Tests" +)] #endif public sealed partial class RedisContainerTest { @@ -49,4 +52,4 @@ public async Task Test2() // 👇 The created and started container is disposed of after this method (test) completes. } // # --8<-- [end:RunTests] -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Xunit.Tests/RedisContainerTest`2.cs b/tests/Testcontainers.Xunit.Tests/RedisContainerTest`2.cs index 18b767832..f9e3db24d 100644 --- a/tests/Testcontainers.Xunit.Tests/RedisContainerTest`2.cs +++ b/tests/Testcontainers.Xunit.Tests/RedisContainerTest`2.cs @@ -10,6 +10,7 @@ protected override RedisBuilder Configure(RedisBuilder builder) return builder.WithImage("redis:7.0"); } } + // # --8<-- [end:ConfigureRedisContainer] // # --8<-- [start:InjectContainerFixture] @@ -20,7 +21,10 @@ public sealed partial class RedisContainerTest(RedisContainerFixture fixture) #if XUNIT_V3 [TestCaseOrderer(ordererType: typeof(Testcontainers.Xunit.Tests.AlphabeticalTestCaseOrderer))] #else -[TestCaseOrderer(ordererTypeName: "Testcontainers.Xunit.Tests.AlphabeticalTestCaseOrderer", ordererAssemblyName: "Testcontainers.Xunit.Tests")] +[TestCaseOrderer( + ordererTypeName: "Testcontainers.Xunit.Tests.AlphabeticalTestCaseOrderer", + ordererAssemblyName: "Testcontainers.Xunit.Tests" +)] #endif public sealed partial class RedisContainerTest { @@ -35,7 +39,9 @@ public void ImageShouldMatchDefaultModuleImage() [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public async Task Test1() { - using var redis = await ConnectionMultiplexer.ConnectAsync(fixture.Container.GetConnectionString()); + using var redis = await ConnectionMultiplexer.ConnectAsync( + fixture.Container.GetConnectionString() + ); await redis.GetDatabase().StringSetAsync("key", "value"); Assert.True(redis.IsConnected); } @@ -45,9 +51,11 @@ public async Task Test1() [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))] public async Task Test2() { - using var redis = await ConnectionMultiplexer.ConnectAsync(fixture.Container.GetConnectionString()); + using var redis = await ConnectionMultiplexer.ConnectAsync( + fixture.Container.GetConnectionString() + ); var redisValue = await redis.GetDatabase().StringGetAsync("key"); Assert.Equal("value", redisValue); } // # --8<-- [end:RunTests] -} \ No newline at end of file +} diff --git a/tests/Testcontainers.Xunit.Tests/Testcontainers.Xunit.Tests.csproj b/tests/Testcontainers.Xunit.Tests/Testcontainers.Xunit.Tests.csproj index f72f16ae8..7a2939957 100644 --- a/tests/Testcontainers.Xunit.Tests/Testcontainers.Xunit.Tests.csproj +++ b/tests/Testcontainers.Xunit.Tests/Testcontainers.Xunit.Tests.csproj @@ -1,27 +1,27 @@ - - net9.0 - false - false - - - - - - - - - - - - - - - - - - - PreserveNewest - - - \ No newline at end of file + + net9.0 + false + false + + + + + + + + + + + + + + + + + + + PreserveNewest + + + diff --git a/tests/Testcontainers.Xunit.Tests/Usings.cs b/tests/Testcontainers.Xunit.Tests/Usings.cs index f5132184e..0ee5f2e4d 100644 --- a/tests/Testcontainers.Xunit.Tests/Usings.cs +++ b/tests/Testcontainers.Xunit.Tests/Usings.cs @@ -16,4 +16,4 @@ global using Xunit.v3; #else global using Xunit.Abstractions; -#endif \ No newline at end of file +#endif diff --git a/tests/Testcontainers.XunitV3.Tests/Testcontainers.XunitV3.Tests.csproj b/tests/Testcontainers.XunitV3.Tests/Testcontainers.XunitV3.Tests.csproj index cd6595f8c..27bb53710 100644 --- a/tests/Testcontainers.XunitV3.Tests/Testcontainers.XunitV3.Tests.csproj +++ b/tests/Testcontainers.XunitV3.Tests/Testcontainers.XunitV3.Tests.csproj @@ -1,32 +1,32 @@ - - net9.0 - false - false - Exe - $(DefineConstants);XUNIT_V3 - - - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - \ No newline at end of file + + net9.0 + false + false + Exe + $(DefineConstants);XUNIT_V3 + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + +