public TestcontainersVolumeTest(VolumeFixture volumeFixture)
        {
            var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                        .WithImage("alpine")
                                        .WithEntrypoint("/bin/sh", "-c")
                                        .WithCommand("touch /tmp/$(uname -n) && tail -f /dev/null")
                                        .WithResourceReaperSessionId(volumeFixture.SessionId)
                                        .WithVolumeMount(volumeFixture.Name, Destination);

            this.testcontainer1 = testcontainersBuilder
                                  .WithHostname(nameof(this.testcontainer1))
                                  .Build();

            this.testcontainer2 = testcontainersBuilder
                                  .WithHostname(nameof(this.testcontainer2))
                                  .Build();
        }
Пример #2
0
            public async Task DockerEndpoint()
            {
                // Given
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithDockerEndpoint(TestcontainersSettings.OS.DockerEndpointAuthConfig)
                                            .WithImage("alpine")
                                            .WithEntrypoint(KeepTestcontainersUpAndRunning.Command);

                // When
                // Then
                await using (ITestcontainersContainer testcontainer = testcontainersBuilder.Build())
                {
                    var exception = await Record.ExceptionAsync(() => testcontainer.StartAsync());

                    Assert.Null(exception);
                }
            }
Пример #3
0
    private async Task <TestcontainersContainer> LaunchMongoContainerAsync(int port)
    {
        var waitOS = EnvironmentTools.IsWindows()
            ? Wait.ForWindowsContainer()
            : Wait.ForUnixContainer();

        var mongoContainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                     .WithImage(MongoDbImage)
                                     .WithName($"mongo-db-{port}")
                                     .WithPortBinding(port, MongoDbPort)
                                     .WithWaitStrategy(waitOS.UntilPortIsAvailable(MongoDbPort));

        var container = mongoContainersBuilder.Build();
        await container.StartAsync();

        return(container);
    }
Пример #4
0
            public async Task WorkingDirectory()
            {
                // Given
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("alpine")
                                            .WithCommand("/bin/sh", "-c", "test -d /tmp && exit $? || exit $?")
                                            .WithWorkingDirectory("/tmp");

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

                    Assert.Equal(0, await testcontainer.GetExitCode());
                }
            }
            public async Task QueryContainerInformationOfRunningContainer()
            {
                // Given
                // When
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("nginx");

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

                    Assert.NotEmpty(testcontainer.Name);
                    Assert.NotEmpty(testcontainer.IPAddress);
                    Assert.NotEmpty(testcontainer.MacAddress);
                }
            }
Пример #6
0
        public TestcontainersNetworkTest(NetworkFixture networkFixture)
        {
            var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                        .WithImage("alpine")
                                        .WithEntrypoint(KeepTestcontainersUpAndRunning.Command)
                                        .WithNetwork(networkFixture.Network.Id, networkFixture.Network.Name);

            this.testcontainer1 = testcontainersBuilder
                                  .WithHostname(nameof(this.testcontainer1))
                                  .WithNetworkAliases(nameof(this.testcontainer1) + AliasSuffix)
                                  .Build();

            this.testcontainer2 = testcontainersBuilder
                                  .WithHostname(nameof(this.testcontainer2))
                                  .WithNetworkAliases(nameof(this.testcontainer2) + AliasSuffix)
                                  .Build();
        }
            public async Task QueryContainerInformationOfNotCreatedContainer()
            {
                // Given
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("nginx");

                // When
                // Then
                await using (IDockerContainer testcontainer = testcontainersBuilder.Build())
                {
                    Assert.Throws <InvalidOperationException>(() => testcontainer.Name);
                    Assert.Throws <InvalidOperationException>(() => testcontainer.IpAddress);
                    Assert.Throws <InvalidOperationException>(() => testcontainer.MacAddress);
                    Assert.Throws <InvalidOperationException>(() => testcontainer.GetMappedPublicPort(0));
                    await Assert.ThrowsAsync <InvalidOperationException>(() => testcontainer.StopAsync());
                }
            }
