2020-12-23 11:35:49 +01:00
// Copyright (c) Umbraco.
// See LICENSE for more details.
2020-10-09 11:37:25 +02:00
using System.Collections ;
using System.ComponentModel ;
2020-03-31 18:01:27 +11:00
using System.IO ;
2020-10-09 11:37:25 +02:00
using System.Linq ;
2020-03-13 14:43:41 +11:00
using System.Net ;
2020-04-03 13:16:01 +11:00
using System.Reflection ;
2020-10-26 10:47:14 +00:00
using System.Threading ;
2020-09-03 12:29:23 +02:00
using Microsoft.AspNetCore.Hosting ;
using Microsoft.AspNetCore.Http ;
2020-09-21 21:06:24 +02:00
using Microsoft.Extensions.FileProviders ;
2020-09-03 12:29:23 +02:00
using Microsoft.Extensions.Hosting ;
2020-09-23 07:17:05 +02:00
using Microsoft.Extensions.Logging ;
2020-09-03 12:29:23 +02:00
using Microsoft.Extensions.Options ;
using Moq ;
2020-10-09 11:37:25 +02:00
using NUnit.Framework ;
2021-02-09 10:22:42 +01:00
using Umbraco.Cms.Core ;
using Umbraco.Cms.Core.Cache ;
using Umbraco.Cms.Core.Configuration.Models ;
using Umbraco.Cms.Core.Diagnostics ;
using Umbraco.Cms.Core.Hosting ;
using Umbraco.Cms.Core.Logging ;
using Umbraco.Cms.Core.Models ;
using Umbraco.Cms.Core.Models.Entities ;
using Umbraco.Cms.Core.Net ;
using Umbraco.Cms.Core.PropertyEditors ;
using Umbraco.Cms.Core.Runtime ;
2021-02-12 13:36:50 +01:00
using Umbraco.Cms.Infrastructure.Persistence ;
v10 SQLite support + distributed locking abstractions (#11922)
* Created Persistence.SQLite project skeleton.
* SQLite database initialization
* Various changes and hacks to make things work.
* WIP integration tests
* Fix thread safety tests
* Fix tests that relied on tie breaker sorting.
Spent a fair amount of time looking for a less lazy fix but gave up.
* Convert right join to left join ContentTypeRepository.PerformGetByQuery
SQLite doesn't support right join
* Fix test Can_Generate_Delete_SubQuery_Statement
Worth noting that NPoco.DatabaseTypes.SQLiteDatabaseType doesn't override
EscapeSqlIdentifier so NPoco will escape with [].
SQLite docs say > "A keyword enclosed in square brackets is an identifier.
This is not standard SQL.
This quoting mechanism is used by MS Access and SQL Server and is
included in SQLite for compatibility."
Also could have updated SqliteSyntaxProvider to match npoco but
decided against it.
* Fixes for paginated custom order by
* Fix tests broken by lack of unique indexes.
* Fix SqlServerTableByTableTest tests.
These tests didn't actually do anything as the tables already exist so schema creator just returned.
Did however point out that the default implementation for DoesTableExist just returns false so added a default naive implementation.
* Fix ValidateLoginSession - SelectTop must come later
* dry up database cleanup
* Fix up db migration tests.
We can't drop pk in sqlite without recreating table.
Test looks to be testing that add column works as intended which we can test.
* Prevent schema creation errors.
* SQLite ignore lock tests, WAL back on.
* Fix package schema tests
* Fix NPocoFetchTests - case sensitivity not under test
* Fix AdvancedMigrationTests (where possible)
Migrations probably need a good look later.
Maybe nuke old migrations and only support moving to v10 from v9.
If we do that can do some cleanup.
* Cleanup test database configuration
* Run integration tests against SQLite on build agent.
* Drop MS.Data.SQLite
System.Data.SQLite was quicker to roll out due to more CLR type mapping
* YAML
* Skip Umbraco.Tests.Integration.SqlCe
* Drop SqlServerTableByTable tests.
Until this week they did nothing anyway as they with NewSchemaPerTest
so the tests all passed as CreateTable was no op (already exists).
Also all of the tables are created in an empty database by SchemaValidationTest.cs
DatabaseSchemaCreation_Produces_DatabaseSchemaResult_With_Zero_Errors
* Might aswell run against macOS also.
* Copy azure pipelines task header layout
* Delete SQLCe projects
* Remove SQL CE specific code.
* Remove SQL CE NuSpec, template params, build script setup
* Delete umbraco-netcore-only.sln
* Add SkipTests solution configuration and use for codeql
* Remove reference to deleted nuspec file.
* Refactor ConnectionStrings WRT DataDirectory placeholder & ProviderName.
At this point you can try out SQLite support by setting the following
in appsettings.json and then completing the install process.
"ConnectionStrings": {
"umbracoDbDSN": "Data Source=|DataDirectory|/umbraco.sqlite",
"umbracoDbDSN_ProviderName": "System.Data.SQLite"
},
Not currently possible via installer UI without provider name pre-set in
configuration.
* Switch to Microsoft.Data.Sqlite
Some gross hacks but will be good to find out if this works
with apple silicon.
* Enable selection of SQLite via installer UI (also quick install)
* Remove SqlServerDbProviderFactoryCreator to cleanup a TODO
* Move SQL Server support to its own class library
* Add persistence dependencies to Umbraco.CMS metapackage
* Bugfix packages delete query
Created invalid query for SQLite.
* Try out cypress tests Linux + SQLite
* Prevent cypress test artifact upload failure on attempt 2+
* LocalDb bugfixes
* Drop redundant enum
* Move SqlClient constant
* Misc whitespace
* Remove IsSqlCe extension (TODO: drop non 9->10 migrations later).
* Umbraco.Persistence.* -> Umbraco.Cms.Persistence.*
* Display quick install defaults and per provider default database name.
* Misc remove old comment
* little re-arrange
* Remove almost all usages of IsSqlite extension.
* visual adjustments
* Custom Database Configuration is last step and should then say Install.
* use text instead of disabled inputs
* move legend, rename to Install
* Update SqlMainDomLock to work without distributed locks.
* Added IDistributedLockingMechanism interface and in memory impl.
* Drop locking from ISqlSyntaxProvider & wire up scope to abstraction.
* Added SqlServerDistributedLockingMechanism
* Move distributed locking interfaces and exceptions to Core + xmldocs.
* Fix tests, Misc cleanup, Add SQL distributed locking integration tests
* Provide mechanism to specify DistributedLockingMechanism in config
(even if added by composer)
* Nomplementation -> NoImplementation
* Fix misleading comment
* Integration tests use SqlServerDistributedLockingMechanism when possible
* Handle up-gradable locks SqlServerDistributedLockingMechanism.
TODO: InMemoryDistributedLockingMechanism.
Note: Nuked SqlServerDistributedLockingMechanismTests, will still sleep
at night.
Is covered by Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Persistence.LockTests
* Make tests pass for InMemoryDistributedLockingMechanism, pretty hacky.
* Tweak constraints on WithCollectionBuilder so i can drop bad constructor
* Added SqliteDistributedLockingMechanism
* Dropped InMemoryDistributedMechanism + magic
InMemoryDistributedMechanism was pretty rubbish and now we have
a decent implementation for SQLite as we no longer block readers
see 8d1f42b.
Also drop the CollectionBuilder setup, instead do the same as we do
for syntax providers etc, it's more automagical so we never require an
explicit selection although we are allowing for it.
However keeping the optional IUmbracoBuilder constructor param for
CollectionBuilders as it's extremely useful.
* Fix quick install "" database name.
* Hide Database Configuration section when a connection string is pre-set.
Doesn't seem worth it to extract db name from connection string.
* Ensure wal test 2+
* Fix logging inconsistencies.
* Ensure in transaction when obtaining locks + no-op the SQLite read lock.
There's no point in running the query just to make a single test pass.
* Fix installer database display names
* Allow SQLite shared cache without losing deferred transactions
* Opt into shared cache for new SQLite databases + fix filename
* Fix misc inconsistency in .gitignore
* Prefer our interceptor interface
* Restore DEBUG_DATABASES code OnConnectionOpened in case it's used.
* Back to private cache.
* Added retry strategy for SQLite + refactor out SQL server specific stuff
* Fix SQL server tests.
* Misc - Orphaned comment, incorrect casing.
* InMemory SQLite test database & turn shared cache back on everywhere.
Co-authored-by: Niels Lyngsø <niels.lyngso@gmail.com>
2022-03-11 16:14:20 +00:00
using Umbraco.Cms.Persistence.SqlServer.Services ;
2021-02-10 14:45:44 +01:00
using Umbraco.Cms.Tests.Common ;
Examine 2.0 integration (#10241)
* Init commit for examine 2.0 work, most old umb examine tests working, probably a lot that doesn't
* Gets Umbraco Examine tests passing and makes some sense out of them, fixes some underlying issues.
* Large refactor, remove TaskHelper, rename Notifications to be consistent, Gets all examine/lucene indexes building and startup ordered in the correct way, removes old files, creates new IUmbracoIndexingHandler for abstracting out all index operations for umbraco data, abstracts out IIndexRebuilder, Fixes Stack overflow with LiveModelsProvider and loading assemblies, ports some changes from v8 for startup handling with cold boots, refactors out LastSyncedFileManager
* fix up issues with rebuilding and management dashboard.
* removes old files, removes NetworkHelper, fixes LastSyncedFileManager implementation to ensure the machine name is used, fix up logging with cold boot state.
* Makes MainDom safer to use and makes PublishedSnapshotService lazily register with MainDom
* lazily acquire application id (fix unit tests)
* Fixes resource casing and missing test file
* Ensures caches when requiring internal services for PublishedSnapshotService, UseNuCache is a separate call, shouldn't be buried in AddWebComponents, was also causing issues in integration tests since nucache was being used for the Id2Key service.
* For UmbracoTestServerTestBase enable nucache services
* Fixing tests
* Fix another test
* Fixes tests, use TestHostingEnvironment, make Tests.Common use net5, remove old Lucene.Net.Contrib ref.
* Fixes up some review notes
* Fixes issue with doubly registering PublishedSnapshotService meanig there could be 2x instances of it
* Checks for parseexception when executing the query
* Use application root instead of duplicating functionality.
* Added Examine project to netcore only solution file
* Fixed casing issue with LazyLoad, that is not lowercase.
* uses cancellationToken instead of bool flag, fixes always reading lastId from the LastSyncedFileManager, fixes RecurringHostedServiceBase so that there isn't an overlapping thread for the same task type
* Fix tests
* remove legacy test project from solution file
* Fix test
Co-authored-by: Bjarke Berg <mail@bergmania.dk>
2021-05-18 18:31:38 +10:00
using Umbraco.Cms.Tests.Common.Testing ;
2021-02-10 11:42:04 +01:00
using Umbraco.Cms.Web.Common.AspNetCore ;
2021-02-09 11:26:22 +01:00
using Umbraco.Extensions ;
2020-10-26 10:47:14 +00:00
using File = System . IO . File ;
2021-02-09 10:22:42 +01:00
using IHostingEnvironment = Umbraco . Cms . Core . Hosting . IHostingEnvironment ;
2020-03-13 14:43:41 +11:00
2022-06-21 08:09:38 +02:00
namespace Umbraco.Cms.Tests.Integration.Implementations ;
public class TestHelper : TestHelperBase
2020-03-13 14:43:41 +11:00
{
2022-06-21 08:09:38 +02:00
private readonly IWebHostEnvironment _hostEnvironment ;
private readonly IApplicationShutdownRegistry _hostingLifetime ;
private readonly IHttpContextAccessor _httpContextAccessor ;
private readonly IIpResolver _ipResolver ;
private readonly IBackOfficeInfo _backOfficeInfo ;
private IHostingEnvironment _hostingEnvironment ;
private readonly string _tempWorkingDir ;
public TestHelper ( )
: base ( typeof ( TestHelper ) . Assembly )
2020-03-13 14:43:41 +11:00
{
2022-06-21 08:09:38 +02:00
var httpContext = new DefaultHttpContext ( ) ;
httpContext . Connection . RemoteIpAddress = IPAddress . Parse ( "127.0.0.1" ) ;
_httpContextAccessor = Mock . Of < IHttpContextAccessor > ( x = > x . HttpContext = = httpContext ) ;
_ipResolver = new AspNetCoreIpResolver ( _httpContextAccessor ) ;
var contentRoot = Assembly . GetExecutingAssembly ( ) . GetRootDirectorySafe ( ) ;
// The mock for IWebHostEnvironment has caused a good few issues.
// We can UseContentRoot, UseWebRoot etc on the host builder instead.
// possibly going down rabbit holes though as would need to cleanup all usages of
// GetHostingEnvironment & GetWebHostEnvironment.
var hostEnvironment = new Mock < IWebHostEnvironment > ( ) ;
// This must be the assembly name for the WebApplicationFactory to work.
hostEnvironment . Setup ( x = > x . ApplicationName ) . Returns ( GetType ( ) . Assembly . GetName ( ) . Name ) ;
hostEnvironment . Setup ( x = > x . ContentRootPath ) . Returns ( ( ) = > contentRoot ) ;
hostEnvironment . Setup ( x = > x . ContentRootFileProvider ) . Returns ( ( ) = > new PhysicalFileProvider ( contentRoot ) ) ;
hostEnvironment . Setup ( x = > x . WebRootPath ) . Returns ( ( ) = > WorkingDirectory ) ;
hostEnvironment . Setup ( x = > x . WebRootFileProvider ) . Returns ( ( ) = > new PhysicalFileProvider ( WorkingDirectory ) ) ;
hostEnvironment . Setup ( x = > x . EnvironmentName ) . Returns ( "Tests" ) ;
// We also need to expose it as the obsolete interface since netcore's WebApplicationFactory casts it.
hostEnvironment . As < Microsoft . AspNetCore . Hosting . IHostingEnvironment > ( ) ;
_hostEnvironment = hostEnvironment . Object ;
_hostingLifetime = new AspNetCoreApplicationShutdownRegistry ( Mock . Of < IHostApplicationLifetime > ( ) ) ;
ConsoleLoggerFactory = LoggerFactory . Create ( builder = > builder . AddConsole ( ) ) ;
ProfilingLogger = new ProfilingLogger ( ConsoleLoggerFactory . CreateLogger < ProfilingLogger > ( ) , Profiler ) ;
}
2020-03-13 14:43:41 +11:00
2022-06-21 08:09:38 +02:00
public IUmbracoBootPermissionChecker UmbracoBootPermissionChecker { get ; } =
new TestUmbracoBootPermissionChecker ( ) ;
2020-03-13 14:43:41 +11:00
2022-06-21 08:09:38 +02:00
public AppCaches AppCaches { get ; } = new (
NoAppCache . Instance ,
NoAppCache . Instance ,
new IsolatedCaches ( type = > NoAppCache . Instance ) ) ;
2020-03-13 14:43:41 +11:00
2022-06-21 08:09:38 +02:00
public ILoggerFactory ConsoleLoggerFactory { get ; }
2020-12-23 11:35:49 +01:00
2022-06-21 08:09:38 +02:00
public IProfilingLogger ProfilingLogger { get ; }
2020-03-13 14:43:41 +11:00
2022-06-21 08:09:38 +02:00
public IProfiler Profiler { get ; } = new NoopProfiler ( ) ;
2020-03-13 14:43:41 +11:00
2022-06-21 08:09:38 +02:00
public override IBulkSqlInsertProvider BulkSqlInsertProvider = > new SqlServerBulkSqlInsertProvider ( ) ;
2020-03-13 14:43:41 +11:00
2022-06-21 08:09:38 +02:00
public override IMarchal Marchal { get ; } = new AspNetCoreMarchal ( ) ;
2020-03-13 14:43:41 +11:00
2022-06-21 08:09:38 +02:00
public IHttpContextAccessor GetHttpContextAccessor ( ) = > _httpContextAccessor ;
2020-03-13 14:43:41 +11:00
2022-06-21 08:09:38 +02:00
public IWebHostEnvironment GetWebHostEnvironment ( ) = > _hostEnvironment ;
2020-03-13 14:43:41 +11:00
2022-06-21 08:09:38 +02:00
public override IHostingEnvironment GetHostingEnvironment ( )
= > _hostingEnvironment ? ? = new TestHostingEnvironment (
GetIOptionsMonitorOfHostingSettings ( ) ,
GetIOptionsMonitorOfWebRoutingSettings ( ) ,
_hostEnvironment ) ;
2020-03-31 17:27:51 +11:00
2022-06-21 08:09:38 +02:00
private IOptionsMonitor < HostingSettings > GetIOptionsMonitorOfHostingSettings ( )
{
var hostingSettings = new HostingSettings ( ) ;
return Mock . Of < IOptionsMonitor < HostingSettings > > ( x = > x . CurrentValue = = hostingSettings ) ;
}
private IOptionsMonitor < WebRoutingSettings > GetIOptionsMonitorOfWebRoutingSettings ( )
{
var webRoutingSettings = new WebRoutingSettings ( ) ;
return Mock . Of < IOptionsMonitor < WebRoutingSettings > > ( x = > x . CurrentValue = = webRoutingSettings ) ;
}
2020-09-03 12:29:23 +02:00
2022-06-21 08:09:38 +02:00
public override IApplicationShutdownRegistry GetHostingEnvironmentLifetime ( ) = > _hostingLifetime ;
public override IIpResolver GetIpResolver ( ) = > _ipResolver ;
/// <summary>
/// Some test files are copied to the /bin (/bin/debug) on build, this is a utility to return their physical path based
/// on a virtual path name
/// </summary>
public override string MapPathForTestFiles ( string relativePath )
{
if ( ! relativePath . StartsWith ( "~/" ) )
2021-02-08 11:00:15 +01:00
{
2022-06-21 08:09:38 +02:00
throw new ArgumentException ( "relativePath must start with '~/'" , nameof ( relativePath ) ) ;
2021-02-08 11:00:15 +01:00
}
2022-06-21 08:09:38 +02:00
var codeBase = typeof ( TestHelperBase ) . Assembly . CodeBase ;
var uri = new Uri ( codeBase ) ;
var path = uri . LocalPath ;
var bin = Path . GetDirectoryName ( path ) ;
return relativePath . Replace ( "~/" , bin + "/" ) ;
}
2020-03-13 14:43:41 +11:00
2022-06-21 08:09:38 +02:00
public void AssertPropertyValuesAreEqual ( object actual , object expected , Func < IEnumerable , IEnumerable > sorter = null , string [ ] ignoreProperties = null )
{
const int dateDeltaMilliseconds = 1000 ; // 1s
2020-03-25 15:06:22 +11:00
2022-06-21 08:09:38 +02:00
var properties = expected . GetType ( ) . GetProperties ( ) ;
foreach ( var property in properties )
2020-04-14 16:55:54 +01:00
{
2022-06-21 08:09:38 +02:00
// Ignore properties that are attributed with EditorBrowsableState.Never.
var att = property . GetCustomAttribute < EditorBrowsableAttribute > ( false ) ;
if ( att ! = null & & att . State = = EditorBrowsableState . Never )
2020-12-23 11:35:49 +01:00
{
2022-06-21 08:09:38 +02:00
continue ;
2020-12-23 11:35:49 +01:00
}
2020-04-14 16:55:54 +01:00
2022-06-21 08:09:38 +02:00
// Ignore explicitly ignored properties.
if ( ignoreProperties ! = null & & ignoreProperties . Contains ( property . Name ) )
{
continue ;
}
2020-04-14 16:55:54 +01:00
2022-06-21 08:09:38 +02:00
var actualValue = property . GetValue ( actual , null ) ;
var expectedValue = property . GetValue ( expected , null ) ;
AssertAreEqual ( property , expectedValue , actualValue , sorter , dateDeltaMilliseconds ) ;
2020-04-14 16:55:54 +01:00
}
2022-06-21 08:09:38 +02:00
}
2020-10-09 11:37:25 +02:00
2022-06-21 08:09:38 +02:00
private static void AssertListsAreEqual ( PropertyInfo property , IEnumerable expected , IEnumerable actual , Func < IEnumerable , IEnumerable > sorter = null , int dateDeltaMilliseconds = 0 )
{
2024-09-10 15:17:29 +01:00
// this is pretty hackerific but saves us some code to write
sorter ? ? = enumerable = >
2020-10-09 11:37:25 +02:00
{
2024-09-10 15:17:29 +01:00
// semi-generic way of ensuring any collection of IEntity are sorted by Ids for comparison
var entities = enumerable . OfType < IEntity > ( ) . ToList ( ) ;
return entities . Count > 0 ? entities . OrderBy ( x = > x . Id ) : entities ;
} ;
2020-10-09 11:37:25 +02:00
2022-06-21 08:09:38 +02:00
var expectedListEx = sorter ( expected ) . Cast < object > ( ) . ToList ( ) ;
var actualListEx = sorter ( actual ) . Cast < object > ( ) . ToList ( ) ;
2020-10-09 11:37:25 +02:00
2022-06-21 08:09:38 +02:00
if ( actualListEx . Count ! = expectedListEx . Count )
{
Assert . Fail (
"Collection {0}.{1} does not match. Expected IEnumerable containing {2} elements but was IEnumerable containing {3} elements" ,
property . PropertyType . Name ,
property . Name ,
expectedListEx . Count ,
actualListEx . Count ) ;
2020-10-09 11:37:25 +02:00
}
2022-06-21 08:09:38 +02:00
for ( var i = 0 ; i < actualListEx . Count ; i + + )
2020-10-09 11:37:25 +02:00
{
2022-06-21 08:09:38 +02:00
AssertAreEqual ( property , expectedListEx [ i ] , actualListEx [ i ] , sorter , dateDeltaMilliseconds ) ;
}
}
2020-10-09 11:37:25 +02:00
2022-06-21 08:09:38 +02:00
private static void AssertAreEqual ( PropertyInfo property , object expected , object actual , Func < IEnumerable , IEnumerable > sorter = null , int dateDeltaMilliseconds = 0 )
{
if ( ! ( expected is string ) & & expected is IEnumerable enumerable )
{
// sort property collection by alias, not by property ids
// on members, built-in properties don't have ids (always zero)
if ( expected is PropertyCollection )
2020-12-23 11:35:49 +01:00
{
2022-06-21 08:09:38 +02:00
sorter = e = > ( ( PropertyCollection ) e ) . OrderBy ( x = > x . Alias ) ;
2020-12-23 11:35:49 +01:00
}
2020-10-09 11:37:25 +02:00
2022-06-21 08:09:38 +02:00
// compare lists
AssertListsAreEqual ( property , ( IEnumerable ) actual , enumerable , sorter , dateDeltaMilliseconds ) ;
}
else if ( expected is DateTime expectedDateTime )
{
// compare date & time with delta
var actualDateTime = ( DateTime ) actual ;
var delta = ( actualDateTime - expectedDateTime ) . TotalMilliseconds ;
Assert . IsTrue (
Math . Abs ( delta ) < = dateDeltaMilliseconds ,
"Property {0}.{1} does not match. Expected: {2} but was: {3}" ,
property . DeclaringType . Name ,
property . Name ,
expected ,
actual ) ;
}
else if ( expected is Property expectedProperty )
{
// compare values
var actualProperty = ( Property ) actual ;
var expectedPropertyValues =
expectedProperty . Values . OrderBy ( x = > x . Culture ) . ThenBy ( x = > x . Segment ) . ToArray ( ) ;
var actualPropertyValues = actualProperty . Values . OrderBy ( x = > x . Culture ) . ThenBy ( x = > x . Segment ) . ToArray ( ) ;
if ( expectedPropertyValues . Length ! = actualPropertyValues . Length )
2020-12-23 11:35:49 +01:00
{
2022-06-21 08:09:38 +02:00
Assert . Fail (
$"{property.DeclaringType.Name}.{property.Name}: Expected {expectedPropertyValues.Length} but got {actualPropertyValues.Length}." ) ;
2020-12-23 11:35:49 +01:00
}
2020-10-09 11:37:25 +02:00
2022-06-21 08:09:38 +02:00
for ( var i = 0 ; i < expectedPropertyValues . Length ; i + + )
2020-10-09 11:37:25 +02:00
{
2022-06-21 08:09:38 +02:00
// This is not pretty, but since a property value can be a datetime we can't just always compare them as is.
// This is made worse by the fact that PublishedValue is not always set, meaning we can't lump it all into the same if block
if ( expectedPropertyValues [ i ] . EditedValue is DateTime expectedEditDateTime )
2020-12-23 11:35:49 +01:00
{
2022-06-21 08:09:38 +02:00
var actualEditDateTime = ( DateTime ) actualPropertyValues [ i ] . EditedValue ;
AssertDateTime (
expectedEditDateTime ,
actualEditDateTime ,
$"{property.DeclaringType.Name}.{property.Name}: Expected draft value \" { expectedPropertyValues [ i ] . EditedValue } \ " but got \"{actualPropertyValues[i].EditedValue}\"." ,
dateDeltaMilliseconds ) ;
2020-12-23 11:35:49 +01:00
}
2022-06-21 08:09:38 +02:00
else
2020-12-23 11:35:49 +01:00
{
2022-06-21 08:09:38 +02:00
Assert . AreEqual (
expectedPropertyValues [ i ] . EditedValue ,
actualPropertyValues [ i ] . EditedValue ,
$"{property.DeclaringType.Name}.{property.Name}: Expected draft value \" { expectedPropertyValues [ i ] . EditedValue } \ " but got \"{actualPropertyValues[i].EditedValue}\"." ) ;
2020-12-23 11:35:49 +01:00
}
2022-06-21 08:09:38 +02:00
if ( expectedPropertyValues [ i ] . PublishedValue is DateTime expectedPublishDateTime )
2020-10-09 11:37:25 +02:00
{
2022-06-21 08:09:38 +02:00
var actualPublishedDateTime = ( DateTime ) actualPropertyValues [ i ] . PublishedValue ;
AssertDateTime (
expectedPublishDateTime ,
actualPublishedDateTime ,
$"{property.DeclaringType.Name}.{property.Name}: Expected published value \" { expectedPropertyValues [ i ] . PublishedValue } \ " but got \"{actualPropertyValues[i].PublishedValue}\"." ,
dateDeltaMilliseconds ) ;
}
else
{
Assert . AreEqual (
expectedPropertyValues [ i ] . PublishedValue ,
actualPropertyValues [ i ] . PublishedValue ,
$"{property.DeclaringType.Name}.{property.Name}: Expected published value \" { expectedPropertyValues [ i ] . PublishedValue } \ " but got \"{actualPropertyValues[i].PublishedValue}\"." ) ;
2020-10-09 11:37:25 +02:00
}
}
}
2022-06-21 08:09:38 +02:00
else if ( expected is IDataEditor expectedEditor )
{
Assert . IsInstanceOf < IDataEditor > ( actual ) ;
var actualEditor = ( IDataEditor ) actual ;
Assert . AreEqual ( expectedEditor . Alias , actualEditor . Alias ) ;
2020-10-21 13:28:13 +02:00
2022-06-21 08:09:38 +02:00
// what else shall we test?
}
else
2020-10-21 13:28:13 +02:00
{
2022-06-21 08:09:38 +02:00
// directly compare values
Assert . AreEqual (
expected ,
actual ,
"Property {0}.{1} does not match. Expected: {2} but was: {3}" ,
property . DeclaringType . Name ,
property . Name ,
expected ? . ToString ( ) ? ? "<null>" ,
actual ? . ToString ( ) ? ? "<null>" ) ;
2020-10-21 13:28:13 +02:00
}
2022-06-21 08:09:38 +02:00
}
2020-10-26 10:47:14 +00:00
2022-06-21 08:09:38 +02:00
private static void AssertDateTime ( DateTime expected , DateTime actual , string failureMessage , int dateDeltaMiliseconds = 0 )
{
var delta = ( actual - expected ) . TotalMilliseconds ;
Assert . IsTrue ( Math . Abs ( delta ) < = dateDeltaMiliseconds , failureMessage ) ;
}
public void DeleteDirectory ( string path )
{
Try ( ( ) = >
2020-10-26 10:47:14 +00:00
{
2022-06-21 08:09:38 +02:00
if ( Directory . Exists ( path ) = = false )
2020-10-26 10:47:14 +00:00
{
2022-06-21 08:09:38 +02:00
return ;
}
2020-12-23 11:35:49 +01:00
2022-06-21 08:09:38 +02:00
foreach ( var file in Directory . EnumerateFiles ( path , "*" , SearchOption . AllDirectories ) )
{
File . Delete ( file ) ;
}
} ) ;
2020-10-26 10:47:14 +00:00
2022-06-21 08:09:38 +02:00
Try ( ( ) = >
{
if ( Directory . Exists ( path ) = = false )
2020-10-26 10:47:14 +00:00
{
2022-06-21 08:09:38 +02:00
return ;
}
2020-12-23 11:35:49 +01:00
2022-06-21 08:09:38 +02:00
Directory . Delete ( path , true ) ;
} ) ;
}
2020-10-26 10:47:14 +00:00
2022-06-21 08:09:38 +02:00
public static void TryAssert ( Action action , int maxTries = 5 , int waitMilliseconds = 200 ) = >
Try < AssertionException > ( action , maxTries , waitMilliseconds ) ;
2020-10-26 10:47:14 +00:00
2022-06-21 08:09:38 +02:00
public static void Try ( Action action , int maxTries = 5 , int waitMilliseconds = 200 ) = >
Try < Exception > ( action , maxTries , waitMilliseconds ) ;
2020-10-26 10:47:14 +00:00
2022-06-21 08:09:38 +02:00
public static void Try < T > ( Action action , int maxTries = 5 , int waitMilliseconds = 200 )
where T : Exception
{
var tries = 0 ;
while ( true )
2020-10-26 10:47:14 +00:00
{
2022-06-21 08:09:38 +02:00
try
{
action ( ) ;
break ;
}
catch ( T )
2020-10-26 10:47:14 +00:00
{
2022-06-21 08:09:38 +02:00
if ( tries + + > maxTries )
2020-10-26 10:47:14 +00:00
{
2022-06-21 08:09:38 +02:00
throw ;
2020-10-26 10:47:14 +00:00
}
2020-12-23 11:35:49 +01:00
2022-06-21 08:09:38 +02:00
Thread . Sleep ( waitMilliseconds ) ;
2020-10-26 10:47:14 +00:00
}
}
2020-03-13 14:43:41 +11:00
}
}