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

Enable pattern code style #3358

Merged
merged 1 commit into from
Feb 12, 2022
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
30 changes: 25 additions & 5 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,22 @@ dotnet_diagnostic.CA1507.severity=warning # not default, increased severity to e
# CA2215: Dispose methods should call base class dispose
dotnet_diagnostic.CA2215.severity=warning # not default, increased severity to ensure it is applied

# IDE0019: Use pattern matching
# Keep this in sync with csharp_style_pattern_matching_over_as_with_null_check
dotnet_diagnostic.IDE0019.severity = warning # not default, increased severity to ensure it is applied

# IDE0020:
# Keep this in sync with csharp_style_pattern_matching_over_is_with_cast_check
dotnet_diagnostic.IDE0020.severity = warning # not default, increased severity to ensure it is applied

# IDE0078: Use pattern matching
# Keep this in sync with csharp_style_prefer_pattern_matching
dotnet_diagnostic.IDE0078.severity = warning # not default, increased severity to ensure it is applied

# IDE0083: Use pattern matching (not operator)
# Keep this in sync with csharp_style_prefer_not_pattern
dotnet_diagnostic.IDE0083.severity = warning # not default, increased severity to ensure it is applied

#### C# Coding Conventions ####

# var preferences
Expand All @@ -183,11 +199,15 @@ csharp_style_expression_bodied_operators = false:silent
csharp_style_expression_bodied_properties = true:silent

# Pattern matching preferences
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_prefer_not_pattern = true:suggestion
csharp_style_prefer_pattern_matching = true:silent
csharp_style_prefer_switch_expression = true:suggestion
# Keep this in sync with IDE0019
csharp_style_pattern_matching_over_as_with_null_check = true:warning
# Keep this in sync with IDE0020 and IDE0038
csharp_style_pattern_matching_over_is_with_cast_check = true:warning
# Keep this in sync with IDE0083
csharp_style_prefer_not_pattern = true:warning
# Keep this in sync with IDE0078
csharp_style_prefer_pattern_matching = true:warning
csharp_style_prefer_switch_expression = true:warning

# Null-checking preferences
csharp_style_conditional_delegate_call = true:suggestion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ private static void NormalizeAndAppendString(StringBuilder b, string name)
char c = name[i];
if (NeedsEscaping(c, i))
{
if (c == '\\' || c == '\'')
if (c is '\\' or '\'')
{
// var encoded = Convert.ToString(((uint)c), 16);
// b.Append("\\u");
Expand Down Expand Up @@ -494,15 +494,11 @@ private static bool NeedsEscaping(char c, int pos)
}

var category = CharUnicodeInfo.GetUnicodeCategory(c);
if (category == UnicodeCategory.NonSpacingMark // Mn
|| category == UnicodeCategory.SpacingCombiningMark // Mc
|| category == UnicodeCategory.ConnectorPunctuation // Pc
|| category == UnicodeCategory.Format) // Cf
{
return false;
}

return true;
return category
is not UnicodeCategory.NonSpacingMark // Mn
and not UnicodeCategory.SpacingCombiningMark // Mc
and not UnicodeCategory.ConnectorPunctuation // Pc
and not UnicodeCategory.Format; // Cf
}

private static string GetTypeString(Type type, bool closedType)
Expand Down
43 changes: 15 additions & 28 deletions src/Microsoft.TestPlatform.AdapterUtilities/TestIdProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,20 +145,14 @@ public Sha1Implementation()
/// </returns>
private static uint F(int t, uint b, uint c, uint d)
{
if (t >= 0 && t <= 19)
return t switch
{
return (b & c) | (~b & d);
}
else if ((t >= 20 && t <= 39) || (t >= 60 && t <= 79))
{
return b ^ c ^ d;
}
else
{
return t >= 40 && t <= 59
? (b & c) | (b & d) | (c & d)
: throw new ArgumentException("Argument out of bounds! 0 <= t < 80", nameof(t));
}
>= 0 and <= 19 => b & c | ~b & d,
>= 20 and <= 39 or >= 60 and <= 79 => b ^ c ^ d,
_ => t is >= 40 and <= 59
? b & c | b & d | c & d
: throw new ArgumentException("Argument out of bounds! 0 <= t < 80", nameof(t))
};
}

