-
-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathIntegrationTestContext.cs
204 lines (170 loc) · 7.67 KB
/
IntegrationTestContext.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
using System.Text.Json;
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace TestBuildingBlocks;
/// <summary>
/// Base class for a test context that creates a new database and server instance before running tests and cleans up afterwards. You can either use this
/// as a fixture on your tests class (init/cleanup runs once before/after all tests) or have your tests class inherit from it (init/cleanup runs once
/// before/after each test). See <see href="https://xunit.net/docs/shared-context" /> for details on shared context usage.
/// </summary>
/// <typeparam name="TStartup">
/// The server Startup class, which can be defined in the test project or API project.
/// </typeparam>
/// <typeparam name="TDbContext">
/// The Entity Framework Core database context, which can be defined in the test project or API project.
/// </typeparam>
[UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)]
public class IntegrationTestContext<TStartup, TDbContext> : IntegrationTest
where TStartup : class
where TDbContext : TestableDbContext
{
private readonly Lazy<WebApplicationFactory<TStartup>> _lazyFactory;
private readonly TestControllerProvider _testControllerProvider = new();
private Action<ILoggingBuilder>? _loggingConfiguration;
private Action<IServiceCollection>? _beforeServicesConfiguration;
private Action<IServiceCollection>? _afterServicesConfiguration;
protected override JsonSerializerOptions SerializerOptions
{
get
{
var options = Factory.Services.GetRequiredService<IJsonApiOptions>();
return options.SerializerOptions;
}
}
public WebApplicationFactory<TStartup> Factory => _lazyFactory.Value;
public IntegrationTestContext()
{
_lazyFactory = new Lazy<WebApplicationFactory<TStartup>>(CreateFactory);
}
public void UseController<TController>()
where TController : ControllerBase
{
_testControllerProvider.AddController(typeof(TController));
}
protected override HttpClient CreateClient()
{
return Factory.CreateClient();
}
private WebApplicationFactory<TStartup> CreateFactory()
{
string postgresPassword = Environment.GetEnvironmentVariable("PGPASSWORD") ?? "postgres";
string dbConnectionString = $"Host=localhost;Port=5432;Database=JsonApiTest-{Guid.NewGuid():N};User ID=postgres;" +
$"Password={postgresPassword};Include Error Detail=true";
var factory = new IntegrationTestWebApplicationFactory();
factory.ConfigureLogging(_loggingConfiguration);
factory.ConfigureServicesBeforeStartup(services =>
{
_beforeServicesConfiguration?.Invoke(services);
services.ReplaceControllers(_testControllerProvider);
services.AddDbContext<TDbContext>(options =>
{
options.UseNpgsql(dbConnectionString, builder => builder.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
#if DEBUG
options.EnableSensitiveDataLogging();
options.EnableDetailedErrors();
#endif
});
});
factory.ConfigureServicesAfterStartup(_afterServicesConfiguration);
// We have placed an appsettings.json in the TestBuildingBlock project folder and set the content root to there. Note that controllers
// are not discovered in the content root but are registered manually using IntegrationTestContext.UseController.
WebApplicationFactory<TStartup> factoryWithConfiguredContentRoot =
factory.WithWebHostBuilder(builder => builder.UseSolutionRelativeContentRoot($"test/{nameof(TestBuildingBlocks)}"));
using IServiceScope scope = factoryWithConfiguredContentRoot.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<TDbContext>();
dbContext.Database.EnsureCreated();
return factoryWithConfiguredContentRoot;
}
public void ConfigureLogging(Action<ILoggingBuilder> loggingConfiguration)
{
_loggingConfiguration = loggingConfiguration;
}
public void ConfigureServicesBeforeStartup(Action<IServiceCollection> servicesConfiguration)
{
_beforeServicesConfiguration = servicesConfiguration;
}
public void ConfigureServicesAfterStartup(Action<IServiceCollection> servicesConfiguration)
{
_afterServicesConfiguration = servicesConfiguration;
}
public async Task RunOnDatabaseAsync(Func<TDbContext, Task> asyncAction)
{
await using AsyncServiceScope scope = Factory.Services.CreateAsyncScope();
var dbContext = scope.ServiceProvider.GetRequiredService<TDbContext>();
await asyncAction(dbContext);
}
public override async Task DisposeAsync()
{
try
{
if (_lazyFactory.IsValueCreated)
{
await RunOnDatabaseAsync(async dbContext => await dbContext.Database.EnsureDeletedAsync());
await _lazyFactory.Value.DisposeAsync();
}
}
finally
{
await base.DisposeAsync();
}
}
private sealed class IntegrationTestWebApplicationFactory : WebApplicationFactory<TStartup>
{
private Action<ILoggingBuilder>? _loggingConfiguration;
private Action<IServiceCollection>? _beforeServicesConfiguration;
private Action<IServiceCollection>? _afterServicesConfiguration;
public void ConfigureLogging(Action<ILoggingBuilder>? loggingConfiguration)
{
_loggingConfiguration = loggingConfiguration;
}
public void ConfigureServicesBeforeStartup(Action<IServiceCollection>? servicesConfiguration)
{
_beforeServicesConfiguration = servicesConfiguration;
}
public void ConfigureServicesAfterStartup(Action<IServiceCollection>? servicesConfiguration)
{
_afterServicesConfiguration = servicesConfiguration;
}
protected override IHostBuilder CreateHostBuilder()
{
// @formatter:wrap_chained_method_calls chop_always
// @formatter:keep_existing_linebreaks true
return Host.CreateDefaultBuilder(null)
.ConfigureAppConfiguration(builder =>
{
// For tests asserting on log output, we discard the logging settings from appsettings.json.
// But using appsettings.json for all other tests makes it easy to quickly toggle when debugging.
if (_loggingConfiguration != null)
{
builder.Sources.Clear();
}
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureServices(services =>
{
_beforeServicesConfiguration?.Invoke(services);
});
webBuilder.UseStartup<TStartup>();
webBuilder.ConfigureServices(services =>
{
_afterServicesConfiguration?.Invoke(services);
});
})
.ConfigureLogging(options =>
{
_loggingConfiguration?.Invoke(options);
});
// @formatter:keep_existing_linebreaks restore
// @formatter:wrap_chained_method_calls restore
}
}
}