Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: fix analyzer warnings (2) #711

Merged
merged 17 commits into from
Jan 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Source/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<NoWarn>$(NoWarn);1701;1702;MA0003;MA0004;MA0042;MA0076;MA0106</NoWarn>
<NoWarn>$(NoWarn);1701;1702;MA0003;MA0004;MA0042;MA0076;MA0105;MA0106</NoWarn>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,7 @@ private FileStreamMock(MemoryStream stream,

throw ExceptionFactory.FileAlreadyExists(
_fileSystem.Execute.Path.GetFullPath(base.Name), 17);
}
else if (_mode.Equals(FileMode.CreateNew))
} else if (_mode.Equals(FileMode.CreateNew))
{
throw ExceptionFactory.FileAlreadyExists(
_fileSystem.Execute.Path.GetFullPath(Name),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,8 @@ private bool MatchesFilter(ChangeDescription changeDescription)
}
else if (!string.Equals(
_fileSystem.Execute.Path.GetDirectoryName(changeDescription.Path),
fullPath))
fullPath,
_fileSystem.Execute.StringComparisonMode))
{
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ private abstract class SimulatedPath(MockFileSystem fileSystem) : IPath
return path + extension;
}

#pragma warning disable CA1845 // Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring
return path.Substring(0, dotIndex.Value) + extension;
#pragma warning restore CA1845
}

/// <inheritdoc cref="IPath.Combine(string, string)" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ namespace Testably.Abstractions.Testing.Helpers;
internal static class FilePlatformIndependenceExtensions
{
#pragma warning disable SYSLIB1045
#pragma warning disable MA0110
private static readonly Regex PathTransformRegex = new("^[a-zA-Z]:(?<path>.*)$",
RegexOptions.None,
TimeSpan.FromMilliseconds(1000));
#pragma warning restore MA0110
#pragma warning restore SYSLIB1045

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion Source/Testably.Abstractions.Testing/Helpers/PathHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ private static void CheckPathCharacters(string path, MockFileSystem fileSystem,
string paramName, int? hResult)
{
#pragma warning disable CA2249 // Consider using String.Contains with char instead of String.IndexOf not possible in .NETSTANDARD2.0
if (path.IndexOf('\0') >= 0)
if (path.IndexOf('\0', StringComparison.Ordinal) >= 0)
#pragma warning restore CA2249
{
throw ExceptionFactory.PathHasIllegalCharacters(path, paramName, hResult);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,18 @@ internal static bool EndsWith(
return @this.EndsWith($"{value}", StringComparison.Ordinal);
}

/// <summary>
/// Reports the zero-based index of the first occurrence of the specified Unicode character in this string. A parameter
/// specifies the type of search to use for the specified character.
/// </summary>
internal static int IndexOf(
this string @this,
char value,
StringComparison comparisonType)
{
return @this.IndexOf(value);
}

/// <summary>
/// Returns a new string in which all occurrences of a specified string in the current instance are replaced with
/// another specified string, using the provided comparison type.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ internal MethodStatistic(int counter, string name, params ParameterDescription[]
Parameters = parameters;
}

#pragma warning disable MA0089 // Use an overload with char instead of string
/// <inheritdoc cref="object.ToString()" />
public override string ToString()
=> $"{Name}({string.Join(",", Parameters.Select(p => p.ToString()))})";
#pragma warning restore MA0089
}
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ public SpanParameterDescription(ReadOnlySpan<T> value) : base(false)

/// <inheritdoc cref="object.ToString()" />
public override string ToString()
=> $"[{string.Join(",", Value)}]";
=> $"[{string.Join(',', Value)}]";
}
#endif
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ private sealed class FixtureFactory
private ICustomization? _customizeWith;
private static Lazy<ICustomization[]> _domainCustomisation { get; } = new(Initialize);

