Example #1
0
		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			Forms.Init();

			Framework = MobileDependencyProvider.GetFramework ();

			LoadApplication (new MobileTestApp (Framework));

			return base.FinishedLaunching (app, options);
		}
Example #2
0
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			Forms.Init (this, bundle);

			DependencyInjector.RegisterAssembly (typeof(NewTlsDependencyProvider).Assembly);

			Framework = TestFramework.GetLocalFramework (typeof(NewTlsDependencyProvider).Assembly);

			LoadApplication (new MobileTestApp (Framework));
		}
        public void TestApplyMatchingIfScopes(
            string environmentType, string nodeName, string expectedFirst, string expectedSecond, string expectedThird, string expectedFourth)
        {
            //-- Arrange

            var framework = new TestFramework(base.Module);
            framework.NodeConfiguration.EnvironmentType = environmentType;
            framework.NodeConfiguration.NodeName = nodeName;

            var one = framework.ConfigSection<ISectionOne>();
            var two = framework.ConfigSection<ISectionTwo>();

            var xml =
                @"<CONFIGURATION>
                    <IF environment-type='dev' comment='only for dev environments'>
                        <One first='1-DEV' />
                        <Two fourth='4-DEV' />
                    </IF>
                    <IF environment-type='prod' comment='only for prod environments'>
                        <One first='1-PROD' />
                        <Two fourth='4-PROD' />
                    </IF>
                    <IF node='BACKEND' comment='only for backend node instances'>
                        <One second='2-BACKEND' />
                        <Two third='3-BACKEND' />
                    </IF>
                    <IF node='!BACKEND' comment='for all but backend node instances'>
                        <One second='2-NOT-BACKEND' />
                        <Two third='3-NOT-BACKEND' />
                    </IF>
                </CONFIGURATION>";

            var loader = new XmlConfigurationLoader(
                framework,
                framework.LoggerAuto<IConfigurationLogger>(),
                new IConfigurationSection[] { one, two });

            //-- Act

            loader.LoadConfigurationDocument(XDocument.Parse(xml));

            //-- Assert

            Assert.That(one.First, Is.EqualTo(expectedFirst));
            Assert.That(one.Second, Is.EqualTo(expectedSecond));
            Assert.That(two.Third, Is.EqualTo(expectedThird));
            Assert.That(two.Fourth, Is.EqualTo(expectedFourth));
        }
Example #4
0
        public static bool PosTest3()
        {
            ExplStruct p;
            bool       retval = false;

            TestFramework.BeginScenario("\n\nTest #3 (Roundtrip of a simple structre (explicit layout) by reference. Verify that values updated on unmanaged side reflect on managed side)");
            //direct pinvoke

            //cdecl
            try
            {
                p = new ExplStruct(DialogResult.None, 10);
                TestFramework.LogInformation(" Case 2: Direct p/invoke cdecl calling convention");
                retval = DoCdeclSimpleExplStructByRef(ref p);

                if (retval == false)
                {
                    TestFramework.LogError("01", "PInvokeTests->PosTest3 : Unexpected error occurred on unmanaged side");
                    return(false);
                }
                if ((p.type != DialogResult.OK) || (!p.b))
                {
                    Console.WriteLine("\nExpected values:\n SimpleStruct->type=1\nSimpleStruct->b=TRUE\n");
                    Console.WriteLine("\nActual values:\n SimpleStruct->type=" + p.type + "\nSimpleStruct->b=" + p.b);
                    TestFramework.LogError("02", "PInvokeTests->PosTest3 : Returned values are different from expected values");
                    retval = false;
                }
            }
            catch (Exception e)
            {
                TestFramework.LogError("03", "Unexpected exception: " + e.ToString());
                retval = false;
            }

            //Delegate pinvoke --- cdecl
            try
            {
                p = new ExplStruct(DialogResult.None, 10);
                TestFramework.LogInformation(" Case 4: Delegate p/invoke cdecl calling convention");
                CdeclSimpleExplStructByRefDelegate std = GetFptrCdeclSimpleExplStructByRef(18);

                retval = std(ref p);

                if (retval == false)
                {
                    TestFramework.LogError("01", "PInvokeTests->PosTest3 : Unexpected error occurred on unmanaged side");
                    return(false);
                }
                if ((p.type != DialogResult.OK) || (!p.b))
                {
                    Console.WriteLine("\nExpected values:\n SimpleStruct->type=1\nSimpleStruct->b=TRUE\n");
                    Console.WriteLine("\nActual values:\n SimpleStruct->type=" + p.type + "\nSimpleStruct->b=" + p.b);
                    TestFramework.LogError("02", "PInvokeTests->PosTest3 : Returned values are different from expected values");
                    retval = false;
                }
            }
            catch (Exception e)
            {
                TestFramework.LogError("03", "Unexpected exception: " + e.ToString());
                retval = false;
            }


            return(retval);
        }
Example #5
0
 public void WhenDtoIsBlank_ShouldThrow_InputValidationException()
 {
     FluentActions.Invoking(() => TestFramework.SendAsync(new UpdatePartnerCommand()))
     .Should().ThrowExactly <InputValidationException>();
 }
Example #6
0
 public Server(TestApp app, TestFramework framework, ServerConnection server)
     : base(app)
 {
     this.framework = framework;
     this.server    = server;
 }
Example #7
0
        public static async Task <TestServer> StartServer(TestApp app, IPortableEndPoint address, TestFramework framework, CancellationToken cancellationToken)
        {
            var support    = DependencyInjector.Get <IServerHost> ();
            var connection = await support.Listen(address, cancellationToken);

            var serverConnection = await StartServer(app, framework, connection, cancellationToken);

            var server = new Server(app, framework, serverConnection);
            await server.Initialize(cancellationToken);

            return(server);
        }