/// <summary>
Expand All @@ -173,22 +167,15 @@ private static uint F(int t, uint b, uint c, uint d)
/// </returns>
private static uint K(int t)
{
if (t >= 0 && t <= 19)
{
return 0x5A827999u;
}
else if (t >= 20 && t <= 39)
{
return 0x6ED9EBA1u;
}
else if (t >= 40 && t <= 59)
return t switch
{
return 0x8F1BBCDCu;
}
else
{
return t >= 60 && t <= 79 ? 0xCA62C1D6u : throw new ArgumentException("Argument out of bounds! 0 <= t < 80", nameof(t));
}
>= 0 and <= 19 => 0x5A827999u,
>= 20 and <= 39 => 0x6ED9EBA1u,
>= 40 and <= 59 => 0x8F1BBCDCu,
_ => t is >= 60 and <= 79
? 0xCA62C1D6u
: throw new ArgumentException("Argument out of bounds! 0 <= t < 80", nameof(t))
};
}

/// <summary>
Expand Down
7 changes: 3 additions & 4 deletions src/Microsoft.TestPlatform.Client/Execution/TestRunRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,10 +189,9 @@ public bool WaitForCompletion(int timeout)
throw new ObjectDisposedException("testRunRequest");
}

if (State != TestRunState.InProgress
&& !(State == TestRunState.Completed
|| State == TestRunState.Canceled
|| State == TestRunState.Aborted))
if (State
is not TestRunState.InProgress
and not (TestRunState.Completed or TestRunState.Canceled or TestRunState.Aborted))
{
// If run is already terminated, then we should not throw an exception.
throw new InvalidOperationException(ClientResources.WaitForCompletionOperationIsNotAllowedWhenNoTestRunIsActive);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ private void SendTextMessage(DataCollectionContext context, string text, TestMes
ValidateArg.NotNull(text, nameof(text));

Debug.Assert(
level >= TestMessageLevel.Informational && level <= TestMessageLevel.Error,
level is >= TestMessageLevel.Informational and <= TestMessageLevel.Error,
"Invalid level: " + level);

// Make sure the data collection context is not a derived data collection context. This
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.TestPlatform.Common/Filtering/FastFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ internal void AddCondition(Condition condition)
AddProperty(condition.Name, condition.Value);

// Don't support `Contains`.
if (_fastFilterOperation != Operation.Equal && _fastFilterOperation != Operation.NotEqual)
if (_fastFilterOperation is not Operation.Equal and not Operation.NotEqual)
{
_containsValidFilter = false;
}
Expand Down
7 changes: 4 additions & 3 deletions src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,10 @@ private static bool AddFallbackFakesSettings(

// The fallback settings is for the old implementation of fakes
// that only supports .Net Framework versions
if (framework != FrameworkVersion.Framework35 &&
framework != FrameworkVersion.Framework40 &&
framework != FrameworkVersion.Framework45)
if (framework
is not FrameworkVersion.Framework35
and not FrameworkVersion.Framework40
and not FrameworkVersion.Framework45)
{
return false;
}
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.TestPlatform.CoreUtilities/ValidateArg.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ public static void TypeOf<T>([ValidatedNotNull] object arg, string parameterName
{
NotNull(arg, parameterName);

if (!(arg is T))
if (arg is not T)
{
var message = string.Format(CultureInfo.CurrentCulture, Resources.Error_ArgumentNotTypeOf, typeof(T).FullName);
throw new ArgumentException(message, parameterName);
Expand Down Expand Up @@ -218,7 +218,7 @@ public static void TypeOf<T>([ValidatedNotNull] object arg, string parameterName
{
NotNull(arg, parameterName, propertyName);

if (!(arg is T))
if (arg is not T)
{
var message = string.Format(CultureInfo.CurrentCulture, Resources.Error_ArgumentPropertyNotTypeOf, propertyName, typeof(T).FullName);
throw new ArgumentException(message, parameterName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -381,8 +381,7 @@ internal static Dictionary<LazyExtension<ITestDiscoverer, ITestDiscovererCapabil
{
var sourcesToCheck = sources;

if (discoverer.Metadata.AssemblyType == AssemblyType.Native ||
discoverer.Metadata.AssemblyType == AssemblyType.Managed)
if (discoverer.Metadata.AssemblyType is AssemblyType.Native or AssemblyType.Managed)
{
assemblyTypeToSoucesMap ??= GetAssemblyTypeToSoucesMap(sources, assemblyProperties);
sourcesToCheck = assemblyTypeToSoucesMap[AssemblyType.None].Concat(assemblyTypeToSoucesMap[discoverer.Metadata.AssemblyType]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ public void OnMessageReceived(object sender, MessageReceivedEventArgs messageRec
else
{
var flag = Environment.GetEnvironmentVariable("VSTEST_DISABLE_PROTOCOL_3_VERSION_DOWNGRADE");
var flagIsEnabled = flag != null && flag != "0";
var flagIsEnabled = flag is not null and not "0";
var dowgradeIsDisabled = flagIsEnabled;
_protocolVersion = dowgradeIsDisabled ? negotiatedVersion : 2;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ private bool RunTestInternalWithExecutors(IEnumerable<Tuple<Uri, string>> execut
// host by default.
// Same goes if all adapters implement the new test executor interface but at
// least one of them needs the test platform to attach to the default test host.
if (!(executor.Value is ITestExecutor2)
if (executor.Value is not ITestExecutor2
|| ShouldAttachDebuggerToTestHost(executor, executorUriExtensionTuple, RunContext))
{
EqtTrace.Verbose("Attaching to default test host.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ protected override bool ShouldAttachDebuggerToTestHost(
{
// If the adapter doesn't implement the new test executor interface we should attach to
// the default test host by default to preserve old behavior.
return !(executor?.Value is ITestExecutor2 convertedExecutor)
return executor?.Value is not ITestExecutor2 convertedExecutor
|| convertedExecutor.ShouldAttachToTestHost(
_executorUriVsSourceList[executorUriExtensionTuple],
runContext);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ protected override bool ShouldAttachDebuggerToTestHost(
{
// If the adapter doesn't implement the new test executor interface we should attach to
// the default test host by default to preserve old behavior.
return !(executor?.Value is ITestExecutor2 convertedExecutor)
return executor?.Value is not ITestExecutor2 convertedExecutor
|| convertedExecutor.ShouldAttachToTestHost(_executorUriVsTestList[executorUri], runContext);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ private bool TryGetProcDumpExecutable(int processId, out string path)
}
else
{
filename = _environment.OperatingSystem == PlatformOperatingSystem.Unix || _environment.OperatingSystem == PlatformOperatingSystem.OSX
filename = _environment.OperatingSystem is PlatformOperatingSystem.Unix or PlatformOperatingSystem.OSX
? Constants.ProcdumpUnixProcess
: throw new NotSupportedException($"Not supported platform {_environment.OperatingSystem}");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public WindowsHangDumper(Action<string> logWarning)
public void Dump(int processId, string outputDirectory, DumpTypeOption type)
{
var process = Process.GetProcessById(processId);
var processTree = process.GetProcessTree().Where(p => p.Process.ProcessName != "conhost" && p.Process.ProcessName != "WerFault").ToList();
var processTree = process.GetProcessTree().Where(p => p.Process.ProcessName is not "conhost" and not "WerFault").ToList();

if (processTree.Count > 1)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public TestRunMessageEventArgs(TestMessageLevel level, string message)
throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, nameof(message));
}

if (level < TestMessageLevel.Informational || level > TestMessageLevel.Error)
if (level is < TestMessageLevel.Informational or > TestMessageLevel.Error)
{
throw new ArgumentOutOfRangeException(nameof(level));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,10 @@ public DiaNavigationData GetDiaNavigationData(MethodInfo methodInfo)
internal static bool IsPortable(Stream stream)
{
// First four bytes should be 'BSJB'
#pragma warning disable IDE0078 // Use pattern matching (may change code meaning)
var result = (stream.ReadByte() == 'B') && (stream.ReadByte() == 'S') && (stream.ReadByte() == 'J')
&& (stream.ReadByte() == 'B');
#pragma warning restore IDE0078 // Use pattern matching (may change code meaning)
stream.Position = 0;
return result;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.TestPlatform.ObjectModel/TestResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,6 @@ public static class TestResultProperties

private static bool ValidateOutcome(object value)
{
return (TestOutcome)value <= TestOutcome.NotFound && (TestOutcome)value >= TestOutcome.None;
return (TestOutcome)value is <= TestOutcome.NotFound and >= TestOutcome.None;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ private static string GetArchitectureForSource(string imagePath)

// magic number.32bit or 64bit assembly.
UInt16 magic = reader.ReadUInt16();
if (magic != 0x010B && magic != 0x020B)
if (magic is not 0x010B and not 0x020B)
{
validImage = false;
}
Expand Down
44 changes: 15 additions & 29 deletions src/Microsoft.TestPlatform.ObjectModel/Utilities/Sha1Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,20 +67,14 @@ internal class Sha1Implementation
/// </returns>
private static uint F(int t, uint b, uint c, uint d)
{
if (t >= 0 && t <= 19)
return t switch
{
return (b & c) | (~b & d);
}
else if ((t >= 20 && t <= 39) || (t >= 60 && t <= 79))
{
return b ^ c ^ d;
}
else
{
return t >= 40 && t <= 59
? (b & c) | (b & d) | (c & d)
: throw new ArgumentException("Argument out of bounds! 0 <= t < 80", nameof(t));
}
>= 0 and <= 19 => b & c | ~b & d,
>= 20 and <= 39 or >= 60 and <= 79 => b ^ c ^ d,
_ => t is >= 40 and <= 59
? b & c | b & d | c & d
: throw new ArgumentException("Argument out of bounds! 0 <= t < 80", nameof(t))
};
}

/// <summary>
Expand All @@ -95,23 +89,15 @@ private static uint F(int t, uint b, uint c, uint d)
/// </returns>
private static uint K(int t)
{

if (t >= 0 && t <= 19)
return t switch
{
return 0x5A827999u;
}
else if (t >= 20 && t <= 39)
{
return 0x6ED9EBA1u;
}
else if (t >= 40 && t <= 59)
{
return 0x8F1BBCDCu;
}
else
{
return t >= 60 && t <= 79 ? 0xCA62C1D6u : throw new ArgumentException("Argument out of bounds! 0 <= t < 80", nameof(t));
}
>= 0 and <= 19 => 0x5A827999u,
>= 20 and <= 39 => 0x6ED9EBA1u,
>= 40 and <= 59 => 0x8F1BBCDCu,
_ => t is >= 60 and <= 79
? 0xCA62C1D6u
: throw new ArgumentException("Argument out of bounds! 0 <= t < 80", nameof(t))
};
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ public int GetProcessId(object process)
public string GetNativeDllDirectory()
{
var osArchitecture = new PlatformEnvironment().Architecture;
return osArchitecture == PlatformArchitecture.ARM || osArchitecture == PlatformArchitecture.ARM64
return osArchitecture is PlatformArchitecture.ARM or PlatformArchitecture.ARM64
? Path.Combine(GetCurrentProcessLocation(), GetCurrentProcessArchitecture().ToString().ToLower(), Arm)
: Path.Combine(GetCurrentProcessLocation(), GetCurrentProcessArchitecture().ToString().ToLower());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ public PlatformOperatingSystem OperatingSystem
// CLR 2.x. See below link for more information:
// http://www.mono-project.com/docs/faq/technical/#how-to-detect-the-execution-platform
int p = (int)Environment.OSVersion.Platform;
return (p == 4) || (p == 6) || (p == 128) ? PlatformOperatingSystem.Unix : PlatformOperatingSystem.Windows;
return p is 4 or 6 or 128
? PlatformOperatingSystem.Unix
: PlatformOperatingSystem.Windows;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ public virtual TestProcessStartInfo GetTestHostProcessStartInfo(
&& !IsWinOnArm())
{
// testhost.exe is 64-bit and has no suffix other versions have architecture suffix.
var exeName = _architecture == Architecture.X64 || _architecture == Architecture.Default || _architecture == Architecture.AnyCPU
var exeName = _architecture is Architecture.X64 or Architecture.Default or Architecture.AnyCPU
? "testhost.exe"
: $"testhost.{_architecture.ToString().ToLowerInvariant()}.exe";

Expand All @@ -283,7 +283,7 @@ public virtual TestProcessStartInfo GetTestHostProcessStartInfo(
{
// testhost.dll is present in path {testHostNugetRoot}\lib\netcoreapp2.1\testhost.dll
// testhost.(x86).exe is present in location {testHostNugetRoot}\build\netcoreapp2.1\{x86/x64}\{testhost.x86.exe/testhost.exe}
var folderName = _architecture == Architecture.X64 || _architecture == Architecture.Default || _architecture == Architecture.AnyCPU
var folderName = _architecture is Architecture.X64 or Architecture.Default or Architecture.AnyCPU
? Architecture.X64.ToString().ToLowerInvariant()
: _architecture.ToString().ToLowerInvariant();

Expand Down
Loading