Compare commits
4 commits
f2ae01729a
...
49b9619af7
| Author | SHA1 | Date | |
|---|---|---|---|
| 49b9619af7 | |||
| 349ddc03f5 | |||
| 20a6f22ec3 | |||
| 0d2d4160af |
17 changed files with 492 additions and 373 deletions
|
|
@ -9,8 +9,10 @@
|
||||||
<PackageVersion Include="HigginsSoft.IdentityServer8.EntityFramework" Version="8.1.0-alpha.171" />
|
<PackageVersion Include="HigginsSoft.IdentityServer8.EntityFramework" Version="8.1.0-alpha.171" />
|
||||||
<PackageVersion Include="IdentityModel.OidcClient" Version="6.0.0" />
|
<PackageVersion Include="IdentityModel.OidcClient" Version="6.0.0" />
|
||||||
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.9" />
|
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.9" />
|
||||||
|
<PackageVersion Include="Microsoft.AspNetCore.Hosting" Version="2.3.11" />
|
||||||
<PackageVersion Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.9" />
|
<PackageVersion Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.9" />
|
||||||
<PackageVersion Include="Microsoft.AspNetCore.Identity.UI" Version="10.0.9" />
|
<PackageVersion Include="Microsoft.AspNetCore.Identity.UI" Version="10.0.9" />
|
||||||
|
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.9" />
|
||||||
<PackageVersion Include="Microsoft.AspNetCore.Razor" Version="2.3.0" />
|
<PackageVersion Include="Microsoft.AspNetCore.Razor" Version="2.3.0" />
|
||||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.9" />
|
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.9" />
|
||||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.9" />
|
<PackageVersion Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.9" />
|
||||||
|
|
|
||||||
|
|
@ -56,6 +56,7 @@ pas vers un serveur HTTP.
|
||||||
|---------------------------------|-------------------------------------------------------------------|
|
|---------------------------------|-------------------------------------------------------------------|
|
||||||
| `Services/OidcLoginPhase` | Enum des étapes du flow : `Idle / Discovering / OpeningBrowser / AwaitingCallback / ExchangingCode / Success / Error` |
|
| `Services/OidcLoginPhase` | Enum des étapes du flow : `Idle / Discovering / OpeningBrowser / AwaitingCallback / ExchangingCode / Success / Error` |
|
||||||
| `Services/YavscApiClient` | Client HTTP de l'API Yavsc. Porte `LoginInteractiveAsync(IProgress<OidcLoginPhase>)` et `TrySilentLoginAsync`. Refresh silencieux sur 401 et sur access-token bientôt expiré. |
|
| `Services/YavscApiClient` | Client HTTP de l'API Yavsc. Porte `LoginInteractiveAsync(IProgress<OidcLoginPhase>)` et `TrySilentLoginAsync`. Refresh silencieux sur 401 et sur access-token bientôt expiré. |
|
||||||
|
| `Services/BlogApiClient` | Mapper DTO↔path pour la sous-API blog. **Note** : `pathPrefix` est *relatif* à `/api/v1/` (que porte déjà `BaseAddress`) — ex. `"blog"` pour matcher `[Route(APIPrefix + "/blog")]`. Ne pas ré-inclure `api/`. |
|
||||||
| `Services/SingleInstance` | Named-pipe helper. `TryHandOffAsync` côté 2ᵉ instance, `StartServerAsync` côté instance vivante. |
|
| `Services/SingleInstance` | Named-pipe helper. `TryHandOffAsync` côté 2ᵉ instance, `StartServerAsync` côté instance vivante. |
|
||||||
| `Services/CustomSchemeBrowser` | `IBrowser` OidcClient qui ouvre le système + attend le pipe. |
|
| `Services/CustomSchemeBrowser` | `IBrowser` OidcClient qui ouvre le système + attend le pipe. |
|
||||||
| `Services/SchemeUrlDetector` | Détection pure, testable, du `postit://callback` dans argv. |
|
| `Services/SchemeUrlDetector` | Détection pure, testable, du `postit://callback` dans argv. |
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,16 @@ namespace PostIt.Services;
|
||||||
/// <see cref="YavscApiClient"/>. This class is a thin DTO↔path
|
/// <see cref="YavscApiClient"/>. This class is a thin DTO↔path
|
||||||
/// mapper, nothing more.
|
/// mapper, nothing more.
|
||||||
///
|
///
|
||||||
|
/// <para><b>URL convention.</b> <see cref="YavscApiClient"/>'s
|
||||||
|
/// <c>BaseAddress</c> already terminates with <c>/api/v1/</c>
|
||||||
|
/// (see <c>Settings.ApiUrl</c>). The path prefix below is
|
||||||
|
/// therefore <i>relative</i> to that version segment: a prefix of
|
||||||
|
/// <c>"blog"</c> resolves to <c>…/api/v1/blog</c>, which matches
|
||||||
|
/// the <c>[Route(APIPrefix + "/blog")]</c> attribute on
|
||||||
|
/// <c>Yavsc.Blogs.Controllers.BlogApiController</c>. Do not
|
||||||
|
/// re-include the <c>api/</c> segment here — that produced 404s
|
||||||
|
/// in the past (see commit "PostIt: fix blog API double-prefix").</para>
|
||||||
|
///
|
||||||
/// The class is intentionally non-IDisposable: it does not own the
|
/// The class is intentionally non-IDisposable: it does not own the
|
||||||
/// <see cref="YavscApiClient"/> it depends on. Lifetimes are managed
|
/// <see cref="YavscApiClient"/> it depends on. Lifetimes are managed
|
||||||
/// by the consumer (typically a singleton service registered with
|
/// by the consumer (typically a singleton service registered with
|
||||||
|
|
@ -22,7 +32,7 @@ namespace PostIt.Services;
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class BlogApiClient
|
public sealed class BlogApiClient
|
||||||
{
|
{
|
||||||
private const string DefaultPathPrefix = "api/blog";
|
private const string DefaultPathPrefix = "blog";
|
||||||
|
|
||||||
private readonly YavscApiClient _api;
|
private readonly YavscApiClient _api;
|
||||||
private readonly string _pathPrefix;
|
private readonly string _pathPrefix;
|
||||||
|
|
|
||||||
|
|
@ -128,9 +128,28 @@ public partial class MainPageViewModel : ViewModelBase
|
||||||
[RelayCommand]
|
[RelayCommand]
|
||||||
internal async Task Save()
|
internal async Task Save()
|
||||||
{
|
{
|
||||||
|
// No selection means "create a new post from the editor".
|
||||||
|
// The server is the source of truth, so we POST without an id
|
||||||
|
// and let BlogApiController assign one. The local view-model
|
||||||
|
// is then rebound to the server-issued record.
|
||||||
if (SelectedPost is null)
|
if (SelectedPost is null)
|
||||||
{
|
{
|
||||||
StatusMessage = "A post must be selected before saving.";
|
var draft = new BlogPost
|
||||||
|
{
|
||||||
|
Title = string.Empty,
|
||||||
|
Article = string.Empty,
|
||||||
|
DateCreated = DateTime.UtcNow,
|
||||||
|
DateModified = DateTime.UtcNow
|
||||||
|
};
|
||||||
|
await ExecuteAsync(async () =>
|
||||||
|
{
|
||||||
|
var created = await BlogClient.CreatePostAsync(draft);
|
||||||
|
if (created is not null)
|
||||||
|
{
|
||||||
|
SelectedPost = created;
|
||||||
|
StatusMessage = $"Created post {created.Id}.";
|
||||||
|
}
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -176,19 +195,6 @@ public partial class MainPageViewModel : ViewModelBase
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
[RelayCommand]
|
|
||||||
internal void New()
|
|
||||||
{
|
|
||||||
SelectedPost = new BlogPost
|
|
||||||
{
|
|
||||||
Title = string.Empty,
|
|
||||||
Article = string.Empty,
|
|
||||||
DateCreated = DateTime.UtcNow,
|
|
||||||
DateModified = DateTime.UtcNow
|
|
||||||
};
|
|
||||||
StatusMessage = "New blog post ready.";
|
|
||||||
}
|
|
||||||
|
|
||||||
[RelayCommand]
|
[RelayCommand]
|
||||||
internal void OpenSettings()
|
internal void OpenSettings()
|
||||||
{
|
{
|
||||||
|
|
@ -253,7 +259,6 @@ public partial class MainPageViewModel : ViewModelBase
|
||||||
LoadPostsCommand.NotifyCanExecuteChanged();
|
LoadPostsCommand.NotifyCanExecuteChanged();
|
||||||
SaveCommand.NotifyCanExecuteChanged();
|
SaveCommand.NotifyCanExecuteChanged();
|
||||||
DeleteCommand.NotifyCanExecuteChanged();
|
DeleteCommand.NotifyCanExecuteChanged();
|
||||||
NewCommand.NotifyCanExecuteChanged();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool CanSave() => SelectedPost is not null && !IsBusy;
|
private bool CanSave() => SelectedPost is not null && !IsBusy;
|
||||||
|
|
|
||||||
|
|
@ -32,7 +32,6 @@
|
||||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||||
<Button Command="{Binding LoadPosts}" Content="Load posts" />
|
<Button Command="{Binding LoadPosts}" Content="Load posts" />
|
||||||
<Button Command="{Binding Search}" Content="Filter" />
|
<Button Command="{Binding Search}" Content="Filter" />
|
||||||
<Button Command="{Binding New}" Content="New post" />
|
|
||||||
<Button Command="{Binding Save}" Content="Save" />
|
<Button Command="{Binding Save}" Content="Save" />
|
||||||
<Button Command="{Binding Delete}" Content="Delete" />
|
<Button Command="{Binding Delete}" Content="Delete" />
|
||||||
<!--
|
<!--
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,6 @@ namespace Yavsc.Blogs.Controllers
|
||||||
[Authorize("BlogScope")]
|
[Authorize("BlogScope")]
|
||||||
[Produces("application/json")]
|
[Produces("application/json")]
|
||||||
[Route(APIPrefix + "/blog")]
|
[Route(APIPrefix + "/blog")]
|
||||||
|
|
||||||
public class BlogApiController : Controller
|
public class BlogApiController : Controller
|
||||||
{
|
{
|
||||||
private readonly BlogSpotService blogSpotService;
|
private readonly BlogSpotService blogSpotService;
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
using Yavsc.Models;
|
using Yavsc.Models;
|
||||||
|
using Yavsc.Tests.Shared;
|
||||||
|
|
||||||
namespace Yavsc.Org.Tests.Controllers;
|
namespace Yavsc.Org.Tests.Controllers;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ using System.Net.Http;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.AspNetCore.Mvc.Testing;
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
using Yavsc.Tests.Shared;
|
||||||
|
|
||||||
namespace Yavsc.Org.Tests.Controllers;
|
namespace Yavsc.Org.Tests.Controllers;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,6 @@
|
||||||
|
|
||||||
<!-- Yavsc.Org.Tests-specific versions -->
|
<!-- Yavsc.Org.Tests-specific versions -->
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageVersion Include="Microsoft.AspNetCore.Hosting" Version="2.3.11" />
|
|
||||||
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.9" />
|
|
||||||
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.9" />
|
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.9" />
|
||||||
<PackageVersion Include="Microsoft.Extensions.Options" Version="10.0.9" />
|
<PackageVersion Include="Microsoft.Extensions.Options" Version="10.0.9" />
|
||||||
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.9" />
|
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.9" />
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ using System.Linq;
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Yavsc.Tests.Shared;
|
||||||
|
|
||||||
namespace Yavsc.Org.Tests;
|
namespace Yavsc.Org.Tests;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Hosting;
|
||||||
using Microsoft.AspNetCore.Mvc.Testing;
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
using Microsoft.AspNetCore.TestHost;
|
using Microsoft.AspNetCore.TestHost;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Yavsc.Tests.Shared;
|
||||||
|
|
||||||
namespace Yavsc.Org.Tests;
|
namespace Yavsc.Org.Tests;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,7 @@
|
||||||
|
|
||||||
using IdentityServer8.EntityFramework.Entities;
|
using IdentityServer8.EntityFramework.Entities;
|
||||||
using IdentityServer8.Models;
|
using IdentityServer8.Models;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.AspNetCore.Hosting;
|
|
||||||
using Microsoft.AspNetCore.Hosting.Server;
|
using Microsoft.AspNetCore.Hosting.Server;
|
||||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||||
using Microsoft.AspNetCore.Identity;
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
|
@ -12,129 +10,69 @@ using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using System.Net;
|
|
||||||
using System.Security.Cryptography;
|
|
||||||
using System.Security.Cryptography.X509Certificates;
|
|
||||||
using Yavsc;
|
using Yavsc;
|
||||||
using Yavsc.Extensions;
|
using Yavsc.Extensions;
|
||||||
using Yavsc.Interfaces;
|
using Yavsc.Interfaces;
|
||||||
using Yavsc.Models;
|
using Yavsc.Models;
|
||||||
using Yavsc.Server.Helpers;
|
using Yavsc.Server.Helpers;
|
||||||
|
using Yavsc.Tests.Shared;
|
||||||
using Client = IdentityServer8.EntityFramework.Entities.Client;
|
using Client = IdentityServer8.EntityFramework.Entities.Client;
|
||||||
using Yavsc.Org.Tests.Fakes;
|
using Yavsc.Org.Tests.Fakes;
|
||||||
|
|
||||||
|
namespace Yavsc.Org.Tests;
|
||||||
|
|
||||||
namespace Yavsc.Org.Tests
|
/// <summary>
|
||||||
|
/// Specialisation of <see cref="WebHostFixture"/> for the Yavsc.Org
|
||||||
{
|
/// host. Adds:
|
||||||
|
/// <list type="bullet">
|
||||||
|
/// <item><description>In-memory configuration (<c>ConnectionStrings</c>,
|
||||||
|
/// <c>Smtp</c>) before <c>ConfigureWebAppServices</c> runs.</description></item>
|
||||||
|
/// <item><description>Test-only <see cref="TestAuthPolicyProvider"/>
|
||||||
|
/// (from <c>Yavsc.Tests.Shared</c>) swapped in for
|
||||||
|
/// <see cref="IAuthorizationPolicyProvider"/>.</description></item>
|
||||||
|
/// <item><description>Recording <see cref="RecordingSmtpClientFactory"/>
|
||||||
|
/// fake for <see cref="ISmtpClientFactory"/>.</description></item>
|
||||||
|
/// <item><description>IdentityServer8 client + API scope + test user
|
||||||
|
/// seeded into the in-memory database.</description></item>
|
||||||
|
/// </list>
|
||||||
|
/// All cross-cutting Kestrel / cert / address plumbing is inherited
|
||||||
|
/// from <see cref="WebHostFixture"/>.
|
||||||
|
/// </summary>
|
||||||
[CollectionDefinition("Yavsc Server")]
|
[CollectionDefinition("Yavsc Server")]
|
||||||
public class WebServerFixture : IDisposable
|
public sealed class WebServerFixture : WebHostFixture
|
||||||
{
|
{
|
||||||
private static readonly Lazy<X509Certificate2> _selfSignedCertificate = new Lazy<X509Certificate2>(CreateSelfSignedCertificate);
|
private static IConfiguration? _sharedConfiguration;
|
||||||
private static readonly object _sync = new object();
|
private static SiteSettings? _sharedSiteSettings;
|
||||||
private static WebApplication? _app;
|
private static ILogger? _sharedLogger;
|
||||||
private static bool _isInitialized = false;
|
|
||||||
private static int _instanceCount = 0;
|
|
||||||
private static readonly List<string> _sharedAddresses = new List<string>();
|
|
||||||
private static string? _sharedTestClientId;
|
private static string? _sharedTestClientId;
|
||||||
private static string? _sharedTestClientSecret;
|
private static string? _sharedTestClientSecret;
|
||||||
private static string? _sharedTestingUserName;
|
private static string? _sharedTestingUserName;
|
||||||
private static string? _sharedTestingUserPassword;
|
private static string? _sharedTestingUserPassword;
|
||||||
private static string? _sharedTestingUserEmail;
|
private static string? _sharedTestingUserEmail;
|
||||||
private static RecordingSmtpClientFactory? _sharedSmtpClientFactory;
|
private static RecordingSmtpClientFactory? _sharedSmtpClientFactory;
|
||||||
private static IServiceProvider? _sharedServices;
|
|
||||||
private static IConfiguration? _sharedConfiguration;
|
|
||||||
private static SiteSettings? _sharedSiteSettings;
|
|
||||||
private static Microsoft.Extensions.Logging.ILogger? _sharedLogger;
|
|
||||||
|
|
||||||
public List<string> Addresses { get; private set; } = new List<string>();
|
|
||||||
public Microsoft.Extensions.Logging.ILogger? Logger { get; internal set; }
|
|
||||||
|
|
||||||
private SiteSettings? siteSettings;
|
|
||||||
|
|
||||||
public IConfiguration? Configuration { get; private set; }
|
public IConfiguration? Configuration { get; private set; }
|
||||||
|
|
||||||
public string? TestClientId { get; private set; }
|
public string? TestClientId { get; private set; }
|
||||||
|
public string? TestClientSecret { get; set; }
|
||||||
public IServiceProvider? Services { get; private set; }
|
|
||||||
public string? TestingUserName { get; private set; }
|
public string? TestingUserName { get; private set; }
|
||||||
public string? TestingUserPassword { get; private set; }
|
public string? TestingUserPassword { get; private set; }
|
||||||
|
public string? TestingUserEmail { get; set; }
|
||||||
public string? ProtectedTestingApiKey { get; internal set; }
|
public string? ProtectedTestingApiKey { get; internal set; }
|
||||||
public ApplicationUser? TestingUser { get; private set; }
|
public ApplicationUser? TestingUser { get; private set; }
|
||||||
public bool DbCreated { get; internal set; }
|
public bool DbCreated { get; internal set; }
|
||||||
public SiteSettings? SiteSettings { get => siteSettings; set => siteSettings = value; }
|
public SiteSettings? SiteSettings { get; set; }
|
||||||
public string? TestClientSecret { get; set; }
|
|
||||||
public string? TestingUserEmail { get; set; }
|
|
||||||
public RecordingSmtpClientFactory? SmtpClientFactory { get; private set; }
|
public RecordingSmtpClientFactory? SmtpClientFactory { get; private set; }
|
||||||
public WebServerFixture()
|
public ILogger? Logger { get; internal set; }
|
||||||
{
|
|
||||||
lock (_sync)
|
|
||||||
{
|
|
||||||
_instanceCount++;
|
|
||||||
if (!_isInitialized)
|
|
||||||
{
|
|
||||||
|
|
||||||
SetupHost().Wait();
|
protected override WebApplication BuildApp(WebApplicationBuilder builder)
|
||||||
_isInitialized = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
CopySharedState();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
{
|
||||||
lock (_sync)
|
|
||||||
{
|
|
||||||
_instanceCount--;
|
|
||||||
if (_instanceCount == 0 && _app != null)
|
|
||||||
{
|
|
||||||
_app.StopAsync().Wait();
|
|
||||||
_app = null;
|
|
||||||
_isInitialized = false;
|
|
||||||
_sharedAddresses.Clear();
|
|
||||||
_sharedServices = null;
|
|
||||||
_sharedConfiguration = null;
|
|
||||||
_sharedSiteSettings = null;
|
|
||||||
_sharedLogger = null;
|
|
||||||
_sharedTestClientId = null;
|
|
||||||
_sharedTestClientSecret = null;
|
|
||||||
_sharedTestingUserName = null;
|
|
||||||
_sharedTestingUserPassword = null;
|
|
||||||
_sharedTestingUserEmail = null;
|
|
||||||
_sharedSmtpClientFactory = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void CopySharedState()
|
|
||||||
{
|
|
||||||
Addresses = new List<string>(_sharedAddresses);
|
|
||||||
Logger = _sharedLogger;
|
|
||||||
Configuration = _sharedConfiguration;
|
|
||||||
Services = _sharedServices;
|
|
||||||
SiteSettings = _sharedSiteSettings;
|
|
||||||
TestClientId = _sharedTestClientId;
|
|
||||||
TestClientSecret = _sharedTestClientSecret;
|
|
||||||
TestingUserName = _sharedTestingUserName;
|
|
||||||
TestingUserPassword = _sharedTestingUserPassword;
|
|
||||||
TestingUserEmail = _sharedTestingUserEmail;
|
|
||||||
SmtpClientFactory = _sharedSmtpClientFactory;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task SetupHost()
|
|
||||||
{
|
|
||||||
var builder = WebApplication.CreateBuilder();
|
|
||||||
|
|
||||||
// WebApplication.CreateBuilder defaults WebRootPath to
|
// WebApplication.CreateBuilder defaults WebRootPath to
|
||||||
// {ContentRoot}/wwwroot. The test assembly runs from
|
// {ContentRoot}/wwwroot. The test assembly runs from
|
||||||
// src/Yavsc.Org.Tests/bin/.../, which has no wwwroot of
|
// src/Yavsc.Org.Tests/bin/.../, which has no wwwroot of
|
||||||
// its own — so point the host at the Yavsc.Org project's
|
// its own — so point the host at the Yavsc.Org project's
|
||||||
// wwwroot so that ConfigurePipeline's
|
// wwwroot so that ConfigurePipeline's static-assets middleware
|
||||||
|
// can resolve it. The AddConfiguration extension takes care of
|
||||||
|
// that plus the in-memory overrides below.
|
||||||
builder.AddConfiguration(null).AddInMemoryCollection(new Dictionary<string, string?>
|
builder.AddConfiguration(null).AddInMemoryCollection(new Dictionary<string, string?>
|
||||||
{
|
{
|
||||||
[$"ConnectionStrings:{YavscConstants.YavscConnectionStringName}"] = "InMemory",
|
[$"ConnectionStrings:{YavscConstants.YavscConnectionStringName}"] = "InMemory",
|
||||||
|
|
@ -147,15 +85,6 @@ namespace Yavsc.Org.Tests
|
||||||
["Smtp:Password"] = "test-pass",
|
["Smtp:Password"] = "test-pass",
|
||||||
});
|
});
|
||||||
|
|
||||||
// Configure Kestrel for HTTPS with self-signed certificate on a dynamic port
|
|
||||||
builder.WebHost.ConfigureKestrel(options =>
|
|
||||||
{
|
|
||||||
options.Listen(IPAddress.Loopback, 0, listenOptions =>
|
|
||||||
{
|
|
||||||
listenOptions.UseHttps(_selfSignedCertificate.Value);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
Configuration = builder.Configuration;
|
Configuration = builder.Configuration;
|
||||||
|
|
||||||
// Swap the production authorization policy provider for
|
// Swap the production authorization policy provider for
|
||||||
|
|
@ -178,29 +107,10 @@ namespace Yavsc.Org.Tests
|
||||||
builder.Services.AddSingleton<ISmtpClientFactory>(smtpFactory);
|
builder.Services.AddSingleton<ISmtpClientFactory>(smtpFactory);
|
||||||
_sharedSmtpClientFactory = smtpFactory;
|
_sharedSmtpClientFactory = smtpFactory;
|
||||||
|
|
||||||
_app = builder.ConfigureWebAppServices();
|
var app = builder.ConfigureWebAppServices();
|
||||||
|
SiteSettings = app.Services.GetRequiredService<IOptions<SiteSettings>>().Value;
|
||||||
|
|
||||||
// Note: a recording ISmtpClientFactory is registered
|
using (var migrationScope = app.Services.CreateScope())
|
||||||
// BEFORE ConfigureWebAppServices() above (further up in
|
|
||||||
// this method) so the production TryAddSingleton inside
|
|
||||||
// ConfigureWebAppServices becomes a no-op.
|
|
||||||
// _sharedSmtpClientFactory is captured there.
|
|
||||||
|
|
||||||
// The MSBuild target CopyYavscOrgStaticAssets in
|
|
||||||
// Yavsc.Org.Tests.csproj mirrors the Yavsc.Org static
|
|
||||||
// assets manifest into the test bin directory. Call
|
|
||||||
// MapStaticAssets() with the explicit path so the test
|
|
||||||
// host resolves the manifest by file location rather
|
|
||||||
// than by {AssemblyName}.staticwebassets.* convention
|
|
||||||
// (which would look for Yavsc.Org.Tests.staticwebassets.*,
|
|
||||||
// a file we don't produce).
|
|
||||||
var testRuntimeManifest = Path.Combine(AppContext.BaseDirectory,
|
|
||||||
"Yavsc.Org.staticwebassets.runtime.json");
|
|
||||||
|
|
||||||
Services = _app.Services;
|
|
||||||
SiteSettings = _app.Services.GetRequiredService<IOptions<SiteSettings>>().Value;
|
|
||||||
|
|
||||||
using (var migrationScope = _app.Services.CreateScope())
|
|
||||||
{
|
{
|
||||||
var db = migrationScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
var db = migrationScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||||
db.Database.EnsureDeleted();
|
db.Database.EnsureDeleted();
|
||||||
|
|
@ -213,7 +123,7 @@ namespace Yavsc.Org.Tests
|
||||||
TestClientSecret = Guid.CreateVersion7().ToString();
|
TestClientSecret = Guid.CreateVersion7().ToString();
|
||||||
EnsureUser(TestingUserName, TestingUserPassword, TestingUserEmail, migrationScope);
|
EnsureUser(TestingUserName, TestingUserPassword, TestingUserEmail, migrationScope);
|
||||||
AddAuthorizedClient(migrationScope, TestClientId, TestClientSecret);
|
AddAuthorizedClient(migrationScope, TestClientId, TestClientSecret);
|
||||||
TestingUser = await db.Users.FirstOrDefaultAsync(u => u.UserName == TestingUserName);
|
TestingUser = db.Users.FirstOrDefaultAsync(u => u.UserName == TestingUserName).Result;
|
||||||
|
|
||||||
// Add test API scope if it doesn't exist
|
// Add test API scope if it doesn't exist
|
||||||
var testScope = db.ApiScopes.FirstOrDefault(s => s.Name == "test");
|
var testScope = db.ApiScopes.FirstOrDefault(s => s.Name == "test");
|
||||||
|
|
@ -240,10 +150,7 @@ namespace Yavsc.Org.Tests
|
||||||
Enabled = true,
|
Enabled = true,
|
||||||
Scopes = new List<IdentityServer8.EntityFramework.Entities.ApiResourceScope>
|
Scopes = new List<IdentityServer8.EntityFramework.Entities.ApiResourceScope>
|
||||||
{
|
{
|
||||||
new IdentityServer8.EntityFramework.Entities.ApiResourceScope
|
new IdentityServer8.EntityFramework.Entities.ApiResourceScope { Scope = "test" }
|
||||||
{
|
|
||||||
Scope = "test"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
db.ApiResources.Add(apiResource);
|
db.ApiResources.Add(apiResource);
|
||||||
|
|
@ -251,13 +158,6 @@ namespace Yavsc.Org.Tests
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
_app = await _app.ConfigurePipeline(testRuntimeManifest);
|
|
||||||
|
|
||||||
await _app.StartAsync();
|
|
||||||
|
|
||||||
_sharedServices = _app.Services;
|
|
||||||
_sharedConfiguration = Configuration;
|
_sharedConfiguration = Configuration;
|
||||||
_sharedSiteSettings = SiteSettings;
|
_sharedSiteSettings = SiteSettings;
|
||||||
_sharedTestClientId = TestClientId;
|
_sharedTestClientId = TestClientId;
|
||||||
|
|
@ -265,21 +165,39 @@ namespace Yavsc.Org.Tests
|
||||||
_sharedTestingUserName = TestingUserName;
|
_sharedTestingUserName = TestingUserName;
|
||||||
_sharedTestingUserPassword = TestingUserPassword;
|
_sharedTestingUserPassword = TestingUserPassword;
|
||||||
_sharedTestingUserEmail = TestingUserEmail;
|
_sharedTestingUserEmail = TestingUserEmail;
|
||||||
_sharedLogger = _app.Services.GetRequiredService<ILoggerFactory>().CreateLogger<WebServerFixture>();
|
_sharedLogger = app.Services.GetRequiredService<ILoggerFactory>().CreateLogger<WebServerFixture>();
|
||||||
Logger = _sharedLogger;
|
Logger = _sharedLogger;
|
||||||
|
SmtpClientFactory = smtpFactory;
|
||||||
|
|
||||||
var server = _app.Services.GetRequiredService<IServer>();
|
return app;
|
||||||
var addressFeatures = server.Features.Get<IServerAddressesFeature>();
|
}
|
||||||
|
|
||||||
if (addressFeatures?.Addresses != null)
|
protected override async Task<WebApplication> ConfigurePipelineAsync(WebApplication app)
|
||||||
{
|
{
|
||||||
_sharedAddresses.Clear();
|
// The MSBuild target CopyYavscOrgStaticAssets in
|
||||||
foreach (var address in addressFeatures.Addresses)
|
// Yavsc.Org.Tests.csproj mirrors the Yavsc.Org static
|
||||||
|
// assets manifest into the test bin directory. Call
|
||||||
|
// MapStaticAssets() with the explicit path so the test
|
||||||
|
// host resolves the manifest by file location rather
|
||||||
|
// than by {AssemblyName}.staticwebassets.* convention
|
||||||
|
// (which would look for Yavsc.Org.Tests.staticwebassets.*,
|
||||||
|
// a file we don't produce).
|
||||||
|
var testRuntimeManifest = Path.Combine(AppContext.BaseDirectory,
|
||||||
|
"Yavsc.Org.staticwebassets.runtime.json");
|
||||||
|
return await app.ConfigurePipeline(testRuntimeManifest);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void CopySpecialisedSharedState()
|
||||||
{
|
{
|
||||||
_sharedAddresses.Add(address);
|
TestClientId = _sharedTestClientId;
|
||||||
Addresses.Add(address);
|
TestClientSecret = _sharedTestClientSecret;
|
||||||
}
|
TestingUserName = _sharedTestingUserName;
|
||||||
}
|
TestingUserPassword = _sharedTestingUserPassword;
|
||||||
|
TestingUserEmail = _sharedTestingUserEmail;
|
||||||
|
SmtpClientFactory = _sharedSmtpClientFactory;
|
||||||
|
Configuration = _sharedConfiguration;
|
||||||
|
SiteSettings = _sharedSiteSettings;
|
||||||
|
Logger = _sharedLogger;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void AddAuthorizedClient(IServiceScope scope, string testClientId, string testClientSecret)
|
private void AddAuthorizedClient(IServiceScope scope, string testClientId, string testClientSecret)
|
||||||
|
|
@ -343,9 +261,7 @@ namespace Yavsc.Org.Tests
|
||||||
{
|
{
|
||||||
if (TestingUser == null)
|
if (TestingUser == null)
|
||||||
{
|
{
|
||||||
|
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
|
||||||
var userManager =
|
|
||||||
scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
|
|
||||||
|
|
||||||
TestingUser = new ApplicationUser
|
TestingUser = new ApplicationUser
|
||||||
{
|
{
|
||||||
|
|
@ -358,26 +274,8 @@ namespace Yavsc.Org.Tests
|
||||||
|
|
||||||
Assert.True(result.Succeeded);
|
Assert.True(result.Succeeded);
|
||||||
|
|
||||||
ApplicationDbContext dbContext =
|
ApplicationDbContext dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||||
scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
|
||||||
TestingUser = dbContext.Users.FirstOrDefault(u => u.UserName == testingUserName);
|
TestingUser = dbContext.Users.FirstOrDefault(u => u.UserName == testingUserName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static X509Certificate2 CreateSelfSignedCertificate()
|
|
||||||
{
|
|
||||||
var rsa = RSA.Create(2048);
|
|
||||||
var certRequest = new CertificateRequest("CN=localhost", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
|
||||||
|
|
||||||
certRequest.CertificateExtensions.Add(
|
|
||||||
new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));
|
|
||||||
|
|
||||||
certRequest.CertificateExtensions.Add(
|
|
||||||
new X509EnhancedKeyUsageExtension(
|
|
||||||
new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false));
|
|
||||||
|
|
||||||
var certificate = certRequest.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(3650)));
|
|
||||||
return certificate;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -46,6 +46,7 @@
|
||||||
<ProjectReference Include="..\Yavsc.Org\Yavsc.Org.csproj" />
|
<ProjectReference Include="..\Yavsc.Org\Yavsc.Org.csproj" />
|
||||||
<ProjectReference Include="..\Yavsc.Abstract\Yavsc.Abstract.csproj" />
|
<ProjectReference Include="..\Yavsc.Abstract\Yavsc.Abstract.csproj" />
|
||||||
<ProjectReference Include="..\Yavsc.Server\Yavsc.Server.csproj" />
|
<ProjectReference Include="..\Yavsc.Server\Yavsc.Server.csproj" />
|
||||||
|
<ProjectReference Include="..\Yavsc.Tests.Shared\Yavsc.Tests.Shared.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Using Include="Xunit" />
|
<Using Include="Xunit" />
|
||||||
|
|
|
||||||
8
src/Yavsc.Tests.Shared/Directory.Packages.props
Normal file
8
src/Yavsc.Tests.Shared/Directory.Packages.props
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
<Project>
|
||||||
|
<!--
|
||||||
|
Yavsc.Tests.Shared has no project-specific package versions.
|
||||||
|
The shared library only needs the canonical Hosting / Mvc.Testing
|
||||||
|
versions, all of which are declared at the repository root.
|
||||||
|
-->
|
||||||
|
<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Packages.props', '$(MSBuildThisFileDirectory)../'))" />
|
||||||
|
</Project>
|
||||||
|
|
@ -1,24 +1,30 @@
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
using System.Security.Claims;
|
||||||
|
|
||||||
namespace Yavsc.Org.Tests;
|
namespace Yavsc.Tests.Shared;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Authorization policy provider used by integration tests. Replaces the
|
/// Authorization policy provider used by integration tests. Replaces the
|
||||||
/// production provider in the WebApplicationFactory so that any
|
/// production provider in the test host so that any policy-protected
|
||||||
/// policy-protected controller can be exercised by sending a
|
/// controller can be exercised by sending a <c>X-Test-Role: …</c>
|
||||||
/// <c>X-Test-Role: Administrator</c> header — no login roundtrip, no
|
/// header — no login roundtrip, no cookie, no database user.
|
||||||
/// cookie, no database user.
|
|
||||||
///
|
///
|
||||||
/// The role names accepted in the header are the same as the
|
/// Any policy that requires a role short-circuits to success when the
|
||||||
/// production <see cref="YavscConstants.AdminGroupName"/>. Any
|
/// matching header is present; otherwise the production policy is
|
||||||
/// policy that requires one of those roles short-circuits to success
|
/// preserved. The test does not perform a real login, so we attach an
|
||||||
/// when the matching header is present; otherwise the production
|
/// in-memory <see cref="ClaimsPrincipal"/> carrying the role claim to
|
||||||
/// policy is preserved.
|
/// the request <see cref="HttpContext.User"/> before the assertion
|
||||||
|
/// fires, so claim-based requirements (e.g. <c>RequireRole("Admin")</c>)
|
||||||
|
/// also pass.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class TestAuthPolicyProvider : IAuthorizationPolicyProvider
|
public sealed class TestAuthPolicyProvider : IAuthorizationPolicyProvider
|
||||||
{
|
{
|
||||||
|
/// <summary>HTTP header read by the test bypass to learn the role.</summary>
|
||||||
public const string HeaderName = "X-Test-Role";
|
public const string HeaderName = "X-Test-Role";
|
||||||
|
|
||||||
|
/// <summary>Conventional admin role name; the production default.</summary>
|
||||||
public const string AdminRole = "Administrator";
|
public const string AdminRole = "Administrator";
|
||||||
|
|
||||||
private readonly DefaultAuthorizationPolicyProvider _fallback;
|
private readonly DefaultAuthorizationPolicyProvider _fallback;
|
||||||
|
|
@ -42,26 +48,21 @@ public sealed class TestAuthPolicyProvider : IAuthorizationPolicyProvider
|
||||||
// ASP.NET Core sets ctx.Resource to the HttpContext when
|
// ASP.NET Core sets ctx.Resource to the HttpContext when
|
||||||
// the authorization middleware invokes the policy. Use
|
// the authorization middleware invokes the policy. Use
|
||||||
// the request headers directly to honour X-Test-Role.
|
// the request headers directly to honour X-Test-Role.
|
||||||
var http = ctx.Resource as Microsoft.AspNetCore.Http.HttpContext;
|
var http = ctx.Resource as HttpContext;
|
||||||
if (http is null) return false;
|
if (http is null) return false;
|
||||||
var role = http.Request.Headers[HeaderName].ToString();
|
var role = http.Request.Headers[HeaderName].ToString();
|
||||||
if (string.IsNullOrEmpty(role)) return false;
|
if (string.IsNullOrEmpty(role)) return false;
|
||||||
// The test does not perform a real login, so the
|
|
||||||
// authenticated user has no claims. Attach an
|
|
||||||
// in-memory identity carrying the role claim to the
|
|
||||||
// HttpContext (ctx.User is read-only) so the
|
|
||||||
// production policy's claim requirement is satisfied.
|
|
||||||
if (http.User.Identity is null || !http.User.Identity.IsAuthenticated)
|
if (http.User.Identity is null || !http.User.Identity.IsAuthenticated)
|
||||||
{
|
{
|
||||||
var identity = new System.Security.Claims.ClaimsIdentity(
|
var identity = new ClaimsIdentity(
|
||||||
new[]
|
new[]
|
||||||
{
|
{
|
||||||
new System.Security.Claims.Claim(
|
new Claim(
|
||||||
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
|
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
|
||||||
role),
|
role),
|
||||||
},
|
},
|
||||||
authenticationType: "TestAuth");
|
authenticationType: "TestAuth");
|
||||||
http.User = new System.Security.Claims.ClaimsPrincipal(identity);
|
http.User = new ClaimsPrincipal(identity);
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
})
|
})
|
||||||
172
src/Yavsc.Tests.Shared/WebHostFixture.cs
Normal file
172
src/Yavsc.Tests.Shared/WebHostFixture.cs
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.AspNetCore.Hosting.Server;
|
||||||
|
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using System.Net;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
|
||||||
|
namespace Yavsc.Tests.Shared;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Base class for ASP.NET Core integration test hosts. Provides the
|
||||||
|
/// cross-cutting plumbing shared by every test fixture in the
|
||||||
|
/// repository:
|
||||||
|
///
|
||||||
|
/// <list type="bullet">
|
||||||
|
/// <item><description>Kestrel with a self-signed HTTPS certificate
|
||||||
|
/// on a dynamically-allocated port (no port collisions between
|
||||||
|
/// parallel xUnit test classes).</description></item>
|
||||||
|
/// <item><description>A per-process single-instance host initialised
|
||||||
|
/// on first construction and torn down when the last fixture is
|
||||||
|
/// disposed — same lazy + lock + count pattern as the original Org
|
||||||
|
/// fixture, lifted out of the specialisation.</description></item>
|
||||||
|
/// <item><description>Address discovery via
|
||||||
|
/// <see cref="IServerAddressesFeature"/>.</description></item>
|
||||||
|
/// </list>
|
||||||
|
///
|
||||||
|
/// The actual service registration, middleware pipeline and route
|
||||||
|
/// mapping are the responsibility of the subclass, through
|
||||||
|
/// <see cref="BuildApp"/>.
|
||||||
|
/// </summary>
|
||||||
|
public abstract class WebHostFixture : IDisposable
|
||||||
|
{
|
||||||
|
private static readonly Lazy<X509Certificate2> _selfSignedCertificate =
|
||||||
|
new Lazy<X509Certificate2>(CreateSelfSignedCertificate);
|
||||||
|
private static readonly object _sync = new object();
|
||||||
|
private static WebApplication? _app;
|
||||||
|
private static bool _isInitialized;
|
||||||
|
private static int _instanceCount;
|
||||||
|
private static readonly List<string> _sharedAddresses = new();
|
||||||
|
private static IServiceProvider? _sharedServices;
|
||||||
|
|
||||||
|
/// <summary>HTTPS listen URLs the host bound to.</summary>
|
||||||
|
public IReadOnlyList<string> Addresses { get; private set; } = Array.Empty<string>();
|
||||||
|
|
||||||
|
/// <summary>The DI service provider of the running host. Read from
|
||||||
|
/// the shared static slot so every fixture instance (xUnit creates
|
||||||
|
/// one per <c>IClassFixture</c>) sees the same provider after the
|
||||||
|
/// first initialisation. Throws if <see cref="IsInitialized"/> is
|
||||||
|
/// false.</summary>
|
||||||
|
public IServiceProvider Services => _sharedServices
|
||||||
|
?? throw new InvalidOperationException(
|
||||||
|
"WebHostFixture has not been initialised. Call InitializeAsync first.");
|
||||||
|
|
||||||
|
/// <summary>True once <see cref="InitializeAsync"/> has completed
|
||||||
|
/// successfully and the host is running.</summary>
|
||||||
|
public bool IsInitialized { get; private set; }
|
||||||
|
|
||||||
|
protected WebHostFixture()
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
_instanceCount++;
|
||||||
|
if (!_isInitialized)
|
||||||
|
{
|
||||||
|
InitializeAsync().GetAwaiter().GetResult();
|
||||||
|
_isInitialized = true;
|
||||||
|
}
|
||||||
|
CopySharedState();
|
||||||
|
CopySpecialisedSharedState();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CopySharedState()
|
||||||
|
{
|
||||||
|
Addresses = _sharedAddresses.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Hook for specialisations to copy any other shared
|
||||||
|
/// state (test client credentials, user names, factories, etc.)
|
||||||
|
/// from the static slots exposed by the base class onto instance
|
||||||
|
/// properties. Called once per fixture construction, after
|
||||||
|
/// <see cref="InitializeAsync"/> has populated the shared state
|
||||||
|
/// the first time.</summary>
|
||||||
|
protected virtual void CopySpecialisedSharedState() { }
|
||||||
|
|
||||||
|
/// <summary>Specialisations register their services and middleware
|
||||||
|
/// here. The base class has already configured Kestrel HTTPS on a
|
||||||
|
/// dynamic port — do not bind additional listeners.</summary>
|
||||||
|
/// <param name="builder">The <see cref="WebApplicationBuilder"/>
|
||||||
|
/// configured with Kestrel HTTPS on a dynamic port and the shared
|
||||||
|
/// self-signed certificate.</param>
|
||||||
|
/// <returns>The fully built <see cref="WebApplication"/>, ready
|
||||||
|
/// for <c>ConfigurePipeline</c> + <c>StartAsync</c>.</returns>
|
||||||
|
protected abstract WebApplication BuildApp(WebApplicationBuilder builder);
|
||||||
|
|
||||||
|
/// <summary>Apply the production pipeline to <paramref name="app"/>.
|
||||||
|
/// Defaults to identity + routing + auth + MapStaticAssets; override
|
||||||
|
/// only if your host needs a different shape.</summary>
|
||||||
|
protected virtual async Task<WebApplication> ConfigurePipelineAsync(WebApplication app)
|
||||||
|
{
|
||||||
|
await Task.CompletedTask;
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task InitializeAsync()
|
||||||
|
{
|
||||||
|
var builder = WebApplication.CreateBuilder();
|
||||||
|
|
||||||
|
builder.WebHost.ConfigureKestrel(options =>
|
||||||
|
{
|
||||||
|
options.Listen(IPAddress.Loopback, 0, listenOptions =>
|
||||||
|
{
|
||||||
|
listenOptions.UseHttps(_selfSignedCertificate.Value);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
var app = BuildApp(builder);
|
||||||
|
app = await ConfigurePipelineAsync(app);
|
||||||
|
await app.StartAsync();
|
||||||
|
|
||||||
|
_app = app;
|
||||||
|
_sharedServices = app.Services;
|
||||||
|
|
||||||
|
var server = app.Services.GetRequiredService<IServer>();
|
||||||
|
var addressFeatures = server.Features.Get<IServerAddressesFeature>();
|
||||||
|
_sharedAddresses.Clear();
|
||||||
|
if (addressFeatures?.Addresses is not null)
|
||||||
|
{
|
||||||
|
foreach (var address in addressFeatures.Addresses)
|
||||||
|
{
|
||||||
|
_sharedAddresses.Add(address);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Addresses = _sharedAddresses.ToArray();
|
||||||
|
IsInitialized = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual void Dispose()
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
_instanceCount--;
|
||||||
|
if (_instanceCount == 0 && _app is not null)
|
||||||
|
{
|
||||||
|
_app.StopAsync().GetAwaiter().GetResult();
|
||||||
|
_app = null;
|
||||||
|
_isInitialized = false;
|
||||||
|
_sharedAddresses.Clear();
|
||||||
|
_sharedServices = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static X509Certificate2 CreateSelfSignedCertificate()
|
||||||
|
{
|
||||||
|
var rsa = RSA.Create(2048);
|
||||||
|
var certRequest = new CertificateRequest("CN=localhost", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||||
|
|
||||||
|
certRequest.CertificateExtensions.Add(
|
||||||
|
new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));
|
||||||
|
|
||||||
|
certRequest.CertificateExtensions.Add(
|
||||||
|
new X509EnhancedKeyUsageExtension(
|
||||||
|
new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false));
|
||||||
|
|
||||||
|
return certRequest.CreateSelfSigned(
|
||||||
|
new DateTimeOffset(DateTime.UtcNow.AddDays(-1)),
|
||||||
|
new DateTimeOffset(DateTime.UtcNow.AddDays(3650)));
|
||||||
|
}
|
||||||
|
}
|
||||||
21
src/Yavsc.Tests.Shared/Yavsc.Tests.Shared.csproj
Normal file
21
src/Yavsc.Tests.Shared/Yavsc.Tests.Shared.csproj
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
<RootNamespace>Yavsc.Tests.Shared</RootNamespace>
|
||||||
|
<!--
|
||||||
|
Shared library of test fixtures (WebHostFixture, auth bypass,
|
||||||
|
etc.) consumed by both Yavsc.Org.Tests and Yavsc.Blogs.Tests.
|
||||||
|
Not a test project itself: no xUnit, no test runner, no
|
||||||
|
TestSdk. The consumer projects own the test execution and
|
||||||
|
inherit from the shared base classes.
|
||||||
|
-->
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Hosting" />
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
Loading…
Add table
Add a link
Reference in a new issue