Exemple #1
0
        private async Task TestDatabase(Func <string, string> funcAppSettings, Func <SqlCommand, long> validateNextHi, string entityName)
        {
            var testcontainersBuilder = new TestcontainersBuilder <MsSqlTestcontainer>()
                                        .WithDatabase(new MsSqlTestcontainerConfiguration
            {
                Password = "******",
            });

            await using var testcontainer = testcontainersBuilder.Build();
            await testcontainer.StartAsync();

            var builder = new ConfigurationBuilder();

            builder.AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(funcAppSettings(testcontainer.ConnectionString))));

            var  factory   = new HiLoGeneratorFactory(builder.Build());
            var  generator = factory.GetKeyGenerator(entityName);
            long key       = generator.GetKey();

            _output.WriteLine($"Key generated: '{key}'");
            key.Should().BeGreaterThan(0, "is expected the key to be greater than 0.");

            await using var connection = new SqlConnection(testcontainer.ConnectionString);
            connection.Open();
            await using var cmd = new SqlCommand();
            cmd.Connection      = connection;
            long nexttHi = validateNextHi(cmd);

            _output.WriteLine($"Next Hi value: '{nexttHi}'");
            nexttHi.Should().Be(2, "is expected the next Hi value to be equal to 2 (first execution).");
        }
        public async void InsertOnlyTimescale()
        {
            var image = await new ImageFromDockerfileBuilder()
                        .WithDockerfile("timescale.dockerfile")
                        .WithDockerfileDirectory("docker")
                        .WithDeleteIfExists(true)
                        .WithName("ohm-graphite-insert-only-timescale")
                        .Build();

            var testContainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                        .WithImage(image)
                                        .WithEnvironment("POSTGRES_PASSWORD", "123456")
                                        .WithPortBinding(5432, assignRandomHostPort: true)
                                        .WithWaitStrategy(Wait.ForUnixContainer()
                                                          .UntilCommandIsCompleted("pg_isready -h 'localhost' -p '5432'"));

            await using var container = testContainersBuilder.Build();
            await container.StartAsync();

            string selectStr = $"Host={container.Hostname};Username=postgres;Password=123456;Port={container.GetMappedPublicPort(5432)};Database=timescale_built";
            var    epoch     = new DateTime(2001, 1, 13);

            string connStr = $"Host={container.Hostname};Username=ohm;Password=itsohm;Port={container.GetMappedPublicPort(5432)};Database=timescale_built";

            using var writer     = new TimescaleWriter(connStr, false, "my-pc");
            await using var conn = new NpgsqlConnection(selectStr);
            await writer.ReportMetrics(epoch, TestSensorCreator.Values());

            conn.Open();
            await using var cmd = new NpgsqlCommand("SELECT COUNT(*) FROM ohm_stats", conn);
            Assert.Equal(3, Convert.ToInt32(cmd.ExecuteScalar()));
        }
Exemple #3
0
            public async Task OutputConsumer()
            {
                // Given
                using (var consumer = Consume.RedirectStdoutAndStderrToStream(new MemoryStream(), new MemoryStream()))
                {
                    // When
                    var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                                .WithImage("nginx")
                                                .WithCommand("/bin/sh", "-c", "hostname > /dev/stdout && hostname > /dev/stderr")
                                                .WithOutputConsumer(consumer);

                    await using (IDockerContainer testcontainer = testcontainersBuilder.Build())
                    {
                        await testcontainer.StartAsync();
                    }

                    consumer.Stdout.Position = 0;
                    consumer.Stderr.Position = 0;

                    // Then
                    using (var streamReader = new StreamReader(consumer.Stdout, leaveOpen: true))
                    {
                        Assert.NotEmpty(await streamReader.ReadToEndAsync());
                    }

                    using (var streamReader = new StreamReader(consumer.Stderr, leaveOpen: true))
                    {
                        Assert.NotEmpty(await streamReader.ReadToEndAsync());
                    }
                }
            }
        public async Task ConnectionEstablished()
        {
            // Given
            var testcontainersBuilder = new TestcontainersBuilder <RabbitMqTestcontainer>()
                                        .WithMessageBroker(new RabbitMqTestcontainerConfiguration
            {
                Username = "******",
                Password = "******",
            });

            // When
            // Then
            using (var testcontainer = testcontainersBuilder.Build())
            {
                await testcontainer.StartAsync();

                var factory = new ConnectionFactory {
                    Uri = new Uri(testcontainer.ConnectionString)
                };

                using (var connection = factory.CreateConnection())
                {
                    Assert.True(connection.IsOpen);
                }
            }
        }