Пример #8
0
            public async Task ExposedPorts()
            {
                // Given
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("alpine")
                                            .WithEntrypoint(KeepTestcontainersUpAndRunning.Command)
                                            .WithExposedPort(80);

                // When
                // Then
                await using (ITestcontainersContainer testcontainer = testcontainersBuilder.Build())
                {
                    var exception = await Record.ExceptionAsync(() => testcontainer.StartAsync());

                    Assert.Null(exception);
                }
            }
Пример #9
0
            public async Task RandomHostPortBindings()
            {
                // Given
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("nginx")
                                            .WithEntrypoint(KeepTestcontainersUpAndRunning.Command)
                                            .WithPortBinding(80, true);

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

                    Assert.NotEqual(0, testcontainer.GetMappedPublicPort(80));
                }
            }
Пример #10
0
        public async void InsertTagGraphiteTest()
        {
            var testContainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                        .WithDockerEndpoint(DockerUtils.DockerEndpoint())
                                        .WithImage("graphiteapp/graphite-statsd")
                                        .WithEnvironment("REDIS_TAGDB", "y")
                                        .WithPortBinding(2003, assignRandomHostPort: true)
                                        .WithPortBinding(80, assignRandomHostPort: true)
                                        .WithPortBinding(8080, assignRandomHostPort: true)
                                        .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(8080));

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

            var port = container.GetMappedPublicPort(2003);

            using var writer = new GraphiteWriter(container.Hostname, port, "my-pc", tags: true);
            using var client = new HttpClient();
            for (int attempts = 0;; attempts++)
            {
                try
                {
                    await writer.ReportMetrics(DateTime.Now, TestSensorCreator.Values());

                    var resp = await client.GetAsync(
                        $"http://{container.Hostname}:{container.GetMappedPublicPort(80)}/render?format=csv&target=seriesByTag('sensor_type=Temperature','hardware_type=CPU')");

                    var content = await resp.Content.ReadAsStringAsync();

                    Assert.Contains("host=my-pc", content);
                    Assert.Contains("app=ohm", content);
                    Assert.Contains("sensor_type=Temperature", content);
                    break;
                }
                catch (Exception)
                {
                    if (attempts >= 10)
                    {
                        throw;
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }
        }
Пример #11
0
        public async void CanInsertIntoPasswordLessInfluxdb()
        {
            var testContainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                        .WithDockerEndpoint(DockerUtils.DockerEndpoint())
                                        .WithImage("influxdb:1.8-alpine")
                                        .WithEnvironment("INFLUXDB_DB", "mydb")
                                        .WithEnvironment("INFLUXDB_USER", "my_user")
                                        .WithEnvironment("INFLUXDB_HTTP_AUTH_ENABLED", "false")
                                        .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 config  = new InfluxConfig(new Uri(baseUrl), "mydb", "my_user", null);

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

                    var resp = await client.GetAsync(
                        $"{baseUrl}/query?pretty=true&db=mydb&q=SELECT%20*%20FROM%20Temperature");

                    Assert.True(resp.IsSuccessStatusCode);
                    var content = await resp.Content.ReadAsStringAsync();

                    Assert.Contains("/intelcpu/0/temperature/0", content);
                    break;
                }
                catch (Exception)
                {
                    if (attempts >= 10)
                    {
                        throw;
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }
        }
            public async Task UntilPortIsAvailable()
            {
                // Given
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("mcr.microsoft.com/windows/servercore:ltsc2019")
                                            .WithEntrypoint("PowerShell", "-NoLogo", "-Command", "$tcpListener = [System.Net.Sockets.TcpListener]1337; $tcpListener.Start(); ping -t localhost | Out-Null")
                                            .WithWaitStrategy(Wait.ForWindowsContainer()
                                                              .UntilPortIsAvailable(1337));

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

                    Assert.True(true);
                }
            }
            public async Task UntilCommandIsCompleted()
            {
                // Given
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("mcr.microsoft.com/windows/servercore:ltsc2019")
                                            .WithEntrypoint("PowerShell", "-NoLogo", "-Command", "ping -t localhost | Out-Null")
                                            .WithWaitStrategy(Wait.ForWindowsContainer()
                                                              .UntilCommandIsCompleted("Exit !(Test-Path -Path 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe')"));

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

                    Assert.True(true);
                }
            }