Example #8
0
        private string GenerateUnitTestContents(TestGenerationContext context)
        {
            TestFramework testFramework = context.TestFramework;
            MockFramework mockFramework = context.MockFramework;

            string pascalCaseShortClassName = null;

            foreach (string suffix in ClassSuffixes)
            {
                if (className.EndsWith(suffix))
                {
                    pascalCaseShortClassName = suffix;
                    break;
                }
            }

            if (pascalCaseShortClassName == null)
            {
                pascalCaseShortClassName = className;
            }

            string classVariableName = pascalCaseShortClassName.Substring(0, 1).ToLowerInvariant() + pascalCaseShortClassName.Substring(1);

            string fileTemplate = StaticBoilerplateSettings.GetTemplate(mockFramework, TemplateType.File);
            var    builder      = new StringBuilder();

            for (int i = 0; i < fileTemplate.Length; i++)
            {
                char c = fileTemplate[i];
                if (c == '$')
                {
                    int endIndex = -1;
                    for (int j = i + 1; j < fileTemplate.Length; j++)
                    {
                        if (fileTemplate[j] == '$')
                        {
                            endIndex = j;
                            break;
                        }
                    }

                    if (endIndex < 0)
                    {
                        // We couldn't find the end index for the replacement property name. Continue.
                        builder.Append(c);
                    }
                    else
                    {
                        // Calculate values on demand from switch statement. Some are preset values, some need a bit of calc like base name,
                        // some are dependent on the test framework (attributes), some need to pull down other templates and loop through mock fields
                        string propertyName = fileTemplate.Substring(i + 1, endIndex - i - 1);
                        switch (propertyName)
                        {
                        case "UsingStatements":
                            WriteUsings(builder, context);
                            break;

                        case "Namespace":
                            builder.Append(context.UnitTestNamespace);
                            break;

                        case "MockFieldDeclarations":
                            WriteMockFieldDeclarations(builder, context);
                            break;

                        case "MockFieldInitializations":
                            WriteMockFieldInitializations(builder, context);
                            break;

                        case "ExplicitConstructor":
                            WriteExplicitConstructor(builder, context, FindIndent(fileTemplate, i));
                            break;

                        case "ClassName":
                            builder.Append(context.ClassName);
                            break;

                        case "ClassNameShort":
                            builder.Append(GetShortClassName(context.ClassName));
                            break;

                        case "ClassNameShortLower":
                            builder.Append(GetShortClassNameLower(context.ClassName));
                            break;

                        case "TestClassAttribute":
                            builder.Append(TestFrameworkAbstraction.GetTestClassAttribute(testFramework));
                            break;

                        case "TestInitializeAttribute":
                            builder.Append(TestFrameworkAbstraction.GetTestInitializeAttribute(testFramework));
                            break;

                        case "TestCleanupAttribute":
                            builder.Append(TestFrameworkAbstraction.GetTestCleanupAttribute(testFramework));
                            break;

                        case "TestMethodAttribute":
                            builder.Append(TestFrameworkAbstraction.GetTestMethodAttribute(testFramework));
                            break;

                        default:
                            // We didn't recognize it, just pass through.
                            builder.Append($"${propertyName}$");
                            break;
                        }

                        i = endIndex;
                    }
                }
                else
                {
                    builder.Append(c);
                }
            }

            SyntaxTree tree          = CSharpSyntaxTree.ParseText(builder.ToString());
            SyntaxNode formattedNode = Formatter.Format(tree.GetRoot(), CreateUnitTestBoilerplateCommandPackage.VisualStudioWorkspace);

            return(formattedNode.ToString());
        }
Example #9
0
 private static string GetTemplateSettingsKey(TestFramework testFramework, MockFramework mockFramework, TemplateType templateType)
 {
     return(GetTemplateSettingsKey(testFramework.Name, mockFramework.Name, templateType.ToString()));
 }