Exemple #5
0
            public async Task BindMountAndEnvironment()
            {
                // Given
                const string target = "tmp";

                const string file = "dayOfWeek";

                var dayOfWeek = DateTime.UtcNow.DayOfWeek.ToString();

                // When
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("nginx")
                                            .WithEntrypoint("/bin/sh", "-c", $"printf $dayOfWeek > /{target}/{file} && tail -f /dev/null")
                                            .WithEnvironment("dayOfWeek", dayOfWeek)
                                            .WithBindMount(TempDir, $"/{target}")
                                            .WithWaitStrategy(Wait.ForUnixContainer()
                                                              .UntilFileExists(Path.Combine(TempDir, file)));

                await using (ITestcontainersContainer testcontainer = testcontainersBuilder.Build())
                {
                    await testcontainer.StartAsync();
                }

                // Then
                Assert.Equal(dayOfWeek, await File.ReadAllTextAsync(Path.Combine(TempDir, file)));
            }
Exemple #6
0
        private static async Task Main(string[] args)
        {
            Console.WriteLine("Press any key to start LocalStack container");
            Console.ReadLine();

            ITestcontainersBuilder <TestcontainersContainer> localStackBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                                                                 .WithName("LocalStack-0.12.10")
                                                                                 .WithImage("localstack/localstack:0.12.10")
                                                                                 .WithCleanUp(true)
                                                                                 .WithEnvironment("DEFAULT_REGION", "eu-central-1")
                                                                                 .WithEnvironment("SERVICES", "iam,lambda,dynamodb,apigateway,s3,sns,cloudformation,cloudwatch,sts")
                                                                                 .WithEnvironment("DOCKER_HOST", "unix:///var/run/docker.sock")
                                                                                 .WithEnvironment("LS_LOG", "info")
                                                                                 .WithPortBinding(4566, 4566);

            TestcontainersContainer container = localStackBuilder.Build();

            Console.WriteLine("Starting LocalStack Container");
            await container.StartAsync();

            Console.WriteLine("LocalStack Container started");

            Console.WriteLine("Press any key to stop LocalStack container");
            Console.ReadLine();

            Console.WriteLine("Stopping LocalStack Container");
            await container.StopAsync();

            Console.WriteLine("LocalStack Container stopped");
        }
        public KafkaFixture(IMessageSink messageSink)
        {
            var builder = new TestcontainersBuilder <KafkaTestcontainer>()
                          .WithKafka(new FixedKafkaTestcontainerConfiguration());

            _container = builder.Build();
        }
        public OracleSqlFixture()
        {
            var builder = new TestcontainersBuilder <OracleTestcontainer>()
                          .WithDatabase(new OracleTestcontainerConfiguration());

            _container = builder.Build();
        }
            public async Task OutputConsumer()
            {
                // Given
                using (var output = new OutputConsumerConsoleFixture())
                {
                    // When
                    var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                                .WithImage("nginx")
                                                .WithOutputConsumer(output)
                                                .WithCommand("/bin/bash", "-c", "hostname > /dev/stdout && hostname > /dev/stderr");

                    using (var testcontainer = testcontainersBuilder.Build())
                    {
                        await testcontainer.StartAsync();
                    }

                    output.Stdout.Position = 0;
                    output.Stderr.Position = 0;

                    // Then
                    using (var streamReader = new StreamReader(output.Stdout))
                    {
                        Assert.NotEmpty(streamReader.ReadToEnd());
                    }

                    using (var streamReader = new StreamReader(output.Stderr))
                    {
                        Assert.NotEmpty(streamReader.ReadToEnd());
                    }
                }
            }
        public LocalStackFixture(IOptions <LocalStackOptions> options, Amazon.Extensions.NETCore.Setup.AWSOptions awsOptions)
        {
            var localStackBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                    .WithImage("localstack/localstack")
                                    .WithCleanUp(true)
                                    .WithOutputConsumer(Consume.RedirectStdoutAndStderrToConsole())
                                    .WithEnvironment("DEFAULT_REGION", "eu-central-1")
                                    .WithEnvironment("SERVICES", "s3")
                                    .WithEnvironment("DOCKER_HOST", "unix:///var/run/docker.sock")
                                    .WithEnvironment("DEBUG", "1")
                                    .WithPortBinding(4566, 4566);

            if (awsOptions != null)
            {
                if (awsOptions.Credentials != null)
                {
                    var awsCreds = awsOptions.Credentials.GetCredentials();
                    localStackBuilder.WithEnvironment("AWS_ACCESS_KEY_ID", awsCreds.AccessKey)
                    .WithEnvironment("AWS_SECRET_ACCESS_KEY", awsCreds.SecretKey);
                }
            }

            _localStackContainer = localStackBuilder.Build();
            this.options         = options;
        }
