/// <summary>
 /// Asserts that the rule has failed to execute successfully for each method in the type.
 /// </summary>
 /// <typeparam name="T">Type containing the methods.</typeparam>
 /// <param name="expectedCount">Expected defect count for each method.</param>
 protected void AssertRuleFailure <T> (int expectedCount)
 {
     foreach (MethodDefinition method in DefinitionLoader.GetTypeDefinition <T> ().Methods)
     {
         base.AssertRuleFailure(method, expectedCount);
     }
 }
Example #2
0
 public void SetUp()
 {
     // A type always has a method (implicit constructor) so we have to hack our own
     // methodless class.
     DoesNotApplyClassSpecial = DefinitionLoader.GetTypeDefinition <DoesNotApplyClass1> ();
     DoesNotApplyClassSpecial.Methods.Clear();
 }
        public void AnonymousMethodTest()
        {
            MethodDefinition method = null;
            // compiler generated code is compiler dependant, check for [g]mcs (inner type)
            TypeDefinition type = DefinitionLoader.GetTypeDefinition(typeof(AvoidUnusedParametersTest).Assembly, "AvoidUnusedParametersTest/<>c__CompilerGenerated0");

            if (type != null)
            {
                method = DefinitionLoader.GetMethodDefinition(type, "<AnonymousMethodWithUnusedParameters>c__2", null);
            }
            // otherwise try for csc (inside same class)
            if (method == null)
            {
                type = DefinitionLoader.GetTypeDefinition <AvoidUnusedParametersTest> ();
                foreach (MethodDefinition md in type.Methods)
                {
                    if (md.Name.StartsWith("<AnonymousMethodWithUnusedParameters>"))
                    {
                        method = md;
                        break;
                    }
                }
            }
            Assert.IsNotNull(method, "method not found!");
            AssertRuleDoesNotApply(method);
        }
Example #4
0
        public void CohesivenessMeasurementTest()
        {
            Type[] types = Assembly.GetExecutingAssembly().GetTypes();
            ExpectedCohesivenessAttribute expectedCoh;
            double coh;

            foreach (Type type in types)
            {
                if (0 == type.GetCustomAttributes(typeof(ExpectedCohesivenessAttribute), false).Length)
                {
                    continue;
                }

                expectedCoh = (ExpectedCohesivenessAttribute)
                              type.GetCustomAttributes(
                    typeof(ExpectedCohesivenessAttribute), false)[0];

                AvoidLackOfCohesionOfMethodsRule rule = new AvoidLackOfCohesionOfMethodsRule();
                coh = rule.GetCohesivenessForType(
                    DefinitionLoader.GetTypeDefinition(type));

                Assert.IsTrue(
                    Math.Abs(coh - expectedCoh.Value) <= expectedCoh.Delta,
                    "Cohesiveness for type '{0}' is {1} but should have been {2} +/- {3}.",
                    type, coh, expectedCoh.Value, expectedCoh.Delta);
            }
        }
Example #5
0
        public void FxCop_ManuallySuppressed()
        {
            AssemblyDefinition assembly = CreateAssembly("SuppressedVersion", ModuleKind.Dll);
            TypeDefinition     type     = DefinitionLoader.GetTypeDefinition <SuppressMessageAttribute> ();

            MethodDefinition ctor = DefinitionLoader.GetMethodDefinition(type, ".ctor",
                                                                         new Type [] { typeof(string), typeof(string) });
            CustomAttribute ca = new CustomAttribute(assembly.MainModule.Import(ctor));

            ca.ConstructorArguments.Add(
                new CustomAttributeArgument(
                    assembly.MainModule.TypeSystem.String, "Microsoft.Design"));
            ca.ConstructorArguments.Add(
                new CustomAttributeArgument(
                    assembly.MainModule.TypeSystem.String, "CA1016:MarkAssembliesWithAssemblyVersion"));
            assembly.CustomAttributes.Add(ca);

            var stream = new MemoryStream();

            assembly.Write(stream);

            stream.Position = 0;

            assembly = AssemblyDefinition.ReadAssembly(stream);

            AssertRuleDoesNotApply(assembly);
        }