Example #10
0
 public CodeWriter(TestFramework testFramework)
 {
     TestFramework  = testFramework;
     m_ScopeTracker = new(this);         //We only need one. It can be reused.
 }
 bool IsSupportedByTestFramework(IProject project)
 {
     return(TestFramework.IsTestProject(project));
 }
 private static string GetDictionaryKey(TestFramework testFramework, MockFramework mockFramework, TemplateType templateType)
 {
     return($"{testFramework.Name}_{mockFramework.Name}_{templateType}");
 }
            private static void Issue17245_Case2(int breakingPaketLength)
            {
                int sequenceNumber = 0x3030;   //  "00"

                System.Console.Clear();
                Console.WriteLine("TestProcessFrameData Issue17245_Case2(): Interleaved RTSPResponse");
                Console.WriteLine("breakingPaketLength = " + breakingPaketLength);
                Console.WriteLine("Correct output is 3 rows saying 'ProcessRtpPacket()...', 1 yellow row, and finaly a single row 'ProcessRtpPacket()...':");
                Console.WriteLine("");

                TestFramework tf = new TestFramework();
                //Console.WriteLine(line + sequenceNumber);
                byte[] buffer = GeneratePayload(1400);
                Media.Rtp.RtpPacket p1 = new Media.Rtp.RtpPacket(2, false, false, false, 0, 0, _senderSSRC, sequenceNumber++, _timeStamp, buffer);
                buffer = p1.Prepare().ToArray();
                tf.Send(GenerateEncapsulatingHeader(buffer.Length));
                tf.Send(buffer);

                //Console.WriteLine(line + sequenceNumber);
                buffer = GeneratePayload(1400);
                Media.Rtp.RtpPacket p2 = new Media.Rtp.RtpPacket(2, false, false, false, 0, 0, _senderSSRC, sequenceNumber++, _timeStamp, buffer);
                buffer = p2.Prepare().ToArray();
                tf.Send(GenerateEncapsulatingHeader(buffer.Length));
                tf.Send(buffer);

                //Console.WriteLine(line + sequenceNumber);
                buffer = GeneratePayload(breakingPaketLength);
                Media.Rtp.RtpPacket p3 = new Media.Rtp.RtpPacket(2, false, false, false, 0, 0, _senderSSRC, sequenceNumber++, _timeStamp, buffer);
                buffer = p3.Prepare().ToArray();
                tf.Send(GenerateEncapsulatingHeader(buffer.Length));
                tf.Send(buffer);

                Media.Rtsp.RtspMessage keepAlive = new Media.Rtsp.RtspMessage(Media.Rtsp.RtspMessageType.Response);
                keepAlive.StatusCode = Media.Rtsp.RtspStatusCode.OK;
                keepAlive.CSeq = 34;
                keepAlive.SetHeader(Media.Rtsp.RtspHeaders.Session, "A9B8C7D6");
                keepAlive.SetHeader(Media.Rtsp.RtspHeaders.UserAgent, "Testing $UserAgent $009\r\n$\0:\0");
                keepAlive.SetHeader("Ignore", "$UserAgent $009\r\n$\0\0\aRTSP/1.0");
                keepAlive.SetHeader("$", string.Empty);
                keepAlive.SetHeader(Media.Rtsp.RtspHeaders.Date, DateTime.Now.ToUniversalTime().ToString("r"));
                buffer = keepAlive.Prepare().ToArray();
                tf.Send(buffer);

                //Console.WriteLine(line + sequenceNumber);
                buffer = GeneratePayload(1400);
                Media.Rtp.RtpPacket p4 = new Media.Rtp.RtpPacket(2, false, false, false, 0, 0, _senderSSRC, sequenceNumber++, _timeStamp, buffer);
                buffer = p4.Prepare().ToArray();
                tf.Send(GenerateEncapsulatingHeader(buffer.Length));
                tf.Send(buffer);

                //  Kick of the processing eventually ending up in RtpClient.ProcessFrameData()
                tf.HaveRtpClientWorkerThreadProcessSocketData();
            }
            private static void Issue17245_Case1(int breakingPaketLength)
            {
                int sequenceNumber = 0x3030;   //  "00"
                string line = "Case1(): SequenceNumber = ";

                System.Console.Clear();
                Console.WriteLine("TestProcessFrameData Issue17245_Case1(): Discarding of Encapsulating Frame Header");
                Console.WriteLine("breakingPaketLength = " + breakingPaketLength);
                Console.WriteLine("Correct output is 5 rows saying 'Case1()...' and 5 rows 'ProcessRtpPacket()...'");
                Console.WriteLine("No yellow rows!!!");
                Console.WriteLine("");

                TestFramework tf = new TestFramework();

                Console.WriteLine(line + sequenceNumber);
                byte[] buffer = GeneratePayload(1400);
                Media.Rtp.RtpPacket p1 = new Media.Rtp.RtpPacket(2, false, false, false, 0, 0, _senderSSRC, sequenceNumber++, _timeStamp, buffer);
                buffer = p1.Prepare().ToArray();
                tf.Send(GenerateEncapsulatingHeader(buffer.Length));
                tf.Send(buffer);

                Console.WriteLine(line + sequenceNumber);
                buffer = GeneratePayload(1400);
                Media.Rtp.RtpPacket p2 = new Media.Rtp.RtpPacket(2, false, false, false, 0, 0, _senderSSRC, sequenceNumber++, _timeStamp, buffer);
                buffer = p2.Prepare().ToArray();
                tf.Send(GenerateEncapsulatingHeader(buffer.Length));
                tf.Send(buffer);

                Console.WriteLine(line + sequenceNumber);
                buffer = GeneratePayload(breakingPaketLength); //  Length 1245 to 1247 looses packets and it does not recover
                Media.Rtp.RtpPacket p3 = new Media.Rtp.RtpPacket(2, false, false, false, 0, 0, _senderSSRC, sequenceNumber++, _timeStamp, buffer);
                buffer = p3.Prepare().ToArray();
                tf.Send(GenerateEncapsulatingHeader(buffer.Length));
                tf.Send(buffer);

                Console.WriteLine(line + sequenceNumber);
                buffer = GeneratePayload(1400);
                Media.Rtp.RtpPacket p4 = new Media.Rtp.RtpPacket(2, false, false, false, 0, 0, _senderSSRC, sequenceNumber++, _timeStamp, buffer);
                buffer = p4.Prepare().ToArray();
                tf.Send(GenerateEncapsulatingHeader(buffer.Length));
                tf.Send(buffer);

                Console.WriteLine(line + sequenceNumber);
                buffer = GeneratePayload(1400);
                Media.Rtp.RtpPacket p5 = new Media.Rtp.RtpPacket(2, false, false, false, 0, 0, _senderSSRC, sequenceNumber++, _timeStamp, buffer);
                buffer = p5.Prepare().ToArray();
                tf.Send(GenerateEncapsulatingHeader(buffer.Length));
                tf.Send(buffer);

                //  Kick of the processing eventually ending up in RtpClient.ProcessFrameData()
                tf.HaveRtpClientWorkerThreadProcessSocketData();
            }
            /// <summary>
            /// This test case is added to demonstrate the risk of handing a byte array to a constructor.
            /// A ctor can only return a single object even if the byte array it is given may contain more
            /// than one object.
            /// This violates OO as the caller is burdened with having to now about what should be a feature
            /// of using the class it is calling.
            /// </summary>
            public static void BackToBackRtspMessages()
            {
                System.Console.Clear();
                Console.WriteLine("TestProcessFrameData Case3(): Two back to back RTSP Responses");
                Console.WriteLine("Correct output would be 2 'ProcessInterleaveData():...' detailing RTSP responses CSeq 34 and 35:");
                Console.WriteLine("");

                TestFramework tf = new TestFramework();

                Media.Rtsp.RtspMessage keepAlive = new Media.Rtsp.RtspMessage(Media.Rtsp.RtspMessageType.Response);
                keepAlive.StatusCode = Media.Rtsp.RtspStatusCode.OK;
                keepAlive.CSeq = 34;
                keepAlive.SetHeader(Media.Rtsp.RtspHeaders.Session, "A9B8C7D6");
                keepAlive.SetHeader(Media.Rtsp.RtspHeaders.Date, DateTime.Now.ToUniversalTime().ToString("r"));
                byte[] buffer = keepAlive.Prepare().ToArray();
                tf.Send(buffer);

                keepAlive = new Media.Rtsp.RtspMessage(Media.Rtsp.RtspMessageType.Response);
                keepAlive.StatusCode = Media.Rtsp.RtspStatusCode.OK;
                keepAlive.CSeq = 35;
                keepAlive.SetHeader(Media.Rtsp.RtspHeaders.Session, "A9B8C7D6");
                keepAlive.SetHeader(Media.Rtsp.RtspHeaders.Date, DateTime.Now.ToUniversalTime().ToString("r"));
                buffer = keepAlive.Prepare().ToArray();
                tf.Send(buffer);

                //  Kick of the processing eventually ending up in RtpClient.ProcessFrameData()
                tf.HaveRtpClientWorkerThreadProcessSocketData();
            }
        public CodecStreamVerification VerifyCodecStream(int index)
        {
            var stream = _dataBlock.CodecStreams[index];
            var result = TestFramework.GetResults(stream);

            return(new CodecStreamVerification(stream, result, "Stream " + stream.StreamNumber + "(" + stream.Name + ") from " + _description + ", with Results:" + Environment.NewLine + TestFramework.GetDescriptionText(result)));
        }
Example #17
0
        private static void CreateEntryForTestFramework(string oldTemplate, TemplateType templateType, TestFramework testFramework, MockFramework mockFramework)
        {
            string newTemplate;

            // If it's a File template, we need to replace some framework-based placeholders for test attributes.
            if (templateType == TemplateType.File)
            {
                newTemplate = StringUtilities.ReplaceTokens(
                    oldTemplate,
                    (tokenName, propertyIndex, builder) =>
                {
                    switch (tokenName)
                    {
                    case "TestClassAttribute":
                        builder.Append(testFramework.TestClassAttribute);
                        break;

                    case "TestInitializeAttribute":
                        builder.Append(testFramework.TestInitializeAttribute);
                        break;

                    case "TestCleanupAttribute":
                        builder.Append(testFramework.TestCleanupAttribute);
                        break;

                    case "TestMethodAttribute":
                        builder.Append(testFramework.TestMethodAttribute);
                        break;

                    default:
                        // Pass through all other tokens.
                        builder.Append($"${tokenName}$");
                        break;
                    }
                });
            }
            else
            {
                newTemplate = oldTemplate;
            }

            Store.SetString(CollectionPath, GetTemplateSettingsKey(testFramework, mockFramework, templateType), newTemplate);
        }
Example #18
0
 public static void Throw(string message)
 {
     TestFramework.Throw(message);
 }
        private async Task <TestGenerationContext> CollectTestGenerationContextAsync(ProjectItemSummary selectedFile, EnvDTE.Project targetProject, TestFramework testFramework, MockFramework mockFramework)
        {
            string targetProjectNamespace = targetProject.Properties.Item("DefaultNamespace").Value as string;

            return(await this.CollectTestGenerationContextAsync(selectedFile, targetProjectNamespace, testFramework, mockFramework));
        }
 //-------------------------------------------------------------------------------------------------------------------------------------------------
 public TestThreadLog(TestFramework framework)
 {
     _framework = framework;
     _logId = framework.NewGuid();
     _startedAtUtc = framework.UtcNow;
 }
