-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathComponentTestBase.cs
161 lines (141 loc) · 5.77 KB
/
ComponentTestBase.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
using System;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using MccSoft.IntegreSql.EF.DatabaseInitialization;
using MccSoft.LowLevelPrimitives;
using MccSoft.TemplateApp.App.Setup;
using MccSoft.TemplateApp.ComponentTests.Infrastructure;
using MccSoft.TemplateApp.Domain;
using MccSoft.TemplateApp.Http;
using MccSoft.TemplateApp.Persistence;
using MccSoft.Testing;
using MccSoft.Testing.Database;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OpenIddict.Abstractions;
namespace MccSoft.TemplateApp.ComponentTests;
public class ComponentTestBase : TestBase<TemplateAppDbContext>, IDisposable
{
protected TestServer TestServer { get; private set; }
protected HttpClient Client { get; private set; }
protected IConfiguration Configuration { get; private set; }
protected AuthenticationClient AuthenticationClient { get; private set; }
protected User _defaultUser;
protected ComponentTestBase(
ITestOutputHelper outputHelper,
DatabaseType databaseType = DatabaseType.Postgres
)
: base(
outputHelper,
databaseType,
adjustNpgsqlDataSource: builder =>
TemplateAppDbContext.MapEnums(builder.EnableDynamicJson())
)
{
var application = CreateWebApplicationFactory(ConnectionString);
TestServer = application.Server;
Client = application.CreateClient(
new WebApplicationFactoryClientOptions { BaseAddress = new Uri($"https://localhost") }
);
Client.Timeout = TimeSpan.FromSeconds(300);
Configuration = CreateService<IConfiguration>();
AuthenticationClient = new AuthenticationClient(Client);
var context = CreateService<TemplateAppDbContext>();
_defaultUser = context.Users.First(u => u.UserName == "admin");
Identity.RemoveClaims("sub");
Identity.AddClaim("sub", _defaultUser.Id);
Identity.AddClaim(CustomTenantIdAccessor.TenantIdClaim, _defaultUser.TenantId.ToString());
}
private ComponentTestFixture CreateWebApplicationFactory(string connectionString)
{
ComponentTestFixture application = new ComponentTestFixture()
{
OutputHelper = OutputHelper,
}
.ConfigureTestServices(services =>
{
RegisterServices(services, null, null);
services.RemoveDbContextRegistration<TemplateAppDbContext>();
RegisterDbContext(services, connectionString);
})
.UseSetting("ConnectionStrings:DefaultConnection", connectionString);
application
.UseSetting(SetupDatabase.DisableMigrationOptionName, "true")
.UseSetting(SetupAuth.DisableSignOutLockedUserMiddleware, "true");
return application;
}
/// <summary>
/// If you'd like to stub authorized user with certain Id you could do it like:
/// Identity.AddClaims("id", "1231-123-123")
/// </summary>
public ClaimsIdentity Identity
{
get => AuthenticationOptions.Identity;
set => AuthenticationOptions.Identity = value;
}
private TestAuthenticationOptions AuthenticationOptions =>
CreateService<IOptionsMonitor<TestAuthenticationOptions>>()
.Get(TestAuthenticationOptions.Scheme);
protected override IServiceProvider CreateServiceProvider(
Action<IServiceCollection> configureRegistrations
)
{
return TestServer.Services;
}
/// <summary>
/// Insert some data that you want to be available in every test.
///
/// Note, that this method is executed only once, when template database is initially created.
/// !!IT IS NOT CALLED IN EACH TEST!!!
/// (though, created data is available in each test by backing up
/// and restoring a DB from template for each test)
/// </summary>
protected override DatabaseSeedingOptions<TemplateAppDbContext> SeedDatabase() =>
new DatabaseSeedingOptions<TemplateAppDbContext>(
nameof(TemplateAppDbContext) + "ComponentTest",
async (dbContext) =>
{
var webFactory = CreateWebApplicationFactory(
dbContext.Database.GetConnectionString()
);
await SetupDatabase.DoRunMigration(webFactory.Services);
}
)
{
DisableEnsureCreated = true
};
/// <summary>
/// Creates a NEW DbContext.
/// Resolving it from ServiceProvider is not enough, because we will get the same DbContext every time.
/// </summary>
protected override TemplateAppDbContext CreateDbContext(IServiceProvider serviceProvider) =>
SetupDatabase.CreateDbContext(serviceProvider);
protected override void RegisterServices(
IServiceCollection services,
IConfiguration configuration,
IWebHostEnvironment environment
)
{
// Here you could override type registration (e.g. mock http clients that call other microservices).
// If you need to remove existing registration before registering you could do this by calling:
// services.RemoveRegistration<TService>();
services.AddSingleton(
(
_backgroundJobClient = HangfireMock.CreateHangfireMock(() => TestServer.Services)
).Object
);
}
protected override void DisposeImpl()
{
base.DisposeImpl();
_databaseInitializer.RemoveDatabase(ConnectionString);
_databaseInitializer.Dispose();
// Do not dispose of TestServer, it is disposed together with the applicationFactory.
}
}