Exemple #11
0
            public async Task VolumeAndEnvironment()
            {
                // Given
                const string target = "tmp";

                const string file = "dayOfWeek";

                var dayOfWeek = DateTime.Now.DayOfWeek.ToString();

                // When
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("nginx")
                                            .WithCommand("/bin/sh", "-c", $"printf $dayOfWeek > /{target}/{file}")
                                            .WithEnvironment("dayOfWeek", dayOfWeek)
                                            .WithMount(TempDir, $"/{target}")
                                            .WithWaitStrategy(Wait.ForUnixContainer()
                                                              .UntilFileExists($"{TempDir}/{file}"));

                await using (IDockerContainer testcontainer = testcontainersBuilder.Build())
                {
                    await testcontainer.StartAsync();
                }

                // Then
                Assert.Equal(dayOfWeek, await File.ReadAllTextAsync($"{TempDir}/{file}"));
            }
        public ElasticsearchFixture()
        {
            var containerBuilder = new TestcontainersBuilder <ElasticsearchTestContainer>()
                                   .WithElasticsearch(new ElasticsearchTestContainerConfiguration());

            _container = containerBuilder.Build();
        }
        public async Task ConnectionEstablished()
        {
            // Given
            var testcontainersBuilder = new TestcontainersBuilder <MsSqlTestcontainer>()
                                        .WithDatabase(new MsSqlTestcontainerConfiguration
            {
                Password = "******", // See following password policy: https://hub.docker.com/r/microsoft/mssql-server-linux/
            });

            // When
            // Then
            await using (var testcontainer = testcontainersBuilder.Build())
            {
                await testcontainer.StartAsync();

                await using (var connection = new SqlConnection(testcontainer.ConnectionString))
                {
                    connection.Open();

                    await using (var cmd = new SqlCommand())
                    {
                        cmd.Connection  = connection;
                        cmd.CommandText = "SELECT 1";
                        cmd.ExecuteReader();
                    }
                }
            }
        }