Example #6
0
        private void AssertClass <T> ()
        {
            TestRunner runner;
            bool       failed = false;
            RuleResult result;

            //
            // We assert that exactly 1 error is raised among all the methods in the class
            //

            runner = new TestRunner(new DelegatesPassedToNativeCodeMustIncludeExceptionHandlingRule());

            foreach (MethodDefinition method in DefinitionLoader.GetTypeDefinition <T> ().Methods)
            {
                result = runner.CheckMethod(method);
                if (result == RuleResult.Failure)
                {
                    Assert.IsFalse(failed);
                    Assert.AreEqual(1, runner.Defects.Count);
                    failed = true;
                }
            }

            Assert.IsTrue(failed);
        }
 /// <summary>
 /// Asserts that the rule does not apply to all methods of the type.
 /// </summary>
 /// <typeparam name="T">Type containing the methods.</typeparam>
 protected void AssertRuleDoesNotApply <T> ()
 {
     foreach (MethodDefinition method in DefinitionLoader.GetTypeDefinition <T> ().Methods)
     {
         base.AssertRuleDoesNotApply(method);
     }
 }
 /// <summary>
 /// Asserts that the rule has been executed successfully for each method in the type.
 /// </summary>
 /// <typeparam name="T">Type containing the methods.</typeparam>
 protected void AssertRuleSuccess <T> ()
 {
     foreach (MethodDefinition method in DefinitionLoader.GetTypeDefinition <T> ().Methods)
     {
         base.AssertRuleSuccess(method);
     }
 }
        public void StaticType()
        {
            // the nice generic-based test syntax won't work on static types :(
            Assembly       a    = typeof(AvoidConstructorsInStaticTypesTest).Assembly;
            TypeDefinition type = DefinitionLoader.GetTypeDefinition(a, "Test.Rules.Correctness.AvoidConstructorsInStaticTypesTest/StaticClass");

            AssertRuleDoesNotApply(type);
        }
        public void Cecil()
        {
            // Cecil reports what being set on the type, not how the runtime treats it
            TypeDefinition nse = DefinitionLoader.GetTypeDefinition <NonSerializableEnum> ();

            Assert.IsFalse(nse.IsSerializable, "NonSerializableEnum");
            TypeDefinition se = DefinitionLoader.GetTypeDefinition <SerializableEnum> ();

            Assert.IsTrue(se.IsSerializable, "SerializableEnum");
        }
        public void RaiseAnalyzeModuleEvent()
        {
            if (raisedAnalyzeModuleEvent)
            {
                return;
            }

            raisedAnalyzeModuleEvent = true;
            ((TestRunner)Runner).OnModule(DefinitionLoader.GetTypeDefinition <PreferXmlAbstractionsTest> ().Module);
        }
        public void IsComVisible()
        {
            TypeDefinition type = DefinitionLoader.GetTypeDefinition <ExplicitComVisibleClass> ();

            Assert.IsTrue(type.IsComVisible() ?? false, "true");
            type = SimpleTypes.Class;
            Assert.IsNull(type.IsComVisible(), "null");
            type = DefinitionLoader.GetTypeDefinition <ExplicitComInvisibleClass> ();
            Assert.IsFalse(type.IsComVisible() ?? true, "false");
        }
        public void Yield()
        {
            AssertRuleSuccess <CompilerGeneratedInnerIterator> ("TypesInside");
            TypeDefinition inner = (DefinitionLoader.GetTypeDefinition <CompilerGeneratedInnerIterator> ().NestedTypes [0] as TypeDefinition);

            foreach (MethodDefinition method in inner.Methods)
            {
                AssertRuleDoesNotApply(method);
            }
        }
Example #14
0
        public void RaiseAnalyzeModuleEvent()
        {
            if (raisedAnalyzeModuleEvent)
            {
                return;
            }

            raisedAnalyzeModuleEvent = true;
            ((TestRunner)Runner).OnModule(DefinitionLoader.GetTypeDefinition <XmlCases> ().Module);
        }
Example #15
0
        public void Unrestricted_Boolean()
        {
            TypeDefinition t  = DefinitionLoader.GetTypeDefinition <UnrestrictedTrue> ();
            PermissionSet  ps = t.SecurityDeclarations [0].ToPermissionSet();

            Assert.IsTrue(ps.IsUnrestricted(), "IsUnrestricted");

            t  = DefinitionLoader.GetTypeDefinition <UnrestrictedFalse> ();
            ps = t.SecurityDeclarations [0].ToPermissionSet();
            Assert.IsFalse(ps.IsUnrestricted(), "!IsUnrestricted");
        }
        public void DoesNotApplyGeneratedCode()
        {
            var declaring_type = DefinitionLoader.GetTypeDefinition <HasFinalizer> ();

            Assert.IsTrue(declaring_type.HasNestedTypes, "HasFinalizer-HasNestedTypes");
            Assert.AreEqual(1, declaring_type.NestedTypes.Count, "HasFinalized-NestedTypesCount-1");

            var type = declaring_type.NestedTypes [0];

            Assert.IsTrue(type.IsGeneratedCode(), "NestedType-IsGeneratedCode-True");
            AssertRuleDoesNotApply(type);
        }
Example #17
0
        public void GenericsTest()
        {
            Type           type = typeof(BadGenericEquality <>);
            TypeDefinition td   = DefinitionLoader.GetTypeDefinition(type);

            MethodDefinition md = DefinitionLoader.GetMethodDefinition(td, "op_Equality", null);

            AssertRuleFailure(md, 2);

            md = DefinitionLoader.GetMethodDefinition(td, "op_Inequality", null);
            AssertRuleSuccess(md);
        }
        public void TestNonPrivateStaticCtorDefinedClass()
        {
            TypeDefinition   inspectedType = DefinitionLoader.GetTypeDefinition <NonPrivateStaticCtorDefinedClass> ();
            MethodDefinition static_ctor   = null;

            foreach (MethodDefinition ctor in inspectedType.Methods)
            {
                if (ctor.IsConstructor && ctor.IsStatic)
                {
                    static_ctor = ctor;
                    break;
                }
            }

            static_ctor.IsPublic = true; // change it from private to public
            AssertRuleFailure(inspectedType, 1);
        }
        public void Initialize()
        {
            // ensure that the rule does not apply for types defined in 1.x assemblies
            TypeDefinition violator    = DefinitionLoader.GetTypeDefinition <ConsiderUsingStopwatchTest> ();
            TargetRuntime  realRuntime = violator.Module.Runtime;

            try {
                // fake assembly runtime version and do the check
                violator.Module.Runtime = TargetRuntime.Net_1_1;
                Rule.Active             = true;
                Rule.Initialize(Runner);
                Assert.IsFalse(Rule.Active, "Active");
            }
            catch {
                // rollback
                violator.Module.Runtime = realRuntime;
                Rule.Active             = true;
            }
        }