public IFixture GetFixtureFactory()
public Fixture GetFixtureFactory()
{
var fixture = new Fixture();
fixture.Customize(new AutoNSubstituteCustomization());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private static string ExtractFileNamePrefixFromMarker(string marker)
protected abstract void GenerateSource(
StringBuilder sourceBuilder, ClassModel @class);

private StringBuilder GetSourceBuilder()
private static StringBuilder GetSourceBuilder()
=> new(
@"//------------------------------------------------------------------------------
// <auto-generated>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public void Execute(GeneratorExecutionContext context)
return;
}

new GlobalGenerator().GenerateClass(context);
GlobalGenerator.GenerateClass(context);
foreach (ClassGeneratorBase classGenerator in _classGenerators)
{
foreach (ClassModel classModel in _syntaxReceiver
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

namespace Testably.Abstractions.Tests.SourceGenerator;

public class GlobalGenerator
public static class GlobalGenerator
{
public void GenerateClass(GeneratorExecutionContext context)
public static void GenerateClass(GeneratorExecutionContext context)
{
StringBuilder sourceBuilder = GetSourceBuilder();
GenerateSource(sourceBuilder);
Expand All @@ -15,7 +15,7 @@ public void GenerateClass(GeneratorExecutionContext context)
SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
}

private void GenerateSource(StringBuilder sourceBuilder)
private static void GenerateSource(StringBuilder sourceBuilder)
=> sourceBuilder.Append(@"
using Xunit;

Expand All @@ -37,7 +37,7 @@ public class TimeSystemTestSettingsFixture : ICollectionFixture<TestSettingsFixt
// ICollectionFixture<> interfaces.
}");

private StringBuilder GetSourceBuilder()
private static StringBuilder GetSourceBuilder()
=> new(
@"//------------------------------------------------------------------------------
// <auto-generated>
Expand Down
30 changes: 19 additions & 11 deletions Tests/Settings/Testably.Abstractions.TestSettings/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,23 @@ namespace Testably.Abstractions.TestSettings;

internal static class Helper
{
private static readonly JsonSerializerOptions ReadJsonSerializerOptions;
private static readonly JsonSerializerOptions WriteJsonSerializerOptions;

static Helper()
{
ReadJsonSerializerOptions = new JsonSerializerOptions();
ReadJsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
WriteJsonSerializerOptions = new JsonSerializerOptions
{
WriteIndented = true,
Converters =
{
new JsonStringEnumConverter()
}
};
}

public static TestEnvironment ChangeTestSettings(
Action<TestEnvironment> change)
{
Expand All @@ -26,9 +43,7 @@ private static TestEnvironment ReadTestSettings()
{
string path = GetTestSettingsPath();
string content = File.ReadAllText(path);
JsonSerializerOptions options = new();
options.Converters.Add(new JsonStringEnumConverter());
return JsonSerializer.Deserialize<TestEnvironment>(content, options)
return JsonSerializer.Deserialize<TestEnvironment>(content, ReadJsonSerializerOptions)
?? throw new NotSupportedException("The file has an invalid syntax!");
}
catch (Exception)
Expand All @@ -39,14 +54,7 @@ private static TestEnvironment ReadTestSettings()

private static void WriteTestSettings(TestEnvironment environment)
{
string content = JsonSerializer.Serialize(environment, new JsonSerializerOptions
{
WriteIndented = true,
Converters =
{
new JsonStringEnumConverter()
}
});
string content = JsonSerializer.Serialize(environment, WriteJsonSerializerOptions);
string path = GetTestSettingsPath();
File.WriteAllText(path, content);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,10 @@ private sealed class DummyZipArchiveEntry(
/// <inheritdoc cref="IZipArchiveEntry.CompressedLength" />
public long CompressedLength => stream?.Length ?? 0L;

#pragma warning disable MA0041
/// <inheritdoc cref="IZipArchiveEntry.Crc32" />
public uint Crc32 => 0u;
#pragma warning restore MA0041

/// <inheritdoc cref="IZipArchiveEntry.ExternalAttributes" />
public int ExternalAttributes { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,12 @@ public static string PrintType(this Type type)

if (type.GenericTypeArguments.Length > 0)
{

#pragma warning disable MA0089 // Use an overload with char instead of string
return type.Name.Substring(0, type.Name.Length - 2) +
"<" + string.Join(",",
type.GenericTypeArguments.Select(x => x.PrintType())) + ">";
#pragma warning restore MA0089
}

return type.Name;
Expand All @@ -166,11 +169,11 @@ internal static bool IsTypeNameEqual(string? systemTypeName,
}

return systemTypeName != null &&
(abstractionTypeName.Equals(systemTypeName) ||
abstractionTypeName.Equals("I" + systemTypeName) ||
(abstractionTypeName.Equals(systemTypeName, StringComparison.Ordinal) ||
abstractionTypeName.Equals("I" + systemTypeName, StringComparison.Ordinal) ||
(Parity.AcceptedTypeMapping.TryGetValue(systemTypeName,
out string? acceptedName) &&
acceptedName.Equals(abstractionTypeName)));
acceptedName.Equals(abstractionTypeName, StringComparison.Ordinal)));
}

private static bool AreExtensionMethodsEqual(MethodInfo systemMethod,
Expand All @@ -186,7 +189,7 @@ private static bool AreExtensionMethodsEqual(MethodInfo systemMethod,
for (int i = 0; i < systemParameters.Length - 1; i++)
{
if (!string.Equals(systemParameters[i + 1].Name,
abstractionParameters[i].Name))
abstractionParameters[i].Name, StringComparison.Ordinal))
{
return false;
}
Expand Down Expand Up @@ -225,7 +228,8 @@ private static bool AreMethodsEqual(MethodInfo systemMethod,

for (int i = 0; i < systemParameters.Length; i++)
{
if (!string.Equals(systemParameters[i].Name, abstractionParameters[i].Name))
if (!string.Equals(systemParameters[i].Name, abstractionParameters[i].Name,
StringComparison.Ordinal))
{
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

public sealed partial class ExecuteTests
{
#if CAN_SIMULATE_OTHER_OS
public sealed class SimulatedPathTests
{
#if CAN_SIMULATE_OTHER_OS
[Theory]
[InlineData(SimulationMode.Linux)]
[InlineData(SimulationMode.MacOS)]
Expand All @@ -15,6 +15,6 @@ public void FileSystem_ShouldBeMockFileSystem(SimulationMode simulationMode)

sut.Execute.Path.FileSystem.Should().BeSameAs(sut);
}
#endif
}
#endif
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ public void NormalizePath_Unix_RootedPath_ShouldRemoveDriveInfo(string part1)

MockFileSystem fileSystem = new();

string path =
fileSystem.GetDefaultDrive().Name.Replace("\\", "/", StringComparison.Ordinal) + part1;
string path = fileSystem.GetDefaultDrive().Name.Replace('\\', '/') + part1;
string expectedPath = part1.PrefixRoot(fileSystem);
path = path.NormalizePath(fileSystem);

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,9 @@ public async Task Method_ReadAsync_ByteArray_Int_Int_CancellationToken_ShouldReg
int count = 2;
CancellationToken cancellationToken = CancellationToken.None;

#pragma warning disable CA1835 // Change the 'ReadAsync' method call to use the 'Stream.ReadAsync(Memory<byte>, CancellationToken)' overload
_ = await fileStream.ReadAsync(buffer, offset, count, cancellationToken);
#pragma warning restore CA1835

sut.Statistics.TotalCount.Should().Be(2);
sut.Statistics.FileStream["foo"]
Expand Down Expand Up @@ -342,7 +344,9 @@ public async Task Method_WriteAsync_ByteArray_Int_Int_CancellationToken_ShouldRe
int count = 2;
CancellationToken cancellationToken = CancellationToken.None;

#pragma warning disable CA1835 // Change the 'WriteAsync' method call to use the 'Stream.WriteAsync(ReadOnlyMemory<byte>, CancellationToken)' overload
await fileStream.WriteAsync(buffer, offset, count, cancellationToken);
#pragma warning restore CA1835

sut.Statistics.TotalCount.Should().Be(2);
sut.Statistics.FileStream["foo"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ public void ToString_WithReadOnlySpan_ShouldSetIsOutParameterToFalse(string buff
{
ReadOnlySpan<char> value = buffer.AsSpan();
ParameterDescription sut = ParameterDescription.FromParameter(value);
string expectedString = $"[{string.Join(",", buffer.ToCharArray())}]";
string expectedString = $"[{string.Join(',', buffer.ToCharArray())}]";

string? result = sut.ToString();

Expand All @@ -129,7 +129,7 @@ public void ToString_WithSpan_ShouldSetIsOutParameterToFalse(int[] buffer)
{
Span<int> value = buffer.AsSpan();
ParameterDescription sut = ParameterDescription.FromParameter(value);
string expectedString = $"[{string.Join(",", buffer)}]";
string expectedString = $"[{string.Join(',', buffer)}]";

string? result = sut.ToString();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ private static void CheckMethodCall(StringBuilder builder,
Type mockType,
Type testType)
{
#pragma warning disable MA0089 // Use an overload with char instead of string
string expectedName = $"Method_{methodInfo.Name}_{string.Join("_", methodInfo
.GetParameters()
.Select(x => FirstCharToUpperAsSpan(GetName(x.ParameterType, true)
Expand All @@ -44,6 +45,7 @@ private static void CheckMethodCall(StringBuilder builder,
// ReSharper disable once StringLiteralTypo
.Replace("IEnumerablestring", "IEnumerableString", StringComparison.Ordinal)
.Replace("[]", "Array", StringComparison.Ordinal))))}{(parameters.Length > 0 ? "_" : "")}ShouldRegisterCall";
#pragma warning restore MA0089
if (testType.GetMethod(expectedName) != null)
{
return;
Expand Down Expand Up @@ -303,8 +305,10 @@ private static string GetName(Type type, bool firstCharUpperCase)
int idx = type.Name.IndexOf('`', StringComparison.Ordinal);
if (idx > 0)
{
#pragma warning disable MA0089 // Use an overload with char instead of string
return
$"{type.Name.Substring(0, idx)}<{string.Join(",", type.GenericTypeArguments.Select(x => GetName(x, firstCharUpperCase)))}>";
#pragma warning restore MA0089
}

return type.ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ public void
string currentDirectory = FileSystem.Directory.GetCurrentDirectory();
int directoryCount = currentDirectory.Length -
currentDirectory
.Replace($"{FileSystem.Path.DirectorySeparatorChar}", "")
.Replace($"{FileSystem.Path.DirectorySeparatorChar}", "", StringComparison.Ordinal)
.Length;

StringBuilder sb = new();
Expand Down
Loading
Loading