Example #21
0
 public void AlternatingRequestResponse()
 {
     TestFramework.RunOnce(new AlternatingRequestResponseThreads());
 }
 //-----------------------------------------------------------------------------------------------------------------------------------------------------
 public TestThreadLogAppender(TestFramework framework)
 {
     _framework = framework;
     _threadLog = new TestThreadLog(framework);
 }
Example #23
0
        private string GenerateUnitTestContentsOld(
            string unitTestNamespace,
            string className,
            string classNamespace,
            IList <InjectableProperty> properties,
            IList <InjectableType> constructorTypes)
        {
            TestFramework testFramework = Utilities.FindTestFramework(this.SelectedProject.Project);
            MockFramework mockFramework = Utilities.FindMockFramework(this.SelectedProject.Project);

            if (mockFramework == MockFramework.Unknown)
            {
                mockFramework = MockFramework.Moq;
            }

            string pascalCaseShortClassName = null;

            foreach (string suffix in ClassSuffixes)
            {
                if (className.EndsWith(suffix))
                {
                    pascalCaseShortClassName = suffix;
                    break;
                }
            }

            if (pascalCaseShortClassName == null)
            {
                pascalCaseShortClassName = className;
            }

            string classVariableName = pascalCaseShortClassName.Substring(0, 1).ToLowerInvariant() + pascalCaseShortClassName.Substring(1);

            List <InjectableType> injectedTypes = new List <InjectableType>(properties);

            injectedTypes.AddRange(constructorTypes.Where(t => t != null));

            var mockFields = new List <MockField>();

            foreach (InjectableType injectedType in injectedTypes)
            {
                mockFields.Add(
                    new MockField(
                        mockFramework == MockFramework.SimpleStubs ? "stub" + injectedType.TypeBaseName : "mock" + injectedType.TypeBaseName,
                        mockFramework == MockFramework.SimpleStubs ? "Stub" + injectedType.TypeName : injectedType.TypeName));
            }

            List <string> namespaces = new List <string>();

            namespaces.AddRange(MockFrameworkAbstraction.GetUsings(mockFramework));
            namespaces.Add(TestFrameworkAbstraction.GetUsing(testFramework));
            namespaces.Add(classNamespace);
            namespaces.AddRange(injectedTypes.Select(t => t.TypeNamespace));
            namespaces = namespaces.Distinct().ToList();
            namespaces.Sort(StringComparer.Ordinal);

            StringBuilder builder = new StringBuilder();

            foreach (string ns in namespaces)
            {
                builder.AppendLine($"using {ns};");
            }

            builder.Append(
                Environment.NewLine +
                "namespace ");

            builder.Append(unitTestNamespace);
            builder.Append(
                Environment.NewLine +
                "{" + Environment.NewLine +
                $"[{TestFrameworkAbstraction.GetTestClassAttribute(testFramework)}]" + Environment.NewLine +
                "public class ");
            builder.Append(className);
            builder.Append(
                "Tests" + Environment.NewLine +
                "{" + Environment.NewLine);
            if (mockFramework == MockFramework.Moq)
            {
                builder.Append("private MockRepository mockRepository;" + Environment.NewLine);

                if (mockFields.Count > 0)
                {
                    builder.AppendLine();
                }
            }

            foreach (MockField field in mockFields)
            {
                if (mockFramework == MockFramework.SimpleStubs)
                {
                    builder.AppendLine($"private {field.TypeName} {field.Name};");
                }
                else
                {
                    builder.AppendLine($"private Mock<{field.TypeName}> {field.Name};");
                }
            }

            builder.Append(
                Environment.NewLine +
                $"[{TestFrameworkAbstraction.GetTestInitializeAttribute(testFramework)}]" + Environment.NewLine +
                "public void TestInitialize()" + Environment.NewLine +
                "{" + Environment.NewLine);

            if (mockFramework == MockFramework.Moq)
            {
                builder.AppendLine("this.mockRepository = new MockRepository(MockBehavior.Strict);");

                if (mockFields.Count > 0)
                {
                    builder.AppendLine();
                }
            }

            foreach (MockField field in mockFields)
            {
                string fieldCreationStatement;

                if (mockFramework == MockFramework.SimpleStubs)
                {
                    fieldCreationStatement = $"new {field.TypeName}()";
                }
                else
                {
                    fieldCreationStatement = $"this.mockRepository.Create<{field.TypeName}>()";
                }

                builder.AppendLine($"this.{field.Name} = {fieldCreationStatement};");
            }

            builder.Append(
                "}" + Environment.NewLine +
                Environment.NewLine);

            if (mockFramework == MockFramework.Moq)
            {
                builder.Append(
                    $"[{TestFrameworkAbstraction.GetTestCleanupAttribute(testFramework)}]" + Environment.NewLine +
                    "public void TestCleanup()" + Environment.NewLine +
                    "{" + Environment.NewLine +
                    "this.mockRepository.VerifyAll();" + Environment.NewLine +
                    "}" + Environment.NewLine +
                    Environment.NewLine);
            }

            builder.Append(
                $"[{TestFrameworkAbstraction.GetTestMethodAttribute(testFramework)}]" + Environment.NewLine +
                "public void TestMethod1()" + Environment.NewLine +
                "{" + Environment.NewLine +
                "" + Environment.NewLine +
                "" + Environment.NewLine);

            builder.AppendLine($"{className} {classVariableName} = this.Create{pascalCaseShortClassName}();");
            builder.AppendLine("");
            builder.AppendLine("");
            builder.AppendLine("}");
            builder.AppendLine();
            builder.AppendLine($"private {className} Create{pascalCaseShortClassName}()");
            builder.AppendLine("{");
            builder.Append($"return new {className}");

            if (constructorTypes.Count > 0)
            {
                builder.AppendLine("(");

                for (int i = 0; i < constructorTypes.Count; i++)
                {
                    string         mockReferenceStatement;
                    InjectableType constructorType = constructorTypes[i];
                    if (constructorType == null)
                    {
                        mockReferenceStatement = "TODO";
                    }
                    else if (mockFramework == MockFramework.SimpleStubs)
                    {
                        mockReferenceStatement = $"this.stub{constructorType.TypeBaseName}";
                    }
                    else
                    {
                        mockReferenceStatement = $"this.mock{constructorType.TypeBaseName}.Object";
                    }

                    builder.Append($"    {mockReferenceStatement}");

                    if (i < constructorTypes.Count - 1)
                    {
                        builder.AppendLine(",");
                    }
                }

                builder.Append(")");
            }
            else if (properties.Count == 0)
            {
                builder.Append("()");
            }

            if (properties.Count > 0)
            {
                builder.AppendLine();
                builder.AppendLine("{");

                foreach (InjectableProperty property in properties)
                {
                    string mockReferenceStatement;
                    if (mockFramework == MockFramework.SimpleStubs)
                    {
                        mockReferenceStatement = $"this.stub{property.TypeBaseName}";
                    }
                    else
                    {
                        mockReferenceStatement = $"this.mock{property.TypeBaseName}.Object";
                    }

                    builder.AppendLine($"{property.Name} = {mockReferenceStatement},");
                }

                builder.Append(@"}");
            }

            builder.AppendLine(";");
            builder.AppendLine("}");
            builder.AppendLine("}");
            builder.AppendLine("}");

            SyntaxTree tree          = CSharpSyntaxTree.ParseText(builder.ToString());
            SyntaxNode formattedNode = Formatter.Format(tree.GetRoot(), CreateUnitTestBoilerplateCommandPackage.VisualStudioWorkspace);

            return(formattedNode.ToString());

            //return builder.ToString();
        }
        private async Task <TestGenerationContext> CollectTestGenerationContextAsync(
            ProjectItemSummary selectedFile,
            string targetProjectNamespace,
            TestFramework testFramework,
            MockFramework mockFramework,
            IBoilerplateSettings settings)
        {
            Microsoft.CodeAnalysis.Solution solution = CreateUnitTestBoilerplateCommandPackage.VisualStudioWorkspace.CurrentSolution;
            DocumentId documentId = solution.GetDocumentIdsWithFilePath(selectedFile.FilePath).FirstOrDefault();

            if (documentId == null)
            {
                throw new InvalidOperationException("Could not find document in solution with file path " + selectedFile.FilePath);
            }

            var document = solution.GetDocument(documentId);

            SyntaxNode root = await document.GetSyntaxRootAsync();

            SemanticModel semanticModel = await document.GetSemanticModelAsync();

            SyntaxNode firstClassLikeDeclaration = root.DescendantNodes().FirstOrDefault(node =>
            {
                var kind = node.Kind();
                return(kind == SyntaxKind.ClassDeclaration || kind == SyntaxKind.StructDeclaration || kind == (SyntaxKind)9063);                // record - Cannot update CodeAnalysis library because it's not found in VS 2019
            });

            if (firstClassLikeDeclaration == null)
            {
                throw new InvalidOperationException("Could not find class, struct or record declaration.");
            }

            if (firstClassLikeDeclaration.ChildTokens().Any(node => node.Kind() == SyntaxKind.AbstractKeyword))
            {
                throw new InvalidOperationException("Cannot unit test an abstract class.");
            }

            SyntaxToken classIdentifierToken = firstClassLikeDeclaration.ChildTokens().FirstOrDefault(n => n.Kind() == SyntaxKind.IdentifierToken);

            if (classIdentifierToken == default(SyntaxToken))
            {
                throw new InvalidOperationException("Could not find class identifier.");
            }

            object namespaceDeclarationSyntax = null;

            // 8842 is NamespaceDeclaration
            // 8845 is FileScopedNamespaceDeclaration
            // We would normally look for a node descended from BaseNamespaceDeclarationSyntax, but we don't have that type defined in the v1 Microsoft.CodeAnalysis DLL.
            // We can fix this once we are building against a higher version and can drop support for VS 2019.
            if (!TypeUtilities.TryGetParentSyntax(firstClassLikeDeclaration, (syntaxNode) => { return(syntaxNode.RawKind == 8842 || syntaxNode.RawKind == 8845); }, out namespaceDeclarationSyntax))
            {
                throw new InvalidOperationException("Could not find class namespace.");
            }

            // Find property injection types
            var injectableProperties = new List <InjectableProperty>();

            // We need to get the name via reflection since the DLL we are building against does not have the BaseNamespaceDeclarationSyntax or FileScopedNamespaceDeclarationSyntax types.
            string qualifiedNamespaceString = namespaceDeclarationSyntax.GetType().GetProperty("Name").GetValue(namespaceDeclarationSyntax, null).ToString();

            string           classFullName = qualifiedNamespaceString + "." + classIdentifierToken;
            INamedTypeSymbol classType     = semanticModel.Compilation.GetTypeByMetadataName(classFullName);

            foreach (ISymbol member in classType.GetBaseTypesAndThis().SelectMany(n => n.GetMembers()))
            {
                if (member.Kind == SymbolKind.Property)
                {
                    IPropertySymbol property = (IPropertySymbol)member;

                    foreach (AttributeData attribute in property.GetAttributes())
                    {
                        if (PropertyInjectionAttributeNames.Contains(attribute.AttributeClass.ToString()))
                        {
                            var injectableProperty = InjectableProperty.TryCreateInjectableProperty(property.Name, property.Type.ToString(), mockFramework);
                            if (injectableProperty != null)
                            {
                                injectableProperties.Add(injectableProperty);
                            }
                        }
                    }
                }
            }

            string className = classIdentifierToken.ToString();

            // Find constructor injection types
            List <InjectableType> constructorInjectionTypes = new List <InjectableType>();

            SyntaxNode constructorDeclaration = firstClassLikeDeclaration.ChildNodes().FirstOrDefault(n => n.Kind() == SyntaxKind.ConstructorDeclaration);

            if (constructorDeclaration != null)
            {
                constructorInjectionTypes.AddRange(
                    GetParameterListNodes(constructorDeclaration)
                    .Select(node => InjectableType.TryCreateInjectableTypeFromParameterNode(node, semanticModel, mockFramework)));
            }

            // Find public method declarations
            IList <MethodDescriptor> methodDeclarations = new List <MethodDescriptor>();

            foreach (MethodDeclarationSyntax methodDeclaration in
                     firstClassLikeDeclaration.ChildNodes().Where(
                         n => n.Kind() == SyntaxKind.MethodDeclaration &&
                         ((MethodDeclarationSyntax)n).Modifiers.Any(m => m.IsKind(SyntaxKind.PublicKeyword))))
            {
                var parameterList  = GetParameterListNodes(methodDeclaration).ToList();
                var parameterTypes = GetArgumentDescriptors(parameterList, semanticModel, mockFramework);

                var attributeList = GetAttributeListNodes(methodDeclaration);

                var isAsync =
                    methodDeclaration.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)) ||
                    DoesReturnTask(methodDeclaration);

                var hasReturnType = !DoesReturnNonGenericTask(methodDeclaration) && !DoesReturnVoid(methodDeclaration);

                string returnType = methodDeclaration.ReturnType.ToFullString();

                methodDeclarations.Add(new MethodDescriptor(methodDeclaration.Identifier.Text, parameterTypes, isAsync, hasReturnType, returnType, attributeList));
            }

            string unitTestNamespace;

            string relativePath = this.GetRelativePath(selectedFile);

            if (string.IsNullOrEmpty(relativePath))
            {
                unitTestNamespace = targetProjectNamespace;
            }
            else
            {
                List <string> defaultNamespaceParts  = targetProjectNamespace.Split('.').ToList();
                List <string> unitTestNamespaceParts = new List <string>(defaultNamespaceParts);
                unitTestNamespaceParts.AddRange(relativePath.Split('\\'));

                unitTestNamespace = string.Join(".", unitTestNamespaceParts);
            }

            List <InjectableType> injectedTypes = new List <InjectableType>(injectableProperties);

            injectedTypes.AddRange(constructorInjectionTypes.Where(t => t != null));

            GenerateMockNames(injectedTypes);

            return(new TestGenerationContext(
                       mockFramework,
                       testFramework,
                       document,
                       settings,
                       unitTestNamespace,
                       className,
                       qualifiedNamespaceString,
                       injectableProperties,
                       constructorInjectionTypes,
                       injectedTypes,
                       methodDeclarations));
        }
