-
Notifications
You must be signed in to change notification settings - Fork 0
/
TestFactory.cs
72 lines (49 loc) · 2.17 KB
/
TestFactory.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
namespace Test;
public class TestFactory : IDisposable
{
WebApplicationFactory<Program> Factory;
string UnitTestConnectionString;
string UnitTestDbName;
public HttpClient Client;
IServiceScope ServiceScope;
public IServiceProvider Services => ServiceScope.ServiceProvider;
public TestFactory()
{
}
/// <summary>
/// Initialize a test factory with IsUnitTest environment, test database dropped and service scope, http client allocted.
/// </summary>
public async Task InitAsync(CancellationToken cancellationToken = default)
{
// retrieve configuration before start web app factory in order to drop test db
{
var builder = new ConfigurationBuilder();
builder.SetupAppSettings("Development");
var config = builder.Build();
UnitTestConnectionString = config.GetConfigVar<string>(CONFIG_KEY_UnitTestConnectionString);
UnitTestDbName = UnitTestConnectionString.Split(';')
.Select(w => w.Trim())
.First(w => w.StartsWith("Database="))
.StripBegin("Database=");
await DropDbAsync(cancellationToken);
}
// setting this config var cause the connection string database to another given name
Environment.SetEnvironmentVariable(CONFIG_KEY_IsUnitTest.Replace(":", "__"), "true");
Factory = new WebApplicationFactory<Program>();
Client = Factory.CreateClient();
ServiceScope = Factory.Services.CreateScope();
}
async Task DropDbAsync(CancellationToken cancellationToken = default)
{
var ss = UnitTestConnectionString.Split(';');
var NoDbConnectionString = string.Join(';', ss
.Where(r => r.Trim().Length > 0 && !r.Trim().StartsWith("Database", StringComparison.InvariantCultureIgnoreCase)));
await using var dataSource = NpgsqlDataSource.Create(NoDbConnectionString);
await using var cmd = dataSource.CreateCommand($"DROP DATABASE IF EXISTS \"{UnitTestDbName}\" WITH (FORCE)");
await cmd.ExecuteNonQueryAsync(cancellationToken);
}
public void Dispose()
{
Factory.Dispose();
}
}