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
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
[
#nullable enable

using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using TUnit.Assertions.Core;
using TUnit.Assertions.Tests.TestData;

namespace TUnit.Assertions.Extensions;

/// <summary>
/// Generated assertion for ContainsMessage
/// </summary>
public sealed class _ContainsMessage_String_Bool_Assertion : Assertion<string[]>
{
private readonly string _needle;
private readonly bool _exact;

public _ContainsMessage_String_Bool_Assertion(AssertionContext<string[]> context, string needle, bool exact)
: base(context)
{
_needle = needle;
_exact = exact;
}

protected override Task<AssertionResult> CheckAsync(EvaluationMetadata<string[]> metadata)
{
var value = metadata.Value;
var exception = metadata.Exception;

if (exception != null)
{
return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().FullName}"));
}

if (value is null)
{
return Task.FromResult(AssertionResult.Failed("Actual value is null"));
}

var result = value!.ContainsMessage(_needle, _exact);
return Task.FromResult(result
? AssertionResult.Passed
: AssertionResult.Failed($"found {value}"));
}

protected override string GetExpectation()
{
return $"to contain message '{_needle}'";
}
}

public static partial class MethodWithDefaultValuesExtensions
{
/// <summary>
/// Generated extension method for ContainsMessage
/// </summary>
public static _ContainsMessage_String_Bool_Assertion ContainsMessage(this IAssertionSource<string[]> source, string needle, bool exact = true, [CallerArgumentExpression(nameof(needle))] string? needleExpression = null, [CallerArgumentExpression(nameof(exact))] string? exactExpression = null)
{
source.Context.ExpressionBuilder.Append($".ContainsMessage({needleExpression}, {exactExpression})");
return new _ContainsMessage_String_Bool_Assertion(source.Context, needle, exact);
}

}

]
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
[
#nullable enable

using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using TUnit.Assertions.Core;
using TUnit.Assertions.Tests.TestData;

namespace TUnit.Assertions.Extensions;

/// <summary>
/// Generated assertion for ContainsMessage
/// </summary>
public sealed class _ContainsMessage_String_Bool_Assertion : Assertion<string[]>
{
private readonly string _needle;
private readonly bool _exact;

public _ContainsMessage_String_Bool_Assertion(AssertionContext<string[]> context, string needle, bool exact)
: base(context)
{
_needle = needle;
_exact = exact;
}

protected override Task<AssertionResult> CheckAsync(EvaluationMetadata<string[]> metadata)
{
var value = metadata.Value;
var exception = metadata.Exception;

if (exception != null)
{
return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().FullName}"));
}

if (value is null)
{
return Task.FromResult(AssertionResult.Failed("Actual value is null"));
}

var result = value!.ContainsMessage(_needle, _exact);
return Task.FromResult(result
? AssertionResult.Passed
: AssertionResult.Failed($"found {value}"));
}

protected override string GetExpectation()
{
return $"to contain message '{_needle}'";
}
}

public static partial class MethodWithDefaultValuesExtensions
{
/// <summary>
/// Generated extension method for ContainsMessage
/// </summary>
public static _ContainsMessage_String_Bool_Assertion ContainsMessage(this IAssertionSource<string[]> source, string needle, bool exact = true, [CallerArgumentExpression(nameof(needle))] string? needleExpression = null, [CallerArgumentExpression(nameof(exact))] string? exactExpression = null)
{
source.Context.ExpressionBuilder.Append($".ContainsMessage({needleExpression}, {exactExpression})");
return new _ContainsMessage_String_Bool_Assertion(source.Context, needle, exact);
}

}

]
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
[
#nullable enable

using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using TUnit.Assertions.Core;
using TUnit.Assertions.Tests.TestData;

namespace TUnit.Assertions.Extensions;

/// <summary>
/// Generated assertion for ContainsMessage
/// </summary>
public sealed class _ContainsMessage_String_Bool_Assertion : Assertion<string[]>
{
private readonly string _needle;
private readonly bool _exact;

public _ContainsMessage_String_Bool_Assertion(AssertionContext<string[]> context, string needle, bool exact)
: base(context)
{
_needle = needle;
_exact = exact;
}

protected override Task<AssertionResult> CheckAsync(EvaluationMetadata<string[]> metadata)
{
var value = metadata.Value;
var exception = metadata.Exception;

if (exception != null)
{
return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().FullName}"));
}

if (value is null)
{
return Task.FromResult(AssertionResult.Failed("Actual value is null"));
}

var result = value!.ContainsMessage(_needle, _exact);
return Task.FromResult(result
? AssertionResult.Passed
: AssertionResult.Failed($"found {value}"));
}

protected override string GetExpectation()
{
return $"to contain message '{_needle}'";
}
}