Example #25
0
 public LocalTestServer(TestApp app, TestFramework framework)
     : base(app)
 {
     Framework = framework;
 }
Example #26
0
 public void RevertTemplateToDefault(TestFramework testFramework, MockFramework mockFramework)
 {
     this.store.RevertTemplateToDefault(testFramework, mockFramework);
 }
Example #27
0
 static Vector4 ToVector4(TestFramework.Color color)
 {
     return new Vector4(color.Red, color.Green, color.Blue, 1f);
 }
        public SelfTestDetectionsResult RunDetectionTests(IList <Project> targetProjects)
        {
            var dte = (DTE2)ServiceProvider.GlobalProvider.GetService(typeof(DTE));

            var result = new SelfTestDetectionsResult();

            var frameworkPickerService = new FrameworkPickerService();
            var defaultSettings        = new MockBoilerplateSettings
            {
                PreferredTestFramework = null,
                PreferredMockFramework = null
            };

            var vsMoqSettings = new MockBoilerplateSettings
            {
                PreferredTestFramework = TestFrameworks.Get(TestFrameworks.VisualStudioName),
                PreferredMockFramework = MockFrameworks.Get(MockFrameworks.MoqName)
            };

            var nunitNSubSettings = new MockBoilerplateSettings
            {
                PreferredTestFramework = TestFrameworks.Get(TestFrameworks.NUnitName),
                PreferredMockFramework = MockFrameworks.Get(MockFrameworks.NSubstituteName)
            };

            var testList = new List <SelfTestDetectionTest>
            {
                new SelfTestDetectionTest("AutoMoqTestCases", defaultSettings, TestFrameworks.VisualStudioName, MockFrameworks.AutoMoqName),
                new SelfTestDetectionTest("NetCoreMoqTestCases", defaultSettings, TestFrameworks.VisualStudioName, MockFrameworks.MoqName),
                new SelfTestDetectionTest("NetCoreNSubstituteTestCases", defaultSettings, TestFrameworks.VisualStudioName, MockFrameworks.NSubstituteName),
                new SelfTestDetectionTest("NetCoreNUnitTestCases", defaultSettings, TestFrameworks.NUnitName, MockFrameworks.MoqName),
                new SelfTestDetectionTest("NetCoreSimpleStubsTestCases", defaultSettings, TestFrameworks.VisualStudioName, MockFrameworks.SimpleStubsName),
                new SelfTestDetectionTest("NetCoreVSRhinoMocksTestCases", defaultSettings, TestFrameworks.VisualStudioName, MockFrameworks.RhinoMocksName),
                new SelfTestDetectionTest("NoFrameworkTestCases", defaultSettings, TestFrameworks.VisualStudioName, MockFrameworks.MoqName),
                new SelfTestDetectionTest("NoFrameworkTestCases", nunitNSubSettings, TestFrameworks.NUnitName, MockFrameworks.NSubstituteName),
                new SelfTestDetectionTest("NSubstituteTestCases", defaultSettings, TestFrameworks.VisualStudioName, MockFrameworks.NSubstituteName),
                new SelfTestDetectionTest("NUnitTestCases", defaultSettings, TestFrameworks.NUnitName, MockFrameworks.MoqName),
                new SelfTestDetectionTest("NUnitUwpTestCases", defaultSettings, TestFrameworks.NUnitName, MockFrameworks.SimpleStubsName),
                new SelfTestDetectionTest("SimpleStubsTestCases", defaultSettings, TestFrameworks.VisualStudioName, MockFrameworks.SimpleStubsName),
                new SelfTestDetectionTest("VSRhinoMocksTestCases", defaultSettings, TestFrameworks.VisualStudioName, MockFrameworks.RhinoMocksName),
                new SelfTestDetectionTest("VSTestCases", defaultSettings, TestFrameworks.VisualStudioName, MockFrameworks.MoqName),
                new SelfTestDetectionTest("XUnitMoqTestCases", defaultSettings, TestFrameworks.XUnitName, MockFrameworks.MoqName),
                new SelfTestDetectionTest("MultipleFrameworkTestCases", defaultSettings, TestFrameworks.NUnitName, MockFrameworks.NSubstituteName),
                new SelfTestDetectionTest("MultipleFrameworkTestCases", vsMoqSettings, TestFrameworks.VisualStudioName, MockFrameworks.MoqName),
            };

            var failures = new List <string>();

            foreach (SelfTestDetectionTest test in testList)
            {
                result.TotalCount++;

                string projectFileName = GetFileNameFromSandboxProjectName(test.ProjectName, dte);

                frameworkPickerService.Settings = test.Settings;

                TestFramework actualTestFramework = frameworkPickerService.FindTestFramework(projectFileName);
                MockFramework actualMockFramework = frameworkPickerService.FindMockFramework(projectFileName);

                if (test.ExpectedTestFramework != actualTestFramework.Name)
                {
                    failures.Add($"Expected {test.ExpectedTestFramework} test framework for {test.ProjectName} but got {actualTestFramework.Name}. (Preferred Framework: {test.Settings.PreferredTestFramework})");
                }
                else if (test.ExpectedMockFramework != actualMockFramework.Name)
                {
                    failures.Add($"Expected {test.ExpectedMockFramework} mock framework for {test.ProjectName} but got {actualMockFramework.Name}. (Preferred Framework: {test.Settings.PreferredMockFramework})");
                }
                else
                {
                    result.SucceededCount++;
                }
            }

            result.Failures = failures;

            return(result);
        }
