|
| 1 | +using System.Numerics; |
| 2 | +using System.Runtime.CompilerServices; |
| 3 | +using TUnit.Assertions.AssertConditions; |
| 4 | +using TUnit.Assertions.AssertConditions.Interfaces; |
| 5 | +using TUnit.Assertions.AssertionBuilders; |
| 6 | + |
| 7 | +namespace MaterialDesignThemes.UITests.TUnit; |
| 8 | + |
| 9 | +public static class IsCloseToExtensions |
| 10 | +{ |
| 11 | + public static IsCloseToWrapper<double> IsCloseTo(this IValueSource<double> valueSource, double expected, double precision, [CallerArgumentExpression(nameof(expected))] string? doNotPopulateThisValue1 = null, [CallerArgumentExpression(nameof(precision))] string? doNotPopulateThisValue2 = null) |
| 12 | + { |
| 13 | + var assertionBuilder = valueSource.RegisterAssertion(new IsCloseToCondition<double>(expected, precision) |
| 14 | + , [doNotPopulateThisValue1, doNotPopulateThisValue2]); |
| 15 | + |
| 16 | + return new IsCloseToWrapper<double>(assertionBuilder); |
| 17 | + } |
| 18 | + |
| 19 | + public static IsCloseToWrapper<float> IsCloseTo(this IValueSource<float> valueSource, float expected, float precision, [CallerArgumentExpression(nameof(expected))] string? doNotPopulateThisValue1 = null, [CallerArgumentExpression(nameof(precision))] string? doNotPopulateThisValue2 = null) |
| 20 | + { |
| 21 | + var assertionBuilder = valueSource.RegisterAssertion(new IsCloseToCondition<float>(expected, precision) |
| 22 | + , [doNotPopulateThisValue1, doNotPopulateThisValue2]); |
| 23 | + |
| 24 | + return new IsCloseToWrapper<float>(assertionBuilder); |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +public class IsCloseToWrapper<TActual>(InvokableAssertionBuilder<TActual> invokableAssertionBuilder) |
| 29 | + : InvokableValueAssertionBuilder<TActual>(invokableAssertionBuilder); |
| 30 | + |
| 31 | +file class IsCloseToCondition<TActual>(TActual expected, TActual tolerance) : BaseAssertCondition<TActual> |
| 32 | + where TActual : |
| 33 | + IFloatingPoint<TActual>, |
| 34 | + INumberBase<TActual> |
| 35 | +{ |
| 36 | + protected override string GetExpectation() => $"to be within {tolerance} of {expected}"; |
| 37 | + |
| 38 | + protected override ValueTask<AssertionResult> GetResult( |
| 39 | + TActual? actualValue, Exception? exception, |
| 40 | + AssertionMetadata assertionMetadata |
| 41 | + ) |
| 42 | + { |
| 43 | + if(actualValue is null) |
| 44 | + return AssertionResult.Fail("received null"); |
| 45 | + |
| 46 | + TActual difference = actualValue - expected; |
| 47 | + TActual absoluteDifference = TActual.Abs(difference); |
| 48 | + bool isInRange = absoluteDifference <= tolerance; |
| 49 | + return AssertionResult.FailIf(!isInRange, $"received {actualValue}"); |
| 50 | + } |
| 51 | +} |
0 commit comments