public static partial class MethodWithDefaultValuesExtensions
{
/// <summary>
/// Generated extension method for ContainsMessage
/// </summary>
public static _ContainsMessage_String_Bool_Assertion ContainsMessage(this IAssertionSource<string[]> source, string needle, bool exact = true, [CallerArgumentExpression(nameof(needle))] string? needleExpression = null, [CallerArgumentExpression(nameof(exact))] string? exactExpression = null)
{
source.Context.ExpressionBuilder.Append($".ContainsMessage({needleExpression}, {exactExpression})");
return new _ContainsMessage_String_Bool_Assertion(source.Context, needle, exact);
}

}

]
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
[
#nullable enable

using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using TUnit.Assertions.Core;
using TUnit.Assertions.Tests.TestData;

namespace TUnit.Assertions.Extensions;

/// <summary>
/// Generated assertion for ContainsMessage
/// </summary>
public sealed class _ContainsMessage_String_Bool_Assertion : Assertion<string[]>
{
private readonly string _needle;
private readonly bool _exact;

public _ContainsMessage_String_Bool_Assertion(AssertionContext<string[]> context, string needle, bool exact)
: base(context)
{
_needle = needle;
_exact = exact;
}

protected override Task<AssertionResult> CheckAsync(EvaluationMetadata<string[]> metadata)
{
var value = metadata.Value;
var exception = metadata.Exception;

if (exception != null)
{
return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().FullName}"));
}

if (value is null)
{
return Task.FromResult(AssertionResult.Failed("Actual value is null"));
}

var result = value!.ContainsMessage(_needle, _exact);
return Task.FromResult(result
? AssertionResult.Passed
: AssertionResult.Failed($"found {value}"));
}

protected override string GetExpectation()
{
return $"to contain message '{_needle}'";
}
}

public static partial class MethodWithDefaultValuesExtensions
{
/// <summary>
/// Generated extension method for ContainsMessage
/// </summary>
public static _ContainsMessage_String_Bool_Assertion ContainsMessage(this IAssertionSource<string[]> source, string needle, bool exact = true, [CallerArgumentExpression(nameof(needle))] string? needleExpression = null, [CallerArgumentExpression(nameof(exact))] string? exactExpression = null)
{
source.Context.ExpressionBuilder.Append($".ContainsMessage({needleExpression}, {exactExpression})");
return new _ContainsMessage_String_Bool_Assertion(source.Context, needle, exact);
}

}

]
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,23 @@ public Task FileScopedClassWithInlining() => RunTest(
await Assert.That(generatedFiles.Count).IsGreaterThanOrEqualTo(1);
});

[Test]
public Task MethodWithDefaultValues() => RunTest(
Path.Combine(Sourcy.Git.RootDirectory.FullName,
"TUnit.Assertions.SourceGenerator.Tests",
"TestData",
"MethodWithDefaultValues.cs"),
async generatedFiles =>
{
await Assert.That(generatedFiles).HasCount(1);

var mainFile = generatedFiles.First();
await Assert.That(mainFile).IsNotNull();

// Verify that the default value is preserved in the extension method
await Assert.That(mainFile).Contains("bool exact = true");
});

