forked from xiongyuxing/tiku-backend.net
92 lines
3.1 KiB
C#
92 lines
3.1 KiB
C#
using Microsoft.AspNetCore.Mvc.Testing;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Npgsql;
|
|
using Tiku.Application.Auth;
|
|
using Tiku.Application.Storage;
|
|
using Tiku.Domain.Identity;
|
|
using Tiku.Domain.Tenancy;
|
|
using Tiku.Infrastructure.Persistence;
|
|
|
|
namespace Tiku.IntegrationTests.Api;
|
|
|
|
public sealed class ApiTestFactory(
|
|
IWechatOAuthClient? wechatOAuthClient = null,
|
|
IObjectStorageService? objectStorageService = null) : WebApplicationFactory<Program>
|
|
{
|
|
private readonly string databaseName = Guid.NewGuid().ToString();
|
|
|
|
protected override void ConfigureWebHost(Microsoft.AspNetCore.Hosting.IWebHostBuilder builder)
|
|
{
|
|
builder.ConfigureServices(services =>
|
|
{
|
|
foreach (var descriptor in services
|
|
.Where(descriptor =>
|
|
descriptor.ServiceType == typeof(NpgsqlDataSource) ||
|
|
descriptor.ServiceType == typeof(DbContextOptions<TikuDbContext>) ||
|
|
descriptor.ServiceType.FullName?.Contains(nameof(TikuDbContext), StringComparison.Ordinal) == true)
|
|
.ToArray())
|
|
{
|
|
services.Remove(descriptor);
|
|
}
|
|
|
|
services.AddDbContext<TikuDbContext>(options =>
|
|
options.UseInMemoryDatabase(databaseName));
|
|
|
|
if (wechatOAuthClient is not null)
|
|
{
|
|
services.AddSingleton(wechatOAuthClient);
|
|
}
|
|
|
|
if (objectStorageService is not null)
|
|
{
|
|
services.AddSingleton(objectStorageService);
|
|
}
|
|
});
|
|
}
|
|
|
|
public async Task SeedAsync(params object[] entities)
|
|
{
|
|
using var scope = Services.CreateScope();
|
|
var dbContext = scope.ServiceProvider.GetRequiredService<TikuDbContext>();
|
|
dbContext.AddRange(entities);
|
|
await dbContext.SaveChangesAsync();
|
|
}
|
|
|
|
public async Task<Guid> SeedActiveSessionAsync(
|
|
Guid userId,
|
|
Guid? tenantId = null,
|
|
string tokenHash = "integration-test-token-hash")
|
|
{
|
|
var resolvedTenantId = tenantId ?? Guid.NewGuid();
|
|
await SeedAsync(
|
|
new Tenant
|
|
{
|
|
Id = resolvedTenantId,
|
|
Slug = resolvedTenantId.ToString("N"),
|
|
Name = "Test Tenant"
|
|
},
|
|
new User
|
|
{
|
|
Id = userId,
|
|
Phone = "13800000000"
|
|
},
|
|
new AuthSession
|
|
{
|
|
Id = Guid.NewGuid(),
|
|
TenantId = resolvedTenantId,
|
|
UserId = userId,
|
|
TokenHash = tokenHash,
|
|
Provider = "test",
|
|
ExpiresAt = DateTimeOffset.UtcNow.AddHours(1)
|
|
});
|
|
|
|
using var scope = Services.CreateScope();
|
|
var dbContext = scope.ServiceProvider.GetRequiredService<TikuDbContext>();
|
|
return await dbContext.AuthSessions
|
|
.Where(session => session.UserId == userId)
|
|
.Select(session => session.Id)
|
|
.SingleAsync();
|
|
}
|
|
}
|