Пример #14
0
        private TestcontainersContainer BuildSqlServerTestContainer(IServiceProvider serviceProvider)
        {
            var    toDoDbContext             = serviceProvider.GetRequiredService <ToDoDbContext>();
            string connectionString          = toDoDbContext.Database.GetConnectionString();
            var    dbConnectionStringBuilder = new SqlConnectionStringBuilder(connectionString);
            int    portNumber = int.Parse(dbConnectionStringBuilder.DataSource.Split(",")[1]);
            ITestcontainersBuilder <MsSqlTestcontainer> testContainersBuilder
                = new TestcontainersBuilder <MsSqlTestcontainer>()
                  .WithDatabase(new MsSqlTestcontainerConfiguration
            {
                Password = dbConnectionStringBuilder.Password,
                Port     = portNumber
            });

            MsSqlTestcontainer dbTestContainer = testContainersBuilder.Build();

            return(dbTestContainer);
        }
Пример #15
0
        public async Task ConnectionEstablished()
        {
            // Given
            var testcontainersBuilder = new TestcontainersBuilder <RedisTestcontainer>()
                                        .WithDatabase(new RedisTestcontainerConfiguration()); // TODO: Until now the configuration is not applied by `RedisTestcontainerConfiguration`. Use `WithCommand` or mount redis.conf instead.

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

                using (var connection = ConnectionMultiplexer.Connect(testcontainer.ConnectionString))
                {
                    Assert.True(connection.GetServer(testcontainer.Hostname, testcontainer.Port).Ping().Milliseconds > 0, "Cannot connect to Redis Testcontainer.");
                }
            }
        }
Пример #16
0
        public async Task UsingResourceReaperSessionIdDoesNotStartDefaultResourceReaper()
        {
            // Given
            var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                        .WithImage("nginx")
                                        .WithAutoRemove(true)
                                        .WithResourceReaperSessionId(Guid.NewGuid());

            // When
            await using (ITestcontainersContainer testcontainer = testcontainersBuilder.Build())
            {
                await testcontainer.StartAsync()
                .ConfigureAwait(false);
            }

            // Then
            Assert.False(Docker.Exists(DockerResource.Container, DefaultRyukContainerName));
        }
Пример #17
0
        public TestcontainersContainer CreateMySqlContainer()
        {
            var container = new TestcontainersBuilder <TestcontainersContainer>()
                            .WithImage("node:6.11-slim")
                            .WithWorkingDirectory("/mocks")
                            .WithMount("../../../../dependencies/stubby/", "/mocks")
                            .WithEntrypoint("/bin/sh", "-c", "npm install -g [email protected] && stubby -d /mocks/init.yml -s 8882 -a 8889 -w")
                            .WithCleanUp(false)
                            .WithExposedPort("8882")
                            .WithCleanUp(true)
                            .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(8882))
                            .WithPortBinding("8882", true)
                            .Build();

            container.StartAsync().ConfigureAwait(false).GetAwaiter().GetResult();

            return(container);
        }
Пример #18
0
            public async Task ExecCommandInRunningContainerWithStderr()
            {
                // Given
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("alpine")
                                            .WithEntrypoint(KeepTestcontainersUpAndRunning.Command);

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

                    var execResult = await testcontainer.ExecAsync(new[] { "/bin/sh", "-c", "cd missing_directory" });

                    Assert.Contains("can't cd to missing_directory", execResult.Stderr);
                }
            }
