diff --git a/Docs/pages/08-analyzers.md b/Docs/pages/08-analyzers.md index ac0005a2a6..4173fb968b 100644 --- a/Docs/pages/08-analyzers.md +++ b/Docs/pages/08-analyzers.md @@ -197,8 +197,8 @@ The source generator warns with `aweXpect2001` when a type named in ## Expectation generator -The source generator in `aweXpect.Core` reports an error for a method marked with `[GenerateExpectation]` that it -cannot turn into an expectation, see [generated expectations](./11-extending/01-generated-expectations.md): +The source generator in `aweXpect.Core` reports an error for a method marked with `[GenerateExpectation]` or +`[GenerateCollectionExpectation]` that it cannot turn into an expectation, see [generated expectations](./11-extending/01-generated-expectations.md): | Rule | Reported when | |----------------|-----------------------------------------------------------------------------------------------------------| diff --git a/Docs/pages/11-extending/01-generated-expectations.md b/Docs/pages/11-extending/01-generated-expectations.md index 8bd8350da4..b4e560c7dd 100644 --- a/Docs/pages/11-extending/01-generated-expectations.md +++ b/Docs/pages/11-extending/01-generated-expectations.md @@ -112,6 +112,47 @@ private static bool IsUntitled([NotNullWhen(false)] Track? track) Here `IsNotUntitled()` fails for a `null` subject, so the subject cannot be `null` after it. +## Collections + +`[GenerateCollectionExpectation]` generates an expectation on the items of a collection from the same kind of method, +e.g. `AreLongerThan` for `That(tracks).All().AreLongerThan(…)`. It takes the name, the expectation text on a single +item and its plural: + +```csharp no-compile +[GenerateCollectionExpectation("AreLongerThan", "is longer than {minimum}", "are longer than {minimum}")] +private static bool IsLongerThan(Track track, TimeSpan minimum) + => track.Duration > minimum; +``` + +Together with `[GenerateExpectation]`, the text on a single item can be left out, as it is the expectation text of +`[GenerateExpectation]` without `{not}`: + +```csharp no-compile +[GenerateExpectation("Is{Not}LongerThan", "is {not} longer than {minimum}")] +[GenerateCollectionExpectation("AreLongerThan", "are longer than {minimum}")] +private static bool IsLongerThan(Track track, TimeSpan minimum) + => track.Duration > minimum; +``` + +```csharp no-compile +await Expect.That(tracks).All().AreLongerThan(TimeSpan.FromMinutes(2)); +await Expect.That(tracks).AtLeast(2).AreLongerThan(TimeSpan.FromMinutes(2)); +await Expect.That(tracks).None().AreLongerThan(TimeSpan.FromMinutes(5)); +``` + +- The method follows the rules above, and its first parameter is the item. +- The expectation text describes a single item, e.g. "is longer than … for all items". The plural text is used + where the quantifier is the subject, e.g. "has values of which at least 2 are longer than …". The quantifier + carries the negation, so neither text contains `{not}`. +- The result counts the items, e.g. "but only 1 of 3 were", with "did" instead of "were" when the text does not start + with a form of "be". The failure message lists the matching or not matching items and the collection. +- The expectation extends the elements of every kind of collection that can hold the item: an `IEnumerable`, an + `ImmutableArray` and, on .NET 8 or later, an `IAsyncEnumerable`. A `string` item extends the elements of + the collections of strings. +- A `null` item does not match, unless the item parameter is nullable: then the method decides. `[DisallowNull]` and + `NullableOverload` work like for a subject. +- `Summary` and `Remarks` replace or extend the XML documentation, which is derived from the plural text. + ## Diagnostics A method that the generator cannot turn into an expectation is reported as an error, see the diff --git a/Docs/pages/11-extending/04-collections-and-nested-expectations.md b/Docs/pages/11-extending/04-collections-and-nested-expectations.md index 6e2befc4a4..93c45a27fb 100644 --- a/Docs/pages/11-extending/04-collections-and-nested-expectations.md +++ b/Docs/pages/11-extending/04-collections-and-nested-expectations.md @@ -241,7 +241,8 @@ if (expectedValue is IOptionsProvider { Options: Equivalency An expectation on the items of a collection, i.e. an extension method on `IEnumerableElements`, which `All()`, `AtLeast(2)` and the other quantifiers return, derives from `QuantifiedCollectionConstraint`. -`IEnumerableElements` gives access to the quantifier and the subject: +`IEnumerableElements` gives access to the quantifier and the subject. For a condition on a single item, +[`[GenerateCollectionExpectation]`](./01-generated-expectations.md#collections) generates such an expectation. ```csharp public static AndOrResult, IThat?>> AreRadioFriendly( diff --git a/Docs/pages/11-extending/index.md b/Docs/pages/11-extending/index.md index edda630346..763c3b10b3 100644 --- a/Docs/pages/11-extending/index.md +++ b/Docs/pages/11-extending/index.md @@ -62,7 +62,8 @@ public static partial class ThatTrack ``` The source generator in `aweXpect.Core` writes `IsRadioFriendly()` and `IsNotRadioFriendly()` with their failure -messages, see [generated expectations](./01-generated-expectations.md). +messages, see [generated expectations](./01-generated-expectations.md). With `[GenerateCollectionExpectation]`, the +same method also verifies the items of a collection, e.g. `That(tracks).All().AreRadioFriendly()`. When an expectation needs more than a condition, e.g. options, a different result or a nested expectation, write it yourself as described in the rest of this section. diff --git a/Pipeline/Build.Compile.cs b/Pipeline/Build.Compile.cs index f3e8f20475..5139db7487 100644 --- a/Pipeline/Build.Compile.cs +++ b/Pipeline/Build.Compile.cs @@ -135,6 +135,7 @@ partial class Build if (BuildScope == BuildScope.CoreOnly) { projects.Add(Solution.Tests.aweXpect_Core_Tests, Configuration.Debug); + projects.Add(Solution.Tests.aweXpect_Generators_Tests, Configuration.Debug); } foreach (var (project, configuration) in projects) diff --git a/Pipeline/Build.UnitTest.cs b/Pipeline/Build.UnitTest.cs index b267a1caf3..411fb597f5 100644 --- a/Pipeline/Build.UnitTest.cs +++ b/Pipeline/Build.UnitTest.cs @@ -62,7 +62,9 @@ partial class Build Project[] UnitTestProjects(BuildScope buildScope) => buildScope switch { - BuildScope.CoreOnly => [Solution.Tests.aweXpect_Core_Tests,], + // The generator of aweXpect.Core is tested by compiling its output against the Core project, which only the + // Debug configuration references, so its coverage counts for a Core change as well. + BuildScope.CoreOnly => [Solution.Tests.aweXpect_Core_Tests, Solution.Tests.aweXpect_Generators_Tests,], BuildScope.MainOnly => [ Solution.Tests.aweXpect_Analyzers_Tests, @@ -94,9 +96,9 @@ Project[] UnitTestProjects(BuildScope buildScope) .EnableNoLogo()); // The projects that `UnitTests` did not run in Debug: under `CoreOnly` it runs its own projects in Debug. - Project[] projects = UnitTestProjects(BuildScope == BuildScope.CoreOnly - ? BuildScope.MainOnly - : BuildScope.Default); + Project[] projects = BuildScope == BuildScope.CoreOnly + ? UnitTestProjects(BuildScope.MainOnly).Except(UnitTestProjects(BuildScope.CoreOnly)).ToArray() + : UnitTestProjects(BuildScope.Default); AbsolutePath resultsDirectory = TestResultsDirectory / Configuration.Debug; RunUnitTests(projects, framework => framework != NetFramework, diff --git a/Pipeline/Build.cs b/Pipeline/Build.cs index a57fa82f59..f63490b618 100644 --- a/Pipeline/Build.cs +++ b/Pipeline/Build.cs @@ -20,7 +20,7 @@ partial class Build : FalloutBuild /// /// Afterward, you can update the package reference in `Directory.Packages.props` and reset this flag. /// - readonly BuildScope BuildScope = BuildScope.Default; + readonly BuildScope BuildScope = BuildScope.CoreOnly; [Parameter("Github Token")] readonly string GithubToken; [GitRepository] readonly GitRepository Repository; diff --git a/Source/aweXpect.Core.Generators/AnalyzerReleases.Unshipped.md b/Source/aweXpect.Core.Generators/AnalyzerReleases.Unshipped.md index 20dbcdef8e..3f814522e1 100644 --- a/Source/aweXpect.Core.Generators/AnalyzerReleases.Unshipped.md +++ b/Source/aweXpect.Core.Generators/AnalyzerReleases.Unshipped.md @@ -2,6 +2,6 @@ Rule ID | Category | Severity | Notes --------------|--------------------------|----------|--------------------------------------------------------------------- - aweXpect4001 | aweXpect.Core.Generators | Error | The class of a `GenerateExpectation` method cannot hold extensions. - aweXpect4002 | aweXpect.Core.Generators | Error | A `GenerateExpectation` method or its texts are not supported. + aweXpect4001 | aweXpect.Core.Generators | Error | The class of a marked method cannot hold extensions. + aweXpect4002 | aweXpect.Core.Generators | Error | A marked method or its texts are not supported. aweXpect4003 | aweXpect.Core.Generators | Error | The `Result` of a `GenerateExpectation` names no suitable method. diff --git a/Source/aweXpect.Core.Generators/CollectionExpectationWriter.cs b/Source/aweXpect.Core.Generators/CollectionExpectationWriter.cs new file mode 100644 index 0000000000..e3f50fe84d --- /dev/null +++ b/Source/aweXpect.Core.Generators/CollectionExpectationWriter.cs @@ -0,0 +1,287 @@ +using System.Text; +using static aweXpect.Core.Generators.ExpectationWriter; + +namespace aweXpect.Core.Generators; + +/// +/// Writes the source of a . +/// +/// +/// Every type is fully qualified, so that the generated code binds the same in any namespace and without the usings +/// of the declaring file. +/// +internal static class CollectionExpectationWriter +{ + private const string EnumerableType = "global::System.Collections.Generic.IEnumerable"; + private const string AsyncEnumerableType = "global::System.Collections.Generic.IAsyncEnumerable"; + + public static string Write(CollectionExpectationModel model) + { + ClassModel classModel = model.Class; + StringBuilder sb = new(); + sb.AppendLine("// "); + sb.AppendLine("#nullable enable"); + sb.AppendLine(); + AppendUsings(sb, classModel.Usings); + if (classModel.Namespace is not null) + { + sb.Append("namespace ").AppendLine(classModel.Namespace); + sb.AppendLine("{"); + AppendUsings(sb, classModel.NamespaceUsings); + } + + sb.Append(classModel.ClassAccessibility).Append(" static partial class ").AppendLine(classModel.ClassName); + sb.AppendLine("{"); + foreach (ItemModel item in model.Items.Values) + { + AppendExpectations(sb, model, item); + } + + AppendConstraints(sb, model); + sb.AppendLine("}"); + if (classModel.Namespace is not null) + { + sb.AppendLine("}"); + } + + return sb.ToString(); + } + + /// + /// Appends the expectations on every kind of collection that holds the . + /// + private static void AppendExpectations(StringBuilder sb, CollectionExpectationModel model, ItemModel item) + { + string elements = item.IsString + ? "global::aweXpect.IEnumerableStringElements" + : $"global::aweXpect.IEnumerableElements<{item.ItemType}>"; + AppendExpectation(sb, model, elements, $"{EnumerableType}<{item.ItemType}>", + $"{SyncConstraint(item)}<{EnumerableType}<{item.ItemType}>?>", null); + + string structElements = item.IsString + ? "global::aweXpect.IStructEnumerableStringElements" + : $"global::aweXpect.IStructEnumerableElements"; + AppendExpectation(sb, model, structElements, "TEnumerable", + $"{SyncConstraint(item)}", $"{EnumerableType}<{item.ItemType}>"); + + if (model.SupportsAsyncEnumerables) + { + string asyncElements = item.IsString + ? "global::aweXpect.IAsyncEnumerableStringElements" + : $"global::aweXpect.IAsyncEnumerableElements<{item.ItemType}>"; + AppendExpectation(sb, model, asyncElements, $"{AsyncEnumerableType}<{item.ItemType}>", + AsyncConstraint(item), null); + } + } + + /// + /// Appends the constraints of all item types, separated by an empty line. + /// + private static void AppendConstraints(StringBuilder sb, CollectionExpectationModel model) + { + List constraints = []; + foreach (ItemModel item in model.Items.Values) + { + constraints.Add(WriteConstraint(model, item, SyncConstraint(item), "", + $"global::aweXpect.Core.Extending.GeneratedCollectionConstraint", + $"{EnumerableType}<{item.ItemType}>?")); + if (model.SupportsAsyncEnumerables) + { + constraints.Add(WriteConstraint(model, item, AsyncConstraint(item), "", + $"global::aweXpect.Core.Extending.GeneratedAsyncCollectionConstraint<{item.ItemType}>", null)); + } + } + + for (int i = 0; i < constraints.Count; i++) + { + if (i > 0) + { + sb.AppendLine(); + } + + sb.Append(constraints[i]); + } + } + + /// The source to append to. + /// The expectation. + /// The extended elements. + /// The type of the collection that the expectation continues with. + /// The constructed constraint. + /// + /// The interface that a generic struct collection TEnumerable implements, or when + /// the method is not generic. + /// + private static void AppendExpectation(StringBuilder sb, CollectionExpectationModel model, string elements, + string collection, string constraint, string? structConstraint) + { + ClassModel classModel = model.Class; + string thatType = structConstraint is null ? collection + "?" : collection; + string resultType = + $"global::aweXpect.Results.AndOrResult<{collection}, global::aweXpect.Core.IThat<{thatType}>>"; + sb.AppendLine("\t/// "); + AppendDocumentation(sb, model.Summary ?? $"…{ToDocumentation(model.PluralText, classModel)}."); + sb.AppendLine("\t/// "); + if (model.Remarks is { Length: > 0, } remarks) + { + sb.AppendLine("\t/// "); + AppendDocumentation(sb, remarks); + sb.AppendLine("\t/// "); + } + + sb.Append('\t').Append(classModel.MethodAccessibility).Append(" static ").Append(resultType).Append(' ') + .Append(model.Name).Append(structConstraint is null ? "" : "") + .Append("(this ").Append(elements).Append(" elements"); + foreach (ParameterModel parameter in classModel.Parameters.Values) + { + sb.Append(", ").Append(parameter.IsParams ? "params " : "").Append(parameter.Type).Append(' ') + .Append(parameter.Name); + } + + sb.AppendLine(")"); + if (structConstraint is not null) + { + sb.Append("\t\twhere TEnumerable : struct, ").AppendLine(structConstraint); + } + + sb.AppendLine("\t{"); + AppendNullChecks(sb, classModel.Parameters); + int count = classModel.Parameters.Count; + string state = count == 0 + ? "elements.Quantifier" + : $"(elements.Quantifier, {string.Join(", ", classModel.Parameters.Values.Select(p => p.Name))})"; + string arguments = count == 0 + ? "__state" + : string.Concat(Enumerable.Range(0, count + 1).Select(i => (i == 0 ? "" : ", ") + $"__state.Item{i + 1}")); + sb.Append("\t\treturn new ").Append(resultType) + .Append("(global::aweXpect.Core.Extending.ThatExtensions.Get(elements.Subject).ExpectationBuilder.AddConstraint(") + .Append(state).Append(", (__state, __it, __grammars) => new ").Append(constraint) + .Append("(__it, __grammars, ").Append(arguments).AppendLine(")),"); + sb.AppendLine("\t\t\telements.Subject);"); + sb.AppendLine("\t}"); + sb.AppendLine(); + } + + private static string SyncConstraint(ItemModel item) => $"{item.ConstraintPrefix}ElementsConstraint"; + + private static string AsyncConstraint(ItemModel item) => $"{item.ConstraintPrefix}AsyncElementsConstraint"; + + /// The expectation. + /// The item type. + /// The name of the constraint class. + /// The type parameters of the constraint class. + /// The base class of the constraint class. + /// + /// The interface that the generic collection TCollection implements, or when the + /// class is not generic. + /// + private static string WriteConstraint(CollectionExpectationModel model, ItemModel item, string constraintName, + string typeParameters, string baseType, string? collectionConstraint) + { + ClassModel classModel = model.Class; + StringBuilder sb = new(); + sb.Append("\tprivate sealed class ").Append(constraintName).Append(typeParameters).Append(" : ") + .AppendLine(baseType); + if (collectionConstraint is not null) + { + sb.Append("\t\twhere TCollection : ").AppendLine(collectionConstraint); + } + + sb.AppendLine("\t{"); + for (int i = 0; i < classModel.Parameters.Count; i++) + { + sb.Append("\t\tprivate readonly ").Append(classModel.Parameters.Values[i].Type).Append(" _p").Append(i) + .AppendLine(";"); + } + + if (classModel.Parameters.Count > 0) + { + sb.AppendLine(); + } + + sb.Append("\t\tpublic ").Append(constraintName).Append("(string it, ").Append(Grammars) + .Append(" grammars, global::aweXpect.Options.EnumerableQuantifier quantifier"); + for (int i = 0; i < classModel.Parameters.Count; i++) + { + sb.Append(", ").Append(classModel.Parameters.Values[i].Type).Append(" p").Append(i); + } + + sb.AppendLine(")"); + sb.AppendLine("\t\t\t: base(it, grammars, quantifier)"); + sb.AppendLine("\t\t{"); + for (int i = 0; i < classModel.Parameters.Count; i++) + { + sb.Append("\t\t\t_p").Append(i).Append(" = p").Append(i).AppendLine(";"); + } + + sb.AppendLine("\t\t}"); + sb.AppendLine(); + sb.Append("\t\tprotected override string Verb => ").Append(Literal(model.Verb)).AppendLine(";"); + sb.AppendLine(); + AppendIsMatch(sb, model, item); + AppendItemExpectation(sb, model); + sb.AppendLine("\t}"); + return sb.ToString(); + } + + private static void AppendIsMatch(StringBuilder sb, CollectionExpectationModel model, ItemModel item) + { + ClassModel classModel = model.Class; + string owner = classModel.Namespace is null + ? $"global::{classModel.ClassName}" + : $"global::{classModel.Namespace}.{classModel.ClassName}"; + string fields = string.Concat(Enumerable.Range(0, classModel.Parameters.Count).Select(i => $", _p{i}")); + string token = model.PassesCancellationToken ? ", cancellationToken" : ""; + string call = $"{owner}.{classModel.PredicateName}({item.ItemArgument}{fields}{token})"; + string match = model.PredicateKind switch + { + PredicateKind.Boolean when item.FailsOnNull => $"new {ExpectationWriter.ValueTask}(!(item is null) && {call})", + PredicateKind.Boolean => $"new {ExpectationWriter.ValueTask}({call})", + PredicateKind.Task when item.FailsOnNull => $"item is null ? new {ExpectationWriter.ValueTask}(false) : new {ExpectationWriter.ValueTask}({call})", + PredicateKind.Task => $"new {ExpectationWriter.ValueTask}({call})", + _ when item.FailsOnNull => $"item is null ? new {ExpectationWriter.ValueTask}(false) : {call}", + _ => call, + }; + sb.Append("\t\tprotected override ").Append(ExpectationWriter.ValueTask).Append(" IsMatch(").Append(item.ItemType) + .AppendLine(" item, global::System.Threading.CancellationToken cancellationToken)"); + sb.Append("\t\t\t=> ").Append(match).AppendLine(";"); + sb.AppendLine(); + } + + private static void AppendItemExpectation(StringBuilder sb, CollectionExpectationModel model) + { + sb.Append("\t\tprotected override void AppendItemExpectation(").Append(ExpectationWriter.StringBuilder).Append(" stringBuilder, ") + .Append(Grammars).AppendLine(" grammars, string? indentation)"); + sb.AppendLine("\t\t{"); + sb.Append("\t\t\tif (").Append(GrammarsExtensions).AppendLine(".IsPlural(grammars))"); + sb.AppendLine("\t\t\t{"); + AppendTextParts(sb, model.PluralText); + sb.AppendLine("\t\t\t}"); + sb.AppendLine("\t\t\telse"); + sb.AppendLine("\t\t\t{"); + AppendTextParts(sb, model.Text); + sb.AppendLine("\t\t\t}"); + sb.AppendLine("\t\t}"); + } + + private static void AppendTextParts(StringBuilder sb, EquatableArray parts) + { + foreach (TextPart part in parts.Values) + { + if (part.Text is null) + { + sb.Append("\t\t\t\t").Append(ValueFormatters).Append(".Format(").Append(Formatter) + .Append(", stringBuilder, _p").Append(part.ParameterIndex).AppendLine(");"); + } + else + { + sb.Append("\t\t\t\tstringBuilder.Append(").Append(Literal(part.Text)).AppendLine(");"); + } + } + } + + private static string ToDocumentation(EquatableArray parts, ClassModel classModel) + => string.Concat(parts.Values.Select(part => part.Text is null + ? $"" + : EscapeXml(part.Text))); +} diff --git a/Source/aweXpect.Core.Generators/ExpectationGenerator.cs b/Source/aweXpect.Core.Generators/ExpectationGenerator.cs index bdb8179442..d682586799 100644 --- a/Source/aweXpect.Core.Generators/ExpectationGenerator.cs +++ b/Source/aweXpect.Core.Generators/ExpectationGenerator.cs @@ -15,6 +15,7 @@ namespace aweXpect.Core.Generators; public class ExpectationGenerator : IIncrementalGenerator { private const string Attribute = "aweXpect.Core.Extending.GenerateExpectationAttribute"; + private const string CollectionAttribute = "aweXpect.Core.Extending.GenerateCollectionExpectationAttribute"; private const string HelpLink = "https://docs.testably.org/aweXpect/analyzers#expectation-generator"; private static readonly DiagnosticDescriptor InvalidClass = new( @@ -71,99 +72,83 @@ void IIncrementalGenerator.Initialize(IncrementalGeneratorInitializationContext SourceText.From(ExpectationWriter.Write(result.Model), Encoding.UTF8)); } }); + + IncrementalValueProvider supportsAsyncEnumerables = context.CompilationProvider + .Select(static (compilation, _) + => compilation.GetTypeByMetadataName("aweXpect.IAsyncEnumerableElements`1") is not null); + IncrementalValuesProvider collectionExpectations = context.SyntaxProvider + .ForAttributeWithMetadataName(CollectionAttribute, + static (node, _) => node is MethodDeclarationSyntax, + static (ctx, _) => GetCollectionExpectation(ctx)) + .Combine(supportsAsyncEnumerables) + .Select(static (pair, _) => pair.Left.Model is null + ? pair.Left + : pair.Left with { Model = pair.Left.Model with { SupportsAsyncEnumerables = pair.Right, }, }) + .WithTrackingName("CollectionExpectations"); + + context.RegisterSourceOutput(collectionExpectations, static (spc, result) => + { + if (result.Problem is not null) + { + spc.ReportDiagnostic(result.Problem.ToDiagnostic()); + } + + if (result.Model is not null) + { + spc.AddSource(result.Model.Class.HintName, + SourceText.From(CollectionExpectationWriter.Write(result.Model), Encoding.UTF8)); + } + }); } private static ExpectationResult GetExpectation(GeneratorAttributeSyntaxContext context) { - IMethodSymbol method = (IMethodSymbol)context.TargetSymbol; - Location location = ((MethodDeclarationSyntax)context.TargetNode).Identifier.GetLocation(); - INamedTypeSymbol classSymbol = method.ContainingType; - if (!IsExtensionClass(classSymbol, context.TargetNode)) + if (GetSignatureProblem(context, out Signature signature) is { } signatureProblem) { - return Fail(InvalidClass, location, classSymbol.ToDisplayString()); + return new ExpectationResult(null, signatureProblem); } - string methodName = method.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat); AttributeData attribute = context.Attributes[0]; if (attribute.ConstructorArguments.Length != 2 || attribute.ConstructorArguments[0].Value is not string name || attribute.ConstructorArguments[1].Value is not string expectationText) { - return Fail(InvalidMethod, location, methodName, "the name and the expectation text are required"); - } - - if (GetMethodProblem(method) is { } methodProblem) - { - return Fail(InvalidMethod, location, methodName, methodProblem); - } - - bool isAsync = method.ReturnType.SpecialType != SpecialType.System_Boolean; - ImmutableArray parameters = method.Parameters; - bool passesCancellationToken = parameters.Length > 1 && - IsCancellationToken(parameters[parameters.Length - 1].Type); - IParameterSymbol subject = parameters[0]; - List expectationParameters = parameters - .Skip(1) - .Take(parameters.Length - (passesCancellationToken ? 2 : 1)) - .ToList(); - - if (expectationParameters.FirstOrDefault(p => p.Name == "subject") is { } clash) - { - return Fail(InvalidMethod, location, methodName, - $"the parameter '{clash.Name}' would clash with the subject of the expectation"); - } - - if (parameters.Take(expectationParameters.Count + 1) - .FirstOrDefault(p => GetAccessibility(p.Type) < Accessibility.Internal) is { } inaccessible) - { - return Fail(InvalidMethod, location, methodName, - $"the type of the parameter '{inaccessible.Name}' is not accessible outside of '{classSymbol.Name}'"); + return signature.Fail("the name and the expectation text are required"); } if (GetNameProblem(name, GetNamedArgument(attribute, "NegatedName"), out string positiveName, out string? negatedName) is { } nameProblem) { - return Fail(InvalidMethod, location, methodName, nameProblem); + return signature.Fail(nameProblem); } if (GetTextProblem(expectationText, GetNamedArgument(attribute, "NegatedExpectationText"), - expectationParameters.Select(p => p.Name).ToList(), + signature.GetParameterNames(), out EquatableArray positiveText, out EquatableArray negatedText) is { } textProblem) { - return Fail(InvalidMethod, location, methodName, textProblem); + return signature.Fail(textProblem); } string? resultMethod = GetNamedArgument(attribute, "Result"); ResultModel? result = null; if (resultMethod is not null && - !TryFindResultMethod(classSymbol, resultMethod, subject, expectationParameters, out result)) + !TryFindResultMethod(signature.Class, resultMethod, signature.Subject, signature.ExpectationParameters, + out result)) { - return Fail(InvalidResult, location, resultMethod, methodName); + return new ExpectationResult(null, + new Problem(InvalidResult, signature.Location, resultMethod, signature.MethodName)); } - int overloadIndex = classSymbol.GetMembers(method.Name).OfType().ToList() - .FindIndex(m => SymbolEqualityComparer.Default.Equals(m, method)); - string constraintPrefix = overloadIndex > 0 ? $"{method.Name}_{overloadIndex}" : method.Name; - string? ns = classSymbol.ContainingNamespace.IsGlobalNamespace - ? null - : classSymbol.ContainingNamespace.ToDisplayString(NamespaceFormat); - + ClassModel classModel = signature.ToClassModel(context, ""); return new ExpectationResult(new ExpectationModel( - new EquatableArray(((CompilationUnitSyntax)context.TargetNode.SyntaxTree.GetRoot()).Usings - .Where(u => u.GlobalKeyword.IsKind(SyntaxKind.None)) - .Select(u => u.ToString()) - .ToImmutableArray()), - new EquatableArray(context.TargetNode.Ancestors().OfType() - .Reverse() - .SelectMany(n => n.Usings) - .Select(u => u.ToString()) - .ToImmutableArray()), - ns, - Escape(classSymbol.Name), - SyntaxFacts.GetText(classSymbol.DeclaredAccessibility), - GetMethodAccessibility(classSymbol, parameters.Take(expectationParameters.Count + 1)), - $"{classSymbol.ToDisplayString()}.{constraintPrefix}.g.cs", - Escape(method.Name), + classModel.Usings, + classModel.NamespaceUsings, + classModel.Namespace, + classModel.ClassName, + classModel.ClassAccessibility, + classModel.MethodAccessibility, + classModel.HintName, + classModel.PredicateName, positiveName, negatedName, positiveText, @@ -172,17 +157,119 @@ attribute.ConstructorArguments[0].Value is not string name || GetNamedArgument(attribute, "NegatedSummary"), GetNamedArgument(attribute, "Remarks"), GetNamedArgument(attribute, "NegatedRemarks"), - isAsync, - passesCancellationToken, - new EquatableArray(expectationParameters - .Select(p => new ParameterModel(Escape(p.Name), p.Type.ToDisplayString(TypeFormat), p.IsParams, - p.Type.IsReferenceType && p.NullableAnnotation == NullableAnnotation.NotAnnotated)) - .ToImmutableArray()), + signature.IsAsync, + signature.PassesCancellationToken, + classModel.Parameters, result, - GetOverloads(subject, constraintPrefix, + GetOverloads(signature.Subject, signature.ConstraintPrefix, GetNamedArgument(attribute, "NullableOverload") ?? true)), null); } + private static CollectionExpectationResult GetCollectionExpectation(GeneratorAttributeSyntaxContext context) + { + if (GetSignatureProblem(context, out Signature signature) is { } signatureProblem) + { + return new CollectionExpectationResult(null, signatureProblem); + } + + AttributeData attribute = context.Attributes[0]; + ImmutableArray arguments = attribute.ConstructorArguments; + if (arguments.Length is not (2 or 3) || + arguments[0].Value is not string name || + arguments[arguments.Length - 1].Value is not string pluralExpectationText) + { + return signature.FailCollection("the name and the plural expectation text are required"); + } + + if ((arguments.Length == 3 ? arguments[1].Value as string : GetSingularText(signature.Method)) is not + { } expectationText) + { + return signature.FailCollection( + "the expectation text is required, unless the method is also marked with [GenerateExpectation]"); + } + + if (!SyntaxFacts.IsValidIdentifier(name)) + { + return signature.FailCollection($"the name '{name}' is not a valid method name"); + } + + if (expectationText.Contains("{not}") || pluralExpectationText.Contains("{not}")) + { + return signature.FailCollection( + "the expectation text contains '{not}', but the quantifier carries the negation"); + } + + if (!TryParseText(expectationText.Trim(), signature.GetParameterNames(), + out EquatableArray text, out string? unknownPlaceholder) || + !TryParseText(pluralExpectationText.Trim(), signature.GetParameterNames(), + out EquatableArray pluralText, out unknownPlaceholder)) + { + return signature.FailCollection( + $"the placeholder '{{{unknownPlaceholder}}}' names no parameter of the expectation"); + } + + return new CollectionExpectationResult(new CollectionExpectationModel( + signature.ToClassModel(context, ".Elements"), + name, + text, + pluralText, + GetResultVerb(expectationText), + GetNamedArgument(attribute, "Summary"), + GetNamedArgument(attribute, "Remarks"), + GetPredicateKind(signature.Method.ReturnType), + signature.PassesCancellationToken, + GetItems(signature.Subject, signature.ConstraintPrefix, + GetNamedArgument(attribute, "NullableOverload") ?? true), + false), null); + } + + /// + /// The expectation text of the GenerateExpectationAttribute on the without + /// {not}, which is the text on a single item, or without that attribute. + /// + private static string? GetSingularText(IMethodSymbol method) + => method.GetAttributes() + .FirstOrDefault(a => a.AttributeClass?.ToDisplayString() == Attribute)? + .ConstructorArguments.ElementAtOrDefault(1).Value is string text + ? text.Replace("{not}", "").Replace(" ", " ").Trim() + : null; + + /// + /// Checks the class, the method and its parameters, which both attributes require alike. + /// + private static Problem? GetSignatureProblem(GeneratorAttributeSyntaxContext context, out Signature signature) + { + IMethodSymbol method = (IMethodSymbol)context.TargetSymbol; + Location location = ((MethodDeclarationSyntax)context.TargetNode).Identifier.GetLocation(); + INamedTypeSymbol classSymbol = method.ContainingType; + string methodName = method.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat); + signature = new Signature(method, location, classSymbol, methodName); + if (!IsExtensionClass(classSymbol, context.TargetNode)) + { + return new Problem(InvalidClass, location, classSymbol.ToDisplayString()); + } + + if (GetMethodProblem(method) is { } methodProblem) + { + return new Problem(InvalidMethod, location, methodName, methodProblem); + } + + if (signature.ExpectationParameters.FirstOrDefault(p => p.Name == "subject") is { } clash) + { + return new Problem(InvalidMethod, location, methodName, + $"the parameter '{clash.Name}' would clash with the subject of the expectation"); + } + + if (signature.SignatureParameters.FirstOrDefault(p => GetAccessibility(p.Type) < Accessibility.Internal) is + { } inaccessible) + { + return new Problem(InvalidMethod, location, methodName, + $"the type of the parameter '{inaccessible.Name}' is not accessible outside of '{classSymbol.Name}'"); + } + + return null; + } + private static string? GetNameProblem(string name, string? explicitNegatedName, out string positiveName, out string? negatedName) { @@ -225,9 +312,30 @@ attribute.ConstructorArguments[0].Value is not string name || return null; } - private static ExpectationResult Fail(DiagnosticDescriptor descriptor, Location location, string subject, - string reason = "") - => new(null, new Problem(descriptor, location, subject, reason)); + /// + /// The verb in the past tense that stands in for the expectation in the result, e.g. "were" in "but only 1 of 3 + /// were", which is "were" for a form of "be" and "did" for any other verb, as English requires do-support for it. + /// + private static string GetResultVerb(string expectationText) + { + string trimmed = expectationText.Trim(); + int space = trimmed.IndexOf(' '); + return (space < 0 ? trimmed : trimmed.Substring(0, space)) switch + { + "" or "is" or "are" or "was" or "were" => "were", + _ => "did", + }; + } + + private static PredicateKind GetPredicateKind(ITypeSymbol returnType) + { + if (returnType.SpecialType == SpecialType.System_Boolean) + { + return PredicateKind.Boolean; + } + + return returnType.Name == "Task" ? PredicateKind.Task : PredicateKind.ValueTask; + } /// /// The compiler requires every part of a partial class to be marked, so the part that declares the method is @@ -284,16 +392,6 @@ method.Parent is ClassDeclarationSyntax declaration && return null; } - /// - /// The extension methods are public, unless the class or a type in their signature is only internal, which a - /// public method must not expose. - /// - private static string GetMethodAccessibility(INamedTypeSymbol classSymbol, IEnumerable parameters) - => classSymbol.DeclaredAccessibility == Accessibility.Public && - parameters.All(p => GetAccessibility(p.Type) == Accessibility.Public) - ? "public" - : "internal"; - /// /// The accessibility of the , limited by its containing types and its type arguments. /// @@ -316,10 +414,6 @@ named.Name is "Task" or "ValueTask" && ns.ToDisplayString() == "System.Threading.Tasks" && named.TypeArguments[0].SpecialType == SpecialType.System_Boolean; - private static bool IsCancellationToken(ITypeSymbol type) - => type is { Name: "CancellationToken", ContainingNamespace: var ns, } && - ns.ToDisplayString() == "System.Threading"; - private static bool TryParseText(string text, List parameterNames, out EquatableArray parts, out string? unknownPlaceholder) { @@ -464,6 +558,43 @@ static EquatableArray Single(OverloadModel overload) => new(ImmutableArray.Create(overload)); } + /// + /// The item types whose collections the expectation extends, following the rule for + /// subjects of for the items. + /// + private static EquatableArray GetItems(IParameterSymbol subject, string constraintPrefix, + bool nullableOverload) + { + ITypeSymbol type = subject.Type; + bool disallowNull = subject.GetAttributes() + .Any(a => IsCodeAnalysisAttribute(a, "DisallowNullAttribute")); + string generatedPrefix = $"{constraintPrefix}_Generated"; + string display = type.ToDisplayString(TypeFormat); + + if (type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) + { + return Items(new ItemModel(display, false, generatedPrefix, disallowNull, + disallowNull ? "item.Value" : "item")); + } + + if (type.IsValueType) + { + ItemModel value = new(display, false, generatedPrefix, false, "item"); + return nullableOverload + ? Items(value, new ItemModel(display + "?", false, + generatedPrefix + "Nullable", true, "item.Value")) + : Items(value); + } + + string nullable = type.WithNullableAnnotation(NullableAnnotation.Annotated).ToDisplayString(TypeFormat); + bool failsOnNull = type.NullableAnnotation != NullableAnnotation.Annotated || disallowNull; + return Items(new ItemModel(nullable, type.SpecialType == SpecialType.System_String, generatedPrefix, + failsOnNull, "item")); + + static EquatableArray Items(params ItemModel[] items) + => new(items.ToImmutableArray()); + } + private static bool IsCodeAnalysisAttribute(AttributeData attribute, string name) => attribute.AttributeClass is { Name: var attributeName, ContainingNamespace: var ns, } && attributeName == name && @@ -484,4 +615,99 @@ private static bool IsCodeAnalysisAttribute(AttributeData attribute, string name private static string Escape(string name) => SyntaxFacts.GetKeywordKind(name) != SyntaxKind.None ? "@" + name : name; + + /// + /// The marked method, split into the subject, the parameters of the expectation and the cancellation token. + /// + private sealed class Signature + { + public Signature(IMethodSymbol method, Location location, INamedTypeSymbol classSymbol, string methodName) + { + Method = method; + Location = location; + Class = classSymbol; + MethodName = methodName; + ImmutableArray parameters = method.Parameters; + PassesCancellationToken = parameters.Length > 1 && + IsCancellationToken(parameters[parameters.Length - 1].Type); + ExpectationParameters = parameters + .Skip(1) + .Take(parameters.Length - (PassesCancellationToken ? 2 : 1)) + .ToList(); + SignatureParameters = parameters.Take(ExpectationParameters.Count + 1).ToList(); + int overloadIndex = classSymbol.GetMembers(method.Name).OfType().ToList() + .FindIndex(m => SymbolEqualityComparer.Default.Equals(m, method)); + ConstraintPrefix = overloadIndex > 0 ? $"{method.Name}_{overloadIndex}" : method.Name; + } + + public IMethodSymbol Method { get; } + public Location Location { get; } + public INamedTypeSymbol Class { get; } + public string MethodName { get; } + public bool PassesCancellationToken { get; } + public bool IsAsync => Method.ReturnType.SpecialType != SpecialType.System_Boolean; + public IParameterSymbol Subject => Method.Parameters[0]; + + /// + /// The parameters after the subject, without the cancellation token. + /// + public List ExpectationParameters { get; } + + /// + /// The subject and the , whose types appear in the generated signatures. + /// + public List SignatureParameters { get; } + + public List GetParameterNames() => ExpectationParameters.Select(p => p.Name).ToList(); + + /// + /// The prefix of the generated constraints, which tells overloads of the method apart. + /// + public string ConstraintPrefix { get; } + + public ExpectationResult Fail(string reason) + => new(null, new Problem(InvalidMethod, Location, MethodName, reason)); + + public CollectionExpectationResult FailCollection(string reason) + => new(null, new Problem(InvalidMethod, Location, MethodName, reason)); + + public ClassModel ToClassModel(GeneratorAttributeSyntaxContext context, string hintSuffix) + => new( + new EquatableArray(((CompilationUnitSyntax)context.TargetNode.SyntaxTree.GetRoot()).Usings + .Where(u => u.GlobalKeyword.IsKind(SyntaxKind.None)) + .Select(u => u.ToString()) + .ToImmutableArray()), + new EquatableArray(context.TargetNode.Ancestors().OfType() + .Reverse() + .SelectMany(n => n.Usings) + .Select(u => u.ToString()) + .ToImmutableArray()), + Class.ContainingNamespace.IsGlobalNamespace + ? null + : Class.ContainingNamespace.ToDisplayString(NamespaceFormat), + Escape(Class.Name), + SyntaxFacts.GetText(Class.DeclaredAccessibility), + GetMethodAccessibility(Class, SignatureParameters), + $"{Class.ToDisplayString()}.{ConstraintPrefix}{hintSuffix}.g.cs", + Escape(Method.Name), + new EquatableArray(ExpectationParameters + .Select(p => new ParameterModel(Escape(p.Name), p.Type.ToDisplayString(TypeFormat), p.IsParams, + p.Type.IsReferenceType && p.NullableAnnotation == NullableAnnotation.NotAnnotated)) + .ToImmutableArray())); + + /// + /// The extension methods are public, unless the class or a type in their signature is only internal, which a + /// public method must not expose. + /// + private static string GetMethodAccessibility(INamedTypeSymbol classSymbol, + IEnumerable parameters) + => classSymbol.DeclaredAccessibility == Accessibility.Public && + parameters.All(p => GetAccessibility(p.Type) == Accessibility.Public) + ? "public" + : "internal"; + + private static bool IsCancellationToken(ITypeSymbol type) + => type is { Name: "CancellationToken", ContainingNamespace: var ns, } && + ns.ToDisplayString() == "System.Threading"; + } } diff --git a/Source/aweXpect.Core.Generators/ExpectationModel.cs b/Source/aweXpect.Core.Generators/ExpectationModel.cs index 5391ebe901..f597e71271 100644 --- a/Source/aweXpect.Core.Generators/ExpectationModel.cs +++ b/Source/aweXpect.Core.Generators/ExpectationModel.cs @@ -33,6 +33,72 @@ internal sealed record ExpectationModel( ResultModel? Result, EquatableArray Overloads); +/// +/// The collection expectation that a method marked with GenerateCollectionExpectationAttribute yields. +/// +/// The class that receives the extension methods. +/// The name of the expectation. +/// The expectation on a single item. +/// The plural of the expectation on a single item. +/// The verb in the past tense in the result, e.g. "were" in "but only 1 of 3 were". +/// The XML documentation of the summary, if given. +/// The XML documentation of the remarks, if given. +/// What the predicate returns. +/// Whether the predicate ends with a cancellation token. +/// The item types whose collections are extended. +/// Whether the referenced aweXpect.Core supports IAsyncEnumerable. +internal sealed record CollectionExpectationModel( + ClassModel Class, + string Name, + EquatableArray Text, + EquatableArray PluralText, + string Verb, + string? Summary, + string? Remarks, + PredicateKind PredicateKind, + bool PassesCancellationToken, + EquatableArray Items, + bool SupportsAsyncEnumerables); + +/// +/// The parts of a generated file that only depend on the class and the signature of the marked method. +/// +internal sealed record ClassModel( + EquatableArray Usings, + EquatableArray NamespaceUsings, + string? Namespace, + string ClassName, + string ClassAccessibility, + string MethodAccessibility, + string HintName, + string PredicateName, + EquatableArray Parameters); + +/// +/// What the marked method returns. +/// +internal enum PredicateKind +{ + Boolean, + Task, + ValueTask, +} + +/// +/// One item type whose collections the expectation extends, with its own constraints. +/// +/// The type of the items. +/// Whether the item type is , whose collections have their own elements. +/// The prefix of the names of the nested constraint classes. +/// Whether a item does not match. +/// The expression that passes the item to the predicate. +internal readonly record struct ItemModel( + string ItemType, + bool IsString, + string ConstraintPrefix, + bool FailsOnNull, + string ItemArgument); + /// /// The method that describes the subject after "but", and which of the optional arguments it takes. /// @@ -76,6 +142,12 @@ internal readonly record struct OverloadModel( /// internal sealed record ExpectationResult(ExpectationModel? Model, Problem? Problem); +/// +/// The outcome of inspecting a method marked for a collection expectation: the expectation to generate, or the +/// problem that prevents it. +/// +internal sealed record CollectionExpectationResult(CollectionExpectationModel? Model, Problem? Problem); + /// /// A diagnostic to report. /// diff --git a/Source/aweXpect.Core.Generators/ExpectationWriter.cs b/Source/aweXpect.Core.Generators/ExpectationWriter.cs index feb7046020..d270073e97 100644 --- a/Source/aweXpect.Core.Generators/ExpectationWriter.cs +++ b/Source/aweXpect.Core.Generators/ExpectationWriter.cs @@ -13,13 +13,13 @@ namespace aweXpect.Core.Generators; internal static class ExpectationWriter { private const string ConstraintResult = "global::aweXpect.Core.Constraints.ConstraintResult"; - private const string Formatter = "global::aweXpect.Formatting.Format.Formatter"; - private const string Grammars = "global::aweXpect.Core.ExpectationGrammars"; - private const string GrammarsExtensions = "global::aweXpect.Core.ExpectationGrammarsExtensions"; + internal const string Formatter = "global::aweXpect.Formatting.Format.Formatter"; + internal const string Grammars = "global::aweXpect.Core.ExpectationGrammars"; + internal const string GrammarsExtensions = "global::aweXpect.Core.ExpectationGrammarsExtensions"; private const string Outcome = "global::aweXpect.Core.Constraints.Outcome"; - private const string StringBuilder = "global::System.Text.StringBuilder"; - private const string ValueFormatters = "global::aweXpect.Formatting.ValueFormatters"; - private const string ValueTask = "global::System.Threading.Tasks.ValueTask"; + internal const string StringBuilder = "global::System.Text.StringBuilder"; + internal const string ValueFormatters = "global::aweXpect.Formatting.ValueFormatters"; + internal const string ValueTask = "global::System.Threading.Tasks.ValueTask"; public static string Write(ExpectationModel model) { @@ -60,7 +60,7 @@ public static string Write(ExpectationModel model) return sb.ToString(); } - private static void AppendUsings(StringBuilder sb, EquatableArray usings) + internal static void AppendUsings(StringBuilder sb, EquatableArray usings) { foreach (string directive in usings.Values) { @@ -91,7 +91,7 @@ private static void AppendExpectation(StringBuilder sb, ExpectationModel model, sb.AppendLine(")"); sb.AppendLine("\t{"); - AppendNullChecks(sb, model); + AppendNullChecks(sb, model.Parameters); string arguments = string.Concat(Enumerable.Range(0, model.Parameters.Count) .Select(i => model.Parameters.Count == 1 ? ", __state" : $", __state.Item{i + 1}")); string constraint = $"new {overload.ConstraintName}(__it, __grammars{arguments})"; @@ -129,9 +129,9 @@ private static void AppendExpectationHeader(StringBuilder sb, ExpectationModel m } } - private static void AppendNullChecks(StringBuilder sb, ExpectationModel model) + internal static void AppendNullChecks(StringBuilder sb, EquatableArray parameters) { - foreach (string name in model.Parameters.Values.Where(p => p.RequiresNotNull).Select(p => p.Name)) + foreach (string name in parameters.Values.Where(p => p.RequiresNotNull).Select(p => p.Name)) { string rawName = name.TrimStart('@'); sb.Append("\t\tif (").Append(name).AppendLine(" is null)"); @@ -340,7 +340,7 @@ private static string ToDocumentation(EquatableArray parts, Expectatio ? $"" : EscapeXml(part.Text))); - private static void AppendDocumentation(StringBuilder sb, string text) + internal static void AppendDocumentation(StringBuilder sb, string text) { foreach (string line in text.Replace("\r\n", "\n").Split('\n')) { @@ -348,9 +348,9 @@ private static void AppendDocumentation(StringBuilder sb, string text) } } - private static string EscapeXml(string text) + internal static string EscapeXml(string text) => text.Replace("&", "&").Replace("<", "<").Replace(">", ">"); - private static string Literal(string text) + internal static string Literal(string text) => SymbolDisplay.FormatLiteral(text, true); } diff --git a/Source/aweXpect.Core/Core/Extending/GenerateCollectionExpectationAttribute.cs b/Source/aweXpect.Core/Core/Extending/GenerateCollectionExpectationAttribute.cs new file mode 100644 index 0000000000..74c6073248 --- /dev/null +++ b/Source/aweXpect.Core/Core/Extending/GenerateCollectionExpectationAttribute.cs @@ -0,0 +1,87 @@ +using System; + +namespace aweXpect.Core.Extending; + +/// +/// Generates an expectation on the elements of a collection from the marked method, which +/// decides whether a single item meets it, e.g. That(tracks).All().AreRadioFriendly(). +/// +/// +/// The method follows the rules of : it returns +/// , or +/// of , its first parameter is the +/// item, the other parameters become the parameters of the expectation, and it may end with a +/// . Both attributes can mark the same method. +/// +/// The expectation extends the elements that a quantifier like All() or AtLeast(2) selects, of every +/// kind of collection that can hold the item. A item does not match, unless the item +/// parameter is nullable: then the method decides, and [DisallowNull] on the parameter restores that a +/// item does not match. +/// +[AttributeUsage(AttributeTargets.Method)] +public sealed class GenerateCollectionExpectationAttribute : Attribute +{ + /// + /// Generates the expectation on the elements of a collection, with the + /// on a single item and its plural. + /// + public GenerateCollectionExpectationAttribute(string name, string expectationText, string pluralExpectationText) + { + Name = name; + ExpectationText = expectationText; + PluralExpectationText = pluralExpectationText; + } + + /// + /// Generates the expectation on the elements of a collection, whose text on a single + /// item is the expectation text of the on the same method, without + /// {not}. + /// + /// + /// The method has to be marked with as well. + /// + public GenerateCollectionExpectationAttribute(string name, string pluralExpectationText) + { + Name = name; + PluralExpectationText = pluralExpectationText; + } + + /// + /// The name of the expectation, e.g. AreRadioFriendly. + /// + public string Name { get; } + + /// + /// The text of the expectation on a single item in the failure message, e.g. "is radio friendly" in + /// "is radio friendly for all items", or to use the expectation text of the + /// on the same method. + /// + /// + /// The quantifier carries the negation, so the text is never negated. Its placeholders name parameters of the + /// method, whose formatted values replace them. + /// + public string? ExpectationText { get; } + + /// + /// The plural of the , e.g. "are radio friendly" in + /// "has values of which at least 2 are radio friendly". + /// + public string PluralExpectationText { get; } + + /// + /// Whether an expectation on a non-nullable value type also extends the collections of its nullable type, in + /// which a item does not match. Defaults to . + /// + public bool NullableOverload { get; set; } = true; + + /// + /// The XML documentation of the summary of the expectation, instead of one that is derived from the + /// . + /// + public string? Summary { get; set; } + + /// + /// The XML documentation of the remarks of the expectation. + /// + public string? Remarks { get; set; } +} diff --git a/Source/aweXpect.Core/Core/Extending/GeneratedAsyncCollectionConstraint.cs b/Source/aweXpect.Core/Core/Extending/GeneratedAsyncCollectionConstraint.cs new file mode 100644 index 0000000000..e92cd4f7ec --- /dev/null +++ b/Source/aweXpect.Core/Core/Extending/GeneratedAsyncCollectionConstraint.cs @@ -0,0 +1,80 @@ +#if NET8_0_OR_GREATER +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using aweXpect.Core.Constraints; +using aweXpect.Core.EvaluationContext; +using aweXpect.Options; + +namespace aweXpect.Core.Extending; + +/// +/// The base class of the constraints that generates for an +/// , which classify every item with . +/// +/// +/// The items are only read until the outcome is determined. +/// +/// The type of the items in the collection. +/// The name of the subject. +/// The grammars of the expectation. +/// The quantifier for the items. +public abstract class GeneratedAsyncCollectionConstraint( + string it, + ExpectationGrammars grammars, + EnumerableQuantifier quantifier) + : QuantifiedCollectionConstraintBase?, TItem>(it, grammars, quantifier), + IAsyncContextConstraint?> +{ + private IMaterializedAsyncEnumerable? _collection; + + /// + public async ValueTask IsMetBy(IAsyncEnumerable? actual, IEvaluationContext context, + CancellationToken cancellationToken) + { + StartEvaluation(); + Actual = actual; + _collection = null; + if (actual is null) + { + return this; + } + + IAsyncEnumerable items = context.UseMaterializedAsyncEnumerable(actual, cancellationToken); + _collection = items as IMaterializedAsyncEnumerable; + try + { + await foreach (TItem item in items) + { + Record(item, await IsMatch(item, cancellationToken)); + if (IsDetermined) + { + CompleteEarly(); + return this; + } + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + Outcome = Outcome.Undecided; + return this; + } + + Complete(); + return this; + } + + /// + /// Whether the matches the expectation. + /// + protected abstract ValueTask IsMatch(TItem item, CancellationToken cancellationToken); + + /// + public override void AppendContexts(ResultContextCollector contexts) + { + contexts.AddCollectionContext(_collection); + base.AppendContexts(contexts); + } +} +#endif diff --git a/Source/aweXpect.Core/Core/Extending/GeneratedCollectionConstraint.cs b/Source/aweXpect.Core/Core/Extending/GeneratedCollectionConstraint.cs new file mode 100644 index 0000000000..3449704644 --- /dev/null +++ b/Source/aweXpect.Core/Core/Extending/GeneratedCollectionConstraint.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using aweXpect.Core.Constraints; +using aweXpect.Core.EvaluationContext; +using aweXpect.Core.Helpers; +using aweXpect.Options; + +namespace aweXpect.Core.Extending; + +/// +/// The base class of the constraints that generates for a +/// collection that is enumerated synchronously, which classify every item with . +/// +/// +/// A collection whose number of items is known is read to its end, so that the result counts all items, e.g. "but +/// only 2 of 5 were". Any other collection is only read until the outcome is determined. +/// +/// The type of the collection. +/// The type of the items in the collection. +/// The name of the subject. +/// The grammars of the expectation. +/// The quantifier for the items. +public abstract class GeneratedCollectionConstraint( + string it, + ExpectationGrammars grammars, + EnumerableQuantifier quantifier) + : QuantifiedCollectionConstraintBase(it, grammars, quantifier), + IAsyncContextConstraint + where TCollection : IEnumerable? +{ + private static readonly bool IsImmutableArray = typeof(TCollection).IsValueType && + typeof(TCollection).IsGenericType && + typeof(TCollection).GetGenericTypeDefinition().FullName == + "System.Collections.Immutable.ImmutableArray`1"; + + private IEnumerable? _collection; + private bool _isDefaultImmutableArray; + + /// + /// + /// When throws for an item after the ones that determine the outcome, the reading ends + /// there, so that the outcome is the same as for a collection that is read only until the outcome is determined. + /// + public async ValueTask IsMetBy(TCollection actual, IEvaluationContext context, + CancellationToken cancellationToken) + { + StartEvaluation(); + Actual = actual; + _collection = null; + _isDefaultImmutableArray = false; + if (actual is null) + { + return this; + } + + if (IsImmutableArray && IsDefault((ICollection)actual)) + { + _isDefaultImmutableArray = true; + Outcome = Outcome.FailureBothWays; + return this; + } + + IEnumerable items = context.UseMaterializedEnumerable(actual); + _collection = items; + bool readsAllItems = actual is ICollection or IReadOnlyCollection; + bool hasItems = false; + foreach (TItem item in items) + { + if (cancellationToken.IsCancellationRequested) + { + Outcome = Outcome.Undecided; + return this; + } + + bool isMatch; + try + { + isMatch = await IsMatch(item, cancellationToken); + } + catch (Exception) when (hasItems && IsDetermined) + { + CompleteEarly(); + return this; + } + + hasItems = true; + Record(item, isMatch); + if (!readsAllItems && IsDetermined) + { + CompleteEarly(); + return this; + } + } + + Complete(); + return this; + } + + /// + /// Whether the matches the expectation. + /// + protected abstract ValueTask IsMatch(TItem item, CancellationToken cancellationToken); + + /// + public override void AppendContexts(ResultContextCollector contexts) + { + contexts.AddCollectionContext(_collection); + base.AppendContexts(contexts); + } + + /// + protected override void AppendNormalResult(StringBuilder stringBuilder, string? indentation = null) + { + if (_isDefaultImmutableArray) + { + stringBuilder.ItWasNull(It, Grammars); + } + else + { + base.AppendNormalResult(stringBuilder, indentation); + } + } + + /// + protected override void AppendNegatedResult(StringBuilder stringBuilder, string? indentation = null) + => AppendNormalResult(stringBuilder, indentation); + + /// + /// A default ImmutableArray<T> is the struct's version of a collection, and + /// its count is the cheapest member that tells it apart, as it throws only for a default one. + /// + private static bool IsDefault(ICollection immutableArray) + { + try + { + _ = immutableArray.Count; + return false; + } + catch (InvalidOperationException) + { + return true; + } + } +} diff --git a/Source/aweXpect.Core/PublicAPI/net10.0/PublicAPI.Unshipped.txt b/Source/aweXpect.Core/PublicAPI/net10.0/PublicAPI.Unshipped.txt index b5603c1c41..5e325db1c4 100644 --- a/Source/aweXpect.Core/PublicAPI/net10.0/PublicAPI.Unshipped.txt +++ b/Source/aweXpect.Core/PublicAPI/net10.0/PublicAPI.Unshipped.txt @@ -23,3 +23,27 @@ aweXpect.Core.Extending.GenerateExpectationAttribute.NegatedName.get -> string? aweXpect.Core.Extending.GenerateExpectationAttribute.NegatedName.set -> void aweXpect.Options.StringEqualityOptions.GetOccurrenceDetails(string! actual, string! expected, int count) -> string! static aweXpect.Core.ResultContextCollectorExtensions.AddStringDifferencesContext(this aweXpect.Core.ResultContextCollector! contexts, string? actual, string? expected, aweXpect.Options.StringEqualityOptions! options, aweXpect.Core.ExpectationGrammars grammars) -> void +abstract aweXpect.Core.Extending.GeneratedAsyncCollectionConstraint.IsMatch(TItem item, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +abstract aweXpect.Core.Extending.GeneratedCollectionConstraint.IsMatch(TItem item, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.ExpectationText.get -> string? +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.GenerateCollectionExpectationAttribute(string! name, string! expectationText, string! pluralExpectationText) -> void +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.GenerateCollectionExpectationAttribute(string! name, string! pluralExpectationText) -> void +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Name.get -> string! +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.NullableOverload.get -> bool +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.NullableOverload.set -> void +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.PluralExpectationText.get -> string! +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Remarks.get -> string? +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Remarks.set -> void +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Summary.get -> string? +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Summary.set -> void +aweXpect.Core.Extending.GeneratedAsyncCollectionConstraint +aweXpect.Core.Extending.GeneratedAsyncCollectionConstraint.GeneratedAsyncCollectionConstraint(string! it, aweXpect.Core.ExpectationGrammars grammars, aweXpect.Options.EnumerableQuantifier! quantifier) -> void +aweXpect.Core.Extending.GeneratedAsyncCollectionConstraint.IsMetBy(System.Collections.Generic.IAsyncEnumerable? actual, aweXpect.Core.EvaluationContext.IEvaluationContext! context, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +aweXpect.Core.Extending.GeneratedCollectionConstraint +aweXpect.Core.Extending.GeneratedCollectionConstraint.GeneratedCollectionConstraint(string! it, aweXpect.Core.ExpectationGrammars grammars, aweXpect.Options.EnumerableQuantifier! quantifier) -> void +aweXpect.Core.Extending.GeneratedCollectionConstraint.IsMetBy(TCollection actual, aweXpect.Core.EvaluationContext.IEvaluationContext! context, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +override aweXpect.Core.Extending.GeneratedAsyncCollectionConstraint.AppendContexts(aweXpect.Core.ResultContextCollector! contexts) -> void +override aweXpect.Core.Extending.GeneratedCollectionConstraint.AppendContexts(aweXpect.Core.ResultContextCollector! contexts) -> void +override aweXpect.Core.Extending.GeneratedCollectionConstraint.AppendNegatedResult(System.Text.StringBuilder! stringBuilder, string? indentation = null) -> void +override aweXpect.Core.Extending.GeneratedCollectionConstraint.AppendNormalResult(System.Text.StringBuilder! stringBuilder, string? indentation = null) -> void diff --git a/Source/aweXpect.Core/PublicAPI/net8.0/PublicAPI.Unshipped.txt b/Source/aweXpect.Core/PublicAPI/net8.0/PublicAPI.Unshipped.txt index b5603c1c41..5e325db1c4 100644 --- a/Source/aweXpect.Core/PublicAPI/net8.0/PublicAPI.Unshipped.txt +++ b/Source/aweXpect.Core/PublicAPI/net8.0/PublicAPI.Unshipped.txt @@ -23,3 +23,27 @@ aweXpect.Core.Extending.GenerateExpectationAttribute.NegatedName.get -> string? aweXpect.Core.Extending.GenerateExpectationAttribute.NegatedName.set -> void aweXpect.Options.StringEqualityOptions.GetOccurrenceDetails(string! actual, string! expected, int count) -> string! static aweXpect.Core.ResultContextCollectorExtensions.AddStringDifferencesContext(this aweXpect.Core.ResultContextCollector! contexts, string? actual, string? expected, aweXpect.Options.StringEqualityOptions! options, aweXpect.Core.ExpectationGrammars grammars) -> void +abstract aweXpect.Core.Extending.GeneratedAsyncCollectionConstraint.IsMatch(TItem item, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +abstract aweXpect.Core.Extending.GeneratedCollectionConstraint.IsMatch(TItem item, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.ExpectationText.get -> string? +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.GenerateCollectionExpectationAttribute(string! name, string! expectationText, string! pluralExpectationText) -> void +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.GenerateCollectionExpectationAttribute(string! name, string! pluralExpectationText) -> void +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Name.get -> string! +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.NullableOverload.get -> bool +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.NullableOverload.set -> void +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.PluralExpectationText.get -> string! +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Remarks.get -> string? +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Remarks.set -> void +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Summary.get -> string? +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Summary.set -> void +aweXpect.Core.Extending.GeneratedAsyncCollectionConstraint +aweXpect.Core.Extending.GeneratedAsyncCollectionConstraint.GeneratedAsyncCollectionConstraint(string! it, aweXpect.Core.ExpectationGrammars grammars, aweXpect.Options.EnumerableQuantifier! quantifier) -> void +aweXpect.Core.Extending.GeneratedAsyncCollectionConstraint.IsMetBy(System.Collections.Generic.IAsyncEnumerable? actual, aweXpect.Core.EvaluationContext.IEvaluationContext! context, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +aweXpect.Core.Extending.GeneratedCollectionConstraint +aweXpect.Core.Extending.GeneratedCollectionConstraint.GeneratedCollectionConstraint(string! it, aweXpect.Core.ExpectationGrammars grammars, aweXpect.Options.EnumerableQuantifier! quantifier) -> void +aweXpect.Core.Extending.GeneratedCollectionConstraint.IsMetBy(TCollection actual, aweXpect.Core.EvaluationContext.IEvaluationContext! context, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +override aweXpect.Core.Extending.GeneratedAsyncCollectionConstraint.AppendContexts(aweXpect.Core.ResultContextCollector! contexts) -> void +override aweXpect.Core.Extending.GeneratedCollectionConstraint.AppendContexts(aweXpect.Core.ResultContextCollector! contexts) -> void +override aweXpect.Core.Extending.GeneratedCollectionConstraint.AppendNegatedResult(System.Text.StringBuilder! stringBuilder, string? indentation = null) -> void +override aweXpect.Core.Extending.GeneratedCollectionConstraint.AppendNormalResult(System.Text.StringBuilder! stringBuilder, string? indentation = null) -> void diff --git a/Source/aweXpect.Core/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt b/Source/aweXpect.Core/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt index b5603c1c41..2127a89be4 100644 --- a/Source/aweXpect.Core/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt +++ b/Source/aweXpect.Core/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt @@ -23,3 +23,22 @@ aweXpect.Core.Extending.GenerateExpectationAttribute.NegatedName.get -> string? aweXpect.Core.Extending.GenerateExpectationAttribute.NegatedName.set -> void aweXpect.Options.StringEqualityOptions.GetOccurrenceDetails(string! actual, string! expected, int count) -> string! static aweXpect.Core.ResultContextCollectorExtensions.AddStringDifferencesContext(this aweXpect.Core.ResultContextCollector! contexts, string? actual, string? expected, aweXpect.Options.StringEqualityOptions! options, aweXpect.Core.ExpectationGrammars grammars) -> void +abstract aweXpect.Core.Extending.GeneratedCollectionConstraint.IsMatch(TItem item, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.ExpectationText.get -> string? +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.GenerateCollectionExpectationAttribute(string! name, string! expectationText, string! pluralExpectationText) -> void +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.GenerateCollectionExpectationAttribute(string! name, string! pluralExpectationText) -> void +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Name.get -> string! +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.NullableOverload.get -> bool +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.NullableOverload.set -> void +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.PluralExpectationText.get -> string! +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Remarks.get -> string? +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Remarks.set -> void +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Summary.get -> string? +aweXpect.Core.Extending.GenerateCollectionExpectationAttribute.Summary.set -> void +aweXpect.Core.Extending.GeneratedCollectionConstraint +aweXpect.Core.Extending.GeneratedCollectionConstraint.GeneratedCollectionConstraint(string! it, aweXpect.Core.ExpectationGrammars grammars, aweXpect.Options.EnumerableQuantifier! quantifier) -> void +aweXpect.Core.Extending.GeneratedCollectionConstraint.IsMetBy(TCollection actual, aweXpect.Core.EvaluationContext.IEvaluationContext! context, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +override aweXpect.Core.Extending.GeneratedCollectionConstraint.AppendContexts(aweXpect.Core.ResultContextCollector! contexts) -> void +override aweXpect.Core.Extending.GeneratedCollectionConstraint.AppendNegatedResult(System.Text.StringBuilder! stringBuilder, string? indentation = null) -> void +override aweXpect.Core.Extending.GeneratedCollectionConstraint.AppendNormalResult(System.Text.StringBuilder! stringBuilder, string? indentation = null) -> void diff --git a/Tests/aweXpect.Core.Tests/Core/Extending/GenerateCollectionExpectationAttributeTests.cs b/Tests/aweXpect.Core.Tests/Core/Extending/GenerateCollectionExpectationAttributeTests.cs new file mode 100644 index 0000000000..d0130d87cd --- /dev/null +++ b/Tests/aweXpect.Core.Tests/Core/Extending/GenerateCollectionExpectationAttributeTests.cs @@ -0,0 +1,531 @@ +using System.Collections.Generic; +using System.Threading; +using aweXpect.Core.Extending; +using aweXpect.Core.Tests.TestHelpers; +#if NET8_0_OR_GREATER +using System.Collections.Immutable; +#endif + +namespace aweXpect.Core.Tests.Core.Extending; + +public sealed class GenerateCollectionExpectationAttributeTests +{ +#if NET8_0_OR_GREATER + [Test] + public async Task AsyncEnumerable_WhenCanceled_ShouldBeUndecided() + { + IAsyncEnumerable subject = ToAsyncEnumerable(7, 7); + using CancellationTokenSource cts = new(); + cts.Cancel(); + + async Task Act() + => await That(subject).All().AreLucky().WithCancellation(cts.Token); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is lucky for all items, + but it could not be verified, because the evaluation was already canceled + """); + } + + [Test] + public async Task AsyncEnumerable_WhenMet_ShouldSucceed() + { + IAsyncEnumerable subject = ToAsyncEnumerable(7, 7); + + async Task Act() + => await That(subject).All().AreLucky(); + + await That(Act).DoesNotThrow(); + } + + [Test] + public async Task AsyncEnumerable_WhenNotMet_ShouldFail() + { + IAsyncEnumerable subject = ToAsyncEnumerable(7, 1, 7); + + async Task Act() + => await That(subject).All().AreLucky(); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is lucky for all items, + but only 1 of at least 2 were + + Not matching items: + [1, (… and maybe more)] + + Collection: + [7, 1, (… and maybe more)] + """); + } + + [Test] + public async Task AsyncEnumerable_WhenNull_ShouldFail() + { + IAsyncEnumerable? subject = null; + + async Task Act() + => await That(subject).All().AreLucky(); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is lucky for all items, + but it was + """); + } +#endif + + [Test] + public async Task AsyncPredicate_ShouldReceiveTheCancellationTokenOfTheEvaluation() + { + Account[] subject = [new("Alice", 1), new("Bob", 1),]; + using CancellationTokenSource cts = new(); + + await That(subject).All().AreVerified().WithCancellation(cts.Token); + + await That(subject).All().Satisfy(x => x.ReceivedToken.CanBeCanceled) + .Because("the token of the evaluation is passed on to the predicate for every item"); + } + + [Test] + public async Task AsyncPredicate_WhenNotMet_ShouldFail() + { + Account[] subject = [new("Alice", 6), new("Bob", 1),]; + + async Task Act() + => await That(subject).All().ArePremium(); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is premium for all items, + but only 1 of 2 were + + Not matching items: + [ + Bob + ] + + Collection: + [ + Alice, + Bob + ] + """); + } + + [Test] + public async Task AtLeast_WhenNotMet_ShouldFail() + { + int[] subject = [7, 1, 2,]; + + async Task Act() + => await That(subject).AtLeast(2).AreLucky(); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is lucky for at least 2 items, + but only 1 of 3 were + + Not matching items: + [1, 2] + + Collection: + [7, 1, 2] + """); + } + + [Test] + public async Task Attribute_ShouldKeepTheTextsAndTheOptions() + { + GenerateCollectionExpectationAttribute subject = new("AreLucky", "is lucky", "are lucky") + { + NullableOverload = false, + Summary = "summary", + Remarks = "remarks", + }; + + await That(subject.Name).IsEqualTo("AreLucky"); + await That(subject.ExpectationText).IsEqualTo("is lucky"); + await That(subject.PluralExpectationText).IsEqualTo("are lucky"); + await That(subject.NullableOverload).IsFalse(); + await That(subject.Summary).IsEqualTo("summary"); + await That(subject.Remarks).IsEqualTo("remarks"); + } + + [Test] + public async Task Attribute_WithoutExpectationText_ShouldLeaveItToTheExpectation() + { + GenerateCollectionExpectationAttribute subject = new("AreLucky", "are lucky"); + + await That(subject.Name).IsEqualTo("AreLucky"); + await That(subject.ExpectationText).IsNull() + .Because("the generator takes the text of [GenerateExpectation] on the same method"); + await That(subject.PluralExpectationText).IsEqualTo("are lucky"); + await That(subject.NullableOverload).IsTrue(); + } + + [Test] + public async Task Canceled_ShouldBeUndecided() + { + int[] subject = [7, 7,]; + using CancellationTokenSource cts = new(); + cts.Cancel(); + + async Task Act() + => await That(subject).All().AreLucky().WithCancellation(cts.Token); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is lucky for all items, + but it could not be verified, because the evaluation was already canceled + + Collection: + [7, 7] + """); + } + +#if NET8_0_OR_GREATER + [Test] + public async Task DefaultImmutableArray_ShouldFail() + { + ImmutableArray subject = default; + + async Task Act() + => await That(subject).All().AreLucky(); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is lucky for all items, + but it was + """); + } +#endif + + [Test] + public async Task DoesNotComplyWith_ShouldNegateTheQuantifier() + { + int[] subject = [7, 7,]; + + async Task Act() + => await That(subject).DoesNotComplyWith(x => x.All().AreLucky()); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is lucky not for all items, + but all 2 were + + Collection: + [7, 7] + """); + } + + [Test] + public async Task EndlessCollection_ShouldStopOnceTheOutcomeIsDetermined() + { + IEnumerable subject = Endless(7); + + async Task Act() + => await That(subject).AtLeast(2).AreLucky(); + + await That(Act).DoesNotThrow() + .Because("an enumerable without a known count is only read until the outcome is determined"); + } + +#if NET8_0_OR_GREATER + [Test] + public async Task ImmutableArray_WhenNotMet_ShouldFail() + { + ImmutableArray subject = [7, 1,]; + + async Task Act() + => await That(subject).All().AreLucky(); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is lucky for all items, + but only 1 of 2 were + + Not matching items: + [1] + + Collection: + [7, 1] + """); + } +#endif + + [Test] + public async Task Nested_ShouldUseThePluralText() + { + Dictionary subject = new() + { + ["a"] = 7, + ["b"] = 1, + ["c"] = 2, + }; + + async Task Act() + => await That(subject).Values.AtLeast(2).AreLucky(); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + has values of which at least 2 are lucky, + but only 1 of 3 were + + Not matching items (values): + [1, 2] + + Collection (values): + [7, 1, 2] + """); + } + + [Test] + public async Task NullableItemParameter_ShouldLetThePredicateDecide() + { + Account?[] subject = [null, new("", 1),]; + + async Task Act() + => await That(subject).All().AreNullOrUnnamed(); + + await That(Act).DoesNotThrow(); + } + + [Test] + public async Task NullableOverload_WhenItemIsNull_ShouldNotMatch() + { + int?[] subject = [7, null,]; + + async Task Act() + => await That(subject).All().AreLucky(); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is lucky for all items, + but only 1 of 2 were + + Not matching items: + [] + + Collection: + [7, ] + """); + } + + [Test] + public async Task NullableValueTypeWithDisallowNull_WhenItemIsNull_ShouldNotMatch() + { + int?[] subject = [1, null,]; + + async Task Act() + => await That(subject).All().AreOdd(); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is odd for all items, + but only 1 of 2 were + + Not matching items: + [] + + Collection: + [1, ] + """); + } + + [Test] + public async Task NullCollection_ShouldFail() + { + IEnumerable? subject = null; + + async Task Act() + => await That(subject).All().AreLucky(); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is lucky for all items, + but it was + """); + } + + [Test] + public async Task NullItem_ShouldNotMatch() + { + Account?[] subject = [new("Alice", 1), null,]; + + async Task Act() + => await That(subject).All().HaveOwner("Alice"); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + has owner "Alice" for all items, + but only 1 of 2 did + + Not matching items: + [ + + ] + + Collection: + [ + Alice, + + ] + """); + } + + [Test] + public async Task ParameterIsNull_ShouldThrowArgumentNullException() + { + Account[] subject = [new("Alice", 1),]; + + async Task Act() + => await That(subject).All().HaveOwner(null!); + + await That(Act).Throws() + .WithParamName("owner").And + .WithMessage("The 'owner' cannot be null.").AsPrefix(); + } + + [Test] + public async Task Parameters_ShouldBeFormattedInTheExpectation() + { + int[] subject = [1, 4, 9,]; + + async Task Act() + => await That(subject).All().AreBetween(1, 5); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is between 1 and 5 for all items, + but only 2 of 3 were + + Not matching items: + [9] + + Collection: + [1, 4, 9] + """); + } + + [Test] + public async Task PredicateThrowsAfterTheOutcomeIsDetermined_ShouldStopReadingTheItems() + { + int[] subject = [12, -1, 3,]; + + async Task Act() + => await That(subject).All().AreSingleDigits(); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is a single digit for all items, + but none of at least 1 were + + Not matching items: + [12, (… and maybe more)] + + Collection: + [12, -1, 3] + """) + .Because("the items after the one that determines the outcome cannot change it"); + } + + [Test] + public async Task PredicateThrowsBeforeTheOutcomeIsDetermined_ShouldFail() + { + int[] subject = [-1, 3,]; + + async Task Act() + => await That(subject).All().AreSingleDigits(); + + await That(Act).Throws() + .WithParamName("value"); + } + + [Test] + public async Task Strings_ShouldUseTheStringElements() + { + string?[] subject = ["A", "b", null,]; + + async Task Act() + => await That(subject).None().AreShouted(); + + await That(Act).Throws() + .WithMessage(""" + Expected that subject + is shouted for no items, + but 1 of 3 were + + Matching items: + [ + "A" + ] + + Collection: + [ + "A", + "b", + + ] + """); + } + + [Test] + public async Task SyncPredicate_ShouldReceiveTheCancellationTokenOfTheEvaluation() + { + Account[] subject = [new("Alice", 1),]; + using CancellationTokenSource cts = new(); + + await That(subject).All().AreActive().WithCancellation(cts.Token); + + await That(subject[0].ReceivedToken.CanBeCanceled).IsTrue() + .Because("the token of the evaluation is passed on to the predicate"); + } + + [Test] + public async Task WhenMet_ShouldSucceed() + { + int[] subject = [7, 7,]; + + async Task Act() + => await That(subject).All().AreLucky(); + + await That(Act).DoesNotThrow(); + } + + private static IEnumerable Endless(int value) + { + while (true) + { + yield return value; + } + } + +#if NET8_0_OR_GREATER + private static async IAsyncEnumerable ToAsyncEnumerable(params int[] values) + { + foreach (int value in values) + { + await Task.Yield(); + yield return value; + } + } +#endif +} diff --git a/Tests/aweXpect.Core.Tests/TestHelpers/GeneratedExpectations.cs b/Tests/aweXpect.Core.Tests/TestHelpers/GeneratedExpectations.cs index 857f78b4d2..7350952847 100644 --- a/Tests/aweXpect.Core.Tests/TestHelpers/GeneratedExpectations.cs +++ b/Tests/aweXpect.Core.Tests/TestHelpers/GeneratedExpectations.cs @@ -16,10 +16,12 @@ internal sealed class Account(string name, int level) internal static partial class ThatAccount { + [GenerateCollectionExpectation("HaveOwner", "have owner {owner}")] [GenerateExpectation("HasOwner", "has owner {owner}", NegatedName = "DoesNotHaveOwner", NegatedExpectationText = "does not have owner {owner}")] private static bool HasOwner(Account account, string owner) => account.Name == owner; + [GenerateCollectionExpectation("AreActive", "is active", "are active")] [GenerateExpectation("Is{Not}Active", "is {not} active")] private static bool IsActive(Account account, CancellationToken cancellationToken) { @@ -33,10 +35,12 @@ private static bool IsActive(Account account, CancellationToken cancellationToke [GenerateExpectation("Is{Not}Named", "is {not} named {name}")] private static bool IsNamed(Account account, string name) => account.Name == name; + [GenerateCollectionExpectation("AreNullOrUnnamed", "is null or unnamed", "are null or unnamed")] [GenerateExpectation("Is{Not}NullOrUnnamed", "is {not} null or unnamed")] private static bool IsNullOrUnnamed([NotNullWhen(false)] Account? account) => account is null || account.Name.Length == 0; + [GenerateCollectionExpectation("ArePremium", "is premium", "are premium")] [GenerateExpectation("Is{Not}Premium", "is {not} premium")] private static async ValueTask IsPremium(Account account) { @@ -47,6 +51,7 @@ private static async ValueTask IsPremium(Account account) [GenerateExpectation("IsTheOwner", "is {not} the owner")] private static bool IsTheOwner(Account account) => account.Name == "owner"; + [GenerateCollectionExpectation("AreVerified", "is verified", "are verified")] [GenerateExpectation("Is{Not}Verified", "is {not} verified")] private static async Task IsVerified(Account account, CancellationToken cancellationToken) { @@ -70,12 +75,27 @@ internal static partial class ThatLuckyNumber [GenerateExpectation("Is{Not}AnyOf", "is {not} any of {values}")] private static bool IsAnyOf(int value, params int[] values) => values.Contains(value); + [GenerateCollectionExpectation("AreBetween", "is between {minimum} and {maximum}", "are between {minimum} and {maximum}", + NullableOverload = false)] [GenerateExpectation("Is{Not}Between", "is {not} between {minimum} and {maximum}", NullableOverload = false)] private static bool IsBetween(int value, int minimum, int maximum) => value >= minimum && value <= maximum; + [GenerateCollectionExpectation("AreLucky", "are lucky")] [GenerateExpectation("Is{Not}Lucky", "is {not} lucky")] private static bool IsLucky(int value) => value == 7; + [GenerateCollectionExpectation("AreOdd", "is odd", "are odd")] [GenerateExpectation("Is{Not}Odd", "is {not} odd")] private static bool IsOdd([DisallowNull] int? value) => value.GetValueOrDefault() % 2 != 0; + + [GenerateCollectionExpectation("AreSingleDigits", "is a single digit", "are single digits")] + private static bool IsSingleDigit(int value) + => value >= 0 ? value < 10 : throw new ArgumentOutOfRangeException(nameof(value)); +} + +internal static partial class ThatWord +{ + [GenerateCollectionExpectation("AreShouted", "is shouted", "are shouted")] + private static bool IsShouted(string value) + => string.Equals(value, value.ToUpperInvariant(), StringComparison.Ordinal); } diff --git a/Tests/aweXpect.Generators.Tests/CoreCollectionExpectationGeneratorTests.cs b/Tests/aweXpect.Generators.Tests/CoreCollectionExpectationGeneratorTests.cs new file mode 100644 index 0000000000..d4d1dc46f8 --- /dev/null +++ b/Tests/aweXpect.Generators.Tests/CoreCollectionExpectationGeneratorTests.cs @@ -0,0 +1,530 @@ +using System.Linq; +using aweXpect.Core.Generators; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace aweXpect.Generators.Tests; + +public sealed class CoreCollectionExpectationGeneratorTests +{ + [Test] + public async Task BothAttributes_ShouldGenerateBothExpectations() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreZero", "is zero", "are zero")] + [GenerateExpectation("Is{Not}Zero", "is {not} zero")] + private static bool IsZero(int value) => value == 0; + """); + + await ThatCompiles(result); + await That(result.Generated).Contains(" IsZero(this global::aweXpect.Core.IThat subject)"); + await That(result.Generated).Contains(" AreZero(this global::aweXpect.IEnumerableElements elements)"); + } + + [Test] + [Arguments("is {not} zero", "is zero")] + [Arguments("is zero", "is zero")] + public async Task BothAttributes_WithoutExpectationText_ShouldUseTheExpectationTextWithoutNot( + string expectationText, string expectedText) + { + GeneratorRunner.GeneratorResult result = RunOn( + $$""" + [GenerateCollectionExpectation("AreZero", "are zero")] + [GenerateExpectation("Is{Not}Zero", "{{expectationText}}", NegatedExpectationText = "is not zero")] + private static bool IsZero(int value) => value == 0; + """); + + await ThatCompiles(result); + await That(result.Generated).Contains($"stringBuilder.Append(\"{expectedText}\");").Exactly(4); + await That(result.Generated).Contains("stringBuilder.Append(\"are zero\");").Exactly(4); + } + + [Test] + public async Task CancellationToken_ShouldBePassedToThePredicate() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreZero", "is zero", "are zero", NullableOverload = false)] + private static bool IsZero(int value, CancellationToken cancellationToken) => value == 0; + """); + + await ThatCompiles(result); + await That(result.Generated).Contains("global::Lib.ThatSample.IsZero(item, cancellationToken)"); + await That(result.Generated).Contains(" AreZero(this global::aweXpect.IEnumerableElements elements)") + .Because("the cancellation token is no parameter of the expectation"); + } + + [Test] + public async Task ClassIsNotPartial_ShouldReportADiagnostic() + { + GeneratorRunner.GeneratorResult result = Run( + """ + using aweXpect.Core.Extending; + + namespace Lib; + + public static class ThatSample + { + [GenerateCollectionExpectation("AreZero", "is zero", "are zero")] + private static bool IsZero(int value) => value == 0; + } + """); + + await ThatReports(result, + "aweXpect4001: 'Lib.ThatSample' cannot hold the generated expectation, because extension methods need a top-level, non-generic, static partial class that is not file-local"); + } + + [Test] + public async Task ExpectationTextContainsNot_ShouldReportADiagnostic() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreZero", "is {not} zero", "are {not} zero")] + private static bool IsZero(int value) => value == 0; + """); + + await ThatReports(result, + "aweXpect4002: 'ThatSample.IsZero(int)' cannot generate an expectation, because the expectation text contains '{not}', but the quantifier carries the negation"); + } + + [Test] + public async Task ExpectationTextIsMissing_ShouldReportADiagnostic() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreZero", "are zero")] + private static bool IsZero(int value) => value == 0; + """); + + await ThatReports(result, + "aweXpect4002: 'ThatSample.IsZero(int)' cannot generate an expectation, because the expectation text is required, unless the method is also marked with [GenerateExpectation]"); + } + + [Test] + public async Task LanguageVersionIsCSharp8_ShouldCompile() + { + GeneratorRunner.GeneratorResult result = Run( + """ + using System.Diagnostics.CodeAnalysis; + using System.Threading; + using System.Threading.Tasks; + using aweXpect.Core.Extending; + + namespace Lib + { + public static partial class ThatSample + { + [GenerateCollectionExpectation("AreZero", "is zero", "are zero")] + private static bool IsZero(int value) => value == 0; + + [GenerateCollectionExpectation("AreNamed", "is named {name}", "are named {name}")] + private static bool IsNamed(string value, string name) => value == name; + + [GenerateCollectionExpectation("AreEmpty", "is empty", "are empty")] + private static bool IsEmpty(string? value) => value == ""; + + [GenerateCollectionExpectation("AreReady", "is ready", "are ready")] + private static Task IsReady(string value, CancellationToken cancellationToken) => Task.FromResult(true); + + [GenerateCollectionExpectation("AreOdd", "is odd", "are odd")] + private static ValueTask IsOdd([DisallowNull] int? value) => new ValueTask(value % 2 == 1); + } + } + """, LanguageVersion.CSharp8); + + await ThatCompiles(result); + } + + [Test] + public async Task MethodReturnsNoBoolean_ShouldReportADiagnostic() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreZero", "is zero", "are zero")] + private static int IsZero(int value) => value; + """); + + await ThatReports(result, + "aweXpect4002: 'ThatSample.IsZero(int)' cannot generate an expectation, because it returns neither bool nor Task nor ValueTask"); + } + + [Test] + public async Task NameIsInvalid_ShouldReportADiagnostic() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("Are{Not}Zero", "is zero", "are zero")] + private static bool IsZero(int value) => value == 0; + """); + + await ThatReports(result, + "aweXpect4002: 'ThatSample.IsZero(int)' cannot generate an expectation, because the name 'Are{Not}Zero' is not a valid method name"); + } + + [Test] + public async Task NameIsNull_ShouldReportADiagnostic() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation(null!, "are zero")] + private static bool IsZero(int value) => value == 0; + """); + + await ThatReports(result, + "aweXpect4002: 'ThatSample.IsZero(int)' cannot generate an expectation, because the name and the plural expectation text are required"); + } + + [Test] + public async Task NullableOverloadIsFalse_ShouldOnlyExtendTheValueType() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreZero", "is zero", "are zero", NullableOverload = false)] + private static bool IsZero(int value) => value == 0; + """); + + await ThatCompiles(result); + await That(result.Generated).DoesNotContain("int?"); + } + + [Test] + public async Task NullableReferenceType_ShouldLetThePredicateDecide() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreEmpty", "is empty", "are empty")] + private static bool IsEmpty(string? value) => value == ""; + """); + + await ThatCompiles(result); + await That(result.Generated) + .Contains("=> new global::System.Threading.Tasks.ValueTask(global::Lib.ThatSample.IsEmpty(item));") + .Exactly(2); + } + + [Test] + public async Task NullableValueType_ShouldLetThePredicateDecide() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreZero", "is zero", "are zero")] + private static bool IsZero(int? value) => value == 0; + """); + + await ThatCompiles(result); + await That(result.Generated).Contains(" AreZero(this global::aweXpect.IEnumerableElements elements)"); + await That(result.Generated) + .Contains("=> new global::System.Threading.Tasks.ValueTask(global::Lib.ThatSample.IsZero(item));") + .Exactly(2); + } + + [Test] + public async Task NullableValueTypeWithDisallowNull_ShouldNotMatchNull() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreZero", "is zero", "are zero")] + private static bool IsZero([DisallowNull] int? value) => value == 0; + """); + + await ThatCompiles(result); + await That(result.Generated).Contains(" AreZero(this global::aweXpect.IEnumerableElements elements)"); + await That(result.Generated).Contains("!(item is null) && global::Lib.ThatSample.IsZero(item.Value)").Exactly(2); + await That(result.Generated).DoesNotContain("IEnumerableElements"); + } + + [Test] + public async Task OverloadedPredicates_ShouldGenerateDistinctConstraints() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreZero", "is zero", "are zero", NullableOverload = false)] + private static bool IsZero(int value) => value == 0; + + [GenerateCollectionExpectation("AreZero", "is zero", "are zero", NullableOverload = false)] + private static bool IsZero(long value) => value == 0; + """); + + await ThatCompiles(result); + await That(result.Generated).Contains("class IsZero_GeneratedElementsConstraint<").Once(); + await That(result.Generated).Contains("class IsZero_1_GeneratedElementsConstraint<").Once(); + } + + [Test] + public async Task Parameters_ShouldBeCheckedAndPassedToThePredicate() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreNamed", "is named {name} or {alias}", "are named {name} or {alias}")] + private static bool IsNamed(string value, string name, string? alias) => value == name || value == alias; + """); + + await ThatCompiles(result); + await That(result.Generated) + .Contains("AddConstraint((elements.Quantifier, name, alias), (__state, __it, __grammars) => new ") + .Exactly(3); + await That(result.Generated).Contains("(__it, __grammars, __state.Item1, __state.Item2, __state.Item3)") + .Exactly(3); + await That(result.Generated).Contains("throw global::aweXpect.Core.Tracing.WriteException(new global::System.ArgumentNullException(nameof(name)") + .Exactly(3); + await That(result.Generated).DoesNotContain("nameof(alias)") + .Because("a nullable parameter accepts null"); + await That(result.Generated).Contains("global::Lib.ThatSample.IsNamed(item, _p0, _p1)"); + } + + [Test] + public async Task ParamsParameter_ShouldStayParams() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreAnyOf", "is any of {values}", "are any of {values}", NullableOverload = false)] + private static bool IsAnyOf(int value, params int[] values) => Array.IndexOf(values, value) >= 0; + """); + + await ThatCompiles(result); + await That(result.Generated) + .Contains(" AreAnyOf(this global::aweXpect.IEnumerableElements elements, params int[] values)"); + } + + [Test] + [Arguments("is equal to {expected}", "are equal to {other}")] + [Arguments("is equal to {other}", "are equal to {expected}")] + public async Task PlaceholderNamesNoParameter_ShouldReportADiagnostic(string text, string pluralText) + { + GeneratorRunner.GeneratorResult result = RunOn( + $$""" + [GenerateCollectionExpectation("AreEqual", "{{text}}", "{{pluralText}}")] + private static bool IsEqual(int value, int expected) => value == expected; + """); + + await ThatReports(result, + "aweXpect4002: 'ThatSample.IsEqual(int, int)' cannot generate an expectation, because the placeholder '{other}' names no parameter of the expectation"); + } + + [Test] + public async Task ReferenceType_ShouldExtendEveryKindOfCollection() + { + GeneratorRunner.GeneratorResult result = Run( + """ + using aweXpect.Core.Extending; + + namespace Lib; + + public sealed class Track(int duration) + { + public int Duration { get; } = duration; + } + + public static partial class ThatTrack + { + [GenerateCollectionExpectation("AreLong", "is long", "are long")] + private static bool IsLong(Track track) => track.Duration > 1; + } + """); + + await ThatCompiles(result); + await That(result.Generated) + .Contains("public static global::aweXpect.Results.AndOrResult, global::aweXpect.Core.IThat?>> AreLong(this global::aweXpect.IEnumerableElements elements)"); + await That(result.Generated) + .Contains("public static global::aweXpect.Results.AndOrResult> AreLong(this global::aweXpect.IStructEnumerableElements elements)"); + await That(result.Generated) + .Contains("public static global::aweXpect.Results.AndOrResult, global::aweXpect.Core.IThat?>> AreLong(this global::aweXpect.IAsyncEnumerableElements elements)"); + await That(result.Generated).Contains("!(item is null) && global::Lib.ThatTrack.IsLong(item)").Exactly(2) + .Because("a null item does not match"); + } + + [Test] + public async Task String_ShouldExtendTheStringElements() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreEmpty", "is empty", "are empty")] + private static bool IsEmpty(string value) => value.Length == 0; + """); + + await ThatCompiles(result); + await That(result.Generated).Contains(" AreEmpty(this global::aweXpect.IEnumerableStringElements elements)"); + await That(result.Generated) + .Contains(" AreEmpty(this global::aweXpect.IStructEnumerableStringElements elements)"); + await That(result.Generated).Contains(" AreEmpty(this global::aweXpect.IAsyncEnumerableStringElements elements)"); + await That(result.Generated).DoesNotContain("IEnumerableElements<"); + } + + [Test] + public async Task Summary_ShouldBeDerivedFromThePluralText() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreAbove", "is above {minimum}", "are above {minimum}", + NullableOverload = false, Remarks = "Compares the values.")] + private static bool IsAbove(int value, int minimum) => value > minimum; + """); + + await ThatCompiles(result); + await ThatContainsLines(result, + """ + /// + /// …are above . + /// + /// + /// Compares the values. + /// + """); + } + + [Test] + public async Task Texts_ShouldBeUsedForTheGrammaticalNumber() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreSingleDigits", "is a single digit", "are single digits", NullableOverload = false)] + private static bool IsSingleDigit(int value) => value < 10; + """); + + await ThatCompiles(result); + await ThatContainsLines(result, + """ + if (global::aweXpect.Core.ExpectationGrammarsExtensions.IsPlural(grammars)) + { + stringBuilder.Append("are single digits"); + } + else + { + stringBuilder.Append("is a single digit"); + } + """); + } + + [Test] + public async Task ValueTaskPredicate_ShouldBeReturnedDirectly() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreZero", "is zero", "are zero", NullableOverload = false)] + private static ValueTask IsZero(int value) => new(value == 0); + """); + + await ThatCompiles(result); + await That(result.Generated).Contains("=> global::Lib.ThatSample.IsZero(item);").Exactly(2); + } + + [Test] + public async Task ValueType_ShouldAlsoExtendTheNullableType() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateCollectionExpectation("AreZero", "is zero", "are zero")] + private static Task IsZero(int value) => Task.FromResult(value == 0); + """); + + await ThatCompiles(result); + await That(result.Generated).Contains(" AreZero(this global::aweXpect.IEnumerableElements elements)"); + await That(result.Generated).Contains(" AreZero(this global::aweXpect.IEnumerableElements elements)"); + await That(result.Generated) + .Contains("item is null ? new global::System.Threading.Tasks.ValueTask(false) : new global::System.Threading.Tasks.ValueTask(global::Lib.ThatSample.IsZero(item.Value))") + .Exactly(2); + } + + [Test] + [Arguments("is zero", "were")] + [Arguments("are zero", "were")] + [Arguments("has zero", "did")] + [Arguments("was zero", "were")] + [Arguments("were zero", "were")] + [Arguments("zeroes", "did")] + [Arguments("{value} is zero", "did")] + public async Task Verb_ShouldDependOnTheLeadingVerb(string text, string expectedVerb) + { + GeneratorRunner.GeneratorResult result = RunOn( + $$""" + [GenerateCollectionExpectation("AreZero", "{{text}}", "{{text}}", NullableOverload = false)] + private static bool IsZero(int item, int value) => item == value; + """); + + await ThatCompiles(result); + await That(result.Generated).Contains($"protected override string Verb => \"{expectedVerb}\";").Exactly(2); + } + + [Test] + public async Task WhenClassHasNoNamespace_ShouldCompile() + { + GeneratorRunner.GeneratorResult result = Run( + """ + using aweXpect.Core.Extending; + + public static partial class ThatSample + { + [GenerateCollectionExpectation("AreZero", "is zero", "are zero")] + private static bool IsZero(int value) => value == 0; + } + """); + + await ThatCompiles(result); + await That(result.Generated).DoesNotContain("namespace "); + await That(result.Generated).Contains("global::ThatSample.IsZero(item)"); + } + + [Test] + public async Task WhenOnlyTouched_ShouldReuseTheCachedExpectation() + { + GeneratorDriverRunResult result = GeneratorRunner.RunTwice(new ExpectationGenerator(), + [ + """ + using aweXpect.Core.Extending; + + namespace Lib; + + public static partial class ThatSample + { + [GenerateCollectionExpectation("AreZero", "is zero", "are zero")] + private static bool IsZero(int value) => value == 0; + } + """, + ], "// unrelated"); + + IncrementalStepRunReason[] reasons = result.Results[0].TrackedSteps["CollectionExpectations"] + .SelectMany(x => x.Outputs).Select(x => x.Reason).ToArray(); + await That(reasons).IsNotEmpty(); + await That(reasons).All() + .Satisfy(x => x is IncrementalStepRunReason.Cached or IncrementalStepRunReason.Unchanged) + .Because("the model is compared by value, so an unrelated edit does not regenerate the expectation"); + } + + private static GeneratorRunner.GeneratorResult Run(string source, + LanguageVersion languageVersion = LanguageVersion.Latest) + => GeneratorRunner.Run(new ExpectationGenerator(), [source,], true, languageVersion); + + private static GeneratorRunner.GeneratorResult RunOn(string members) + => Run($$""" + using System; + using System.Diagnostics.CodeAnalysis; + using System.Threading; + using System.Threading.Tasks; + using aweXpect.Core.Extending; + + namespace Lib; + + public static partial class ThatSample + { + {{members}} + } + """); + + private static async Task ThatCompiles(GeneratorRunner.GeneratorResult result) + { + await That(result.GeneratorDiagnostics).IsEmpty(); + await That(result.Errors.Select(x => x.ToString())).IsEmpty(); + await That(result.Warnings.Select(x => x.ToString())).IsEmpty() + .Because("the generated code has to compile without warnings in projects that treat them as errors"); + } + + private static async Task ThatContainsLines(GeneratorRunner.GeneratorResult result, string expected) + => await That(result.Generated.Replace("\r\n", "\n")).Contains(expected.Replace("\r\n", "\n")); + + private static async Task ThatReports(GeneratorRunner.GeneratorResult result, string diagnostic) + { + await That(result.GeneratorDiagnostics.Select(x => $"{x.Id}: {x.GetMessage()}")).IsEqualTo([diagnostic,]); + await That(result.Generated).IsEmpty(); + } +} diff --git a/Tests/aweXpect.Generators.Tests/CoreExpectationGeneratorTests.cs b/Tests/aweXpect.Generators.Tests/CoreExpectationGeneratorTests.cs index dc65d4df75..cea24919e3 100644 --- a/Tests/aweXpect.Generators.Tests/CoreExpectationGeneratorTests.cs +++ b/Tests/aweXpect.Generators.Tests/CoreExpectationGeneratorTests.cs @@ -267,6 +267,19 @@ await ThatReports(result, "aweXpect4002: 'ThatSample.IsZero(int)' cannot generate an expectation, because the name 'Is {Not} Zero' is not a valid method name"); } + [Test] + public async Task NameIsNull_ShouldReportADiagnostic() + { + GeneratorRunner.GeneratorResult result = RunOn( + """ + [GenerateExpectation(null!, "is {not} zero")] + private static bool IsZero(int value) => value == 0; + """); + + await ThatReports(result, + "aweXpect4002: 'ThatSample.IsZero(int)' cannot generate an expectation, because the name and the expectation text are required"); + } + [Test] public async Task NegatedExpectationText_ShouldReplaceTheDerivedText() {