Exemple #14
0
        public static async Task Main(string[] args)
        {
            // requires docker to run a redis container.
            var containerBuilder = new TestcontainersBuilder <RedisTestcontainer>()
                                   .WithDatabase(new RedisTestcontainerConfiguration());

            await using var container = containerBuilder.Build();
            await container.StartAsync();

            var connection = await ConnectionMultiplexer.ConnectAsync(container.ConnectionString);

            connection.UseElasticApm();

            for (var i = 0; i < 10; i++)
            {
                // async
                await Agent.Tracer.CaptureTransaction("Set and Get String", ApiConstants.TypeDb, async() =>
                {
                    var database = connection.GetDatabase();
                    await database.StringSetAsync($"string{i}", i);
                    await database.StringGetAsync($"string{i}");

                    // fire and forget commands may not end up in the profiling session before
                    // transaction end, and the profiling session is finished.
                    await database.StringSetAsync($"string{i}", i, flags: CommandFlags.FireAndForget);
                    await database.StringGetAsync($"string{i}", CommandFlags.FireAndForget);
                });
            }

            await container.StopAsync();
        }
        public TestServerFixture()
        {
            var databaseBuilder = new TestcontainersBuilder <PostgreSqlTestcontainer>()
                                  .WithName($"postgres-integration-{DateTime.Now.Ticks}")
                                  .WithCleanUp(true)
                                  .WithDatabase(new PostgreSqlTestcontainerConfiguration("postgres:13")
            {
                Password = "******",
                Database = "gmapsservicestestdb",
                Username = "******",
                Port     = 5432
            });

            var builder = new WebHostBuilder()
                          .UseEnvironment("Test")
                          .UseConfiguration(new ConfigurationBuilder()
                                            .AddJsonFile("appsettings.test.json")
                                            .Build())
                          .UseStartup <Startup>()
                          .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration));

            _testServer = new TestServer(builder)
            {
                AllowSynchronousIO = true
            };

            GMapsServicesContext = _testServer.Services.GetService(typeof(GMapsServicesContext)) as GMapsServicesContext;

            Client = _testServer.CreateClient();

            _postgreSqlTestcontainer = databaseBuilder.Build();
        }
