Skip to content
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
42 changes: 21 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ rules for your Test and your Prod C# projects.
It also provides:
* [Test helpers](#test-helpers) to use in your unit test projects helping with test logging or running processes.
* A [Playwright Test Builder](#playwright-test-builder) to help you make Web application tests.
* And a [HttpClient mock](#httpclient-mocking) to be able to inject HttpClient when ever you need it in your unit tests;


* A [HttpClient mock](#httpclient-mocking) to be able to inject HttpClient when ever you need it in your unit tests.
* A Dotnet Solution builder that can help to process end to end tests on a project consuming the nuget package you
want to test. It can be very handy to test analyzer or code generation tools. Here is [an example](src/tests/SoloX.CodeQuality.Playwright.E2ETest/Package/PackageNugetTest.cs) where it's used.

## Project dashboard
[![Build - CI](https://github.com/xaviersolau/CodeQuality/actions/workflows/build-ci.yml/badge.svg)](https://github.com/xaviersolau/CodeQuality/actions/workflows/build-ci.yml)
Expand Down Expand Up @@ -52,26 +52,26 @@ You can checkout this Github repository or you can use the NuGet package:

**Install using the command line from the Package Manager:**
```bash
Install-Package SoloX.CodeQuality.Prod -version 2.3.2
Install-Package SoloX.CodeQuality.Prod -version 2.3.3
or
Install-Package SoloX.CodeQuality.Test -version 2.3.2
Install-Package SoloX.CodeQuality.Test -version 2.3.3
```

**Install using the .Net CLI:**
```bash
dotnet add package SoloX.CodeQuality.Prod --version 2.3.2
dotnet add package SoloX.CodeQuality.Prod --version 2.3.3
or
dotnet add package SoloX.CodeQuality.Test --version 2.3.2
dotnet add package SoloX.CodeQuality.Test --version 2.3.3
```

**Install editing your project file (csproj):**
```xml
<PackageReference Include="SoloX.CodeQuality.Prod" Version="2.3.2">
<PackageReference Include="SoloX.CodeQuality.Prod" Version="2.3.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
or
<PackageReference Include="SoloX.CodeQuality.Test" Version="2.3.2">
<PackageReference Include="SoloX.CodeQuality.Test" Version="2.3.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
Expand Down Expand Up @@ -218,17 +218,17 @@ You can checkout this Github repository or use the NuGet package:

**Install using the command line from the Package Manager:**
```bash
Install-Package SoloX.CodeQuality.Playwright -version 2.3.2
Install-Package SoloX.CodeQuality.Playwright -version 2.3.3
```

**Install using the .Net CLI:**
```bash
dotnet add package SoloX.CodeQuality.Playwright --version 2.3.2
dotnet add package SoloX.CodeQuality.Playwright --version 2.3.3
```

**Install editing your project file (csproj):**
```xml
<PackageReference Include="SoloX.CodeQuality.Playwright" Version="2.3.2" />
<PackageReference Include="SoloX.CodeQuality.Playwright" Version="2.3.3" />
```

* * *
Expand Down Expand Up @@ -424,29 +424,29 @@ You can checkout this Github repository or you can use the NuGet package:

**Install using the command line from the Package Manager:**
```bash
Install-Package SoloX.CodeQuality.Test.Helpers -version 2.3.2
Install-Package SoloX.CodeQuality.Test.Helpers -version 2.3.3

Install-Package SoloX.CodeQuality.Test.Helpers.XUnit -version 2.3.2
Install-Package SoloX.CodeQuality.Test.Helpers.XUnit -version 2.3.3

Install-Package SoloX.CodeQuality.Test.Helpers.NUnit -version 2.3.2
Install-Package SoloX.CodeQuality.Test.Helpers.NUnit -version 2.3.3
```

**Install using the .Net CLI:**
```bash
dotnet add package SoloX.CodeQuality.Test.Helpers --version 2.3.2
dotnet add package SoloX.CodeQuality.Test.Helpers --version 2.3.3

dotnet add package SoloX.CodeQuality.Test.Helpers.XUnit --version 2.3.2
dotnet add package SoloX.CodeQuality.Test.Helpers.XUnit --version 2.3.3

dotnet add package SoloX.CodeQuality.Test.Helpers.NUnit --version 2.3.2
dotnet add package SoloX.CodeQuality.Test.Helpers.NUnit --version 2.3.3
```

**Install editing your project file (csproj):**
```xml
<PackageReference Include="SoloX.CodeQuality.Test.Helpers" Version="2.3.2" />
<PackageReference Include="SoloX.CodeQuality.Test.Helpers" Version="2.3.3" />

<PackageReference Include="SoloX.CodeQuality.Test.Helpers.XUnit" Version="2.3.2" />
<PackageReference Include="SoloX.CodeQuality.Test.Helpers.XUnit" Version="2.3.3" />

<PackageReference Include="SoloX.CodeQuality.Test.Helpers.NUnit" Version="2.3.2" />
<PackageReference Include="SoloX.CodeQuality.Test.Helpers.NUnit" Version="2.3.3" />
```

* * *
Expand Down
6 changes: 4 additions & 2 deletions src/SharedProperties.props
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project>

<PropertyGroup>
<Version>2.3.2</Version>
<Version>2.3.3</Version>
<Authors>Xavier Solau</Authors>
<Copyright>Copyright © 2021 Xavier Solau</Copyright>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
Expand All @@ -14,7 +14,9 @@
<CodeQualityHeaderLicense>$(PackageLicenseExpression)</CodeQualityHeaderLicense>
<CodeQualityHeaderLicenseFile>LICENSE</CodeQualityHeaderLicenseFile>

<AssemblyVersion>2.3.2.0</AssemblyVersion>
<AssemblyVersion>2.3.3.0</AssemblyVersion>
<LangVersion>12</LangVersion>

</PropertyGroup>

</Project>
7 changes: 3 additions & 4 deletions src/libs/SoloX.CodeQuality.Playwright/PlaywrightDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,7 @@ private static void InstallPlaywrightBin()
/// <param name="browserNewContextOptionsBuilder">BrowserNewContextOptions builder.</param>
public void SetupBrowserNewContextOptions(string? deviceName = null, Action<BrowserNewContextOptions>? browserNewContextOptionsBuilder = null)
{
BrowserNewContextOptions options;
if (string.IsNullOrEmpty(deviceName) || !Playwright.Devices.TryGetValue(deviceName, out options))
if (string.IsNullOrEmpty(deviceName) || !Playwright.Devices.TryGetValue(deviceName, out var options))
{
options = new BrowserNewContextOptions();
}
Expand Down Expand Up @@ -247,7 +246,7 @@ private async Task GotoPageInternalAsync(string url, Func<IPage, Task> testHandl
var gotoResult = await page.GotoAsync(url, new PageGotoOptions { WaitUntil = WaitUntilState.NetworkIdle, Timeout = 60000 }).ConfigureAwait(false);
gotoResult.Should().NotBeNull();

await gotoResult.FinishedAsync().ConfigureAwait(false);
await gotoResult!.FinishedAsync().ConfigureAwait(false);

gotoResult.Ok.Should().BeTrue();

Expand Down Expand Up @@ -330,7 +329,7 @@ public async ValueTask DisposeAsync()
}

Playwright.Dispose();
Playwright = null;
Playwright = default!;
}

GC.SuppressFinalize(this);
Expand Down
10 changes: 6 additions & 4 deletions src/libs/SoloX.CodeQuality.Playwright/PlaywrightTestBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -303,20 +303,22 @@ private static string GetCallingName()

public static MethodBase GetOriginalAsyncMethod(MethodBase method)
{
var methodDeclaringType = method.DeclaringType!;

// Check if the method is part of a state machine
var asyncStateMachineAttribute = method.DeclaringType.GetCustomAttribute<AsyncStateMachineAttribute>();
var asyncStateMachineAttribute = methodDeclaringType.GetCustomAttribute<AsyncStateMachineAttribute>();

var compilerGeneratedAttribute = method.DeclaringType.GetCustomAttribute<CompilerGeneratedAttribute>();
var compilerGeneratedAttribute = methodDeclaringType.GetCustomAttribute<CompilerGeneratedAttribute>();

if (asyncStateMachineAttribute != null || compilerGeneratedAttribute != null)
{
if (method.Name == "MoveNext")
{
// Get the original type
var declaringType = method.DeclaringType.DeclaringType;
var declaringType = methodDeclaringType.DeclaringType;

// The class name will be something like "<OriginalMethod>d__X"
var declaringTypeName = method.DeclaringType.Name;
var declaringTypeName = methodDeclaringType.Name;

// Regex pattern to extract the original method name from "<MethodName>d__X"
var match = Regex.Match(declaringTypeName, @"\<(?<methodName>.+)\>d__\d+");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' ">
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="[8.0.0,9.0.0)" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="[8.0.0,)" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'net9.0' ">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace SoloX.CodeQuality.Test.Helpers.NUnit.Logger
{
public class TestLogger<T> : ILogger<T>
{
public IDisposable BeginScope<TState>(TState state)
public IDisposable? BeginScope<TState>(TState state) where TState : notnull
{
return new TestLoggerScope<T, TState>(this, state);
}
Expand All @@ -28,8 +28,8 @@ public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception exception,
Func<TState, Exception, string> formatter)
Exception? exception,
Func<TState, Exception?, string> formatter)
{
TestContext.Out.WriteLine($"{logLevel}: {formatter(state, exception)}");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

<PropertyGroup>
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
<Nullable>enable</Nullable>

<PackageId>SoloX.CodeQuality.Test.Helpers.NUnit</PackageId>

Expand All @@ -30,8 +31,8 @@
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' ">
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="[8.0.0,9.0.0)" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="[8.0.0,9.0.0)" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="[8.0.0,)" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="[8.0.0,)" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'net9.0' ">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public TestLogger(ITestOutputHelper testOutputHelper)
this.testOutputHelper = testOutputHelper;
}

public IDisposable BeginScope<TState>(TState state)
public IDisposable? BeginScope<TState>(TState state) where TState : notnull
{
return new TestLoggerScope<T, TState>(this, state);
}
Expand All @@ -35,8 +35,8 @@ public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception exception,
Func<TState, Exception, string> formatter)
Exception? exception,
Func<TState, Exception?, string> formatter)
{
this.testOutputHelper.WriteLine($"{logLevel}: {formatter(state, exception)}");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// </copyright>
// ----------------------------------------------------------------------

using System;
using System.Diagnostics;
using System.IO;
using Xunit;
Expand Down Expand Up @@ -62,8 +63,8 @@ public static void AssertSnapshot(string generated, string snapshotName, string
}

Assert.Equal(
generatedRef.Replace("\r\n", "\n"),
generated.Replace("\r\n", "\n"));
generatedRef.Replace("\r\n", "\n", StringComparison.InvariantCulture),
generated.Replace("\r\n", "\n", StringComparison.InvariantCulture));
}
}

Expand All @@ -74,9 +75,9 @@ public static void AssertSnapshot(string generated, string snapshotName, string
/// <returns>Folder location in the project of the calling code assembly.</returns>
public static string GetLocationFromCallingCodeProjectRoot(string folder)
{
var callingAssembly = new StackTrace().GetFrame(1).GetMethod().DeclaringType.Assembly;
var callingAssembly = new StackTrace().GetFrame(1)!.GetMethod()!.DeclaringType!.Assembly;
var assemblyFolder = Path.GetDirectoryName(callingAssembly.Location);
var projectRoot = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(assemblyFolder)));
var projectRoot = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(assemblyFolder)))!;
return folder != null ? Path.Combine(projectRoot, folder) : projectRoot;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
<Import Project="../../libs/SoloX.CodeQuality.Test/build/SoloX.CodeQuality.Test.targets" />

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
<Nullable>enable</Nullable>

<PackageId>SoloX.CodeQuality.Test.Helpers.XUnit</PackageId>

Expand Down
60 changes: 48 additions & 12 deletions src/libs/SoloX.CodeQuality.Test.Helpers/DotnetHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,35 +20,71 @@ public static class DotnetHelper
private const string PUBLISH = "publish";
private const string RUN = "run";
private const string TEST = "test";
private const string NEW = "new";
private const string SLN = "sln";
private const string ADD = "add";
private const string PACKAGE = "package";
private const string REFERENCE = "reference ";

public static bool Restore(string projectPath, out string stdout, out string stderr)
public static bool Restore(string projectPath, out ProcessResult processResult)
{
return ProcessHelper.Run(projectPath, DOTNET, RESTORE, out stdout, out stderr) == 0;
return Dotnet(projectPath, RESTORE, out processResult);
}

public static bool Build(string projectPath, out string stdout, out string stderr)
public static bool Build(string projectPath, out ProcessResult processResult)
{
return ProcessHelper.Run(projectPath, DOTNET, BUILD, out stdout, out stderr) == 0;
return Dotnet(projectPath, BUILD, out processResult);
}

public static bool Test(string projectPath, out string stdout, out string stderr)
public static bool Test(string projectPath, out ProcessResult processResult)
{
return ProcessHelper.Run(projectPath, DOTNET, TEST, out stdout, out stderr) == 0;
return Dotnet(projectPath, TEST, out processResult);
}

public static bool Publish(string projectPath, out string stdout, out string stderr)
public static bool Publish(string projectPath, out ProcessResult processResult)
{
return ProcessHelper.Run(projectPath, DOTNET, PUBLISH, out stdout, out stderr) == 0;
return Dotnet(projectPath, PUBLISH, out processResult);
}

public static bool Run(string projectPath, out string stdout, out string stderr)
public static bool New(string path, string template, string output, out ProcessResult processResult)
{
return Run(projectPath, string.Empty, out stdout, out stderr);
return Dotnet(path, $"{NEW} {template} --output {output}", out processResult);
}

public static bool Run(string projectPath, string args, out string stdout, out string stderr)
public static bool NewSln(string path, string solutionName, out ProcessResult processResult)
{
return ProcessHelper.Run(projectPath, DOTNET, $"{RUN} {args}", out stdout, out stderr) == 0;
return New(path, SLN, solutionName, out processResult);
}

public static bool SlnAdd(string path, string project, out ProcessResult processResult)
{
return Dotnet(path, $"{SLN} {ADD} {project}", out processResult);
}

public static bool AddPackage(string path, string projectFilePath, string packageName, out ProcessResult processResult)
{
return Dotnet(path, $"{ADD} {projectFilePath} {PACKAGE} {packageName}", out processResult);
}

public static bool AddReference(string path, string projectFilePath, string projectReferenceFilePath, out ProcessResult processResult)
{
return Dotnet(path, $"{ADD} {projectFilePath} {REFERENCE} {projectReferenceFilePath}", out processResult);
}

public static bool Run(string projectPath, out ProcessResult processResult)
{
return Run(projectPath, string.Empty, out processResult);
}

public static bool Run(string projectPath, string args, out ProcessResult processResult)
{
return Dotnet(projectPath, $"{RUN} {args}", out processResult);
}

public static bool Dotnet(string path, string args, out ProcessResult processResult)
{
processResult = ProcessHelper.Run(path, DOTNET, args);
return processResult.ExitCode == 0;
}
}
#pragma warning restore CA1021 // Avoid out parameters
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,14 @@ public class HttpClientMockBuilder : IHttpClientMockBuilder
/// <inheritdoc/>
public IHttpClientRequestMockBuilder WithBaseAddress(Uri baseAddress)
{
if (baseAddress is null)
{
throw new ArgumentNullException(nameof(baseAddress));
}
ArgumentNullException.ThrowIfNull(baseAddress);

if (!string.IsNullOrEmpty(baseAddress.Query))
{
throw new ArgumentException($"{nameof(baseAddress)} should not contain query data");
}

if (!baseAddress.AbsolutePath.EndsWith("/", StringComparison.Ordinal))
if (!baseAddress.AbsolutePath.EndsWith('/'))
{
baseAddress = new Uri($"{baseAddress}/");
}
Expand Down
Loading
Loading