Skip to content

Commit

Permalink
Merge pull request #506 from Whinarn/bug/505-dont-truncate-short-strings
Browse files Browse the repository at this point in the history
Fixed a string truncate bug
  • Loading branch information
ckadluba authored Jan 10, 2024
2 parents 215e91b + 1769dac commit 287b9d3
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Serilog.Sinks.MSSqlServer/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ public static string TruncateOutput(this string value, int dataLength) =>
public static string Truncate(this string value, int maxLength, string suffix)
{
if (value == null) return null;
else if (value.Length <= maxLength) return value;

var suffixLength = suffix?.Length ?? 0;
if (maxLength <= suffixLength) return string.Empty;

var correctedMaxLength = maxLength - suffixLength;
return value.Length <= maxLength ? value : Invariant($"{value.Substring(0, correctedMaxLength)}{suffix}");
return Invariant($"{value.Substring(0, correctedMaxLength)}{suffix}");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@ public void ReturnTruncatedStringWithSuffix()
Assert.Equal("A simple tes...", truncatedMessage);
}

[Theory]
[InlineData("Abc")]
[InlineData("Ab")]
[InlineData("X")]
[Trait("Bugfix", "#505")]
public void ReturnNonTruncatedShortStringWhenMaxLengthIsLessOrEqualToSuffixLength(string inputMessage)
{
// Act
var nonTruncatedMessage = inputMessage.Truncate(3, "...");

// Assert
Assert.Equal(inputMessage, nonTruncatedMessage);
}

[Fact]
public void ReturnTruncatedStringWithEmptySuffix()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,5 +202,28 @@ public void GetAdditionalColumnNameAndValueReturnsTruncatedForCharacterTypesWith
Assert.Equal(columnName, result.Key);
Assert.Equal("Additio...", result.Value);
}

[Fact]
[Trait("Bugfix", "#505")]
public void GetAdditionalColumnNameAndValueReturnsFullStringWithOneDataLength()
{
// Arrange
const string columnName = "AdditionalProperty1";
const string propertyValue = "A";
var additionalColumn = new SqlColumn(columnName, SqlDbType.NVarChar);
additionalColumn.DataLength = 1;
var properties = new Dictionary<string, LogEventPropertyValue>();
_columnSimplePropertyValueResolver.Setup(r => r.GetPropertyValueForColumn(
It.IsAny<SqlColumn>(), It.IsAny<IReadOnlyDictionary<string, LogEventPropertyValue>>()))
.Returns(new KeyValuePair<string, LogEventPropertyValue>(columnName, new ScalarValue(propertyValue)));

// Act
var result = _sut.GetAdditionalColumnNameAndValue(additionalColumn, properties);

// Assert
_columnSimplePropertyValueResolver.Verify(r => r.GetPropertyValueForColumn(additionalColumn, properties), Times.Once);
Assert.Equal(columnName, result.Key);
Assert.Equal(propertyValue, result.Value);
}
}
}

0 comments on commit 287b9d3

Please sign in to comment.