http-api/tst/Application.IntegrationTests/BaseTest.cs

121 lines
3.5 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using cuqmbr.TravelGuide.Configuration.Configuration;
using cuqmbr.TravelGuide.Configuration.Logging;
using cuqmbr.TravelGuide.Configuration.Application;
using cuqmbr.TravelGuide.Configuration.Persistence;
using cuqmbr.TravelGuide.Configuration.Identity;
using Moq;
using System.Globalization;
using cuqmbr.TravelGuide.Application.Common.Interfaces.Services;
using cuqmbr.TravelGuide.Application.Common.Models;
namespace cuqmbr.TravelGuide.Application.IntegrationTests;
public abstract class TestBase : IDisposable
{
protected readonly IServiceCollection _serviceCollection;
private IServiceScope _scope;
public TestBase()
{
_serviceCollection = new ServiceCollection();
_serviceCollection
.ConfigureConfiguration(
new string[]
{
"--Application:Datastore:Type", "inmemory",
"--Application:Logging:LogLevel", "None"
})
.ConfigureLogging()
.ConfigureApplication()
.ConfigurePersistence();
// TODO: Create InMemory configuration for Identity
// .ConfigureIdentity();
SetCulture("en-US");
SetTimeZone("Europe/Kyiv");
}
public T GetService<T>()
{
var serviceProvider = _serviceCollection.BuildServiceProvider();
_scope = serviceProvider.CreateScope();
return _scope.ServiceProvider.GetRequiredService<T>();
}
public void Dispose()
{
_scope.Dispose();
GC.SuppressFinalize(this);
}
protected void SetAuthenticatedUserRoles(IdentityRole[] roles = default!)
{
_serviceCollection
.AddScoped<SessionUserService>(_ =>
{
var mock = new Mock<SessionUserService>();
var guid = Guid.NewGuid();
mock.Setup(s => s.Email).Returns(guid.ToString());
mock.Setup(s => s.Id).Returns(guid.GetHashCode());
mock.Setup(s => s.Uuid).Returns(Guid.NewGuid());
mock.Setup(s => s.IsAuthenticated).Returns(true);
mock.Setup(s => s.Roles).Returns(roles);
return mock.Object;
});
}
protected void SetUnAuthenticatedUser()
{
_serviceCollection
.AddScoped<SessionUserService>(_ =>
{
var mock = new Mock<SessionUserService>();
mock.Setup(s => s.IsAuthenticated).Returns(false);
return mock.Object;
});
}
public void SetCulture(string culture)
{
var cultureInfo = CultureInfo.GetCultureInfo(culture);
_serviceCollection
.AddScoped<SessionCultureService>(_ =>
{
var mock = new Mock<SessionCultureService>();
mock
.Setup(s => s.Culture)
.Returns(cultureInfo);
return mock.Object;
});
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
}
public void SetTimeZone(string timeZone)
{
_serviceCollection
.AddScoped<SessionTimeZoneService>(_ =>
{
var mock = new Mock<SessionTimeZoneService>();
mock
.Setup(s => s.TimeZone)
.Returns(TimeZoneInfo.FindSystemTimeZoneById(timeZone));
return mock.Object;
});
}
}