Exemple #16
0
        public async Task ConnectionEstablished()
        {
            // Given
            var testcontainersBuilder = new TestcontainersBuilder <PostgreSqlTestcontainer>()
                                        .WithDatabase(new PostgreSqlTestcontainerConfiguration
            {
                Database = "db",
                Username = "******",
                Password = "******",
            });

            // When
            // Then
            using (var testcontainer = testcontainersBuilder.Build())
            {
                await testcontainer.StartAsync();

                using (var connection = new NpgsqlConnection(testcontainer.ConnectionString))
                {
                    connection.Open();

                    using (var cmd = new NpgsqlCommand())
                    {
                        cmd.Connection  = connection;
                        cmd.CommandText = "SELECT 1";
                        cmd.ExecuteReader();
                    }
                }
            }
        }
        public async Task InitializeAsync()
        {
            try
            {
                var testcontainersBuilder = new TestcontainersBuilder <MySql56Testcontainer>()
                                            .WithDatabase(new MySql56TestcontainerConfiguration
                {
                    Database = "integrationdefaultdb",
                    Username = "******",
                    Password = this.Password,
                });

                mySqlTestcontainer = testcontainersBuilder.Build();
                await mySqlTestcontainer.StartAsync();

                var databaseMigrationsImageBuilder = new ImageFromDockerfileBuilder()
                                                     .WithName("template-integration-db-migrations")
                                                     .WithDockerfile("Dockerfile")
                                                     .WithDockerfileDirectory("../../../../../db/")
                                                     .WithDeleteIfExists(true);
                this.databaseMigrationsImage = await databaseMigrationsImageBuilder.Build();

                var connectionString = mySqlTestcontainer.ConnectionString;
                connectionString = connectionString.Replace("localhost", "host.docker.internal");
                var databaseMigrationsContainerBuilder = new TestcontainersBuilder <MigrationsTestcontainer>()
                                                         .WithImage(databaseMigrationsImage)
                                                         .WithCommand($"-cs {connectionString}")
                                                         .WithWaitStrategy(Wait.ForUnixContainer());
                this.migrationsTestcontainer = databaseMigrationsContainerBuilder.Build();
                try
                {
                    await migrationsTestcontainer.StartAsync();

                    var exitCode = await migrationsTestcontainer.GetExitCode();

                    if (exitCode > 0)
                    {
                        throw new Exception("Database migrations failed");
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                this.ConnectionStringProvider = new ConnectionStringProvider(new DatabaseOptions
                {
                    Server   = this.Hostname,
                    Port     = this.Port,
                    Username = "******",
                    Password = this.Password,
                });
            }
            catch (Exception e)
            {
                throw;
            }
        }
Exemple #18
0
        public async Task Should_RaiseError_When_LackOfCreateTablePermission()
        {
            var testcontainersBuilder = new TestcontainersBuilder <MsSqlTestcontainer>()
                                        .WithDatabase(new MsSqlTestcontainerConfiguration
            {
                Password = "******",
            });

            await using var testcontainer = testcontainersBuilder.Build();
            await testcontainer.StartAsync();

            string prepareDbScript = @"
                sp_configure 'show advanced options',1
                GO
                RECONFIGURE WITH OVERRIDE
                GO
                sp_configure 'contained database authentication', 1
                GO
                RECONFIGURE WITH OVERRIDE
                GO

                CREATE DATABASE [testDB] CONTAINMENT = PARTIAL;
                GO

                CREATE LOGIN [nhilo_user] WITH PASSWORD = '******';
                GO

                USE [testDB];
                GO

                CREATE USER [nhilo_user] FOR LOGIN [nhilo_user];
                GO
            ";
            await testcontainer.ExecScriptAsync(prepareDbScript);

            var builder = new ConfigurationBuilder();

            builder.AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(
                                                       $@"{{
                    ""NHiLo"":{{
                        ""DefaultMaxLo"" : ""100""
                    }},
                    ""ConnectionStrings"":{{
                        ""NHiLo"":{{
                            ""ConnectionString"":""Server={ testcontainer.Hostname },{ testcontainer.Port };Database=testDB;User Id=nhilo_user;Password=nhilo_p@ssW0rd;"",
                            ""ProviderName"":""Microsoft.Data.SqlClient""
                        }}
                    }}
                }}"
                                                       )));
            var    factory = new HiLoGeneratorFactory(builder.Build());
            Action act     = () => factory.GetKeyGenerator("MSSqlSequenceEntity");

            act.Should().Throw <NHiLoException>()
            .WithInnerException <SqlException>()
            .Where(ex => ex.Number == 262, "262 is the SQL Server's error code for lack of create table permission");
        }
Exemple #19
0
        public SqlServerFixture()
        {
            var containerBuilder = new TestcontainersBuilder <MsSqlTestcontainer>()
                                   .WithDatabase(new MsSqlTestcontainerConfiguration
            {
                Password = "******"
            });

            _container = containerBuilder.Build();
        }