Example #29
0
        public static bool PosTest2()
        {
            string s      = "Before";
            bool   retval = true;
            double d      = 3.142;
            Sstr   p      = new Sstr(100, false, s);

            TestFramework.BeginScenario("\n\nTest #2 (Roundtrip of a simple structre by value. Verify that values updated on unmanaged side reflect on managed side)");
            //direct pinvoke

            // //cdecl calling convention
            try
            {
                TestFramework.LogInformation(" Case 2: Direct p/invoke cdecl calling convention");
                Sstr_simple simple = new Sstr_simple(100, false, d);
                simple = DoCdeclSimpleStruct(simple, ref retval);

                if (retval == false)
                {
                    TestFramework.LogError("01", "PInvokeTests->PosTest2 : values of passed in structure not matched with expected once on unmanaged side.");
                    return(false);
                }
                if ((simple.a != 101) || (!simple.b) || (simple.c != 10.11))
                {
                    Console.WriteLine("\nExpected values:\n SimpleStruct->a=101\nSimpleStruct->b=TRUE\nSimpleStruct->c=10.11\n");
                    Console.WriteLine("\nActual values:\n SimpleStruct->a=" + simple.a + "\nSimpleStruct->b=" + simple.b + "\nSimpleStruct->c=" + simple.c + "\n");
                    TestFramework.LogError("02", "PInvokeTests->PosTest2 : Returned values are different from expected values");
                    retval = false;
                }
            }
            catch (Exception e)
            {
                TestFramework.LogError("03", "Unexpected exception: " + e.ToString());
                retval = false;
            }

            // //delegate pinvoke

            // //cdecl calling convention
            try
            {
                TestFramework.LogInformation(" Case 4: Delegate p/invoke cdecl calling convention");
                Sstr_simple simple            = new Sstr_simple(100, false, d);
                CdeclSimpleStructDelegate std = GetFptrCdeclSimpleStruct(16);

                IntPtr st = std(simple, ref retval);
                simple = Marshal.PtrToStructure <Sstr_simple>(st);


                if (retval == false)
                {
                    TestFramework.LogError("01", "PInvokeTests->PosTest2 : values of passed in structure not matched with expected once on unmanaged side.");
                    return(false);
                }
                if ((simple.a != 101) || (!simple.b) || (simple.c != 10.11))
                {
                    Console.WriteLine("\nExpected values:\n SimpleStruct->a=101\nSimpleStruct->b=TRUE\nSimpleStruct->c=10.11\n");
                    Console.WriteLine("\nActual values:\n SimpleStruct->a=" + simple.a + "\nSimpleStruct->b=" + simple.b + "\nSimpleStruct->c=" + simple.c + "\n");
                    TestFramework.LogError("02", "PInvokeTests->PosTest2 : Returned values are different from expected values");
                    retval = false;
                }
            }
            catch (Exception e)
            {
                TestFramework.LogError("03", "Unexpected exception: " + e.ToString());
                retval = false;
            }
            return(retval);
        }
        public async System.Threading.Tasks.Task GenerateTestFilesAsync(Project classesProject)
        {
            ProjectItem casesFolder = classesProject.ProjectItems.Item("Cases");

            var    dte = (DTE2)ServiceProvider.GlobalProvider.GetService(typeof(DTE));
            string selfTestFilesDirectory = SolutionUtilities.GetSelfTestDirectoryFromSandbox(dte);
            string targetFolder           = Path.Combine(selfTestFilesDirectory, "Actual");

            if (!Directory.Exists(targetFolder))
            {
                Directory.CreateDirectory(targetFolder);
            }

            var classNames = new List <string>();

            foreach (ProjectItem classItem in casesFolder.ProjectItems)
            {
                classNames.Add(Path.GetFileNameWithoutExtension(classItem.Name));
            }

            // testFW|mockFW|className
            var testDefinitions = new HashSet <string>();

            // First, iterate over all test frameworks with Moq and choose all classes
            MockFramework moqFramework = MockFrameworks.Get(MockFrameworks.MoqName);

            foreach (TestFramework testFramework in TestFrameworks.List)
            {
                foreach (string className in classNames)
                {
                    TryAddTestDefinition(testDefinitions, testFramework, moqFramework, className);
                }
            }

            // Next, iterate over all mock frameworks with VS framework and choose all classes
            TestFramework vsFramework = TestFrameworks.Get(TestFrameworks.VisualStudioName);

            foreach (MockFramework mockFramework in MockFrameworks.List)
            {
                foreach (string className in classNames)
                {
                    TryAddTestDefinition(testDefinitions, vsFramework, mockFramework, className);
                }
            }

            // Last, choose a single file and iterate over all mock frameworks and test frameworks
            string classWithGenericInterface = "ClassWithGenericInterface";

            foreach (TestFramework testFramework in TestFrameworks.List)
            {
                foreach (MockFramework mockFramework in MockFrameworks.List)
                {
                    TryAddTestDefinition(testDefinitions, testFramework, mockFramework, classWithGenericInterface);
                }
            }

            foreach (string testDefinition in testDefinitions)
            {
                string[] parts = testDefinition.Split('|');

                string testFrameworkName = parts[0];
                string mockFrameworkName = parts[1];
                string className         = parts[2];

                await this.GenerateTestFileAsync(classesProject, TestFrameworks.Get(testFrameworkName), MockFrameworks.Get(mockFrameworkName), className, targetFolder);
            }
        }
