Listings: Waarom testen we? uit SDN Magazine #145

Listing 1:

 

CREATE TABLE IF NOT EXISTS accounts (
	user_id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
	email VARCHAR ( 255 ) UNIQUE NOT NULL,
	password VARCHAR ( 50 ) NOT NULL,
	first_name VARCHAR ( 50 ) NOT NULL,
	last_name VARCHAR ( 50 ) NOT NULL,
	created_on TIMESTAMP NOT NULL,
	last_login TIMESTAMP
);

Listing 2:

#language: nl-NL

Functionaliteit: Het klantenbestand kan worden opgeschoond

Scenario: Een medewerker kan het klantenbestand opschonen
	Gegeven de medewerker Isabella
	Als de medewerker het klantenbestand opschoont
	Dan bevat het klantenbestand geen inactieve klanten meer die zijn aangemaakt voor 2020-01-01

Listing 3:

[When(@"de medewerker het klantenbestand opschoont")]
public void WhenDeMedewerkerHetKlantenbestandOpschoont()
{
_numberOfAccountsRemoved = _numberOfAccountsRemoved = _accountService.RemoveAllStaleAccounts();
}
Waarbij de functie “RemoveAllStaleAccounts()” het volgende SQL commando uitvoert: “DELETE FROM Accounts WHERE last_login is null AND created_on < '2020-01-01'”

Listing 4:

using DotNet.Testcontainers.Builders;
using DotNet.Testcontainers.Containers;

var testcontainersBuilder =
    new TestcontainersBuilder()
    .WithImage("hello-world")
    .WithName("hello-world")
    .WithOutputConsumer(Consume.RedirectStdoutAndStderrToConsole());

await using (var testcontainers = testcontainersBuilder.Build())
{
    await testcontainers.StartAsync();
    Console.ReadKey();
}

Listing 5:

public PostgreSqlFixture()
{

var testcontainersBuilder =
new TestcontainersBuilder()
.WithDatabase(new PostgreSqlTestcontainerConfiguration()
{
Database = "db",
                    Username = "db_user",
                    Password = "db_password",
})
.WithOutputConsumer(Consume.RedirectStdoutAndStderrToConsole())
.WithWaitStrategy(Wait.ForUnixContainer().UntilCommandIsCompleted($"pg_isready -h 'localhost' -p '5432'"));

            Container = testcontainersBuilder.Build();
}

public async Task UseBackupFile(byte[] backupFile)
{
await Container.CopyFileAsync("/tmp/db_backup.dump", backupFile);

var command = "pg_restore --username=db_user --dbname=db -1 /tmp/db_backup.dump";

await Container.ExecAsync(command.Split(' '));
}

Listing 6:

[BeforeFeature]
public static async Task BeforeFeature(FeatureContext featureContext)
{
PostgreSqlFixture postgreSqlFixture = new();

await postgreSqlFixture.InitializeAsync();
await postgreSqlFixture.UseBackupFile(await File.ReadAllBytesAsync("Support/db_backup.dump"));

var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseNpgsql(postgreSqlFixture.Connection!);

featureContext.Set(postgreSqlFixture);
}

Listing 7:

public async Task InitializeAsync()
{
	await _semaphoreSlim.WaitAsync();
 
	try
	{
		await new ImageFromDockerfileBuilder()
			.WithName(this)
			.WithDockerfileDirectory(CommonDirectoryPath.GetSolutionDirectory(), string.Empty)
			.WithDockerfile("Dockerfile")
			.WithBuildArgument("RESOURCE_REAPER_SESSION_ID", ResourceReaper.DefaultSessionId.ToString("D"))
		.WithDeleteIfExists(false)
		.Build();
	}
	finally
	{
		_semaphoreSlim.Release();
	}
}

Listing 8:

_demoAppNetwork = new TestcontainersNetworkBuilder()
          .WithName(Guid.NewGuid().ToString("D"))
          .Build();

Listing 9:

new TestcontainersBuilder()
          .WithImage(Image)
          .WithNetwork(_demoAppNetwork)
          .WithPortBinding(DemoAppImage.HttpsPort, true)
          .WithEnvironment("ASPNETCORE_URLS", "https://+")
          .WithEnvironment("ASPNETCORE_Kestrel__Certificates__Default__Path", DemoAppImage.CertificateFilePath)
          .WithEnvironment("ASPNETCORE_Kestrel__Certificates__Default__Password", DemoAppImage.CertificatePassword)
          .WithEnvironment("ConnectionStrings__StoreConnectionString", connectionString)
          .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(DemoAppImage.HttpsPort))
          .Build();

Listing 10:

public async Task Get_Accounts_Should_Return_100_Pages_Of_Accounts()
{
	// Arrange
	string ScreenshotFileName() => $"{nameof(Get_Accounts_Should_Return_100_Pages_Of_Accounts)}_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}.png";
 
	using var chrome = new ChromeDriver(_chromeOptions);
 
	// Act
	chrome.Navigate().GoToUrl(_demoAppContainer.BaseAddress);
 
        chrome.GetScreenshot().SaveAsFile(Path.Combine(CommonDirectoryPath.GetProjectDirectory().DirectoryPath, ScreenshotFileName()));
 
        chrome.FindElement(By.Id("accounts_link")).Click();
 
        await Task.Delay(TimeSpan.FromSeconds(5));