Files
Umbraco-CMS/src/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs

165 lines
5.9 KiB
C#
Raw Normal View History


using System;
using System.Linq.Expressions;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
Netcore: Alternate approach for MSDI refactor (#9247) * Doesn't make much sense to have Concrete on IRegister, only on IFactory * Handle FilesTreeController requires IFileSystem of type PhysicalFileSystem * Handle registration of default MediaFileSystem without using RegisterUniqueFor * Remove RegisterFor / RegisterUniqueFor from IRegister * Switch over from LightInject to wrappers around MSDI * Made mapper dependencies more explicit * Remove registration for AngularJsonMediaTypeFormatter It's dependencies aren't registered so container validation fails * Resolve lifetime issue for EnsureValidSessionId by service locating else resolve scoped in singleton * Make registration more explicit for backoffice UserManager * Make install step registrations more explicit * Disable service provider validation so site can launch Maybe this is a problem maybe not, we build about 8000 service providers so maybe everything is fine later... * Further cleanup of IFactory interface * Further cleanup of IRegister interface * Revert "Make registration more explicit for backoffice UserManager" This reverts commit 7215fe836103c597cd0873c66737a79b91ed4c49. * Resolve issue where NewInstallStep would fail to reset password for "SuperUser" Before MSDI, somehow BackOfficeIdentityOptions would be configured with token provider map from IdentityBuilder.AddDefaultTokenProviders. After switchover those config actions are lost. Subclass IdentityBuilder to ensure BackOfficeIdentityOptions doesn't miss config setup upstream. * Initialize current. * Add todo to turn container validation back on. * Migrated ScopeFileSystemsTests to integration tests Signed-off-by: Bjarke Berg <mail@bergmania.dk> * Resolve issue where MediaFileSystem was skipping ShadowFileSystem * Attempt to fix ScopeFileSystemsTests on azure devops Signed-off-by: Bjarke Berg <mail@bergmania.dk> * Be interesting to know what the actual full path is in pipeline. * Clarify intent of CreateMediaTest Doesn't help resolve weird UnauthorizedAccessException but it cuts so much cognitive overhead for the future. * Use ILoggerfactory rather than mock for the manually constructed file PhysicalFileSystem * Maybe resolve failing test on azure pipeline. Co-authored-by: Bjarke Berg <mail@bergmania.dk>
2020-10-26 10:47:14 +00:00
using Microsoft.Extensions.DependencyInjection.Extensions;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Extensions;
using Umbraco.Tests.Integration.Testing;
using Umbraco.Tests.Testing;
using Umbraco.Web;
using Umbraco.Web.Common.Builder;
using Umbraco.Web.Common.Controllers;
using Microsoft.Extensions.Hosting;
using Umbraco.Core.Cache;
using Umbraco.Core.Persistence;
using Umbraco.Core.Runtime;
using Umbraco.Web.BackOffice.Controllers;
namespace Umbraco.Tests.Integration.TestServerTest
{
[TestFixture]
[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, Logger = UmbracoTestOptions.Logger.Console, Boot = true)]
public abstract class UmbracoTestServerTestBase : UmbracoIntegrationTest
{
[SetUp]
public override void Setup()
{
InMemoryConfiguration["ConnectionStrings:" + Constants.System.UmbracoConnectionName] = null;
InMemoryConfiguration["Umbraco:CMS:Hosting:Debug"] = "true";
// create new WebApplicationFactory specifying 'this' as the IStartup instance
var factory = new UmbracoWebApplicationFactory<UmbracoTestServerTestBase>(CreateHostBuilder);
// additional host configuration for web server integration tests
Factory = factory.WithWebHostBuilder(builder =>
{
// Executes after the standard ConfigureServices method
builder.ConfigureTestServices(services =>
{
services.AddAuthentication("Test").AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", options => { });
});
});
Client = Factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
LinkGenerator = Factory.Services.GetRequiredService<LinkGenerator>();
}
public override IHostBuilder CreateHostBuilder()
{
var builder = base.CreateHostBuilder();
builder.ConfigureWebHost(builder =>
{
// need to configure the IWebHostEnvironment too
builder.ConfigureServices((c, s) =>
{
c.HostingEnvironment = TestHelper.GetWebHostEnvironment();
});
// call startup
builder.Configure(app =>
{
UseTestLocalDb(app.ApplicationServices);
Services = app.ApplicationServices;
Configure(app);
});
}).UseEnvironment(Environments.Development);
return builder;
}
/// <summary>
/// Prepare a url before using <see cref="Client"/>.
/// This returns the url but also sets the HttpContext.request into to use this url.
/// </summary>
/// <returns>The string URL of the controller action.</returns>
protected string PrepareUrl<T>(Expression<Func<T, object>> methodSelector)
where T : UmbracoApiController
{
var url = LinkGenerator.GetUmbracoApiService<T>(methodSelector);
var backofficeSecurityFactory = GetRequiredService<IBackOfficeSecurityFactory>();
var umbracoContextFactory = GetRequiredService<IUmbracoContextFactory>();
var httpContextAccessor = GetRequiredService<IHttpContextAccessor>();
httpContextAccessor.HttpContext = new DefaultHttpContext
{
Request =
{
Scheme = "https",
Host = new HostString("localhost", 80),
Path = url,
QueryString = new QueryString(string.Empty)
}
};
backofficeSecurityFactory.EnsureBackOfficeSecurity();
umbracoContextFactory.EnsureUmbracoContext();
return url;
}
protected HttpClient Client { get; private set; }
protected LinkGenerator LinkGenerator { get; private set; }
protected WebApplicationFactory<UmbracoTestServerTestBase> Factory { get; private set; }
[TearDown]
public override void TearDown()
{
base.TearDown();
base.TerminateCoreRuntime();
Factory.Dispose();
}
#region IStartup
public override void ConfigureServices(IServiceCollection services)
{
var typeLoader = services.AddTypeLoader(GetType().Assembly, TestHelper.GetWebHostEnvironment(), TestHelper.GetHostingEnvironment(),
2020-11-24 09:22:38 +00:00
TestHelper.ConsoleLoggerFactory, AppCaches.NoCache, Configuration, TestHelper.Profiler);
2020-11-20 12:24:16 +00:00
var builder = new UmbracoBuilder(services, Configuration, typeLoader);
2020-11-20 12:24:16 +00:00
builder
2020-11-19 09:06:04 +00:00
.AddConfiguration()
.AddTestCore(TestHelper) // This is the important one!
2020-11-19 09:06:04 +00:00
.AddWebComponents()
.AddRuntimeMinifier()
.AddBackOffice()
.AddBackOfficeIdentity()
.AddPreviewSupport()
2020-09-02 18:21:51 +10:00
//.WithMiniProfiler() // we don't want this running in tests
2020-11-19 09:06:04 +00:00
.AddMvcAndRazor(mvcBuilding: mvcBuilder =>
{
mvcBuilder.AddApplicationPart(typeof(ContentController).Assembly);
})
2020-11-19 09:06:04 +00:00
.AddWebServer()
.Build();
}
public override void Configure(IApplicationBuilder app)
{
app.UseUmbraco();
}
#endregion
}
}