Пример #19
0
            public async Task SpecifiedContainerName()
            {
                // Given
                const string name = "/alpine";

                // When
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("alpine")
                                            .WithName(name);

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

                    Assert.Equal(name, testcontainer.Name);
                }
            }
Пример #20
0
            public async Task ExecCommandInRunningContainerWithStdout()
            {
                // Given
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("alpine")
                                            .WithEntrypoint(KeepTestcontainersUpAndRunning.Command);

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

                    var execResult = await testcontainer.ExecAsync(new[] { "/bin/sh", "-c", "ping -c 4 google.com" });

                    Assert.Contains("PING google.com", execResult.Stdout);
                }
            }
Пример #21
0
            public async Task ExecCommandInRunningContainer()
            {
                // Given
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("alpine")
                                            .WithEntrypoint(KeepTestcontainersUpAndRunning.Command);

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

                    var execResult = await testcontainer.ExecAsync(new[] { "/bin/sh", "-c", "exit 255" });

                    Assert.Equal(255, execResult.ExitCode);
                }
            }
Пример #22
0
            public async Task WaitStrategy()
            {
                // Given
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("alpine")
                                            .WithEntrypoint(KeepTestcontainersUpAndRunning.Command)
                                            .WithWaitStrategy(Wait.ForUnixContainer()
                                                              .AddCustomWaitStrategy(new WaitUntilFiveSecondsPassedFixture()));

                // When
                // Then
                await using (ITestcontainersContainer testcontainer = testcontainersBuilder.Build())
                {
                    var exception = await Record.ExceptionAsync(() => testcontainer.StartAsync());

                    Assert.Null(exception);
                }
            }
Пример #23
0
        private async Task <string> StartContainerAsync()
        {
            var postgresBuilder = new TestcontainersBuilder <PostgreSqlTestcontainer>()
                                  .WithDatabase(new PostgreSqlTestcontainerConfiguration {
                Database = "AnimalsDatabase",
                Username = "******",
                Password = "******"
            })
                                  .WithExposedPort(5432);

            _database = postgresBuilder.Build();
            await _database.StartAsync();

            _connection = new NpgsqlConnection(_database.ConnectionString);
            await _connection.OpenAsync();

            //No idea why the password is missing in the connection string
            return($"{_connection.ConnectionString};Password={_database.Password}");
        }
Пример #24
0
            public async Task Hostname()
            {
                // Given
                const string hostname = "alpine";

                // When
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("alpine")
                                            .WithEntrypoint("/bin/sh", "-c", $"hostname | grep '{hostname}' &> /dev/null")
                                            .WithHostname(hostname);

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

                    Assert.Equal(0, await testcontainer.GetExitCode());
                }
            }
Пример #25
0
            public async Task SpecifiedContainerName()
            {
                // Given
                var name = Guid.NewGuid().ToString("D");

                // When
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("alpine")
                                            .WithEntrypoint(KeepTestcontainersUpAndRunning.Command)
                                            .WithName(name);

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

                    Assert.EndsWith(name, testcontainer.Name);
                }
            }
Пример #26
0
        public async Task InitializeAsync()
        {
            //for the moment, use this testcontainer for dotnet https://github.com/HofmeisterAn/dotnet-testcontainers
            ITestcontainersBuilder <PostgreSqlTestcontainer> postgresBuilder =
                new TestcontainersBuilder <PostgreSqlTestcontainer>()
                .WithDatabase(new PostgreSqlTestcontainerConfiguration("postgres:11.5")
            {
                Database = "db",
                Username = "******",
                Password = "******",
            })
                .WithExposedPort(5432);

            _postgres = postgresBuilder.Build();
            await _postgres.StartAsync();

            _connection = new NpgsqlConnection(_postgres.ConnectionString);
            await _connection.OpenAsync();
        }
