Skip to content

Commit

Permalink
use test container
Browse files Browse the repository at this point in the history
  • Loading branch information
pwelter34 committed Oct 31, 2023
1 parent 4a74c03 commit 051c039
Show file tree
Hide file tree
Showing 13 changed files with 142 additions and 46 deletions.
27 changes: 0 additions & 27 deletions .github/workflows/dotnet.yml
Expand Up @@ -24,33 +24,6 @@ jobs:
build:
runs-on: ubuntu-latest

services:
mssql:
image: mcr.microsoft.com/mssql/server:2022-latest
env:
MSSQL_SA_PASSWORD: "!P@ssw0rd"
ACCEPT_EULA: "Y"
ports:
- 1433:1433
volumes:
- mssql_data:/var/opt/mssql

postgres:
image: postgres
env:
POSTGRES_PASSWORD: "!P@ssw0rd"
ports:
- 5432:5432
volumes:
- postgres_data:/var/lib/postgresql/data

redis:
image: redis
ports:
- 6379:6379
volumes:
- redis_data:/data

steps:
- name: Checkout
uses: actions/checkout@v4
Expand Down
Expand Up @@ -5,8 +5,16 @@

namespace FluentCommand.Caching;

public static class ServiceCollectionExtensions
/// <summary>
/// Extension methods for <see cref="DataConfigurationBuilder"/>
/// </summary>
public static class DataConfigurationBuilderExtensions
{
/// <summary>
/// Adds the distributed data cache.
/// </summary>
/// <param name="builder">The data configuration builder.</param>
/// <returns></returns>
public static DataConfigurationBuilder AddDistributedDataCache(this DataConfigurationBuilder builder)
{
builder.AddService(sp =>
Expand Down
27 changes: 26 additions & 1 deletion src/FluentCommand.Json/ConcurrencyTokenJsonConverter.cs
Expand Up @@ -3,11 +3,36 @@

namespace FluentCommand;

/// <summary>
/// Json Converter for <see cref="ConcurrencyToken"/>
/// </summary>
public class ConcurrencyTokenJsonConverter : JsonConverter<ConcurrencyToken>
{
/// <summary>
/// Read and convert the JSON to T.
/// </summary>
/// <param name="reader">The <see cref="T:System.Text.Json.Utf8JsonReader" /> to read from.</param>
/// <param name="typeToConvert">The <see cref="T:System.Type" /> being converted.</param>
/// <param name="options">The <see cref="T:System.Text.Json.JsonSerializerOptions" /> being used.</param>
/// <returns>
/// The value that was converted.
/// </returns>
/// <remarks>
/// A converter may throw any Exception, but should throw <cref>JsonException</cref> when the JSON is invalid.
/// </remarks>
public override ConcurrencyToken Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> new ConcurrencyToken(reader.GetString());
=> new(reader.GetString());

/// <summary>
/// Write the value as JSON.
/// </summary>
/// <param name="writer">The <see cref="T:System.Text.Json.Utf8JsonWriter" /> to write to.</param>
/// <param name="value">The value to convert. Note that the value of <seealso cref="P:System.Text.Json.Serialization.JsonConverter`1.HandleNull" /> determines if the converter handles <see langword="null" /> values.</param>
/// <param name="options">The <see cref="T:System.Text.Json.JsonSerializerOptions" /> being used.</param>
/// <remarks>
/// A converter may throw any Exception, but should throw <cref>JsonException</cref> when the JSON
/// cannot be created.
/// </remarks>
public override void Write(Utf8JsonWriter writer, ConcurrencyToken value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToString());
}
Expand Up @@ -7,6 +7,12 @@
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<Compile Remove="TestResults\**" />
<EmbeddedResource Remove="TestResults\**" />
<None Remove="TestResults\**" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
27 changes: 25 additions & 2 deletions test/FluentCommand.PostgreSQL.Tests/DatabaseFixture.cs
@@ -1,15 +1,36 @@
using System.Threading.Tasks;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

using Npgsql;

using Testcontainers.PostgreSql;

using Xunit;

using XUnit.Hosting;

namespace FluentCommand.PostgreSQL.Tests;

public class DatabaseFixture : TestHostFixture
public class DatabaseFixture : TestHostFixture, IAsyncLifetime
{
private readonly PostgreSqlContainer _postgreSqlContainer = new PostgreSqlBuilder()
.WithDatabase("TrackerDocker")
.Build();

public async Task InitializeAsync()
{
await _postgreSqlContainer.StartAsync();
}

public async Task DisposeAsync()
{
await _postgreSqlContainer.DisposeAsync();
}


protected override void ConfigureLogging(HostBuilderContext context, ILoggingBuilder builder)
{
base.ConfigureLogging(context, builder);
Expand All @@ -18,10 +39,12 @@ protected override void ConfigureLogging(HostBuilderContext context, ILoggingBui

protected override void ConfigureServices(HostBuilderContext context, IServiceCollection services)
{
var trackerConnection = _postgreSqlContainer.GetConnectionString();

services.AddHostedService<DatabaseInitializer>();

services.AddFluentCommand(builder => builder
.UseConnectionName("Tracker")
.UseConnectionString(trackerConnection)
.AddProviderFactory(NpgsqlFactory.Instance)
.AddPostgreSqlGenerator()
);
Expand Down
6 changes: 3 additions & 3 deletions test/FluentCommand.PostgreSQL.Tests/DatabaseInitializer.cs
Expand Up @@ -14,9 +14,9 @@ namespace FluentCommand.PostgreSQL.Tests;
public class DatabaseInitializer : IHostedService, IUpgradeLog
{
private readonly ILogger<DatabaseInitializer> _logger;
private readonly IConfiguration _configuration;
private readonly IDataConfiguration _configuration;

public DatabaseInitializer(ILogger<DatabaseInitializer> logger, IConfiguration configuration)
public DatabaseInitializer(ILogger<DatabaseInitializer> logger, IDataConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
Expand All @@ -25,7 +25,7 @@ public DatabaseInitializer(ILogger<DatabaseInitializer> logger, IConfiguration c

public Task StartAsync(CancellationToken cancellationToken)
{
var connectionString = _configuration.GetConnectionString("Tracker");
var connectionString = _configuration.ConnectionString;

EnsureDatabase.For.PostgresqlDatabase(connectionString, this);

Expand Down
Expand Up @@ -5,6 +5,12 @@
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<Compile Remove="TestResults\**" />
<EmbeddedResource Remove="TestResults\**" />
<None Remove="TestResults\**" />
</ItemGroup>

<ItemGroup>
<None Remove="Scripts\Script001.Tracker.Schema.sql" />
<None Remove="Scripts\Script002.Tracker.Data.sql" />
Expand All @@ -24,6 +30,7 @@
<PackageReference Include="dbup-postgresql" Version="5.0.37" />
<PackageReference Include="Npgsql" Version="7.0.6" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.2" />
<PackageReference Include="Testcontainers.Postgresql" Version="3.5.0" />
<PackageReference Include="XUnit.Hosting" Version="1.0.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3">
<PrivateAssets>all</PrivateAssets>
Expand Down
Expand Up @@ -5,6 +5,12 @@
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<Compile Remove="TestResults\**" />
<EmbeddedResource Remove="TestResults\**" />
<None Remove="TestResults\**" />
</ItemGroup>

<ItemGroup>
<None Remove="Scripts\Script001.Tracker.Schema.sql" />
<None Remove="Scripts\Script002.Tracker.Data.sql" />
Expand Down
4 changes: 2 additions & 2 deletions test/FluentCommand.SqlServer.Tests/DataConfigurationTests.cs
Expand Up @@ -49,7 +49,7 @@ public void GetServices()

var dataConfiguration = services.GetService<IDataConfiguration>();
dataConfiguration.Should().NotBeNull();
dataConfiguration.ConnectionString.Should().NotEndWith("ApplicationIntent=ReadOnly;");
dataConfiguration.ConnectionString.Should().NotContain("Application Intent=ReadOnly");

var dataSession = services.GetService<IDataSession>();
dataSession.Should().NotBeNull();
Expand All @@ -59,7 +59,7 @@ public void GetServices()

var readonlyConfiguration = services.GetService<IDataConfiguration<ReadOnlyIntent>>();
readonlyConfiguration.Should().NotBeNull();
readonlyConfiguration.ConnectionString.Should().EndWith("ApplicationIntent=ReadOnly;");
//readonlyConfiguration.ConnectionString.Should().Contain("Application Intent=ReadOnly");

var readonlySession = services.GetService<IDataSession<ReadOnlyIntent>>();
readonlySession.Should().NotBeNull();
Expand Down
47 changes: 41 additions & 6 deletions test/FluentCommand.SqlServer.Tests/DatabaseFixture.cs
@@ -1,17 +1,44 @@
using System.Threading.Tasks;

using FluentCommand.Caching;

using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

using Testcontainers.MsSql;
using Testcontainers.Redis;

using Xunit;

using XUnit.Hosting;

namespace FluentCommand.SqlServer.Tests;

public class DatabaseFixture : TestHostFixture
public class DatabaseFixture : TestHostFixture, IAsyncLifetime
{
private readonly MsSqlContainer _msSqlContainer = new MsSqlBuilder()
.WithImage("mcr.microsoft.com/mssql/server:2022-latest")
.WithPassword("!P@ss0rd")
.Build();

private readonly RedisContainer _redisContainer = new RedisBuilder()
.Build();


public async Task InitializeAsync()
{
await _msSqlContainer.StartAsync();
await _redisContainer.StartAsync();
}

public async Task DisposeAsync()
{
await _msSqlContainer.DisposeAsync();
await _redisContainer.DisposeAsync();
}

protected override void ConfigureLogging(HostBuilderContext context, ILoggingBuilder builder)
{
base.ConfigureLogging(context, builder);
Expand All @@ -20,8 +47,14 @@ protected override void ConfigureLogging(HostBuilderContext context, ILoggingBui

protected override void ConfigureServices(HostBuilderContext context, IServiceCollection services)
{
var trackerConnection = context.Configuration.GetConnectionString("Tracker");
var cacheConnection = context.Configuration.GetConnectionString("DistributedCache");
// change database from container default
var connectionBuilder = new SqlConnectionStringBuilder(_msSqlContainer.GetConnectionString())
{
InitialCatalog = "TrackerDocker"
};

var trackerConnection = connectionBuilder.ToString();
var cacheConnection = _redisContainer.GetConnectionString();

services.AddHostedService<DatabaseInitializer>();

Expand All @@ -37,13 +70,15 @@ protected override void ConfigureServices(HostBuilderContext context, IServiceCo
.AddDistributedDataCache()
);

var readOnlyConnection = trackerConnection + "ApplicationIntent=ReadOnly;";
// readonly intent connection
connectionBuilder.ApplicationIntent = ApplicationIntent.ReadOnly;

var readOnlyConnection = connectionBuilder.ToString();

services.AddFluentCommand<ReadOnlyIntent>(builder => builder
.UseConnectionString(readOnlyConnection)
.UseSqlServer()
.AddDistributedDataCache()
);
}

}
7 changes: 3 additions & 4 deletions test/FluentCommand.SqlServer.Tests/DatabaseInitializer.cs
Expand Up @@ -8,7 +8,6 @@
using DbUp.Engine.Output;

using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

Expand All @@ -17,9 +16,9 @@ namespace FluentCommand.SqlServer.Tests;
public class DatabaseInitializer : IHostedService, IUpgradeLog
{
private readonly ILogger<DatabaseInitializer> _logger;
private readonly IConfiguration _configuration;
private readonly IDataConfiguration _configuration;

public DatabaseInitializer(ILogger<DatabaseInitializer> logger, IConfiguration configuration)
public DatabaseInitializer(ILogger<DatabaseInitializer> logger, IDataConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
Expand All @@ -28,7 +27,7 @@ public DatabaseInitializer(ILogger<DatabaseInitializer> logger, IConfiguration c

public Task StartAsync(CancellationToken cancellationToken)
{
var connectionString = _configuration.GetConnectionString("Tracker");
var connectionString = _configuration.ConnectionString;

// create database
EnsureDatabase.For
Expand Down
Expand Up @@ -5,6 +5,12 @@
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<Compile Remove="TestResults\**" />
<EmbeddedResource Remove="TestResults\**" />
<None Remove="TestResults\**" />
</ItemGroup>

<ItemGroup>
<None Remove="Scripts\Script001.Tracker.Schema.sql" />
<None Remove="Scripts\Script002.Tracker.Data.sql" />
Expand All @@ -28,6 +34,8 @@
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="7.0.13" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.2" />
<PackageReference Include="Testcontainers.MsSql" Version="3.5.0" />
<PackageReference Include="Testcontainers.Redis" Version="3.5.0" />
<PackageReference Include="XUnit.Hosting" Version="1.0.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3">
<PrivateAssets>all</PrivateAssets>
Expand Down
6 changes: 6 additions & 0 deletions test/FluentCommand.Tests/FluentCommand.Tests.csproj
Expand Up @@ -6,6 +6,12 @@
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>

<ItemGroup>
<Compile Remove="TestResults\**" />
<EmbeddedResource Remove="TestResults\**" />
<None Remove="TestResults\**" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down

0 comments on commit 051c039

Please sign in to comment.