-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathAppServiceTestBase.cs
151 lines (134 loc) · 5.42 KB
/
AppServiceTestBase.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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Audit.Core;
using MccSoft.IntegreSql.EF.DatabaseInitialization;
using MccSoft.LowLevelPrimitives;
using MccSoft.TemplateApp.App.Setup;
using MccSoft.TemplateApp.App.Utils.Localization;
using MccSoft.TemplateApp.Domain;
using MccSoft.TemplateApp.Persistence;
using MccSoft.Testing;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
namespace MccSoft.TemplateApp.App.Tests;
/// <summary>
/// The base class for application service test classes.
/// </summary>
public class AppServiceTestBase : TestBase<TemplateAppDbContext>
{
protected User _defaultUser;
public override bool InsertLoggerInEf => true;
protected AppServiceTestBase(
ITestOutputHelper outputHelper,
DatabaseType? testDatabaseType = DatabaseType.Postgres
)
: base(
outputHelper,
testDatabaseType,
adjustNpgsqlDataSource: builder =>
TemplateAppDbContext.MapEnums(builder.EnableDynamicJson())
)
{
Configuration.AuditDisabled = true;
// initialize some variables to be available in all tests
if (testDatabaseType != null)
{
TaskUtils.RunSynchronously(async () =>
{
await WithDbContext(async db =>
{
using var _ = CustomTenantIdAccessor.IgnoreTenantIdQueryFilter();
_defaultUser = await db.Users.FirstAsync(x => x.Email == "[email protected]");
});
_userAccessorMock.Setup(x => x.GetUserId()).Returns(_defaultUser.Id);
_userAccessorMock.Setup(x => x.GetTenantId()).Returns(_defaultUser.TenantId);
});
}
}
/// <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) + "AppServiceTest",
async (db) =>
{
var tenant = new Tenant();
db.Tenants.Add(tenant);
await db.SaveChangesAsync();
var user = new User("[email protected]");
db.Users.Add(user);
user.SetTenantIdUnsafe(tenant.Id);
await db.SaveChangesAsync();
}
);
protected override void RegisterServices(
IServiceCollection services,
IConfiguration configuration,
IWebHostEnvironment environment
)
{
SetupServices.AddServices(services, configuration, environment);
services
.AddDefaultIdentity<User>()
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddEntityFrameworkStores<TemplateAppDbContext>();
// Here you could override type registration (e.g. mock http clients that call other microservices).
// Most probably you'd need to remove existing registration before registering new one.
// You could remove the registration by calling:
// services.RemoveRegistration<TService>();
}
/// <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);
#region Validation
public record ValidationResult(string MemberNames, string ErrorMessage);
/// <summary>
/// Returns list of validation result for DataAnnotation errors assertion.
/// </summary>
protected IList<ValidationResult> ValidateModel(object model)
{
var provider = new MetadataTranslationProvider(
CreateService<IStringLocalizer<MetadataTranslationProvider.DataAnnotationLocalizer>>()
);
var attributes = GetValidationAttributes(model.GetType());
provider.CreateValidationMetadata(attributes);
var validationResults = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
var context = new ValidationContext(model);
Validator.TryValidateObject(model, context, validationResults, true);
return validationResults
.Select(x => new ValidationResult(string.Join(",", x.MemberNames), x.ErrorMessage))
.ToList();
}
private List<object> GetValidationAttributes(Type type)
{
var properties = TypeDescriptor.GetProperties(type);
var attributes = new List<object>();
for (var i = 0; i < properties.Count; i++)
{
var property = properties[i];
for (var j = 0; j < property.Attributes.Count; j++)
{
attributes.Add(property.Attributes[j]);
}
}
return attributes;
}
#endregion
}