-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathIntegrationTestContext.cs
189 lines (159 loc) · 6.64 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
using System.Reflection;
using System.Text.Json;
using EphemeralMongo;
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.MongoDb.Configuration;
using JsonApiDotNetCore.MongoDb.Repositories;
using JsonApiDotNetCore.Repositories;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using MongoDB.Driver;
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="TMongoDbContextShim">
/// <see cref="MongoDbContextShim" />.
/// </typeparam>
[UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)]
public class IntegrationTestContext<TStartup, TMongoDbContextShim> : IntegrationTest
where TStartup : class
where TMongoDbContextShim : MongoDbContextShim
{
private readonly Lazy<IMongoRunner> _runner;
private readonly Lazy<WebApplicationFactory<TStartup>> _lazyFactory;
private readonly HashSet<Type> _resourceClrTypes = [];
private readonly TestControllerProvider _testControllerProvider = new();
private Action<IServiceCollection>? _configureServices;
protected override JsonSerializerOptions SerializerOptions
{
get
{
var options = Factory.Services.GetRequiredService<IJsonApiOptions>();
return options.SerializerOptions;
}
}
public WebApplicationFactory<TStartup> Factory => _lazyFactory.Value;
public IntegrationTestContext()
{
_runner = new Lazy<IMongoRunner>(StartMongoDb);
_lazyFactory = new Lazy<WebApplicationFactory<TStartup>>(CreateFactory);
}
private IMongoRunner StartMongoDb()
{
return MongoRunnerProvider.Instance.Get();
}
public void UseResourceTypesInNamespace(string? codeNamespace)
{
Assembly assembly = typeof(TStartup).Assembly;
foreach (Type resourceClrType in ResourceTypeFinder.GetResourceClrTypesInNamespace(assembly, codeNamespace))
{
_resourceClrTypes.Add(resourceClrType);
}
}
public void UseController<TController>()
where TController : ControllerBase
{
_testControllerProvider.AddController(typeof(TController));
}
protected override HttpClient CreateClient()
{
return Factory.CreateClient();
}
private WebApplicationFactory<TStartup> CreateFactory()
{
var factory = new IntegrationTestWebApplicationFactory();
factory.ConfigureServices(services =>
{
_configureServices?.Invoke(services);
services.ReplaceControllers(_testControllerProvider);
services.TryAddSingleton(_ =>
{
var client = new MongoClient(_runner.Value.ConnectionString);
return client.GetDatabase($"JsonApiDotNetCore_MongoDb_{Random.Shared.Next()}_Test");
});
services.TryAddScoped<TMongoDbContextShim>();
services.TryAddScoped(typeof(IResourceReadRepository<,>), typeof(MongoRepository<,>));
services.TryAddScoped(typeof(IResourceWriteRepository<,>), typeof(MongoRepository<,>));
services.TryAddScoped(typeof(IResourceRepository<,>), typeof(MongoRepository<,>));
services.AddJsonApi(ConfigureJsonApiOptions, resources: builder =>
{
foreach (Type resourceClrType in _resourceClrTypes)
{
builder.Add(resourceClrType);
}
});
services.AddJsonApiMongoDb();
});
// 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.
return factory.WithWebHostBuilder(builder => builder.UseSolutionRelativeContentRoot($"test/{nameof(TestBuildingBlocks)}"));
}
private void ConfigureJsonApiOptions(JsonApiOptions options)
{
options.IncludeExceptionStackTraceInErrors = true;
options.IncludeRequestBodyInErrors = true;
options.SerializerOptions.WriteIndented = true;
}
public void ConfigureServices(Action<IServiceCollection> configureServices)
{
_configureServices = configureServices;
}
public async Task RunOnDatabaseAsync(Func<TMongoDbContextShim, Task> asyncAction)
{
await using AsyncServiceScope scope = Factory.Services.CreateAsyncScope();
var mongoDbContextShim = scope.ServiceProvider.GetRequiredService<TMongoDbContextShim>();
await asyncAction(mongoDbContextShim);
}
public override async Task DisposeAsync()
{
try
{
if (_lazyFactory.IsValueCreated)
{
await _lazyFactory.Value.DisposeAsync();
}
if (_runner.IsValueCreated)
{
_runner.Value.Dispose();
}
}
finally
{
await base.DisposeAsync();
}
}
private sealed class IntegrationTestWebApplicationFactory : WebApplicationFactory<TStartup>
{
private Action<IServiceCollection>? _configureServices;
public void ConfigureServices(Action<IServiceCollection>? configureServices)
{
_configureServices = configureServices;
}
protected override IHostBuilder CreateHostBuilder()
{
// @formatter:wrap_chained_method_calls chop_always
// @formatter:wrap_before_first_method_call true
return Host
.CreateDefaultBuilder(null)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureServices(services => _configureServices?.Invoke(services));
webBuilder.UseStartup<TStartup>();
});
// @formatter:wrap_before_first_method_call restore
// @formatter:wrap_chained_method_calls restore
}
}
}