#if NET6_0_OR_GREATER
[Test]
public Task RefStructParameter() => RunTest(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using TUnit.Assertions.Attributes;

namespace TUnit.Assertions.Tests.TestData;

/// <summary>
/// Test case: Method with default parameter values
/// Should generate extension method preserving default values
/// </summary>
public static partial class MethodWithDefaultValuesExtensions
{
[GenerateAssertion(ExpectationMessage = "to contain message '{needle}'")]
public static bool ContainsMessage(this string[] strings, string needle, bool exact = true)
{
return exact ? strings.Any(x => x == needle) : strings.Any(x => x.Contains(needle));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
public static string BuildAssertion = "MethodAssertionData";

private static readonly DiagnosticDescriptor MethodMustBeStaticRule = new DiagnosticDescriptor(
id: "TUNITGEN001",

Check warning on line 23 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (de-DE)

Check warning on line 23 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (pl-PL)

Włącz śledzenie wydań analizatora dla projektu analizatora zawierającego regułę „TUNITGEN001” (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 23 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

Check warning on line 23 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

Check warning on line 23 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (ubuntu-latest)

title: "Method must be static",
messageFormat: "Method '{0}' decorated with [GenerateAssertion] must be static",
category: "TUnit.Assertions.SourceGenerator",
Expand All @@ -29,7 +29,7 @@
description: "Methods decorated with [GenerateAssertion] must be static to be used in generated assertions.");

private static readonly DiagnosticDescriptor MethodMustHaveParametersRule = new DiagnosticDescriptor(
id: "TUNITGEN002",

Check warning on line 32 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / integration-tests

Check warning on line 32 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (de-DE)

Check warning on line 32 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (fr-FR)

Activer le suivi de version d'analyseur pour le projet d'analyseur contenant la règle 'TUNITGEN002' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 32 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (pl-PL)

Włącz śledzenie wydań analizatora dla projektu analizatora zawierającego regułę „TUNITGEN002” (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 32 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

Check warning on line 32 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

Check warning on line 32 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

Check warning on line 32 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (ubuntu-latest)

Check warning on line 32 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (ubuntu-latest)

title: "Method must have at least one parameter",
messageFormat: "Method '{0}' decorated with [GenerateAssertion] must have at least one parameter (the value to assert)",
category: "TUnit.Assertions.SourceGenerator",
Expand All @@ -38,18 +38,18 @@
description: "Methods decorated with [GenerateAssertion] must have at least one parameter representing the value being asserted.");

private static readonly DiagnosticDescriptor UnsupportedReturnTypeRule = new DiagnosticDescriptor(
id: "TUNITGEN003",

Check warning on line 41 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (de-DE)

Check warning on line 41 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (fr-FR)

Activer le suivi de version d'analyseur pour le projet d'analyseur contenant la règle 'TUNITGEN003' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 41 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

Check warning on line 41 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

Check warning on line 41 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

Check warning on line 41 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

title: "Unsupported return type",
messageFormat: "Method '{0}' decorated with [GenerateAssertion] has unsupported return type '{1}'. Supported types are: bool, AssertionResult, Task<bool>, Task<AssertionResult>",

Check warning on line 43 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / integration-tests

The diagnostic message should not contain any line return character nor any leading or trailing whitespaces and should either be a single sentence without a trailing period or a multi-sentences with a trailing period

Check warning on line 43 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (de-DE)

Die Diagnosemeldung darf keine Zeilenvorschubzeichen und keine führenden oder nachfolgenden Leerzeichen enthalten und muss entweder einen einzelnen Satz ohne Satzendepunkt oder mehrere Sätze mit Satzendepunkt umfassen.

Check warning on line 43 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (fr-FR)

Le message du diagnostic ne doit comporter aucun caractère de retour de ligne et aucun espace blanc de début ou de fin, et doit tenir en une seule phrase sans point final ou en plusieurs phrases avec un point final

Check warning on line 43 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (pl-PL)

Komunikat dotyczący diagnostyki nie powinien zawierać znaku nowego wiersza ani odstępów na początku i końcu oraz powinien być pojedynczym zdaniem bez kropki na końcu lub wieloma zdaniami z kropkami na końcu

Check warning on line 43 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

The diagnostic message should not contain any line return character nor any leading or trailing whitespaces and should either be a single sentence without a trailing period or a multi-sentences with a trailing period

Check warning on line 43 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

The diagnostic message should not contain any line return character nor any leading or trailing whitespaces and should either be a single sentence without a trailing period or a multi-sentences with a trailing period

Check warning on line 43 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

The diagnostic message should not contain any line return character nor any leading or trailing whitespaces and should either be a single sentence without a trailing period or a multi-sentences with a trailing period

Check warning on line 43 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

The diagnostic message should not contain any line return character nor any leading or trailing whitespaces and should either be a single sentence without a trailing period or a multi-sentences with a trailing period

Check warning on line 43 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (ubuntu-latest)

The diagnostic message should not contain any line return character nor any leading or trailing whitespaces and should either be a single sentence without a trailing period or a multi-sentences with a trailing period
category: "TUnit.Assertions.SourceGenerator",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Methods decorated with [GenerateAssertion] must return bool, AssertionResult, Task<bool>, or Task<AssertionResult>.");

private static readonly DiagnosticDescriptor RefStructRequiresInliningRule = new DiagnosticDescriptor(
id: "TUNITGEN004",

Check warning on line 50 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / integration-tests

Check warning on line 50 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (fr-FR)

Activer le suivi de version d'analyseur pour le projet d'analyseur contenant la règle 'TUNITGEN004' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 50 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (pl-PL)

Włącz śledzenie wydań analizatora dla projektu analizatora zawierającego regułę „TUNITGEN004” (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 50 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

Check warning on line 50 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

Check warning on line 50 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

Check warning on line 50 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (ubuntu-latest)

Check warning on line 50 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (ubuntu-latest)

title: "Ref struct parameter requires method body inlining",
messageFormat: "Method '{0}' has ref struct parameter '{1}' of type '{2}'. Use InlineMethodBody = true and ensure the method has a single-expression or single-return-statement body",

Check warning on line 52 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / integration-tests

The diagnostic message should not contain any line return character nor any leading or trailing whitespaces and should either be a single sentence without a trailing period or a multi-sentences with a trailing period

Check warning on line 52 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (de-DE)

Die Diagnosemeldung darf keine Zeilenvorschubzeichen und keine führenden oder nachfolgenden Leerzeichen enthalten und muss entweder einen einzelnen Satz ohne Satzendepunkt oder mehrere Sätze mit Satzendepunkt umfassen.

Check warning on line 52 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (fr-FR)

Le message du diagnostic ne doit comporter aucun caractère de retour de ligne et aucun espace blanc de début ou de fin, et doit tenir en une seule phrase sans point final ou en plusieurs phrases avec un point final

Check warning on line 52 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (pl-PL)

Komunikat dotyczący diagnostyki nie powinien zawierać znaku nowego wiersza ani odstępów na początku i końcu oraz powinien być pojedynczym zdaniem bez kropki na końcu lub wieloma zdaniami z kropkami na końcu

Check warning on line 52 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

The diagnostic message should not contain any line return character nor any leading or trailing whitespaces and should either be a single sentence without a trailing period or a multi-sentences with a trailing period

Check warning on line 52 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

The diagnostic message should not contain any line return character nor any leading or trailing whitespaces and should either be a single sentence without a trailing period or a multi-sentences with a trailing period

Check warning on line 52 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

The diagnostic message should not contain any line return character nor any leading or trailing whitespaces and should either be a single sentence without a trailing period or a multi-sentences with a trailing period

Check warning on line 52 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

The diagnostic message should not contain any line return character nor any leading or trailing whitespaces and should either be a single sentence without a trailing period or a multi-sentences with a trailing period

Check warning on line 52 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (ubuntu-latest)

The diagnostic message should not contain any line return character nor any leading or trailing whitespaces and should either be a single sentence without a trailing period or a multi-sentences with a trailing period

Check warning on line 52 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (ubuntu-latest)

The diagnostic message should not contain any line return character nor any leading or trailing whitespaces and should either be a single sentence without a trailing period or a multi-sentences with a trailing period
category: "TUnit.Assertions.SourceGenerator",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
Expand Down Expand Up @@ -140,6 +140,8 @@
IsParams = p.IsParams,
IsInterpolatedStringHandler = IsInterpolatedStringHandler(p.Type),
SimpleTypeName = GetSimpleTypeName(p.Type),
HasExplicitDefaultValue = p.HasExplicitDefaultValue,
DefaultValueExpression = p.HasExplicitDefaultValue ? FormatDefaultValue(p.ExplicitDefaultValue, p.Type) : null,
}).ToImmutableEquatableArray();

// Extract custom expectation message and inlining preference if provided
Expand Down Expand Up @@ -825,7 +827,7 @@
// Add null-forgiving operator for reference types if not already present
// This is safe because we've already checked for null above
var isNullable = data.TargetType.IsNullable;
if (isNullable && !string.IsNullOrEmpty(inlinedBody) && !inlinedBody.StartsWith("value!"))

Check warning on line 830 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / integration-tests

Dereference of a possibly null reference.

Check warning on line 830 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (de-DE)

Dereferenzierung eines möglichen Nullverweises.

Check warning on line 830 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (fr-FR)

Déréférencement d'une éventuelle référence null.

Check warning on line 830 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (pl-PL)

Wyłuskanie odwołania, które może mieć wartość null.

Check warning on line 830 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

Dereference of a possibly null reference.

Check warning on line 830 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

Dereference of a possibly null reference.

Check warning on line 830 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

Dereference of a possibly null reference.

Check warning on line 830 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

Dereference of a possibly null reference.

Check warning on line 830 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (ubuntu-latest)

Dereference of a possibly null reference.

Check warning on line 830 in TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (ubuntu-latest)

Dereference of a possibly null reference.
{
// Replace null-conditional operators with null-forgiving + regular operators
// value?.Member becomes value!.Member (safe because we already null-checked)
Expand Down Expand Up @@ -926,6 +928,10 @@
{
var paramsModifier = param.IsParams ? "params " : "";
sb.Append($", {paramsModifier}{param.Type} {param.Name}");
if (param.HasExplicitDefaultValue)
{
sb.Append($" = {param.DefaultValueExpression}");
}
}

// CallerArgumentExpression parameters (skip for params since params must be last)
Expand Down Expand Up @@ -1065,6 +1071,46 @@
return simpleName;
}

private static string FormatDefaultValue(object? defaultValue, ITypeSymbol type)
{
if (defaultValue == null)
{
return "null";
}

if (type.TypeKind == TypeKind.Enum && type is INamedTypeSymbol enumType)
{
foreach (var member in enumType.GetMembers())
{
if (member is IFieldSymbol { HasConstantValue: true } field &&
field.ConstantValue != null &&
field.ConstantValue.Equals(defaultValue))
{
return $"{enumType.ToDisplayString()}.{field.Name}";
}
}

return $"({enumType.ToDisplayString()})({defaultValue})";
}

if (defaultValue is string str)
{
return $"\"{str.Replace("\"", "\\\"")}\"";
}

if (defaultValue is bool b)
{
return b ? "true" : "false";
}

if (defaultValue is char c)
{
return $"'{c}'";
}

return defaultValue.ToString() ?? "null";
}

/// <summary>
/// Collects generic constraints from method type parameters.
/// Returns a list of constraint strings in the format "where T : constraint1, constraint2"
Expand Down Expand Up @@ -1212,6 +1258,8 @@
bool IsRefStruct,
bool IsParams,
bool IsInterpolatedStringHandler,
string SimpleTypeName
string SimpleTypeName,
bool HasExplicitDefaultValue,
string? DefaultValueExpression
);
}
Loading