Files
Umbraco-CMS/tests/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTestBase.cs
Andreas Zerbst 7f1cdf8ef5 Auhorization: Cherrypicked integration tests from V15 (#20492)
* V15 QA Added the authorization integration tests (#18419)

* Added authorization integration tests

* Removed unnecessary tests and update tests for preview controller

* Updated to use the newest changes from v15/dev and added an override for the AuthenticateClientAsync to use the userGroupKey

* Updated CompatibilitySuppressions to include changes from integration tests

* Updated pipelines

* Skips managementApi tests

* Only run necessary tests

* Added new schema per fixture to reduce test setup time

* Fixed failing tests

* Updated test setup

* Updated test

* Added suppression

* Fixed failing tests

* Updated addOnTeardown methods to protected

* Added method for clearing the host

* Added teardown

* Updated model usage

* Added a lot of cleanup for memory leak issues when running tests

* Added CompatibilitySuppressions.xml

* Updated tests

* Cleaned up

* Adjusted base classes

* Updated pipeline

* Updated CompatibilitySuppressions.xml

* Updated test logging

* Fixed reponse

* Updated condition to skip tests

* Updated tests, not done

* Reworked test to expect correct responses with correct setup

* Updated tests

* More updates to tests

* Updated tests

* Cleaned up tests

* Updated setup

* Cleaned up tests to match setup

* Cleaned up setup

* Removed suppression

* Fixed tests

* Move order of checks

* Fix naming

* Formatting

* Dispose of host

* Keep track of if we're disposed

* Compat suppression

* Dont dispose

* Fix failing tests

* removed unused virtual

* Updated CompatibilitySuppressions.xml

---------

Co-authored-by: Andreas Zerbst <andr317c@live.dk>
Co-authored-by: Zeegaan <skrivdetud@gmail.com>
Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
# Conflicts:
#	tests/Umbraco.Tests.Integration/CompatibilitySuppressions.xml
#	tests/Umbraco.Tests.Integration/ManagementApi/ManagementApiTest.cs
#	tests/Umbraco.Tests.Integration/ManagementApi/Policies/AllCultureControllerTests.cs
#	tests/Umbraco.Tests.Integration/ManagementApi/Policies/CreateDocumentTests.cs
#	tests/Umbraco.Tests.Integration/ManagementApi/Policies/UpdateDocumentTests.cs
#	tests/Umbraco.Tests.Integration/ManagementApi/Preview/EndPreviewTests.cs
#	tests/Umbraco.Tests.Integration/ManagementApi/Preview/EnterPreviewTests.cs
#	tests/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs

* Updated test

* Updates

* Removed unnessecary test

---------

Co-authored-by: Nhu Dinh <150406148+nhudinh0309@users.noreply.github.com>
Co-authored-by: Zeegaan <skrivdetud@gmail.com>
Co-authored-by: Nikolaj Geisle <70372949+Zeegaan@users.noreply.github.com>
2025-10-14 10:04:10 +00:00

187 lines
6.7 KiB
C#

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NUnit.Framework;
using Serilog;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Infrastructure.Persistence;
using Umbraco.Cms.Tests.Common.Testing;
using Umbraco.Cms.Tests.Integration.Implementations;
namespace Umbraco.Cms.Tests.Integration.Testing;
/// <summary>
/// Base class for all UmbracoIntegrationTests
/// </summary>
[SingleThreaded]
[NonParallelizable]
public abstract class UmbracoIntegrationTestBase
{
private static readonly Lock _dbLocker = new();
private static ITestDatabase? _dbInstance;
private static TestDbMeta _fixtureDbMeta;
protected static int TestCount = 1;
private readonly List<Action> _fixtureTeardown = new();
private readonly Queue<Action> _testTeardown = new();
private bool _firstTestInFixture = true;
protected Dictionary<string, string> InMemoryConfiguration { get; } = new();
protected IConfiguration Configuration { get; set; }
protected UmbracoTestAttribute TestOptions => TestOptionAttributeBase.GetTestOptions<UmbracoTestAttribute>();
protected TestHelper TestHelper { get; } = new();
protected void AddOnTestTearDown(Action tearDown) => _testTeardown.Enqueue(tearDown);
protected void AddOnFixtureTearDown(Action tearDown) => _fixtureTeardown.Add(tearDown);
[SetUp]
public virtual void SetUp_Logging() =>
TestContext.Out.Write($"Start test {TestCount++}: {TestContext.CurrentContext.Test.Name}");
[TearDown]
public void TearDown_Logging() =>
TestContext.Out.Write($" {TestContext.CurrentContext.Result.Outcome.Status}");
[OneTimeTearDown]
public void FixtureTearDown()
{
foreach (var a in _fixtureTeardown)
{
a();
}
}
[TearDown]
public void TearDown()
{
_firstTestInFixture = false;
while (_testTeardown.TryDequeue(out var a))
{
a();
}
}
protected ILoggerFactory CreateLoggerFactory()
{
try
{
switch (TestOptions.Logger)
{
case UmbracoTestOptions.Logger.Mock:
return NullLoggerFactory.Instance;
case UmbracoTestOptions.Logger.Serilog:
return LoggerFactory.Create(builder =>
{
var path = Path.Combine(TestHelper.WorkingDirectory, "logs", "umbraco_integration_tests_.txt");
Log.Logger = new LoggerConfiguration()
.WriteTo.File(path, rollingInterval: RollingInterval.Day)
.MinimumLevel.Debug()
.ReadFrom.Configuration(Configuration)
.CreateLogger();
builder.AddSerilog(Log.Logger);
});
case UmbracoTestOptions.Logger.Console:
return LoggerFactory.Create(builder =>
{
builder.AddConfiguration(Configuration.GetSection("Logging"))
.AddConsole();
});
}
}
catch
{
// ignored
}
return NullLoggerFactory.Instance;
}
protected void UseTestDatabase(IServiceProvider serviceProvider)
{
if (TestOptions.Database == UmbracoTestOptions.Database.None)
{
return;
}
var state = serviceProvider.GetRequiredService<IRuntimeState>();
var databaseFactory = serviceProvider.GetRequiredService<IUmbracoDatabaseFactory>();
var connectionStrings = serviceProvider.GetRequiredService<IOptionsMonitor<ConnectionStrings>>();
var db = GetOrCreateDatabase(
serviceProvider.GetRequiredService<ILoggerFactory>(),
serviceProvider.GetRequiredService<TestUmbracoDatabaseFactoryProvider>());
TestDbMeta meta = TestOptions.Database switch
{
UmbracoTestOptions.Database.NewSchemaPerTest => SetupPerTestDatabase(db, true),
UmbracoTestOptions.Database.NewEmptyPerTest => SetupPerTestDatabase(db, false),
UmbracoTestOptions.Database.NewSchemaPerFixture => SetupPerFixtureDatabase(db, true),
UmbracoTestOptions.Database.NewEmptyPerFixture => SetupPerFixtureDatabase(db, false),
_ => throw new ArgumentOutOfRangeException(),
};
databaseFactory.Configure(meta.ToStronglyTypedConnectionString());
connectionStrings.CurrentValue.ConnectionString = meta.ConnectionString;
connectionStrings.CurrentValue.ProviderName = meta.Provider;
state.DetermineRuntimeLevel();
serviceProvider.GetRequiredService<IEventAggregator>().Publish(new UnattendedInstallNotification());
}
private TestDbMeta SetupPerTestDatabase(ITestDatabase db, bool withSchema)
{
var meta = withSchema ? db.AttachSchema() : db.AttachEmpty();
AddOnTestTearDown(() => db.Detach(meta));
return meta;
}
private TestDbMeta SetupPerFixtureDatabase(ITestDatabase db, bool withSchema)
{
if (_firstTestInFixture)
{
_fixtureDbMeta = withSchema ? db.AttachSchema() : db.AttachEmpty();
AddOnFixtureTearDown(() => db.Detach(_fixtureDbMeta));
}
return _fixtureDbMeta;
}
private ITestDatabase GetOrCreateDatabase(ILoggerFactory loggerFactory, TestUmbracoDatabaseFactoryProvider dbFactory)
{
lock (_dbLocker)
{
if (_dbInstance != null)
{
return _dbInstance;
}
var settings = new TestDatabaseSettings
{
FilesPath = Path.Combine(TestHelper.WorkingDirectory, "databases"),
DatabaseType =
Configuration.GetValue<TestDatabaseSettings.TestDatabaseType>("Tests:Database:DatabaseType"),
PrepareThreadCount = Configuration.GetValue<int>("Tests:Database:PrepareThreadCount"),
EmptyDatabasesCount = Configuration.GetValue<int>("Tests:Database:EmptyDatabasesCount"),
SchemaDatabaseCount = Configuration.GetValue<int>("Tests:Database:SchemaDatabaseCount"),
SQLServerMasterConnectionString = Configuration.GetValue<string>("Tests:Database:SQLServerMasterConnectionString"),
};
Directory.CreateDirectory(settings.FilesPath);
_dbInstance = TestDatabaseFactory.Create(settings, dbFactory, loggerFactory);
return _dbInstance;
}
}
}