Example #31
0
        public static bool PosTest4()
        {
            ExplStruct p;
            bool       retval = false;

            TestFramework.BeginScenario("\n\nTest #4 (Roundtrip of a simple structre (Explicit layout) by value. Verify that values updated on unmanaged side reflect on managed side)");
            //direct pinvoke

            //cdecl
            try
            {
                p = new ExplStruct(DialogResult.OK, false);
                TestFramework.LogInformation(" Case 2: Direct p/invoke cdecl calling convention");
                p = DoCdeclSimpleExplStruct(p, ref retval);
                if (retval == false)
                {
                    TestFramework.LogError("01", "PInvokeTests->PosTest2 : values of passed in structure not matched with expected once on unmanaged side.");
                    return(false);
                }
                if ((p.type != DialogResult.Cancel) || (p.c != 3.142))
                {
                    Console.WriteLine("\nExpected values:\n SimpleStruct->a=2\nSimpleStruct->c=3.142\n");
                    Console.WriteLine("\nActual values:\n SimpleStruct->a=" + p.type + "\nSimpleStruct->c=" + p.c + "\n");
                    TestFramework.LogError("02", "PInvokeTests->PosTest4 : Returned values are different from expected values");
                    retval = false;
                }
            }
            catch (Exception e)
            {
                TestFramework.LogError("03", "Unexpected exception: " + e.ToString());
                retval = false;
            }

            //delegate pinvoke

            //cdecl
            try
            {
                p = new ExplStruct(DialogResult.OK, false);
                TestFramework.LogInformation(" Case 4: Direct p/invoke cdecl calling convention");

                CdeclSimpleExplStructDelegate std = GetFptrCdeclSimpleExplStruct(20);

                IntPtr st = std(p, ref retval);
                p = Marshal.PtrToStructure <ExplStruct>(st);

                if (retval == false)
                {
                    TestFramework.LogError("01", "PInvokeTests->PosTest2 : values of passed in structure not matched with expected once on unmanaged side.");
                    return(false);
                }
                if ((p.type != DialogResult.Cancel) || (p.c != 3.142))
                {
                    Console.WriteLine("\nExpected values:\n SimpleStruct->a=2\nSimpleStruct->c=3.142\n");
                    Console.WriteLine("\nActual values:\n SimpleStruct->a=" + p.type + "\nSimpleStruct->c=" + p.c + "\n");
                    TestFramework.LogError("02", "PInvokeTests->PosTest4 : Returned values are different from expected values");
                    retval = false;
                }
            }
            catch (Exception e)
            {
                TestFramework.LogError("03", "Unexpected exception: " + e.ToString());
                retval = false;
            }
            return(retval);
        }
 private static string CreateTestDefinition(TestFramework testFramework, MockFramework mockFramework, string className)
 {
     return($"{testFramework.Name}|{mockFramework.Name}|{className}");
 }
 /// <summary>
 /// Locates the test unit with the specified fully qualified name from the provided test framework
 /// </summary>
 /// <param name="root">The framework from which to locate the test unit</param>
 /// <param name="fullyQualifiedName">The test unit's fully qualified name to locate</param>
 /// <returns>The located test unit or null if it was not found</returns>
 public static TestUnit Locate(TestFramework root, string fullyQualifiedName)
 {
     return(Locate(root?.MasterTestSuite, fullyQualifiedName));
 }
        public async System.Threading.Tasks.Task GenerateTestFileAsync(Project classesProject, TestFramework testFramework, MockFramework mockFramework, string className, string targetFolder)
        {
            // TODO: Calc targetFilePath from all the inputs
            string targetFileName = $"{testFramework.Name}_{mockFramework.Name}_{className}.cs";
            string targetFilePath = Path.Combine(targetFolder, targetFileName);

            ProjectItem casesFolder = classesProject.ProjectItems.Item("Cases");
            ProjectItem classToTest = casesFolder.ProjectItems.Item(className + ".cs");

            IComponentModel componentModel        = (IComponentModel)ServiceProvider.GlobalProvider.GetService(typeof(SComponentModel));
            var             testGenerationService = componentModel.GetService <ITestGenerationService>();
            await testGenerationService.GenerateUnitTestFileAsync(new ProjectItemSummary(classToTest), targetFilePath, "UnitTestBoilerplate.SelfTest", testFramework, mockFramework);
        }