Exemple #20
0
        public async void CanInsertIntoInflux2Token()
        {
            var testContainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                        .WithDockerEndpoint(DockerUtils.DockerEndpoint())
                                        .WithImage("influxdb:2.0-alpine")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_MODE", "setup")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_USERNAME", "my-user")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_PASSWORD", "my-password")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_BUCKET", "mydb")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_ORG", "myorg")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_ADMIN_TOKEN", "thisistheinfluxdbtoken")
                                        .WithPortBinding(8086, assignRandomHostPort: true)
                                        .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(8086));

            await using var container = testContainersBuilder.Build();
            await container.StartAsync();

            var baseUrl   = $"http://{container.Hostname}:{container.GetMappedPublicPort(8086)}";
            var configMap = new ExeConfigurationFileMap {
                ExeConfigFilename = "assets/influx2.config"
            };
            var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

            config.AppSettings.Settings["influx2_address"].Value = baseUrl;
            var customConfig = new CustomConfig(config);
            var results      = MetricConfig.ParseAppSettings(customConfig);

            using var writer = new Influx2Writer(results.Influx2, "my-pc");
            for (int attempts = 0;; attempts++)
            {
                try
                {
                    await writer.ReportMetrics(DateTime.Now, TestSensorCreator.Values());

                    var influxDBClient = InfluxDBClientFactory.Create(results.Influx2.Options);
                    var flux           = "from(bucket:\"mydb\") |> range(start: -1h)";
                    var queryApi       = influxDBClient.GetQueryApi();
                    var tables         = await queryApi.QueryAsync(flux, "myorg");

                    var fields = tables.SelectMany(x => x.Records).Select(x => x.GetValueByKey("identifier"));
                    Assert.Contains("/intelcpu/0/temperature/0", fields);
                    break;
                }
                catch (Exception)
                {
                    if (attempts >= 10)
                    {
                        throw;
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }
        }
Exemple #21
0
        public MySqlFixture()
        {
            var builder = new TestcontainersBuilder <MySqlTestcontainer>()
                          .WithDatabase(new MySqlTestcontainerConfiguration
            {
                Database = MySqlDatabaseName,
                Username = MySqlUsername,
                Password = MySqlPassword
            });

            _container = builder.Build();
        }
Exemple #22
0
        public async void CanInsertIntoInflux2()
        {
            var testContainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                        .WithDockerEndpoint(DockerUtils.DockerEndpoint())
                                        .WithImage("influxdb:2.0-alpine")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_MODE", "setup")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_USERNAME", "my-user")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_PASSWORD", "my-password")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_BUCKET", "mydb")
                                        .WithEnvironment("DOCKER_INFLUXDB_INIT_ORG", "myorg")
                                        .WithPortBinding(8086, assignRandomHostPort: true)
                                        .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(8086));

            await using var container = testContainersBuilder.Build();
            await container.StartAsync();

            var baseUrl = $"http://{container.Hostname}:{container.GetMappedPublicPort(8086)}";
            var options = new InfluxDBClientOptions.Builder()
                          .Url(baseUrl)
                          .Authenticate("my-user", "my-password".ToCharArray())
                          .Bucket("mydb")
                          .Org("myorg")
                          .Build();

            var config = new Influx2Config(options);

            using var writer = new Influx2Writer(config, "my-pc");
            for (int attempts = 0;; attempts++)
            {
                try
                {
                    await writer.ReportMetrics(DateTime.Now, TestSensorCreator.Values());

                    var influxDBClient = InfluxDBClientFactory.Create(options);
                    var flux           = "from(bucket:\"mydb\") |> range(start: -1h)";
                    var queryApi       = influxDBClient.GetQueryApi();
                    var tables         = await queryApi.QueryAsync(flux, "myorg");

                    var fields = tables.SelectMany(x => x.Records).Select(x => x.GetValueByKey("identifier"));
                    Assert.Contains("/intelcpu/0/temperature/0", fields);
                    break;
                }
                catch (Exception)
                {
                    if (attempts >= 10)
                    {
                        throw;
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }
        }
Exemple #23
0
        private TestcontainersContainer PrepareVaultContainer()
        {
            var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                        .WithImage("vault")
                                        .WithName("vaultsharp_test")
                                        .WithPortBinding(8200, 8200)
                                        .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(8200))
                                        .WithEnvironment("VAULT_DEV_ROOT_TOKEN_ID", "root")
                                        .WithEnvironment("VAULT_DEV_LISTEN_ADDRESS", "0.0.0.0:8200");

            return(testcontainersBuilder.Build());
        }
        public PostgreSqlFixture()
        {
            var postgresBuilder = new TestcontainersBuilder <PostgreSqlTestcontainer>()
                                  .WithDatabase(new PostgreSqlTestcontainerConfiguration
            {
                Database = PostgresDatabase,
                Username = PostgresUserName,
                Password = PostgresPassword
            });

            _container = postgresBuilder.Build();
        }