Example #20
0
        public void NotApplicableBefore2_0()
        {
            // ensure that the rule does not apply for types defined in 1.x assemblies
            TypeDefinition violator    = DefinitionLoader.GetTypeDefinition <NoUseOfGenerics> ();
            TargetRuntime  realRuntime = violator.Module.Runtime;

            try {
                // fake assembly runtime version and do the check
                violator.Module.Runtime = TargetRuntime.Net_1_1;
                Rule.Active             = true;
                Rule.Initialize(Runner);
                Assert.IsFalse(Rule.Active, "Active");
            }
            catch {
                // rollback
                violator.Module.Runtime = realRuntime;
                Rule.Active             = true;
            }
        }
        public void CyclomaticComplexityMeasurementTest()
        {
            TypeDefinition type = DefinitionLoader.GetTypeDefinition <MethodsWithExpectedCC> ();
            int            actual_cc;
            int            expected_cc;

            foreach (MethodDefinition method in type.Methods)
            {
                if (method.IsConstructor)
                {
                    continue;
                }

                actual_cc   = AvoidComplexMethodsRule.GetCyclomaticComplexity(method);
                expected_cc = GetExpectedComplexity(method);
                Assert.AreEqual(expected_cc, actual_cc,
                                "CC for method '{0}' is {1} but should have been {2}.",
                                method.Name, actual_cc, expected_cc);
            }
        }
        private void AssertFailureCount <T> (int expectedCount)
        {
            TypeDefinition type = DefinitionLoader.GetTypeDefinition <T> ();

            PreCheck(type);

//			runner.OnType (type);
            foreach (MethodDefinition method in type.Methods)
            {
                runner.OnMethod(method);
            }

            PostCheck(rule);

            if (expectedCount != rule.DefectCount)
            {
                Assert.Fail("{0} failed: should have {1} defects but got {2}.",
                            typeof(T).Name, expectedCount, rule.DefectCount);
            }
        }
Example #23
0
 /// <summary>
 /// Asserts that the rule has failed to execute successfully.
 /// </summary>
 /// <param name="expectedCount">Expected defects count.</param>
 /// <typeparam name="T">Type to check.</typeparam>
 protected void AssertRuleFailure <T> (int expectedCount)
 {
     base.AssertRuleFailure(DefinitionLoader.GetTypeDefinition <T> (), expectedCount);
 }
Example #24
0
 /// <summary>
 /// Asserts that the rule has failed to execute successfully.
 /// </summary>
 /// <typeparam name="T">Type to check.</typeparam>
 protected void AssertRuleFailure <T> ()
 {
     base.AssertRuleFailure(DefinitionLoader.GetTypeDefinition <T> ());
 }
Example #25
0
 /// <summary>
 /// Asserts that the rule has been executed successfully.
 /// </summary>
 /// <typeparam name="T">Type to check.</typeparam>
 protected void AssertRuleSuccess <T> ()
 {
     base.AssertRuleSuccess(DefinitionLoader.GetTypeDefinition <T> ());
 }
        protected void AssertRuleDoesNotApply(Type type, string method)
        {
            TypeDefinition td = DefinitionLoader.GetTypeDefinition(type);

            base.AssertRuleDoesNotApply(DefinitionLoader.GetMethodDefinition(td, method, null));
        }
 private int GetSize(Type type)
 {
     return((int)AvoidLargeStructureRule.SizeOfStruct(DefinitionLoader.GetTypeDefinition(type)));
 }
        public void SuccessOnStaticClassTest()
        {
            TypeDefinition type = DefinitionLoader.GetTypeDefinition(typeof(ConsiderUsingStaticTypeTest).Assembly, "Test.Rules.Design.ConsiderUsingStaticTypeTest/StaticClass");

            AssertRuleSuccess(type);
        }
Example #29
0
 /// <summary>
 /// Asserts that the rule does not apply to the type.
 /// </summary>
 /// <typeparam name="T">Type to check.</typeparam>
 protected void AssertRuleDoesNotApply <T> ()
 {
     base.AssertRuleDoesNotApply(DefinitionLoader.GetTypeDefinition <T> ());
 }
        protected void AssertRuleFailure(Type type, string method, int expectedCount)
        {
            TypeDefinition td = DefinitionLoader.GetTypeDefinition(type);

            base.AssertRuleFailure(DefinitionLoader.GetMethodDefinition(td, method, null), expectedCount);
        }