Example #35
0
 public static void SetTemplate(TestFramework testFramework, MockFramework mockFramework, TemplateType templateType, string template)
 {
     Store.SetString(CollectionPath, GetTemplateSettingsKey(testFramework, mockFramework, templateType), template);
 }
 //-----------------------------------------------------------------------------------------------------------------------------------------------------
 private ConfigurationSectionFactory CreateFactoryUnderTest()
 {
     var framework = new TestFramework(base.Module);
     return new ConfigurationSectionFactory(framework.Components, base.Module);
 }
        private async Task <TestGenerationContext> CollectTestGenerationContextAsync(
            ProjectItemSummary selectedFile,
            string targetProjectNamespace,
            TestFramework testFramework,
            MockFramework mockFramework)
        {
            Microsoft.CodeAnalysis.Solution solution = CreateUnitTestBoilerplateCommandPackage.VisualStudioWorkspace.CurrentSolution;
            DocumentId documentId = solution.GetDocumentIdsWithFilePath(selectedFile.FilePath).FirstOrDefault();

            if (documentId == null)
            {
                throw new InvalidOperationException("Could not find document in solution with file path " + selectedFile.FilePath);
            }

            var document = solution.GetDocument(documentId);

            SyntaxNode root = await document.GetSyntaxRootAsync();

            SemanticModel semanticModel = await document.GetSemanticModelAsync();

            SyntaxNode firstClassDeclaration = root.DescendantNodes().FirstOrDefault(node => node.Kind() == SyntaxKind.ClassDeclaration);

            if (firstClassDeclaration == null)
            {
                throw new InvalidOperationException("Could not find class declaration.");
            }

            if (firstClassDeclaration.ChildTokens().Any(node => node.Kind() == SyntaxKind.AbstractKeyword))
            {
                throw new InvalidOperationException("Cannot unit test an abstract class.");
            }

            SyntaxToken classIdentifierToken = firstClassDeclaration.ChildTokens().FirstOrDefault(n => n.Kind() == SyntaxKind.IdentifierToken);

            if (classIdentifierToken == default(SyntaxToken))
            {
                throw new InvalidOperationException("Could not find class identifier.");
            }

            NamespaceDeclarationSyntax namespaceDeclarationSyntax = null;

            if (!TypeUtilities.TryGetParentSyntax(firstClassDeclaration, out namespaceDeclarationSyntax))
            {
                throw new InvalidOperationException("Could not find class namespace.");
            }

            // Find property injection types
            var injectableProperties = new List <InjectableProperty>();

            string           classFullName = namespaceDeclarationSyntax.Name + "." + classIdentifierToken;
            INamedTypeSymbol classType     = semanticModel.Compilation.GetTypeByMetadataName(classFullName);

            foreach (ISymbol member in classType.GetBaseTypesAndThis().SelectMany(n => n.GetMembers()))
            {
                if (member.Kind == SymbolKind.Property)
                {
                    IPropertySymbol property = (IPropertySymbol)member;

                    foreach (AttributeData attribute in property.GetAttributes())
                    {
                        if (PropertyInjectionAttributeNames.Contains(attribute.AttributeClass.ToString()))
                        {
                            var injectableProperty = InjectableProperty.TryCreateInjectableProperty(property.Name, property.Type.ToString(), mockFramework);
                            if (injectableProperty != null)
                            {
                                injectableProperties.Add(injectableProperty);
                            }
                        }
                    }
                }
            }

            string className = classIdentifierToken.ToString();

            // Find constructor injection types
            var        constructorInjectionTypes = new List <InjectableType>();
            SyntaxNode constructorDeclaration    = firstClassDeclaration.ChildNodes().FirstOrDefault(n => n.Kind() == SyntaxKind.ConstructorDeclaration);

            if (constructorDeclaration != null)
            {
                SyntaxNode parameterListNode = constructorDeclaration.ChildNodes().First(n => n.Kind() == SyntaxKind.ParameterList);
                var        parameterNodes    = parameterListNode.ChildNodes().Where(n => n.Kind() == SyntaxKind.Parameter);

                foreach (SyntaxNode node in parameterNodes)
                {
                    constructorInjectionTypes.Add(InjectableType.TryCreateInjectableTypeFromParameterNode(node, semanticModel, mockFramework));
                }
            }

            string unitTestNamespace;

            string relativePath = this.GetRelativePath(selectedFile);

            if (string.IsNullOrEmpty(relativePath))
            {
                unitTestNamespace = targetProjectNamespace;
            }
            else
            {
                List <string> defaultNamespaceParts  = targetProjectNamespace.Split('.').ToList();
                List <string> unitTestNamespaceParts = new List <string>(defaultNamespaceParts);
                unitTestNamespaceParts.AddRange(relativePath.Split('\\'));

                unitTestNamespace = string.Join(".", unitTestNamespaceParts);
            }

            List <InjectableType> injectedTypes = new List <InjectableType>(injectableProperties);

            injectedTypes.AddRange(constructorInjectionTypes.Where(t => t != null));

            GenerateMockNames(injectedTypes);

            return(new TestGenerationContext(
                       mockFramework,
                       testFramework,
                       unitTestNamespace,
                       className,
                       namespaceDeclarationSyntax.Name.ToString(),
                       injectableProperties,
                       constructorInjectionTypes,
                       injectedTypes));
        }
Example #38
0
 public void SeparateThread()
 {
     TestFramework.RunOnce(new SeparateThreads());
 }
        public void DiscoverTests(string testFolderPath, TestFramework testFx, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
        {
            var fileList = Directory.EnumerateFiles(testFolderPath, "*.js", SearchOption.AllDirectories).Where(x => !x.Contains(NodejsConstants.NodeModulesFolder));

            this.DiscoverTests(fileList, testFx, logger, discoverySink);
        }
Example #40
0
 public void RespondFirst()
 {
     TestFramework.RunOnce(new RespondFirstThreads());
 }