Exemple #25
0
        public async Task Should_ConnectToABrandNewDatabaseAndGetKey()
        {
            var testcontainersBuilder = new TestcontainersBuilder <MySqlTestcontainer>()
                                        .WithDatabase(new MySqlTestcontainerConfiguration
            {
                Database = "myDataBase",
                Username = "******",
                Password = "******",
            });

            await using (var testcontainer = testcontainersBuilder.Build())
            {
                await testcontainer.StartAsync();

                var appSettings = $@"{{
                    ""NHiLo"":{{
                        ""DefaultMaxLo"" : ""100""
                    }},
                    ""ConnectionStrings"":{{
                        ""NHiLo"":{{
                            ""ConnectionString"":""{ testcontainer.ConnectionString }"",
                            ""ProviderName"":""MySql.Data.MySqlClient""
                        }}
                    }}
                }}";
                var builder     = new ConfigurationBuilder();
                builder.AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(appSettings)));
                var factory = new HiLoGeneratorFactory(builder.Build());

                var  generator = factory.GetKeyGenerator("myMySqlEntity");
                long key       = generator.GetKey();
                _output.WriteLine($"Key generated: '{key}'");
                key.Should().BeGreaterThan(0, "is expected the key to be greater than 0.");

                await using (var connection = new MySqlConnection(testcontainer.ConnectionString))
                {
                    connection.Open();
                    await using (var cmd = new MySqlCommand())
                    {
                        cmd.Connection  = connection;
                        cmd.CommandText = "SELECT * FROM NHILO WHERE ENTITY = 'myMySqlEntity'";
                        using (var reader = cmd.ExecuteReader())
                        {
                            reader.Read();
                            long nexttHi = reader.GetInt64("NEXT_HI");
                            _output.WriteLine($"Next Hi value: '{nexttHi}'");
                            nexttHi.Should().Be(2, "is expected the next Hi value to be equal to 2 (first execution).");
                        }
                    }
                }
            }
        }
Exemple #26
0
            public async Task Disposable()
            {
                // Given
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("mcr.microsoft.com/windows/nanoserver:1809");

                // When
                // Then
                using (var testcontainer = testcontainersBuilder.Build())
                {
                    await testcontainer.StartAsync();
                }
            }
        public async Task InitializeAsync()
        {
            var containerBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                   .WithImage("sf-node-test-srv")
                                   .WithName("sf-node-container")
                                   .WithPortBinding(3001)
                                   .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(3001));

            Container = containerBuilder.Build();
            await Container.StartAsync();

            PublicPort = Container.GetMappedPublicPort(3001);
        }
        protected TestcontainersContainer BuildConsulContainer()
        {
            var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                        .WithImage(CONTAINER_IMAGE)
                                        .WithName(CONTAINER_NAME)
                                        .WithEnvironment("POSTGRES_USER", DB_USER)
                                        .WithEnvironment("POSTGRES_PASSWORD", DB_PWD)
                                        .WithEnvironment("POSTGRES_DB", DB_DEFAULT)
                                        .WithPortBinding(CONTAINER_PORT, CONTAINER_PORT)
                                        .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(CONTAINER_PORT));

            return(testcontainersBuilder.Build());
        }
        public LocalStackFixture()
        {
            var localStackBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                    .WithImage("localstack/localstack")
                                    .WithCleanUp(true)
                                    .WithEnvironment("DEFAULT_REGION", "eu-central-1")
                                    .WithEnvironment("SERVICES", "dynamodb,sqs")
                                    .WithEnvironment("DOCKER_HOST", "unix:///var/run/docker.sock")
                                    .WithEnvironment("DEBUG", "1")
                                    .WithPortBinding(4566, 4566);

            _localStackContainer = localStackBuilder.Build();
        }
Exemple #30
0
            public async Task SafeDisposable()
            {
                // Given
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("alpine");

                // When
                // Then
                await using (IDockerContainer testcontainer = testcontainersBuilder.Build())
                {
                    await testcontainer.StartAsync();
                }
            }