yavsc/test/yavscTests/WebServerFixture.cs

156 lines
5.8 KiB
C#

6 months ago
using System.Net;
using Microsoft.AspNetCore;
6 months ago
using Microsoft.AspNetCore.Builder;
6 months ago
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Xunit;
using Yavsc;
using Yavsc.Models;
using Yavsc.Services;
using yavscTests.Settings;
6 months ago
using Yavsc.Extensions;
using Microsoft.EntityFrameworkCore;
6 months ago
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Yavsc.Models.Auth;
6 months ago
using Serilog;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;
6 months ago
namespace isnd.tests
{
[CollectionDefinition("Web server collection")]
public class WebServerFixture : IDisposable
{
public List<string> Addresses { get; private set; } = new List<string>();
public Microsoft.Extensions.Logging.ILogger Logger { get; internal set; }
private SiteSettings siteSettings;
6 months ago
public IConfigurationRoot Configuration { get; private set; }
private WebApplication app;
public string TestClientId { get; private set; }
6 months ago
6 months ago
public IServiceProvider Services { get; private set; }
6 months ago
public string TestingUserName { get; private set; }
6 months ago
public string TestingUserPassword { get; private set; }
6 months ago
public string ProtectedTestingApiKey { get; internal set; }
public ApplicationUser TestingUser { get; private set; }
public bool DbCreated { get; internal set; }
public SiteSettings SiteSettings { get => siteSettings; set => siteSettings = value; }
public TestingSetup? TestingSetup { get; internal set; }
public string TestClientSecret { get; private set; } = "TestClientSecret";
6 months ago
public WebServerFixture()
{
6 months ago
SetupHost().Wait();
6 months ago
}
public void Dispose()
{
6 months ago
if (app!=null)
app.StopAsync().Wait();
6 months ago
}
6 months ago
void ConfigureLogger() => Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
.Enrich.FromLogContext()
// uncomment to write to Azure diagnostics stream
//.WriteTo.File(
// @"D:\home\LogFiles\Application\identityserver.txt",
// fileSizeLimitBytes: 1_000_000,
// rollOnFileSizeLimit: true,
// shared: true,
// flushToDiskInterval: TimeSpan.FromSeconds(1))
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Code)
.CreateLogger();
6 months ago
public async Task SetupHost()
6 months ago
{
6 months ago
var builder = WebApplication.CreateBuilder();
ConfigureLogger();
6 months ago
Configuration = builder.Configuration
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
this.app = builder.ConfigureWebAppServices();
6 months ago
Services = app.Services;
6 months ago
using (var migrationScope = app.Services.CreateScope())
6 months ago
{
6 months ago
var db = migrationScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
await db.Database.MigrateAsync();
}
await app.ConfigurePipeline();
app.UseSession();
await app.StartAsync();
6 months ago
6 months ago
var logFactory = app.Services.GetRequiredService<ILoggerFactory>();
6 months ago
Logger = logFactory.CreateLogger<WebServerFixture>();
6 months ago
var server = app.Services.GetRequiredService<IServer>();
6 months ago
var addressFeatures = server.Features.Get<IServerAddressesFeature>();
foreach (var address in addressFeatures.Addresses)
{
Addresses.Add(address);
}
6 months ago
SiteSettings = app.Services.GetRequiredService<IOptions<SiteSettings>>().Value;
6 months ago
6 months ago
using IServiceScope scope = app.Services.CreateScope();
6 months ago
ApplicationDbContext dbContext =
scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
6 months ago
//dbContext.Database.EnsureCreated();
dbContext.Database.Migrate();
6 months ago
TestingUserName = "Tester";
6 months ago
TestingUserPassword = "test";
TestClientId = "testClientId";
TestingUser = await dbContext.Users.FirstOrDefaultAsync(u => u.UserName == TestingUserName);
6 months ago
EnsureUser(TestingUserName, TestingUserPassword);
5 months ago
6 months ago
}
6 months ago
public void EnsureUser(string testingUserName, string password)
6 months ago
{
if (TestingUser == null)
{
6 months ago
using IServiceScope scope = app.Services.CreateScope();
6 months ago
var userManager =
scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
TestingUser = new ApplicationUser
{
6 months ago
UserName = testingUserName,
Email = testingUserName + "@example.com",
EmailConfirmed = true
6 months ago
};
6 months ago
var result = userManager.CreateAsync(TestingUser,password).Result;
6 months ago
Assert.True(result.Succeeded);
ApplicationDbContext dbContext =
scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
TestingUser = dbContext.Users.FirstOrDefault(u => u.UserName == testingUserName);
}
}
}
}