From 767b8d674344fcb0a90f700af3b0f2e7e8ad9cd1 Mon Sep 17 00:00:00 2001 From: Mattias Edlund Date: Thu, 21 Dec 2023 20:50:31 +0100 Subject: [PATCH] Fixed a string truncate bug. --- .../Extensions/StringExtensions.cs | 4 +++- .../AdditionalColumnDataGeneratorTests.cs | 23 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/Serilog.Sinks.MSSqlServer/Extensions/StringExtensions.cs b/src/Serilog.Sinks.MSSqlServer/Extensions/StringExtensions.cs index 1850bb3e..7b3944ba 100644 --- a/src/Serilog.Sinks.MSSqlServer/Extensions/StringExtensions.cs +++ b/src/Serilog.Sinks.MSSqlServer/Extensions/StringExtensions.cs @@ -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}"); } } } diff --git a/test/Serilog.Sinks.MSSqlServer.Tests/Sinks/MSSqlServer/Output/AdditionalColumnDataGeneratorTests.cs b/test/Serilog.Sinks.MSSqlServer.Tests/Sinks/MSSqlServer/Output/AdditionalColumnDataGeneratorTests.cs index 5f3fdb34..0b08096e 100644 --- a/test/Serilog.Sinks.MSSqlServer.Tests/Sinks/MSSqlServer/Output/AdditionalColumnDataGeneratorTests.cs +++ b/test/Serilog.Sinks.MSSqlServer.Tests/Sinks/MSSqlServer/Output/AdditionalColumnDataGeneratorTests.cs @@ -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(); + _columnSimplePropertyValueResolver.Setup(r => r.GetPropertyValueForColumn( + It.IsAny(), It.IsAny>())) + .Returns(new KeyValuePair(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); + } } }