You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Connected.Common.Types/Common.Types.Tests/TestUtils.cs

106 lines
2.8 KiB

using Connected;
using Connected.Notifications.Events;
using Connected.Services;
using Moq;
namespace Common.Types;
internal static class TestUtils
{
public static bool IsAssignableToGenericType<TGenericType>(this Type type)
{
var genericType = typeof(TGenericType);
if (!genericType.IsGenericType)
throw new ArgumentException("The passed type must be a generic type.", nameof(TGenericType));
return type.IsAssignableToGenericType(genericType);
}
public static bool IsAssignableToGenericType(this Type type, Type genericType)
{
if (!genericType.IsGenericType)
throw new ArgumentException("The passed type must be a generic type.", nameof(genericType));
var interfaceTypes = type.GetInterfaces();
foreach (var interfaceType in interfaceTypes)
{
if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == genericType)
return true;
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)
return true;
var baseType = type.BaseType;
if (baseType is null)
return false;
return baseType.IsAssignableToGenericType(genericType);
}
public static bool SequenceEquivalent<T>(this IEnumerable<T> firstSequence, IEnumerable<T> secondSequence)
{
var diff1 = firstSequence.Except(secondSequence);
var diff2 = secondSequence.Except(firstSequence);
return !diff1.Any() && !diff2.Any();
}
public static void SetArguments<TArgs>(this ServiceOperation<TArgs> operation, TArgs args)
where TArgs : IDto
{
typeof(ServiceOperation<TArgs>).GetProperty(nameof(operation.Arguments))!.SetValue(operation, args);
}
public static Moq.Language.Flow.ISetup<IEventService, Task> SetupEvent<TService, TId>(this Moq.Language.ISetupConditionResult<IEventService> setup, string @event)
{
return setup.Setup(e => e.Enqueue(It.IsAny<TService?>(), @event, It.IsAny<TId>()));
}
public static Moq.Language.Flow.ISetup<IEventService, Task> SetupEvent<TService, TId>(this Mock<IEventService> setup, string @event)
{
return setup.Setup(e => e.Enqueue(It.IsAny<TService?>(), @event, It.IsAny<TId>()));
}
public static void VerifyEvent<TService, TId>(this Mock<IEventService> setup, string @event)
{
setup.Verify(e => e.Enqueue(It.IsAny<TService?>(), @event, It.IsAny<TId>()), Times.Exactly(1));
}
public static void SetupIEnumerable<TEnumerable>(this Mock mock, IEnumerable<TEnumerable> data)
{
mock.As<IEnumerable<TEnumerable>>()
.Setup(e => e.GetEnumerator())
.Returns(data.GetEnumerator());
}
public static class AssertExtensions
{
public static async Task Throws(Task action)
{
Exception exception = null;
try
{
await action;
}
catch (Exception ex)
{
exception = ex;
}
if (exception is null)
Assert.Fail("Expected exception, none was thrown.");
}
internal static Task Throws(Func<Task> value)
{
return Throws(value());
}
}
}