Repository navigation
Expand file tree
/
Copy pathWebApplicationFactory.cs
More file actions
195 lines (169 loc) · 7.5 KB
/
Copy pathWebApplicationFactory.cs
File metadata and controls
195 lines (169 loc) · 7.5 KB
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
using System.Data.Common;
using EssentialCSharp.Chat.Common.Services;
using EssentialCSharp.Web.Data;
using EssentialCSharp.Web.Models;
using EssentialCSharp.Web.Services;
using TUnit.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
namespace EssentialCSharp.Web.Tests;
public sealed class WebApplicationFactory : TestWebApplicationFactory<Program>
{
// One GUID per factory instance (field, not computed property) ensures each factory
// gets its own isolated in-memory database and keeps a stable connection string.
private readonly string _sqlConnectionString =
$"DataSource=file:{Guid.NewGuid():N}?mode=memory&cache=shared";
private readonly SemaphoreSlim _schemaInitializationGate = new(1, 1);
// Kept open for the factory lifetime so the shared-cache in-memory database is not dropped
// when per-scope connections are disposed between requests.
private readonly SqliteConnection _keepAliveConnection;
public WebApplicationFactory()
{
_keepAliveConnection = new SqliteConnection(_sqlConnectionString);
_keepAliveConnection.Open();
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
RemoveSingleOrNone(
services,
descriptor => descriptor.ServiceType == typeof(IHostedService) &&
descriptor.ImplementationType == typeof(DatabaseMigrationService),
nameof(DatabaseMigrationService));
RemoveSingleOrNone(
services,
descriptor => descriptor.ServiceType ==
typeof(IDbContextOptionsConfiguration<EssentialCSharpWebContext>),
"IDbContextOptionsConfiguration<EssentialCSharpWebContext>");
RemoveSingleOrNone(
services,
descriptor => descriptor.ServiceType == typeof(DbConnection),
nameof(DbConnection));
// Keep per-scope connections so each request/test scope uses a fresh DbConnection,
// which avoids locking issues from sharing one SqliteConnection instance.
services.AddScoped<DbConnection>(_ =>
{
SqliteConnection conn = new(_sqlConnectionString);
try
{
conn.Open();
}
catch
{
conn.Dispose();
throw;
}
return conn;
});
// The scoped DI container owns this DbConnection instance and disposes it at
// scope end; EF Core treats it as externally owned when passed via UseSqlite.
services.AddDbContext<EssentialCSharpWebContext>((serviceProvider, options) =>
{
DbConnection dbConnection = serviceProvider.GetRequiredService<DbConnection>();
options.UseSqlite(dbConnection);
});
// Ensure schema exists before hosted services by prepending this registration
// at index 0 of the service collection.
RemoveSingleOrNone(
services,
descriptor => descriptor.ServiceType == typeof(IHostedService) &&
descriptor.ImplementationType == typeof(EnsureCreatedHostedService),
nameof(EnsureCreatedHostedService));
ServiceDescriptor ensureCreatedDescriptor =
ServiceDescriptor.Singleton<IHostedService>(
serviceProvider => new EnsureCreatedHostedService(
serviceProvider,
_schemaInitializationGate));
services.Insert(0, ensureCreatedDescriptor);
// Replace IListingSourceCodeService with one backed by TestData
services.RemoveAll<IListingSourceCodeService>();
services.AddSingleton<IListingSourceCodeService>(
_ => TestListingSourceCodeServiceHelper.CreateService());
// Override IChatCompletionService with UnavailableChatService so tests are not
// affected by developer AI configuration or environment variables.
services.RemoveAll<IChatCompletionService>();
services.AddSingleton<IChatCompletionService, UnavailableChatService>();
// Keep chat contract tests off the real hCaptcha network path so failures reflect
// chat availability behavior rather than captcha service reachability.
services.RemoveAll<ICaptchaService>();
services.AddSingleton<ICaptchaService, PassingCaptchaService>();
});
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_keepAliveConnection.Dispose();
_schemaInitializationGate.Dispose();
}
base.Dispose(disposing);
}
private static void RemoveSingleOrNone(
IServiceCollection services,
Func<ServiceDescriptor, bool> predicate,
string descriptorName)
{
List<int> matchIndexes = [];
for (int i = 0; i < services.Count; i++)
{
if (predicate(services[i]))
{
matchIndexes.Add(i);
}
}
if (matchIndexes.Count > 1)
{
throw new InvalidOperationException(
$"Expected at most one '{descriptorName}' registration but found {matchIndexes.Count}.");
}
if (matchIndexes.Count == 1)
{
services.RemoveAt(matchIndexes[0]);
}
}
private sealed class EnsureCreatedHostedService(
IServiceProvider serviceProvider,
SemaphoreSlim schemaInitializationGate) : IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken)
{
await schemaInitializationGate.WaitAsync(cancellationToken);
try
{
using IServiceScope scope = serviceProvider.CreateScope();
EssentialCSharpWebContext dbContext =
scope.ServiceProvider.GetRequiredService<EssentialCSharpWebContext>();
await dbContext.Database.EnsureCreatedAsync(cancellationToken);
}
finally
{
schemaInitializationGate.Release();
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
private sealed class PassingCaptchaService : ICaptchaService
{
private static readonly HCaptchaResult _Success = new()
{
Success = true,
Hostname = "localhost"
};
public Task<HCaptchaResult?> VerifyAsync(string? response, CancellationToken cancellationToken = default) =>
VerifyAsync(response, remoteIp: null, cancellationToken: cancellationToken);
public Task<HCaptchaResult?> VerifyAsync(string? response, string? remoteIp, CancellationToken cancellationToken = default)
{
if (response == "unavailable-captcha-test-token")
return Task.FromResult<HCaptchaResult?>(null);
if (response == "invalid-captcha-test-token")
return Task.FromResult<HCaptchaResult?>(new HCaptchaResult { Success = false });
return Task.FromResult<HCaptchaResult?>(_Success);
}
}
}