tuitio/test/UnitTests/Tuitio.Application.Tests/Fixtures/DependencyInjectionFixture.cs

162 lines
5.4 KiB
C#

// Copyright (c) 2020 Tudor Stanciu
using MediatR;
using MediatR.Pipeline;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using System.Threading.Tasks;
using Tuitio.Domain.Data;
using Tuitio.Domain.Data.DbContexts;
using Tuitio.Domain.Entities;
using Xunit;
namespace Tuitio.Application.Tests.Fixtures
{
public class DependencyInjectionFixture : IAsyncLifetime
{
private readonly Guid _prefix;
private readonly List<SqliteConnection> _connections;
public readonly IServiceProvider ServiceProvider;
public DependencyInjectionFixture()
{
_prefix = Guid.NewGuid();
_connections = new List<SqliteConnection>();
ServiceProvider = BuildServiceProvider();
}
public async Task DisposeAsync()
{
foreach (var con in _connections)
await con.DisposeAsync();
}
public async Task InitializeAsync()
{
await PrepareDbAsync();
SeedData();
}
private IServiceProvider BuildServiceProvider()
{
var configurationBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.tuitio.json", optional: true, reloadOnChange: false);
var configuration = configurationBuilder.Build();
var services = new ServiceCollection();
services.AddSingleton<IConfiguration>(configuration);
services.AddLogging(builder =>
{
builder.SetMinimumLevel(LogLevel.Warning);
builder.AddFilter("Microsoft.*", LogLevel.Warning);
});
// MediatR
services.AddMediatR(typeof(Application.CommandHandlers.AccountLoginHandler).Assembly);
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(RequestPreProcessorBehavior<,>));
// AutoMapper
services.AddAutoMapper(typeof(Application.Mappings.MappingProfile).Assembly);
services.AddDbContext<TuitioDbContext>(options =>
{
options.UseSqlite(GetOrAddInMemoryDatabase("TuitioDbContext"));
options.EnableSensitiveDataLogging();
options.EnableDetailedErrors();
});
services.AddDataAccessServices();
services.AddApplicationServices();
var provider = services.BuildServiceProvider();
return provider;
}
private DbConnection GetOrAddInMemoryDatabase(string code)
{
var connection = new SqliteConnection($"Data Source={_prefix}{code};Mode=Memory;Cache=shared");
_connections.Add(connection);
connection.Open();
return connection;
}
private async Task PrepareDbAsync()
{
var result = await ServiceProvider.GetRequiredService<TuitioDbContext>().Database.EnsureCreatedAsync();
if (!result) throw new Exception("TuitioDbContext exists");
var script = await File.ReadAllTextAsync("seed.sql");
await ServiceProvider.GetRequiredService<TuitioDbContext>().Database.ExecuteSqlRawAsync(script);
}
private void SeedData()
{
using var dbContext = ServiceProvider.GetRequiredService<TuitioDbContext>();
#region UserStatus
dbContext.UserStatuses.AddRange(new Domain.Entities.UserStatus[]
{
new Domain.Entities.UserStatus()
{
StatusId = 1,
StatusCode = "ACTIVE",
StatusName = "Active"
},
new Domain.Entities.UserStatus()
{
StatusId = 2,
StatusCode = "INACTIVE",
StatusName = "Inactive"
},
new Domain.Entities.UserStatus()
{
StatusId = 3,
StatusCode = "BLOCKED",
StatusName = "Blocked"
}
});
#endregion
#region Users
dbContext.Users.Add(new Domain.Entities.AppUser()
{
UserId = 1,
UserName = "tuitio.user",
Password = "9B8769A4A742959A2D0298C36FB70623F2DFACDA8436237DF08D8DFD5B37374C", // pass123
FirstName = "Tuitio",
LastName = "User",
Email = "tuitio.user@tuitio.lab",
SecurityStamp = "A93650FF-1FC4-4999-BAB6-3EEB174F6892",
StatusId = 1,
CreationDate = DateTime.Now,
FailedLoginAttempts = 0,
UserRoles = new UserXUserRole[]
{
new UserXUserRole()
{
UserId = 1,
UserRoleId = 1,
UserRole = new UserRole()
{
UserRoleId = 1,
UserRoleCode = "MOCK_ROLE",
UserRoleName = "Mock role"
}
}
}
});
#endregion
dbContext.SaveChanges();
}
}
}