| | | 1 | | using TUnit.Assertions.Core; |
| | | 2 | | |
| | | 3 | | namespace TestUtilities.StringAssertions; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// A custom TUnit assertion that compares strings with normalized line endings. |
| | | 7 | | /// This is specifically introduced to ease assertions against CSV generated by CsvHelper, |
| | | 8 | | /// which writes CRLF line endings by default following RFC 4180. |
| | | 9 | | /// </summary> |
| | | 10 | | public class StringEqualsWithNormalizedLineEndingsAssertion : Assertion<string> |
| | | 11 | | { |
| | | 12 | | private readonly string _expected; |
| | | 13 | | |
| | | 14 | | public StringEqualsWithNormalizedLineEndingsAssertion(AssertionContext<string> context, string expected) |
| | 1 | 15 | | : base(context) |
| | | 16 | | { |
| | 1 | 17 | | _expected = expected; |
| | 1 | 18 | | } |
| | | 19 | | |
| | | 20 | | protected override Task<AssertionResult> CheckAsync(EvaluationMetadata<string> metadata) |
| | | 21 | | { |
| | 1 | 22 | | var actual = metadata.Value; |
| | | 23 | | |
| | 1 | 24 | | if (actual is null) |
| | | 25 | | { |
| | 1 | 26 | | return Task.FromResult(AssertionResult.Failed("Actual string was null")); |
| | | 27 | | } |
| | | 28 | | |
| | 1 | 29 | | var normalizedActual = actual.ReplaceLineEndings(); |
| | 1 | 30 | | var normalizedExpected = _expected.ReplaceLineEndings(); |
| | | 31 | | |
| | 1 | 32 | | if (normalizedActual == normalizedExpected) |
| | | 33 | | { |
| | 1 | 34 | | return Task.FromResult(AssertionResult.Passed); |
| | | 35 | | } |
| | | 36 | | |
| | 1 | 37 | | return Task.FromResult(AssertionResult.Failed( |
| | 1 | 38 | | $""" |
| | 1 | 39 | | Strings do not match (ignoring line endings). |
| | 1 | 40 | | Expected: |
| | 1 | 41 | | {_expected} |
| | 1 | 42 | | |
| | 1 | 43 | | Actual: |
| | 1 | 44 | | {actual} |
| | 1 | 45 | | """)); |
| | | 46 | | } |
| | | 47 | | |
| | | 48 | | protected override string GetExpectation() |
| | 1 | 49 | | => $"to be equal to \"{_expected}\" (ignoring line endings)"; |
| | | 50 | | } |