Пример #27
0
        public async Task GlobalSetupAsync()
        {
            var instanceBaseUrl = Environment.GetEnvironmentVariable(BaseHassWSApiTest.TestsInstanceBaseUrlVar);

            if (instanceBaseUrl == null)
            {
                // Create temporary directory
                var tmpDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                Directory.CreateDirectory(tmpDirectory);

                // Copy create_token script
                const string createTokenScriptPath     = "./resources/scripts/create_token.py";
                var          createTokenScriptFilename = Path.GetFileName(createTokenScriptPath);
                File.Copy(Path.GetFullPath(createTokenScriptPath), Path.Combine(tmpDirectory, createTokenScriptFilename));

                const int    HassPort              = 8123;
                const string HassVersion           = "latest";
                const string hassConfigPath        = "./resources/config";
                const string tokenFilename         = "TOKEN";
                var          testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                                     .WithImage($"homeassistant/home-assistant:{HassVersion}")
                                                     .WithPortBinding(HassPort, assignRandomHostPort: true)
                                                     .WithExposedPort(HassPort)
                                                     .WithBindMount(Path.GetFullPath(hassConfigPath), "/config")
                                                     .WithBindMount(tmpDirectory, "/tmp")
                                                     .WithWaitStrategy(Wait.ForUnixContainer()
                                                                       .UntilPortIsAvailable(HassPort))
                                                     .WithEntrypoint("/bin/bash", "-c")
                                                     .WithCommand($"python3 /tmp/{createTokenScriptFilename} >/tmp/{tokenFilename} && /init");

                this.hassContainer = testcontainersBuilder.Build();
                await this.hassContainer.StartAsync();

                var mappedPort    = this.hassContainer.GetMappedPublicPort(HassPort);
                var hostTokenPath = Path.Combine(tmpDirectory, tokenFilename);
                var accessToken   = File.ReadLines(hostTokenPath).First();

                Environment.SetEnvironmentVariable(BaseHassWSApiTest.TestsInstanceBaseUrlVar, $"http://localhost:{mappedPort}");
                Environment.SetEnvironmentVariable(BaseHassWSApiTest.TestsAccessTokenVar, accessToken);
            }
        }
Пример #28
0
        public async Task <(string, DbConnection)> StartAsync()
        {
            var postgresBuilder = new TestcontainersBuilder <PostgreSqlTestcontainer>()
                                  .WithName($"EvoMaster-DB-Postgres-{Guid.NewGuid()}")
                                  .WithDatabase(new PostgreSqlTestcontainerConfiguration {
                Database = DatabaseName,
                Username = "******",
                Password = Password
            })
                                  .WithExposedPort(Port).WithCleanUp(true);

            _database = postgresBuilder.Build();
            await _database.StartAsync();

            _connection = new NpgsqlConnection(_database.ConnectionString);
            await _connection.OpenAsync();

            //No idea why the password is missing in the connection string
            var connectionString = $"{_connection.ConnectionString};Password={_database.Password}";

            return(connectionString, _connection);
        }
            public async Task VolumeAndCommand()
            {
                // Given
                const string target = "tmp";

                const string file = "hostname";

                // When
                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("nginx")
                                            .WithMount(TempDir, $"/{target}")
                                            .WithWaitStrategy(Wait.UntilFilesExists($"{TempDir}/{file}"))
                                            .WithCommand("/bin/bash", "-c", $"hostname > /{target}/{file}");

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

                // Then
                Assert.True(File.Exists($"{TempDir}/{file}"), $"{file} does not exist.");
            }
Пример #30
0
            public async Task AutoRemoveTrueShouldRemoveContainer()
            {
                // Given
                string testcontainerId;

                var testcontainersBuilder = new TestcontainersBuilder <TestcontainersContainer>()
                                            .WithImage("alpine")
                                            .WithAutoRemove(true)
                                            .WithCleanUp(false)
                                            .WithEntrypoint(KeepTestcontainersUpAndRunning.Command);

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

                    testcontainerId = testcontainer.Id;
                }

                // Then
                Assert.False(Docker.Exists(DockerResource.Container, testcontainerId));
            }