Skip to content

Commit

Permalink
Improve line ending error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
matt-richardson committed Oct 27, 2023
1 parent 75be255 commit 481cc6a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 9 deletions.
31 changes: 25 additions & 6 deletions src/Assent.Tests/DefaultStringComparerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@ public class DefaultStringComparerTests
[Test]
public void LineEndingDifferencesResultInAFail()
{
new DefaultStringComparer(false)
.Compare("A\r\nb", "A\nb")
.Passed
.Should()
.BeFalse();
var compareResult = new DefaultStringComparer(false)
.Compare("A\r\nb\nc", "A\nb\r\nc");
compareResult.Passed.Should().BeFalse();
compareResult.Error.Should().Contain("Strings differ only by line endings");
}

[Test]
Expand All @@ -24,5 +23,25 @@ public void LineEndingDifferencesResultInSuccessIfNormaliseLineEndingsIsTrue()
.Should()
.BeTrue();
}

[Test]
public void OneFileMissingNewLineAtEndOfFileResultInSuccessIfNormaliseLineEndingsIsTrue()
{
new DefaultStringComparer(true)
.Compare("A\nb\nc\n", "A\nb\nc")
.Passed
.Should()
.BeTrue();
}

[Test]
public void OneFileMissingNewLineAtEndOfFileResultInAFail()
{
new DefaultStringComparer(false)
.Compare("A\nb\nc\n", "A\nb\nc")
.Passed
.Should()
.BeFalse();
}
}
}
}
14 changes: 11 additions & 3 deletions src/Assent/DefaultStringComparer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,21 @@ public CompareResult Compare(string received, string approved)

if (_normaliseLineEndings)
{
received = received.Replace("\r\n", "\n");
approved = approved.Replace("\r\n", "\n");
received = received.Replace("\r\n", "\n").TrimEnd('\n');
approved = approved.Replace("\r\n", "\n").TrimEnd('\n');
}

if (received == approved)
return CompareResult.Pass();

if (!_normaliseLineEndings)
{
var normalisedReceived = received.Replace("\r\n", "\n").TrimEnd('\n');
var normalisedApproved = approved.Replace("\r\n", "\n").TrimEnd('\n');
if (normalisedReceived == normalisedApproved)
return CompareResult.Fail($"Strings differ only by line endings. Enable 'NormaliseLineEndings' to ignore line ending differences.");
}

var length = Math.Min(approved.Length, received.Length);
for (var x = 0; x < length; x++)
if (approved[x] != received[x])
Expand All @@ -43,4 +51,4 @@ public CompareResult Compare(string received, string approved)
return CompareResult.Fail("Strings differ");
}
}
}
}

0 comments on commit 481cc6a

Please sign in to comment.