Esempio n. 1
0
        /// <summary>
        /// Looks for magic numbers within a unit test.
        /// </summary>
        /// <param name="methodDeclaration">
        /// An instance of methodDeclarationSyntax that represents a unit test method. It is
        /// the responsibility of clients to pass actual unit test methods as arguments.
        /// </param>
        /// <returns>
        /// A list of .NET Compiler platform diagnostics. Each diagnostic represents a single
        /// unit test violation.
        /// </returns>
        private IList <Diagnostic> SearchForMagicNumbers(MethodDeclarationSyntax methodDeclaration)
        {
            Contract.Requires(methodDeclaration != null);
            Contract.Ensures(Contract.Result <IList <Diagnostic> >() != null);

            // TODO: Try to make this more generic like the other rules.

            IList <Diagnostic> foundDiagnostics = new List <Diagnostic>();

            if (methodDeclaration.DescendantNodesAndTokens() != null)
            {
                IEnumerable <SyntaxNodeOrToken> childTokens = methodDeclaration
                                                              .DescendantNodesAndTokens()?
                                                              .Where(ct => ct.Kind() == SyntaxKind.NumericLiteralExpression)
                                                              .Select(ct => ct);

                Contract.Assume(childTokens != null);

                foreach (var syntaxToken in childTokens)
                {
                    Contract.Assume(syntaxToken.Parent?.Parent?.Parent != null);

                    // Look for magic numbers in an invocation expression.
                    if (syntaxToken.Parent.Parent.Parent.Kind() == SyntaxKind.InvocationExpression)
                    {
                        foundDiagnostics.Add(Diagnostic.Create(Descriptors.MagicNumberDescriptor, syntaxToken.GetLocation()));
                    }
                }
            }

            return(foundDiagnostics);
        }