How to use A class of NUnit.Framework.Syntax package

Best Nunit code snippet using NUnit.Framework.Syntax.A

UseCollectionConstraintCodeFix.cs

Source:UseCollectionConstraintCodeFix.cs Github

copy

Full Screen

2using System.Collections.Immutable;3using System.Composition;4using System.Globalization;5using System.Threading.Tasks;6using Microsoft.CodeAnalysis;7using Microsoft.CodeAnalysis.CodeActions;8using Microsoft.CodeAnalysis.CodeFixes;9using Microsoft.CodeAnalysis.CSharp;10using Microsoft.CodeAnalysis.CSharp.Syntax;11using NUnit.Analyzers.Constants;12namespace NUnit.Analyzers.UseCollectionConstraint13{14 [ExportCodeFixProvider(LanguageNames.CSharp)]15 [Shared]16 public class UseCollectionConstraintCodeFix : CodeFixProvider17 {18 public override ImmutableArray<string> FixableDiagnosticIds19 => ImmutableArray.Create(AnalyzerIdentifiers.UsePropertyConstraint);20 public sealed override FixAllProvider GetFixAllProvider()21 {22 return WellKnownFixAllProviders.BatchFixer;23 }24 public override async Task RegisterCodeFixesAsync(CodeFixContext context)25 {26 var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);27 if (root is null)28 {29 return;30 }31 context.CancellationToken.ThrowIfCancellationRequested();32 var node = root.FindNode(context.Span);33 if (node is not ArgumentSyntax actualArgument ||34 actualArgument.Expression is not MemberAccessExpressionSyntax actualExpression ||35 actualArgument.Parent is not ArgumentListSyntax argumentList ||36 argumentList.Arguments.Count <= 1 ||37 argumentList.Arguments[1] is not ArgumentSyntax constraintArgument)38 {39 return;40 }41 // We have either a MemberAccessExpression (Is.Zero) or an InvocationExpression (Is.EqualTo(0))42 var constraintMemberExpression = constraintArgument.Expression as MemberAccessExpressionSyntax;43 var constraintExpression = constraintArgument.Expression as InvocationExpressionSyntax;44 if (constraintExpression is not null)45 {46 constraintMemberExpression = constraintExpression.Expression as MemberAccessExpressionSyntax;47 }48 if (constraintMemberExpression is null)49 return;50 ExpressionSyntax innerConstraintExpression = FindLeftMostTerm(constraintMemberExpression);51 if (innerConstraintExpression is not SimpleNameSyntax simple || simple.Identifier.ValueText != NUnitFrameworkConstants.NameOfIs)52 return;53 var nodesToReplace = new Dictionary<SyntaxNode, SyntaxNode>()54 {55 // Replace <expression>.<property> with <expression> in first argument56 { actualArgument.Expression, actualExpression.Expression }57 };58 string description;59 MemberAccessExpressionSyntax? emptyOrNotEmptyExpression = MatchWithEmpty(constraintMemberExpression,60 constraintExpression, innerConstraintExpression);61 if (emptyOrNotEmptyExpression is not null)62 {63 nodesToReplace.Add(constraintArgument.Expression, emptyOrNotEmptyExpression);64 description = $"Use {emptyOrNotEmptyExpression}";65 }66 else67 {68 // Replace Is. with Has.<property>.69 var propertyName = actualExpression.Name;70 var hasPropertyExpression = SyntaxFactory.MemberAccessExpression(71 SyntaxKind.SimpleMemberAccessExpression,72 SyntaxFactory.IdentifierName(NUnitFrameworkConstants.NameOfHas),73 propertyName);74 nodesToReplace.Add(innerConstraintExpression, hasPropertyExpression);75 description = $"Use {NUnitFrameworkConstants.NameOfHas}.{propertyName}";76 }77 var newRoot = root.ReplaceNodes(nodesToReplace.Keys, (node, _) => nodesToReplace[node]);78 var codeAction = CodeAction.Create(79 description,80 _ => Task.FromResult(context.Document.WithSyntaxRoot(newRoot)),81 description);82 context.RegisterCodeFix(codeAction, context.Diagnostics);83 }84 private static MemberAccessExpressionSyntax? MatchWithEmpty(85 MemberAccessExpressionSyntax constraintMemberExpression,86 InvocationExpressionSyntax? constraintExpression,87 ExpressionSyntax innerConstraintExpression)88 {89 MemberAccessExpressionSyntax? emptyOrNotEmptyExpression = null;90 if (constraintMemberExpression.Name.Identifier.ValueText == NUnitFrameworkConstants.NameOfIsZero ||91 IsInvocationTo(constraintExpression, NUnitFrameworkConstants.NameOfIsEqualTo, "0") ||92 IsInvocationTo(constraintExpression, NUnitFrameworkConstants.NameOfIsLessThan, "1"))93 {94 // Replace: '.Zero', '.EqualTo(0)' and '.LessThan(1)' with .Empty95 emptyOrNotEmptyExpression = SyntaxFactory.MemberAccessExpression(96 SyntaxKind.SimpleMemberAccessExpression,97 constraintMemberExpression.Expression,98 SyntaxFactory.IdentifierName(NUnitFrameworkConstants.NameOfIsEmpty));99 }100 else if (constraintMemberExpression.Name.Identifier.ValueText == NUnitFrameworkConstants.NameOfIsPositive ||101 IsInvocationTo(constraintExpression, NUnitFrameworkConstants.NameOfIsGreaterThan, "0") ||102 IsInvocationTo(constraintExpression, NUnitFrameworkConstants.NameOfIsGreaterThanOrEqualTo, "1"))103 {104 // Replace:'Positive', '.GreatherThan(0)', '.GreaterThanOrEqualTo(1)' with .Not.Empty105 // Take care of double negatives: '.Not.Positive' becomes 'Empty'.106 emptyOrNotEmptyExpression = SyntaxFactory.MemberAccessExpression(107 SyntaxKind.SimpleMemberAccessExpression,108 IsNot(constraintMemberExpression) ?109 innerConstraintExpression :110 SyntaxFactory.MemberAccessExpression(111 SyntaxKind.SimpleMemberAccessExpression,112 constraintMemberExpression.Expression,113 SyntaxFactory.IdentifierName(NUnitFrameworkConstants.NameOfIsNot)),114 SyntaxFactory.IdentifierName(NUnitFrameworkConstants.NameOfIsEmpty));115 }116 return emptyOrNotEmptyExpression;117 }118 private static bool IsNot(MemberAccessExpressionSyntax constraintMemberExpression)119 {120 // Detect 'Is.Not' and 'Is.Not.<something>'121 return IsNot(constraintMemberExpression.Name) ||122 (constraintMemberExpression.Expression is MemberAccessExpressionSyntax memberAccessExpression &&123 IsNot(memberAccessExpression.Name));124 static bool IsNot(SimpleNameSyntax simpleName) =>125 simpleName.Identifier.ValueText == NUnitFrameworkConstants.NameOfIsNot;126 }127 private static ExpressionSyntax FindLeftMostTerm(MemberAccessExpressionSyntax constraintMemberExpression)128 {129 ExpressionSyntax innerConstraintExpression = constraintMemberExpression.Expression;130 while (innerConstraintExpression is not SimpleNameSyntax)131 {132 if (innerConstraintExpression is InvocationExpressionSyntax invocationExpression)133 {134 innerConstraintExpression = invocationExpression.Expression;135 }136 else if (innerConstraintExpression is MemberAccessExpressionSyntax memberAccessExpression)137 {138 innerConstraintExpression = memberAccessExpression.Expression;139 }140 else141 {142 break;143 }144 }145 return innerConstraintExpression;146 }147 private static bool IsInvocationTo(InvocationExpressionSyntax? invocationExpression, string name, string value)148 {149 if (invocationExpression is null)150 return false;151 if (invocationExpression.Expression is not MemberAccessExpressionSyntax memberAccessExpression)152 return false;153 var arguments = invocationExpression.ArgumentList.Arguments;154 return memberAccessExpression.Name.Identifier.ValueText == name &&155 arguments.Count == 1 &&156 arguments[0].Expression is LiteralExpressionSyntax literalExpression &&157 literalExpression.Token.ValueText == value;158 }159 }160}...

Full Screen

Full Screen

ExceptionExpectancyMethodModel.cs

Source:ExceptionExpectancyMethodModel.cs Github

copy

Full Screen

1using System.Collections.Generic;2using System.Linq;3using Microsoft.CodeAnalysis;4using Microsoft.CodeAnalysis.CSharp.Syntax;5using NUnit.Migrator.Helpers;6namespace NUnit.Migrator.ExceptionExpectancy.Model7{8 internal class ExceptionExpectancyMethodModel9 {10 public AttributeSyntax[] ExceptionFreeTestCaseAttributeNodes { get; }11 public ExceptionExpectancyAtAttributeLevel[] ExceptionRelatedAttributes { get; }12 public ExceptionExpectancyMethodModel(MethodDeclarationSyntax method, SemanticModel semanticModel, 13 NUnitFramework.Symbols nunit)14 {15 var attributesWithSymbols = GetAttributesWithSymbols(method, semanticModel);16 var attributes = new List<ExceptionExpectancyAtAttributeLevel>();17 var isExpectedException = TryGetFirstExpectedExceptionAttribute(nunit, attributesWithSymbols,18 out ExpectedExceptionAttribute expectedException);19 if (isExpectedException)20 {21 attributes.Add(expectedException);22 }23 var exceptionRelatedTestCases = GetExceptionRelatedTestCases(nunit, attributesWithSymbols, 24 isExpectedException, expectedException);25 attributes.AddRange(exceptionRelatedTestCases);26 ExceptionRelatedAttributes = attributes.ToArray();27 ExceptionFreeTestCaseAttributeNodes = GetExceptionFreeTestCaseAttributeNodes(nunit, attributesWithSymbols, 28 isExpectedException);29 }30 public static bool TryFindDiagnostic(MethodDeclarationSyntax methodSyntax, SemanticModel semanticModel, 31 NUnitFramework.Symbols nunit, out Diagnostic diagnostic)32 {33 var eligibleAttributes = GetEligibleAttributes(methodSyntax, semanticModel, nunit);34 if (eligibleAttributes.Length <= 0)35 {36 diagnostic = null;37 return false;38 }39 var diagnosticLocation = eligibleAttributes.Length == 1 40 ? eligibleAttributes.First().GetLocation()41 : methodSyntax.Identifier.GetLocation();42 var methodName = methodSyntax.Identifier.Text;43 diagnostic = Diagnostic.Create(Descriptors.ExceptionExpectancy, diagnosticLocation, methodName);44 return true;45 }46 private static AttributeSyntax[] GetExceptionFreeTestCaseAttributeNodes(NUnitFramework.Symbols nunit, 47 AttributeWithSymbol[] attributesWithSymbols, bool isExpectedException)48 {49 return attributesWithSymbols50 .Where(x => IsTestCaseAttributeNotExpectingException(x.Attribute, x.Symbol, nunit, isExpectedException))51 .Select(x => x.Attribute)52 .ToArray();53 }54 private static TestCaseExpectingExceptionAttribute[] GetExceptionRelatedTestCases(NUnitFramework.Symbols nunit, 55 AttributeWithSymbol[] attributesWithSymbols, bool isExpectedException, 56 ExpectedExceptionAttribute expectedException)57 {58 return attributesWithSymbols59 .Where(x => IsTestCaseAttributeExpectingException(x.Attribute, x.Symbol, nunit, isExpectedException))60 .Select(x => new TestCaseExpectingExceptionAttribute(x.Attribute, expectedException))61 .ToArray();62 }63 private static bool TryGetFirstExpectedExceptionAttribute(NUnitFramework.Symbols nunit, 64 AttributeWithSymbol[] attributesWithSymbols, out ExpectedExceptionAttribute expectedException)65 {66 var expectedExceptionNode = GetExpectedExceptionAttributes(nunit, attributesWithSymbols)?.FirstOrDefault();67 if (expectedExceptionNode != null)68 {69 expectedException = new ExpectedExceptionAttribute(expectedExceptionNode);70 return true;71 }72 expectedException = null;73 return false;74 }75 private static AttributeWithSymbol[] GetAttributesWithSymbols(BaseMethodDeclarationSyntax method, 76 SemanticModel semanticModel)77 {78 return method.AttributeLists79 .SelectMany(al => al.Attributes)80 .Select(at => new AttributeWithSymbol81 {82 Attribute = at,83 Symbol = semanticModel.GetSymbolInfo(at).Symbol?.ContainingSymbol84 }).ToArray();85 }86 private static AttributeSyntax[] GetEligibleAttributes(BaseMethodDeclarationSyntax method, 87 SemanticModel semanticModel, NUnitFramework.Symbols nunit)88 {89 var attributesWithSymbols = GetAttributesWithSymbols(method, semanticModel);90 var expectedExceptionAttributes = GetExpectedExceptionAttributes(nunit, attributesWithSymbols);91 var doesExpectedExceptionAttributeAlsoExist = expectedExceptionAttributes.Any();92 var testCaseAttributes = attributesWithSymbols.Where(x => IsTestCaseAttributeExpectingException(x.Attribute, x.Symbol, nunit,93 doesExpectedExceptionAttributeAlsoExist))94 .Select(x => x.Attribute);95 return expectedExceptionAttributes.Union(testCaseAttributes).ToArray();96 }97 private static AttributeSyntax[] GetExpectedExceptionAttributes(NUnitFramework.Symbols nunit, 98 AttributeWithSymbol[] attributesWithSymbols)99 {100 return attributesWithSymbols.Where(x => nunit.ExpectedException.Equals(x.Symbol))101 .Select(x => x.Attribute)102 .ToArray();103 }104 private static bool IsTestCaseAttributeExpectingException(AttributeSyntax attribute, ISymbol symbol, 105 NUnitFramework.Symbols nunit, bool doesExpectedExceptionAttributeAlsoExist)106 {107 if (!nunit.TestCase.Equals(symbol))108 return false;109 if (doesExpectedExceptionAttributeAlsoExist)110 return true;111 return attribute.ArgumentList != null 112 && attribute.ArgumentList.Arguments.Any(DefinesExpectedException);113 }114 private static bool IsTestCaseAttributeNotExpectingException(AttributeSyntax attribute, ISymbol symbol, 115 NUnitFramework.Symbols nunit, bool doesExpectedExceptionAttributeAlsoExist)116 {117 if (!nunit.TestCase.Equals(symbol) || doesExpectedExceptionAttributeAlsoExist)118 return false;119 return attribute.ArgumentList == null120 || attribute.ArgumentList.Arguments.All(arg => !DefinesExpectedException(arg));121 }122 private static bool DefinesExpectedException(AttributeArgumentSyntax attributeArg)123 {124 if (attributeArg.NameEquals == null)125 return false;126 var argName = attributeArg.NameEquals.Name.Identifier.ValueText;127 return argName == NUnitFramework.ExpectedExceptionArgument.ExpectedExceptionName128 || argName == NUnitFramework.ExpectedExceptionArgument.ExpectedException;129 }130 private struct AttributeWithSymbol131 {132 public AttributeSyntax Attribute;133 public ISymbol Symbol;134 }135 }136}...

Full Screen

Full Screen

ConstActualValueUsageCodeFix.cs

Source:ConstActualValueUsageCodeFix.cs Github

copy

Full Screen

1using System.Collections.Immutable;2using System.Composition;3using System.Diagnostics.CodeAnalysis;4using System.Linq;5using System.Threading.Tasks;6using Microsoft.CodeAnalysis;7using Microsoft.CodeAnalysis.CodeActions;8using Microsoft.CodeAnalysis.CodeFixes;9using Microsoft.CodeAnalysis.CSharp.Syntax;10using NUnit.Analyzers.Constants;11using NUnit.Analyzers.Extensions;12namespace NUnit.Analyzers.ConstActualValueUsage13{14 [ExportCodeFixProvider(LanguageNames.CSharp)]15 [Shared]16 public class ConstActualValueUsageCodeFix : CodeFixProvider17 {18 internal const string SwapArgumentsDescription = "Swap actual and expected arguments";19 private static readonly string[] SupportedClassicAsserts = new[]20 {21 NUnitFrameworkConstants.NameOfAssertAreEqual,22 NUnitFrameworkConstants.NameOfAssertAreNotEqual,23 NUnitFrameworkConstants.NameOfAssertAreSame,24 NUnitFrameworkConstants.NameOfAssertAreNotSame25 };26 private static readonly string[] SupportedIsConstraints = new[]27 {28 NUnitFrameworkConstants.NameOfIsEqualTo,29 NUnitFrameworkConstants.NameOfIsSameAs,30 NUnitFrameworkConstants.NameOfIsSamePath31 };32 public override ImmutableArray<string> FixableDiagnosticIds33 => ImmutableArray.Create(AnalyzerIdentifiers.ConstActualValueUsage);34 public sealed override FixAllProvider GetFixAllProvider()35 {36 return WellKnownFixAllProviders.BatchFixer;37 }38 public override async Task RegisterCodeFixesAsync(CodeFixContext context)39 {40 var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);41 var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);42 if (root is null || semanticModel is null)43 {44 return;45 }46 context.CancellationToken.ThrowIfCancellationRequested();47 var argumentSyntax = root.FindNode(context.Span);48 var invocationSyntax = argumentSyntax.Ancestors()49 .OfType<InvocationExpressionSyntax>()50 .FirstOrDefault();51 if (invocationSyntax is null)52 return;53 if (!TryFindArguments(semanticModel, invocationSyntax,54 out var expectedArgument,55 out var actualArgument))56 {57 return;58 }59 var newRoot = root60 .ReplaceNodes(new[] { expectedArgument, actualArgument },61 (node, _) => node == actualArgument ? expectedArgument : actualArgument);62 var codeAction = CodeAction.Create(63 SwapArgumentsDescription,64 _ => Task.FromResult(context.Document.WithSyntaxRoot(newRoot)),65 SwapArgumentsDescription);66 context.RegisterCodeFix(codeAction, context.Diagnostics);67 }68 private static bool TryFindArguments(SemanticModel semanticModel, InvocationExpressionSyntax invocationSyntax,69 [NotNullWhen(true)] out ExpressionSyntax? expectedArgument, [NotNullWhen(true)] out ExpressionSyntax? actualArgument)70 {71 expectedArgument = null;72 actualArgument = null;73 var methodSymbol = semanticModel.GetSymbolInfo(invocationSyntax).Symbol as IMethodSymbol;74 if (methodSymbol is null || !methodSymbol.ContainingType.IsAssert())75 return false;76 // option 1: Classic assert (e.g. Assert.AreEqual(expected, actual) )77 if (SupportedClassicAsserts.Contains(methodSymbol.Name) && methodSymbol.Parameters.Length >= 2)78 {79 expectedArgument = invocationSyntax.ArgumentList.Arguments[0].Expression;80 actualArgument = invocationSyntax.ArgumentList.Arguments[1].Expression;81 return true;82 }83 // option 2: Assert with 'actual' and 'constraint' parameters84 // (e.g. Assert.That(actual, Is.EqualTo(expected)))85 if (methodSymbol.Name == NUnitFrameworkConstants.NameOfAssertThat86 && methodSymbol.Parameters.Length >= 2)87 {88 actualArgument = invocationSyntax.ArgumentList.Arguments[0].Expression;89 var constraintExpression = invocationSyntax.ArgumentList.Arguments[1].Expression as InvocationExpressionSyntax;90 if (constraintExpression is null)91 return false;92 expectedArgument = constraintExpression.ArgumentList.Arguments.FirstOrDefault()?.Expression;93 if (expectedArgument is null)94 return false;95 if (constraintExpression.Expression is MemberAccessExpressionSyntax memberAccessExpression96 && SupportedIsConstraints.Contains(memberAccessExpression.Name.ToString()))97 {98 var expressionString = memberAccessExpression.Expression.ToString();99 // e.g. Is.EqualTo or Is.Not.EqualTo100 if (expressionString == NUnitFrameworkConstants.NameOfIs101 || expressionString == $"{NUnitFrameworkConstants.NameOfIs}.{NUnitFrameworkConstants.NameOfIsNot}")102 {103 return true;104 }105 // other cases are not supported106 return false;107 }108 }109 return false;110 }111 }112}...

Full Screen

Full Screen

SyntaxHelper.cs

Source:SyntaxHelper.cs Github

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using Microsoft.CodeAnalysis;5using Microsoft.CodeAnalysis.CSharp.Syntax;6namespace NUnit.Migrator.Helpers7{8 internal static class SyntaxHelper9 {10 internal delegate void ArgumentParseAction(string nameEquals, ExpressionSyntax expression);11 public static MethodDeclarationSyntax WithoutExceptionExpectancyInAttributes(12 this MethodDeclarationSyntax method, AttributeSyntax[] testCasesToRemain)13 {14 var resultMethod = method.RemoveNodes(GetExpectedExceptionsToRemove(method)15 .Union(GetTestCasesToRemove(method, testCasesToRemain))16 .Union(GetTestCaseArgsToRemove(method)),17 SyntaxRemoveOptions.KeepNoTrivia);18 return resultMethod.RemoveNodes(GetEmptyAttributeLists(resultMethod)19 .Union(GetEmptyAttributeArgumentLists(resultMethod)),20 SyntaxRemoveOptions.KeepNoTrivia);21 }22 internal static TypeSyntax[] GetAllBaseTypes(BaseTypeDeclarationSyntax typeDeclaration)23 {24 return typeDeclaration.BaseList?.Types.Select(t => t.Type).ToArray() ?? new TypeSyntax[] {};25 }26 internal static void ParseAttributeArguments(AttributeSyntax attribute,27 ArgumentParseAction argumentParseAction)28 {29 if (attribute?.ArgumentList == null || !attribute.ArgumentList.Arguments.Any())30 return;31 foreach (var argument in attribute.ArgumentList.Arguments)32 {33 var nameEquals = argument.NameEquals?.Name?.Identifier.ValueText;34 argumentParseAction(nameEquals, argument.Expression);35 }36 }37 private static IEnumerable<SyntaxNode> GetEmptyAttributeArgumentLists(BaseMethodDeclarationSyntax resultMethod)38 {39 return GetMethodAttributes(resultMethod, NUnitFramework.TestCaseAttributeSimpleName)40 .Select(at => at.ArgumentList)41 .Where(al => !al.Arguments.Any());42 }43 private static IEnumerable<SyntaxNode> GetEmptyAttributeLists(BaseMethodDeclarationSyntax resultMethod)44 {45 return resultMethod.AttributeLists.Where(al => !al.Attributes.Any());46 }47 private static IEnumerable<SyntaxNode> GetTestCaseArgsToRemove(BaseMethodDeclarationSyntax method)48 {49 return GetMethodAttributes(method, NUnitFramework.TestCaseAttributeSimpleName)50 .SelectMany(at => at.ArgumentList.Arguments)51 .Where(IsArgumentExpectingException);52 }53 private static IEnumerable<SyntaxNode> GetTestCasesToRemove(BaseMethodDeclarationSyntax method, 54 AttributeSyntax[] testCasesToRemain)55 {56 return GetMethodAttributes(method, NUnitFramework.TestCaseAttributeSimpleName,57 at => !testCasesToRemain.Contains(at));58 }59 private static IEnumerable<SyntaxNode> GetExpectedExceptionsToRemove(BaseMethodDeclarationSyntax method)60 {61 return GetMethodAttributes(method, NUnitFramework.ExpectedExceptionSimpleName);62 }63 private static IEnumerable<AttributeSyntax> GetMethodAttributes(BaseMethodDeclarationSyntax method, 64 string simpleName, Predicate<AttributeSyntax> attributePredicate = null)65 {66 return method67 .AttributeLists68 .SelectMany(al => al.Attributes)69 .Where(at => at.Name.ToString() == simpleName 70 && (attributePredicate?.Invoke(at) ?? true));71 }72 private static bool IsArgumentExpectingException(AttributeArgumentSyntax arg)73 {74 var nameEquals = arg.NameEquals?.Name?.Identifier.ToString();75 return nameEquals != null &&76 (nameEquals == NUnitFramework.ExpectedExceptionArgument.ExpectedExceptionName77 || nameEquals == NUnitFramework.ExpectedExceptionArgument.ExpectedException78 || nameEquals == NUnitFramework.ExpectedExceptionArgument.ExpectedMessage79 || nameEquals == NUnitFramework.ExpectedExceptionArgument.MatchType);80 }81 }82}...

Full Screen

Full Screen

MemberAccessBasedMigration.cs

Source:MemberAccessBasedMigration.cs Github

copy

Full Screen

1using System.Linq;2using Microsoft.CodeAnalysis;3using Microsoft.CodeAnalysis.CodeFixes;4using Microsoft.CodeAnalysis.CSharp;5using Microsoft.CodeAnalysis.CSharp.Syntax;6using Microsoft.CodeAnalysis.Diagnostics;7using NUnit.Migrator.Helpers;8namespace NUnit.Migrator.AssertionsAndConstraints9{10 internal abstract class MemberAccessBasedMigration<TMemberAccessContainerNode>11 : ICompilationStartAnalyzing, IFixer12 where TMemberAccessContainerNode : SyntaxNode13 {14 public abstract DiagnosticDescriptor DiagnosticDescriptor { get; }15 public abstract string CreateReplaceWithTargetString(TMemberAccessContainerNode fixedContainer);16 public abstract TMemberAccessContainerNode CreateFixedContainer(TMemberAccessContainerNode container);17 DiagnosticDescriptor ICompilationStartAnalyzing.SupportedDiagnostic => DiagnosticDescriptor;18 public void RegisterAnalysis(CompilationStartAnalysisContext context, NUnitFramework.Symbols nunit)19 {20 context.RegisterSyntaxNodeAction(syntaxNodeAnalysisContext =>21 Analyze(syntaxNodeAnalysisContext, nunit), ContainerSyntaxKind);22 }23 DiagnosticDescriptor IFixer.FixableDiagnostic => DiagnosticDescriptor;24 public void RegisterFixing(CodeFixContext context, Document document, SyntaxNode documentRoot)25 {26 var diagnostics = context.Diagnostics.Where(d => d.Id == DiagnosticDescriptor.Id).ToArray();27 if (!diagnostics.Any())28 return;29 var container = documentRoot.FindNode(context.Span).FirstAncestorOrSelf<TMemberAccessContainerNode>();30 var codeAction = new MemberAccessCodeAction<TMemberAccessContainerNode>(document, container, this);31 context.RegisterCodeFix(codeAction, diagnostics);32 }33 protected abstract SyntaxKind ContainerSyntaxKind { get; }34 protected abstract bool TryGetMemberAccess(TMemberAccessContainerNode container,35 out MemberAccessExpressionSyntax memberAccess);36 protected abstract INamedTypeSymbol[] GetMemberAccessContainingClassSymbolsEligibleForFix(37 NUnitFramework.Symbols nunit);38 private void Analyze(SyntaxNodeAnalysisContext context, NUnitFramework.Symbols nunit)39 {40 var containerNode = (TMemberAccessContainerNode)context.Node;41 if (!TryGetMemberAccess(containerNode, out MemberAccessExpressionSyntax memberAccess))42 return;43 if (!FindOldApiAndProposedFix(context, nunit, memberAccess))44 return;45 context.ReportDiagnostic(Diagnostic.Create(46 DiagnosticDescriptor,47 memberAccess.GetLocation(),48 $"{memberAccess}",49 $"{CreateReplaceWithTargetString(CreateFixedContainer(containerNode))}"));50 }51 private bool FindOldApiAndProposedFix(SyntaxNodeAnalysisContext context,52 NUnitFramework.Symbols nunit, MemberAccessExpressionSyntax memberAccess)53 {54 return MemberAccessMigrationTable.TryGetFixExpression(memberAccess, out ExpressionSyntax _) 55 && DoesMemberAccessSymbolMatchNUnit(context, nunit, memberAccess);56 }57 58 private bool DoesMemberAccessSymbolMatchNUnit(59 SyntaxNodeAnalysisContext context, NUnitFramework.Symbols nunit,60 MemberAccessExpressionSyntax memberAccess)61 {62 var containingClassSymbol = context.SemanticModel.GetSymbolInfo(memberAccess).Symbol?.ContainingSymbol;63 var allowedContainingClassSymbols = GetMemberAccessContainingClassSymbolsEligibleForFix(nunit);64 // since member access may be defined in client code too, we need to distinguish as we migrate nunit only65 if (containingClassSymbol == null66 || !allowedContainingClassSymbols.Any(classSymbol => classSymbol.Equals(containingClassSymbol)))67 {68 return false;69 }70 return true;71 }72 }73}...

Full Screen

Full Screen

AssertExceptionMessageDecorator.cs

Source:AssertExceptionMessageDecorator.cs Github

copy

Full Screen

1using System;2using System.Collections.Generic;3using Microsoft.CodeAnalysis.CSharp;4using Microsoft.CodeAnalysis.CSharp.Syntax;5using NUnit.Migrator.ExceptionExpectancy.Model;6using NUnit.Migrator.Helpers;7namespace NUnit.Migrator.ExceptionExpectancy.CodeActions8{9 internal class AssertExceptionMessageDecorator : AssertExceptionBlockDecorator10 {11 private readonly ExceptionExpectancyAtAttributeLevel _attribute;12 public AssertExceptionMessageDecorator(IAssertExceptionBlockCreator blockCreator,13 ExceptionExpectancyAtAttributeLevel attribute) : base(blockCreator)14 {15 _attribute = attribute;16 }17 public override BlockSyntax Create(MethodDeclarationSyntax method, TypeSyntax assertedType)18 {19 var body = base.Create(method, assertedType);20 return body.AddStatements(CreateAssertExceptionMessageStatement());21 }22 private IEnumerable<ArgumentSyntax> CreateExceptionMessageAssertThatArguments()23 {24 return new[]25 {26 SyntaxFactory.Argument(27 SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,28 SyntaxFactory.IdentifierName(AssignAssertThrowsToLocalVariableDecorator29 .LocalExceptionVariableName),30 SyntaxFactory.IdentifierName(nameof(Exception.Message)))),31 SyntaxFactory.Argument(32 SyntaxFactory.InvocationExpression(33 SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,34 SyntaxFactory.IdentifierName(CreateDoesOrIs()),35 SyntaxFactory.IdentifierName(36 CreateExpectedExceptionMessageAssertionMethod())),37 SyntaxFactory.ArgumentList(38 SyntaxFactory.SingletonSeparatedList(39 SyntaxFactory.Argument(40 SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,41 SyntaxFactory.ParseToken(_attribute.ExpectedMessage42 )))))))43 };44 }45 private string CreateDoesOrIs() => 46 _attribute.MatchType == null 47 || _attribute.MatchType == NUnitFramework.MessageMatch.Exact 48 ? NUnitFramework.IsIdentifier 49 : NUnitFramework.DoesIdentifier;50 private string CreateExpectedExceptionMessageAssertionMethod()51 {52 var matchType = _attribute.MatchType;53 switch (matchType)54 {55 case NUnitFramework.MessageMatch.Contains: return NUnitFramework.Does.Contain;56 case NUnitFramework.MessageMatch.Regex: return NUnitFramework.Does.Match;57 case NUnitFramework.MessageMatch.StartsWith: return NUnitFramework.Does.StartWith;58 default: return NUnitFramework.Is.EqualTo;59 }60 }61 private ExpressionStatementSyntax CreateAssertExceptionMessageStatement()62 {63 return SyntaxFactory.ExpressionStatement(64 SyntaxFactory.InvocationExpression(65 SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,66 SyntaxFactory.IdentifierName(NUnitFramework.AssertIdentifier),67 SyntaxFactory.IdentifierName(NUnitFramework.Assert.ThatIdentifier)),68 SyntaxFactory.ArgumentList(69 SyntaxFactory.SeparatedList(70 CreateExceptionMessageAssertThatArguments()))));71 }72 }73}...

Full Screen

Full Screen

AttributeAnalyzer.cs

Source:AttributeAnalyzer.cs Github

copy

Full Screen

1using System.Linq;2using Microsoft.CodeAnalysis;3using Microsoft.CodeAnalysis.CSharp;4using Microsoft.CodeAnalysis.CSharp.Syntax;5using Microsoft.CodeAnalysis.Diagnostics;6using NUnit.Migrator.Helpers;7namespace NUnit.Migrator.Attributes8{9 public abstract class AttributeAnalyzer : DiagnosticAnalyzer10 {11 public override void Initialize(AnalysisContext context)12 {13 context.RegisterCompilationStartAction(ctx =>14 {15 if (!NUnitFramework.Symbols.TryGetNUnitSymbols(ctx.Compilation, out NUnitFramework.Symbols nunit))16 return; 17 ctx.RegisterSyntaxNodeAction(syntaxNodeContext =>18 CheckAttributeSymbolsAndAnalyze(syntaxNodeContext, nunit, ctx.Compilation), SyntaxKind.Attribute);19 });20 }21 internal abstract INamedTypeSymbol[] GetAnalyzedAttributeSymbols(NUnitFramework.Symbols nunit,22 Compilation compilation);23 protected virtual void Analyze(SyntaxNodeAnalysisContext context, AttributeSyntax attributeSyntax)24 {25 var attributeLocation = attributeSyntax.GetLocation();26 context.ReportDiagnostic(Diagnostic.Create(27 SupportedDiagnostics.First(), attributeLocation, attributeSyntax.Name.ToString()));28 }29 private void CheckAttributeSymbolsAndAnalyze(SyntaxNodeAnalysisContext context, NUnitFramework.Symbols nunit,30 Compilation compilation)31 {32 var attributeSyntax = (AttributeSyntax) context.Node;33 var semanticModel = context.SemanticModel;34 if (!IsNUnitAttributeSymbol(attributeSyntax, nunit, semanticModel, compilation))35 return;36 Analyze(context, attributeSyntax);37 }38 private bool IsNUnitAttributeSymbol(AttributeSyntax attributeSyntax,39 NUnitFramework.Symbols nunit, SemanticModel semanticModel, Compilation compilation)40 {41 var attributeSymbol = semanticModel.GetSymbolInfo(attributeSyntax).Symbol?.ContainingSymbol;42 var analyzedAttributeSymbols = GetAnalyzedAttributeSymbols(nunit, compilation);43 return analyzedAttributeSymbols.Any(analyzedAttr => analyzedAttr.Equals(attributeSymbol));44 }45 }46}...

Full Screen

Full Screen

ExpectedExceptionAttribute.cs

Source:ExpectedExceptionAttribute.cs Github

copy

Full Screen

1using Microsoft.CodeAnalysis.CSharp.Syntax;2using NUnit.Migrator.Helpers;3namespace NUnit.Migrator.ExceptionExpectancy.Model4{5 /// <summary>6 /// <c>NUnit.Framework.ExpectedExceptionAttribute</c>. It was removed at all in v3 of the framework7 /// (https://github.com/nunit/docs/wiki/Breaking-Changes).8 /// See http://nunit.org/docs/2.6.4/exception.html for the complete reference.9 /// </summary>10 internal class ExpectedExceptionAttribute : ExceptionExpectancyAtAttributeLevel11 {12 public ExpectedExceptionAttribute(AttributeSyntax attribute) : base(attribute)13 {14 SyntaxHelper.ParseAttributeArguments(attribute, ParseAttributeArgumentSyntax);15 }16 private void ParseAttributeArgumentSyntax(string nameEquals, ExpressionSyntax expression)17 {18 if (nameEquals != null19 && nameEquals != NUnitFramework.ExpectedExceptionArgument.UserMessage20 && nameEquals != NUnitFramework.ExpectedExceptionArgument.Handler)21 return;22 switch (expression)23 {24 case LiteralExpressionSyntax literal when nameEquals == null && !IsLiteralNullOrEmpty(literal):25 AssertedExceptionTypeName = literal.Token.ValueText;26 break;27 case TypeOfExpressionSyntax typeOf:28 AssertedExceptionTypeName = typeOf.Type.ToString();29 break;30 case LiteralExpressionSyntax literal when nameEquals ==31 NUnitFramework.ExpectedExceptionArgument.UserMessage:32 UserMessage = literal.Token.Text;33 break;34 case LiteralExpressionSyntax literal when nameEquals ==35 NUnitFramework.ExpectedExceptionArgument.Handler:36 HandlerName = literal.Token.ValueText;37 break;38 }39 }40 }41}...

Full Screen

Full Screen

A

Using AI Code Generation

copy

Full Screen

1using NUnit.Framework.Syntax;2using NUnit.Framework.Syntax;3using NUnit.Framework.Syntax;4using NUnit.Framework.Syntax;5using NUnit.Framework.Syntax;6using NUnit.Framework.Syntax;7using NUnit.Framework.Syntax;8using NUnit.Framework.Syntax;9using NUnit.Framework.Syntax;10using NUnit.Framework.Syntax;11using NUnit.Framework.Syntax;12using NUnit.Framework.Syntax;13using NUnit.Framework.Syntax;14using NUnit.Framework.Syntax;15using NUnit.Framework.Syntax;16using NUnit.Framework.Syntax;17using NUnit.Framework.Syntax;18using NUnit.Framework.Syntax;19using NUnit.Framework.Syntax;20using NUnit.Framework.Syntax;21using NUnit.Framework.Syntax;22using NUnit.Framework.Syntax;23using NUnit.Framework.Syntax;24using NUnit.Framework.Syntax;25using NUnit.Framework.Syntax;26using NUnit.Framework.Syntax;27using NUnit.Framework.Syntax;28using NUnit.Framework.Syntax;29using NUnit.Framework.Syntax;

Full Screen

Full Screen

A

Using AI Code Generation

copy

Full Screen

1using NUnit.Framework.Syntax;2using NUnit.Framework.Syntax;3using NUnit.Framework.Syntax;4using NUnit.Framework.Syntax;5using NUnit.Framework.Syntax;6using NUnit.Framework.Syntax;7using NUnit.Framework.Syntax;8using NUnit.Framework.Syntax;9using NUnit.Framework.Syntax;10using NUnit.Framework.Syntax;11using NUnit.Framework.Syntax;12using NUnit.Framework.Syntax;13using NUnit.Framework.Syntax;14using NUnit.Framework.Syntax;15using NUnit.Framework.Syntax;16using NUnit.Framework.Syntax;17using NUnit.Framework.Syntax;18using NUnit.Framework.Syntax;19using NUnit.Framework.Syntax;20using NUnit.Framework.Syntax;21using NUnit.Framework.Syntax;22using NUnit.Framework.Syntax;23using NUnit.Framework.Syntax;24using NUnit.Framework.Syntax;25using NUnit.Framework.Syntax;26using NUnit.Framework.Syntax;27using NUnit.Framework.Syntax;28using NUnit.Framework.Syntax;29using NUnit.Framework.Syntax;30using NUnit.Framework.Syntax;

Full Screen

Full Screen

A

Using AI Code Generation

copy

Full Screen

1using NUnit.Framework.Syntax;2using NUnit.Framework.Syntax;3using NUnit.Framework.Syntax;4using NUnit.Framework.Syntax;5using NUnit.Framework.Syntax;6using NUnit.Framework.Syntax;7using NUnit.Framework.Syntax;8using NUnit.Framework.Syntax;9using NUnit.Framework.Syntax;10using NUnit.Framework.Syntax;11using NUnit.Framework.Syntax;12using NUnit.Framework.Syntax;13using NUnit.Framework.Syntax;14using NUnit.Framework.Syntax;15using NUnit.Framework.Syntax;16using NUnit.Framework.Syntax;17using NUnit.Framework.Syntax;18using NUnit.Framework.Syntax;19using NUnit.Framework.Syntax;20using NUnit.Framework.Syntax;21using NUnit.Framework.Syntax;22using NUnit.Framework.Syntax;23using NUnit.Framework.Syntax;24using NUnit.Framework.Syntax;25using NUnit.Framework.Syntax;

Full Screen

Full Screen

A

Using AI Code Generation

copy

Full Screen

1using NUnit.Framework.Syntax;2using NUnit.Framework;3using NUnit.Framework.Syntax;4using NUnit.Framework;5using NUnit.Framework.Syntax;6using NUnit.Framework;7using NUnit.Framework.Syntax;8using NUnit.Framework;9using NUnit.Framework.Syntax;10using NUnit.Framework;11using NUnit.Framework.Syntax;12using NUnit.Framework;13using NUnit.Framework.Syntax;14using NUnit.Framework;15using NUnit.Framework.Syntax;16using NUnit.Framework;17using NUnit.Framework.Syntax;18using NUnit.Framework;19using NUnit.Framework.Syntax;20using NUnit.Framework;21using NUnit.Framework.Syntax;22using NUnit.Framework;23using NUnit.Framework.Syntax;24using NUnit.Framework;25using NUnit.Framework.Syntax;26using NUnit.Framework;27using NUnit.Framework.Syntax;28using NUnit.Framework;29using NUnit.Framework.Syntax;30using NUnit.Framework;31using NUnit.Framework.Syntax;

Full Screen

Full Screen

A

Using AI Code Generation

copy

Full Screen

1using NUnit.Framework.Syntax;2using NUnit.Framework;3using NUnit.Framework.SyntaxHelpers;4{5 {6 private Assert A;7 private TestFixtureAttribute B;8 private Is C;9 private TestFixtureSetUpAttribute D;10 private TestFixtureTearDownAttribute E;11 private TestAttribute F;12 private SetUpAttribute G;13 private TearDownAttribute H;14 private ExpectedExceptionAttribute I;15 private IgnoreAttribute J;16 private CategoryAttribute K;17 private DescriptionAttribute L;18 private TestResult M;19 private TestSuite N;20 private TestContext O;21 private TestCaseAttribute P;22 private TestCaseSourceAttribute Q;23 private TestFixtureAttribute R;24 private TestFixtureAttribute S;25 private TestFixtureAttribute T;26 private TestFixtureAttribute U;27 private TestFixtureAttribute V;28 private TestFixtureAttribute W;

Full Screen

Full Screen

A

Using AI Code Generation

copy

Full Screen

1using NUnit.Framework.Syntax;2{3 public bool IsTrue()4 {5 return true;6 }7}8using NUnit.Framework.Syntax;9{10 public bool IsTrue()11 {12 return true;13 }14}15using NUnit.Framework.Syntax;16{17 public bool IsTrue()18 {19 return true;20 }21}22using NUnit.Framework.Syntax;23{24 public bool IsTrue()25 {26 return true;27 }28}29using NUnit.Framework.Syntax;30{31 public bool IsTrue()32 {33 return true;34 }35}36using NUnit.Framework.Syntax;37{38 public bool IsTrue()39 {40 return true;41 }42}43using NUnit.Framework.Syntax;44{45 public bool IsTrue()46 {47 return true;48 }49}50using NUnit.Framework.Syntax;51{52 public bool IsTrue()53 {54 return true;55 }56}57using NUnit.Framework.Syntax;58{59 public bool IsTrue()60 {61 return true;62 }63}64using NUnit.Framework.Syntax;65{66 public bool IsTrue()67 {68 return true;69 }70}71using NUnit.Framework.Syntax;72{73 public bool IsTrue()74 {75 return true;76 }77}78using NUnit.Framework.Syntax;79{

Full Screen

Full Screen

A

Using AI Code Generation

copy

Full Screen

1using NUnit.Framework.Syntax;2{3 public void M()4 {5 Assert.AreEqual(1, 2);6 }7}8using NUnit.Framework;9{10 public void M()11 {12 A a = new A();13 a.M();14 }15}16using NUnit.Framework;17{18 public void Test()19 {20 B b = new B();21 b.M();22 }23}

Full Screen

Full Screen

A

Using AI Code Generation

copy

Full Screen

1using NUnit.Framework.Syntax;2{3 {4 public void Test()5 {6 Assert.That("abc", new StartsWith("a"));7 }8 }9}10using NUnit.Framework.Syntax;11{12 {13 public void Test()14 {15 Assert.That("abc", new StartsWith("a"));16 }17 }18}19using NUnit.Framework.Syntax;20{21 {22 public void Test()23 {24 Assert.That("abc", new StartsWith("a"));25 }26 }27}28using NUnit.Framework.Syntax;29{30 {31 public void Test()32 {33 Assert.That("abc", new StartsWith("a"));34 }35 }36}37using NUnit.Framework.Syntax;38{39 {40 public void Test()41 {42 Assert.That("abc", new StartsWith("a"));43 }44 }45}46using NUnit.Framework.Syntax;47{48 {49 public void Test()50 {51 Assert.That("abc", new StartsWith("a"));52 }53 }54}55using NUnit.Framework.Syntax;56{57 {58 public void Test()59 {60 Assert.That("abc", new StartsWith("a"));61 }62 }63}64using NUnit.Framework.Syntax;65{66 {67 public void Test()68 {69 Assert.That("abc", new StartsWith("a"));70 }

Full Screen

Full Screen

Nunit tutorial

Nunit is a well-known open-source unit testing framework for C#. This framework is easy to work with and user-friendly. LambdaTest’s NUnit Testing Tutorial provides a structured and detailed learning environment to help you leverage knowledge about the NUnit framework. The NUnit tutorial covers chapters from basics such as environment setup to annotations, assertions, Selenium WebDriver commands, and parallel execution using the NUnit framework.

Chapters

  1. NUnit Environment Setup - All the prerequisites and setup environments are provided to help you begin with NUnit testing.
  2. NUnit With Selenium - Learn how to use the NUnit framework with Selenium for automation testing and its installation.
  3. Selenium WebDriver Commands in NUnit - Leverage your knowledge about the top 28 Selenium WebDriver Commands in NUnit For Test Automation. It covers web browser commands, web element commands, and drop-down commands.
  4. NUnit Parameterized Unit Tests - Tests on varied combinations may lead to code duplication or redundancy. This chapter discusses how NUnit Parameterized Unit Tests and their methods can help avoid code duplication.
  5. NUnit Asserts - Learn about the usage of assertions in NUnit using Selenium
  6. NUnit Annotations - Learn how to use and execute NUnit annotations for Selenium Automation Testing
  7. Generating Test Reports In NUnit - Understand how to use extent reports and generate reports with NUnit and Selenium WebDriver. Also, look into how to capture screenshots in NUnit extent reports.
  8. Parallel Execution In NUnit - Parallel testing helps to reduce time consumption while executing a test. Deep dive into the concept of Specflow Parallel Execution in NUnit.

NUnit certification -

You can also check out the LambdaTest Certification to enhance your learning in Selenium Automation Testing using the NUnit framework.

YouTube

Watch this tutorial on the LambdaTest Channel to learn how to set up the NUnit framework, run tests and also execute parallel testing.

Run Nunit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in A

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful