Skip to content

Commit

Permalink
改行文字を取り除くstringの拡張メソッドを定義
Browse files Browse the repository at this point in the history
  • Loading branch information
KentaHizume committed Dec 27, 2024
1 parent 435503f commit e391e3b
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public AssetApplicationService(
public async Task<AssetStreamInfo> GetAssetStreamInfoAsync(string assetCode)
{
// ログインジェクションを防ぐために改行文字を取り除きます。
var sanitizedAssetCode = assetCode.Replace(Environment.NewLine, string.Empty).Replace("\n", string.Empty).Replace("\r", string.Empty);
var sanitizedAssetCode = assetCode.RemoveNewLines();
this.logger.LogDebug(Events.DebugEvent, LogMessages.AssetApplicationService_GetAssetStreamInfoStart, sanitizedAssetCode);

Asset? asset;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace System;

/// <summary>
/// <see cref="string"/> クラスの拡張メソッドを提供します。
/// </summary>
public static class StringExtentions
{
/// <summary>
/// 対象の文字列から改行文字(\r、\n)を取り除きます。
/// </summary>
/// <param name="target">対象の文字列。</param>
/// <returns>元の文字列から改行文字を取り除いた文字列。</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="str"/> が <see langword="null"/> です。
/// </exception>
public static string RemoveNewLines(this string? target)
{
ArgumentNullException.ThrowIfNull(target);
return target.Replace("\n", string.Empty).Replace("\r", string.Empty);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
namespace Dressca.UnitTests.SystemCommon;

public class StringExtentionsTest
{
[Fact]
public void RemoveNewLines_null_ArgumentNullExceptionが発生する()
{
// Arrange
string? target = null;

// Act
var action = () => StringExtentions.RemoveNewLines(target);

// Assert
Assert.Throws<ArgumentNullException>("target", action);
}

[Theory]
[InlineData("Line1\r\nLine2", "Line1Line2")] // CRとLFを含む場合
[InlineData("Line1\rLine2", "Line1Line2")] // CRのみを含む場合
[InlineData("Line1\nLine2", "Line1Line2")] // LFのみを含む場合
[InlineData("", "")] // 空文字の場合
[InlineData("Line1Line2", "Line1Line2")] // 改行文字を含まない場合
public void RemoveNewLines_改行文字があれば取り除かれる(string input, string expected)
{
// Arrange

// Act
var actual = input.RemoveNewLines();

// Assert
Assert.Equal(expected, actual);
}
}

0 comments on commit e391e3b

Please sign in to comment.