public void ProjectOutputBinPathChange_CPS()
        {
            var initialBinPath = @"C:\test.dll";

            using (var environment = new TestEnvironment())
            using (var project = CSharpHelpers.CreateCSharpCPSProject(environment, "Test", $"/out:{initialBinPath}"))
            {
                Assert.Equal(initialBinPath, project.TryGetBinOutputPath());
                Assert.Equal(initialBinPath, project.TryGetObjOutputPath());

                // Change output folder.
                var newBinPath = @"C:\NewFolder\test.dll";
                project.SetCommandLineArguments($"/out:{newBinPath}");
                Assert.Equal(newBinPath, project.TryGetBinOutputPath());
                Assert.Equal(newBinPath, project.TryGetObjOutputPath());

                // Change output file name.
                newBinPath = @"C:\NewFolder\test2.dll";
                project.SetCommandLineArguments($"/out:{newBinPath}");
                Assert.Equal(newBinPath, project.TryGetBinOutputPath());
                Assert.Equal(newBinPath, project.TryGetObjOutputPath());

                // Change output file name and folder.
                newBinPath = @"C:\NewFolder3\test3.dll";
                project.SetCommandLineArguments($"/out:{newBinPath}");
                Assert.Equal(newBinPath, project.TryGetBinOutputPath());
                Assert.Equal(newBinPath, project.TryGetObjOutputPath());
            }
        }
        public override string GenerateErrorMessage(TestEnvironment environment)
        {
            const string format = @"
            {0}
            should {1}be within
            {2}
            of
            {3}
            but was
            {4}";

            var codePart = environment.GetCodePart();
            var tolerance = environment.Tolerance.Inspect();
            var expectedValue = environment.Expected.Inspect();
            var actualValue = environment.Actual.Inspect();
            var negated = environment.ShouldMethod.Contains("Not") ? "not " : string.Empty;

            var message = string.Format(format, codePart, negated, tolerance, expectedValue, actualValue);

            if (environment.Actual.CanGenerateDifferencesBetween(environment.Expected))
            {
                message += string.Format(@"
            difference
            {0}",
                    environment.Actual.HighlightDifferencesBetween(environment.Expected));
            }

            return message;
        }
Exemple #3
0
        public static CPSProject CreateCSharpCPSProject(TestEnvironment environment, string projectName, Guid projectGuid, params string[] commandLineArguments)
        {
            var projectFilePath = Path.GetTempPath();
            var binOutputPath = GetOutputPathFromArguments(commandLineArguments) ?? Path.Combine(projectFilePath, projectName + ".dll");

            return CreateCSharpCPSProject(environment, projectName, projectFilePath, binOutputPath, projectGuid, commandLineArguments);
        }
        public void AddCyclicProjectReferencesDeep()
        {
            using (var environment = new TestEnvironment())
            {
                var project1 = CreateCSharpProject(environment, "project1");
                var project2 = CreateCSharpProject(environment, "project2");
                var project3 = CreateCSharpProject(environment, "project3");
                var project4 = CreateCSharpProject(environment, "project4");

                project1.AddProjectReference(new ProjectReference(project2.Id));
                project2.AddProjectReference(new ProjectReference(project3.Id));
                project3.AddProjectReference(new ProjectReference(project4.Id));
                project4.AddProjectReference(new ProjectReference(project1.Id));

                Assert.Equal(true, project1.GetCurrentProjectReferences().Any(pr => pr.ProjectId == project2.Id));
                Assert.Equal(true, project2.GetCurrentProjectReferences().Any(pr => pr.ProjectId == project3.Id));
                Assert.Equal(true, project3.GetCurrentProjectReferences().Any(pr => pr.ProjectId == project4.Id));
                Assert.Equal(false, project4.GetCurrentProjectReferences().Any(pr => pr.ProjectId == project1.Id));

                project4.Disconnect();
                project3.Disconnect();
                project2.Disconnect();
                project1.Disconnect();
            }
        }
 public void UpdateCognacy_NoSimilarSegments()
 {
     var env = new TestEnvironment("hɛ.lo", "he.ɬa");
     env.UpdateCognacy();
     Assert.That(env.WordPair.PredictedCognacy, Is.False);
     Assert.That(env.WordPair.AlignmentNotes, Is.EqualTo(new[] {"1", "2", "3", "2"}));
 }
Exemple #6
0
        public Artist[] Init(TestEnvironment environment)
        {
            if(_artists != null && _artists.Any())
                return _artists;

            IntegrationTestsRuntime.EnsureCleanEnvironment();

            _artists = ClientTestData.Artists.CreateArtists(2);

            using (var client = IntegrationTestsRuntime.CreateDbClient())
            {
                var bulk = new BulkRequest();
                bulk.Include(_artists.Select(i => client.Entities.Serializer.Serialize(i)).ToArray());

                var bulkResponse = client.Documents.BulkAsync(bulk).Result;

                foreach (var row in bulkResponse.Rows)
                {
                    var artist = _artists.Single(i => i.ArtistId == row.Id);
                    client.Entities.Reflector.RevMember.SetValueTo(artist, row.Rev);
                }

                client.Documents.PostAsync(ClientTestData.Shows.ArtistsShows).Wait();
            }

            return _artists;
        }
Exemple #7
0
        public void RuleSet_GeneralOption_CPS()
        {
            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test""  ToolsVersion=""12.0"">
  <IncludeAll Action=""Error"" />
</RuleSet>
";
            using (var ruleSetFile = new DisposableFile())
            using (var environment = new TestEnvironment())
            using (var project = CSharpHelpers.CreateCSharpCPSProject(environment, "Test"))
            {
                File.WriteAllText(ruleSetFile.Path, ruleSetSource);

                var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single();
                var options = (CSharpCompilationOptions)workspaceProject.CompilationOptions;

                Assert.Equal(expected: ReportDiagnostic.Default, actual: options.GeneralDiagnosticOption);

                project.SetRuleSetFile(ruleSetFile.Path);
                project.SetOptions($"/ruleset:{ruleSetFile.Path}");

                workspaceProject = environment.Workspace.CurrentSolution.Projects.Single();
                options = (CSharpCompilationOptions)workspaceProject.CompilationOptions;

                Assert.Equal(expected: ReportDiagnostic.Error, actual: options.GeneralDiagnosticOption);
            }
        }
        public void RuleSet_ProjectSettingOverridesGeneralOption()
        {
            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test""  ToolsVersion=""12.0"">
  <IncludeAll Action=""Warning"" />
</RuleSet>
";

            using (var ruleSetFile = new DisposableFile())
            using (var environment = new TestEnvironment())
            {
                File.WriteAllText(ruleSetFile.Path, ruleSetSource);

                var project = CSharpHelpers.CreateCSharpProject(environment, "Test");

                project.SetRuleSetFile(ruleSetFile.Path);

                var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single();
                var options = (CSharpCompilationOptions)workspaceProject.CompilationOptions;

                Assert.Equal(expected: ReportDiagnostic.Warn, actual: options.GeneralDiagnosticOption);

                project.SetOptionWithMarshaledValue(CompilerOptions.OPTID_WARNINGSAREERRORS, true);

                workspaceProject = environment.Workspace.CurrentSolution.Projects.Single();
                options = (CSharpCompilationOptions)workspaceProject.CompilationOptions;

                Assert.Equal(expected: ReportDiagnostic.Error, actual: options.GeneralDiagnosticOption);
            }
        }
        public override string GenerateErrorMessage(TestEnvironment environment)
        {
            const string format = @"
            Dictionary
            ""{0}""
            should contain key
            ""{1}""
            with value
            ""{2}""
            {3}";

            var codePart = environment.GetCodePart();
            var expectedValue = environment.Expected.Inspect();
            var actualValue = environment.Actual.Inspect();
            var keyValue = environment.Key.Inspect();

            if (environment.HasKey)
            {
                var valueString = string.Format("but value was \"{0}\"", actualValue.Trim('"'));
                return String.Format(format, codePart, keyValue.Trim('"'), expectedValue.Trim('"'), valueString);
            }
            else
            {
                return String.Format(format, codePart, actualValue.Trim('"'), expectedValue.Trim('"'), "but the key does not exist");
            }
        }
Exemple #10
0
        public void RuleSet_SpecificOptions_CPS()
        {
            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <RuleSet Name=""Ruleset1"" Description=""Test""  ToolsVersion=""12.0"">
              <IncludeAll Action=""Warning"" />
              <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
            <Rule Id=""CA1012"" Action=""Error"" />
              </Rules>
            </RuleSet>
            ";

            using (var ruleSetFile = new DisposableFile())
            using (var environment = new TestEnvironment())
            {
                File.WriteAllText(ruleSetFile.Path, ruleSetSource);

                var project = CSharpHelpers.CreateCSharpCPSProject(environment, "Test");

                project.SetRuleSetFile(ruleSetFile.Path);
                CSharpHelpers.SetCommandLineArguments(project, commandLineArguments: $"/ruleset:{ruleSetFile.Path}");

                var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single();
                var options = (CSharpCompilationOptions)workspaceProject.CompilationOptions;

                var ca1012DiagnosticOption = options.SpecificDiagnosticOptions["CA1012"];
                Assert.Equal(expected: ReportDiagnostic.Error, actual: ca1012DiagnosticOption);
            }
        }
Exemple #11
0
        public void RuleSet_ProjectNoWarnOverridesOtherSettings()
        {
            string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <RuleSet Name=""Ruleset1"" Description=""Test""  ToolsVersion=""12.0"">
              <IncludeAll Action=""Warning"" />
              <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
            <Rule Id=""CS1014"" Action=""Info"" />
              </Rules>
            </RuleSet>
            ";

            using (var ruleSetFile = new DisposableFile())
            using (var environment = new TestEnvironment())
            {
                File.WriteAllText(ruleSetFile.Path, ruleSetSource);

                var project = CSharpHelpers.CreateCSharpProject(environment, "Test");

                project.SetRuleSetFile(ruleSetFile.Path);
                project.SetOptionWithMarshaledValue(CompilerOptions.OPTID_NOWARNLIST, "1014");
                project.SetOptionWithMarshaledValue(CompilerOptions.OPTID_WARNASERRORLIST, "1014");

                var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single();
                var options = (CSharpCompilationOptions)workspaceProject.CompilationOptions;

                var ca1014DiagnosticOption = options.SpecificDiagnosticOptions["CS1014"];
                Assert.Equal(expected: ReportDiagnostic.Suppress, actual: ca1014DiagnosticOption);
            }
        }
Exemple #12
0
        public Artist[] Init(TestEnvironment environment)
        {
            if(_artists != null && _artists.Any())
                return _artists;

            IntegrationTestsRuntime.EnsureCleanEnvironment();

            _artists = ClientTestData.Artists.CreateArtists(10);

            using (var client = IntegrationTestsRuntime.CreateDbClient())
            {
                var bulk = new BulkRequest();
                bulk.Include(_artists.Select(i => client.Entities.Serializer.Serialize(i)).ToArray());

                var bulkResponse = client.Documents.BulkAsync(bulk).Result;

                foreach (var row in bulkResponse.Rows)
                {
                    var artist = _artists.Single(i => i.ArtistId == row.Id);
                    client.Entities.Reflector.RevMember.SetValueTo(artist, row.Rev);
                }

                client.Documents.PostAsync(ClientTestData.Views.ArtistsViews).Wait();

                var queryRequests = ClientTestData.Views.AllViewIds.Select(id => new QueryViewRequest(id).Configure(q => q.Stale(Stale.UpdateAfter)));
                var queries = queryRequests.Select(q => client.Views.QueryAsync(q) as Task).ToArray();
                Task.WaitAll(queries);
            }

            return _artists;
        }
        public void FindCommand_FormFirstWordSelectedMatches_CorrectWordPairsSelected()
        {
            using (var env = new TestEnvironment())
            {
                SetupFindCommandTests(env);

                WordPairViewModel[] cognatesArray = env.Cognates.WordPairsView.Cast<WordPairViewModel>().ToArray();
                WordPairViewModel[] noncognatesArray = env.Noncognates.WordPairsView.Cast<WordPairViewModel>().ToArray();

                env.Noncognates.SelectedWordPairs.Clear();
                env.Cognates.SelectedWordPairs.Add(cognatesArray[0]);
                env.FindViewModel.Field = FindField.Form;
                env.FindViewModel.String = "ʊ";
                env.FindViewModel.FindNextCommand.Execute(null);
                Assert.That(env.Cognates.SelectedWordPairs, Is.Empty);
                Assert.That(env.Noncognates.SelectedWordPairs, Is.EquivalentTo(noncognatesArray[0].ToEnumerable()));
                env.FindViewModel.FindNextCommand.Execute(null);
                Assert.That(env.Cognates.SelectedWordPairs, Is.EquivalentTo(cognatesArray[0].ToEnumerable()));
                Assert.That(env.Noncognates.SelectedWordPairs, Is.Empty);
                env.FindViewModel.FindNextCommand.Execute(null);
                Assert.That(env.Cognates.SelectedWordPairs, Is.EquivalentTo(cognatesArray[0].ToEnumerable()));
                Assert.That(env.Noncognates.SelectedWordPairs, Is.Empty);
                // start over
                env.FindViewModel.FindNextCommand.Execute(null);
                Assert.That(env.Cognates.SelectedWordPairs, Is.Empty);
                Assert.That(env.Noncognates.SelectedWordPairs, Is.EquivalentTo(noncognatesArray[0].ToEnumerable()));
            }
        }
Exemple #14
0
 public void BeforeEach()
 {
     _testEnvironment = new TestEnvironment();
     _testEnvironment.RegisterAssemblyAt("multiplyregisteredassembly", "location1");
     _testEnvironment.RegisterAssemblyAt("multiplyregisteredassembly", "location2");
     _testEnvironment.RegisterAssembly("myassembly");
 }
        public override string GenerateErrorMessage(TestEnvironment environment)
        {
            var expected = ((IEnumerable)environment.Expected).Cast<object>().ToArray();
            var actual = ((IEnumerable)environment.Actual).Cast<object>().ToArray();
            var codePart = environment.GetCodePart();
            var expectedFormattedValue = expected.Inspect();

            var missingFromExpected = actual.Where(a => !expected.Any(e => Is.Equal(e, a))).ToArray();
            var missingFromActual = expected.Where(e => !actual.Any(a => Is.Equal(e, a))).ToArray();

            var actualMissingMessage = missingFromActual.Any() ? string.Format("{0} is missing {1}", codePart,
                missingFromActual.Inspect()) : string.Empty;
            var expectedMissingMessage = missingFromExpected.Any() ? string.Format("{0} is missing {1}", expectedFormattedValue,
                missingFromExpected.Inspect()) : string.Empty;

            //"first should be second (ignoring order) but first is missing [4] and second is missing [2]"

            const string format = @"
            {0}
            {1}
            {2} (ignoring order)
            but
            {3}";

            string missingMessage = !string.IsNullOrEmpty(actualMissingMessage) && !string.IsNullOrEmpty(expectedMissingMessage)
                ? string.Format("{0} and {1}", actualMissingMessage, expectedMissingMessage)
                : string.Format("{0}{1}", actualMissingMessage, expectedMissingMessage);
            return string.Format(format, codePart, environment.ShouldMethod.PascalToSpaced(), expectedFormattedValue, missingMessage);
        }
Exemple #16
0
        public void ShouldParseGames()
        {
            // setup
            var env = new TestEnvironment(Logger);
            var menu = new PinballXMenu();
            menu.Games.Add(new PinballXGame() {
                Filename = "Test_Game",
                Description = "Test Game (Test 2016)"
            });

            env.Directory.Setup(d => d.Exists(TestEnvironment.VisualPinballDatabasePath)).Returns(true);
            env.Directory.Setup(d => d.GetFiles(TestEnvironment.VisualPinballDatabasePath)).Returns(new []{ Path.GetFileName(TestEnvironment.VisualPinballDatabaseXmlPath) });
            env.MarshallManager.Setup(m => m.UnmarshallXml("Visual Pinball.xml")).Returns(menu);

            var menuManager = env.Locator.GetService<IMenuManager>();

            // test
            menuManager.Initialize();

            // assert
            menuManager.Systems.ToList().Should().NotBeEmpty().And.HaveCount(1);
            var system = menuManager.Systems[0];
            system.Games.Should().NotBeEmpty().And.HaveCount(1);
            system.Games[0].Filename.Should().Be("Test_Game");
            system.Games[0].Description.Should().Be("Test Game (Test 2016)");
            system.Games[0].DatabaseFile.Should().Be(Path.GetFileName(TestEnvironment.VisualPinballDatabaseXmlPath));
        }
 public void CheckValidPathname_AcceptsMatchedExtensions()
 {
     using (var e = new TestEnvironment())
     {
         Assert.True(FileUtils.CheckValidPathname(e.tempFile.Path, Path.GetExtension(e.tempFile.Path))); // With starting '.'
         Assert.True(FileUtils.CheckValidPathname(e.tempFile.Path, Path.GetExtension(e.tempFile.Path).Substring(1))); // Sans starting '.'
     }
 }
 public void DocumentationModeSetToParseIfNotProducingDocFile_CPS()
 {
     using (var environment = new TestEnvironment())
     using (var project = CSharpHelpers.CreateCSharpCPSProject(environment, "Test", commandLineArguments: @"/doc:"))
     {
         Assert.Equal(DocumentationMode.Parse, project.CurrentParseOptions.DocumentationMode);
     }
 }
 public void UpdateCognacy_RegularConsonantEqual()
 {
     var env = new TestEnvironment("hɛ.lo", "he.ɬa", regularConsEqual: true);
     env.VarietyPair.CognateSoundCorrespondenceFrequencyDistribution[new SoundContext(env.SegmentPool.GetExisting("l"))].Increment(env.SegmentPool.GetExisting("ɬ"), 3);
     env.UpdateCognacy();
     Assert.That(env.WordPair.PredictedCognacy, Is.True);
     Assert.That(env.WordPair.AlignmentNotes, Is.EqualTo(new[] {"1", "2", "1", "2"}));
 }
 public void UpdateCognacy_IgnoreRegularInsertionDeletion()
 {
     var env = new TestEnvironment("hɛ.lo", "he.l", true);
     env.VarietyPair.CognateSoundCorrespondenceFrequencyDistribution[new SoundContext(env.SegmentPool.GetExisting("o"))].Increment(new Ngram<Segment>(), 3);
     env.UpdateCognacy();
     Assert.That(env.WordPair.PredictedCognacy, Is.True);
     Assert.That(env.WordPair.AlignmentNotes, Is.EqualTo(new[] {"1", "2", "1", "-"}));
 }
 public void FixtureSetUp()
 {
     LanguageForgeFolder = new TemporaryFolder("FdoTestFixture");
     _env = new TestEnvironment(
         resetLfProjectsDuringCleanup: false,
         languageForgeServerFolder: LanguageForgeFolder,
         registerLfProxyMock: false
     );
 }
		public void WritingSystemLdmlVerisonGetterGetFileVerison_FileIsVersion3_Returns3()
		{
			using (_environment = new TestEnvironment())
			{
				_environment.WriteContentToWritingSystemLdmlFile(LdmlContentForTests.Version3("en", "", "", ""));
				var versionGetter = new WritingSystemLdmlVersionGetter();
				Assert.That(versionGetter.GetFileVersion(_environment.PathToWritingSystemLdmlFile), Is.EqualTo(3));
			}
		}
 public void CheckValidPathname_RejectsMismatchedExtension()
 {
     using (var e = new TestEnvironment())
     {
         Assert.IsFalse(FileUtils.CheckValidPathname(e.tempFile.Path, "xyz"));
         Assert.IsFalse(FileUtils.CheckValidPathname(e.tempFile.Path, null));
         Assert.IsFalse(FileUtils.CheckValidPathname(e.tempFile.Path, ""));
     }
 }
		public void Read_SampleLogFile_PopulatesChanges()
		{
			using (var e = new TestEnvironment())
			{
				var log = new WritingSystemChangeLog(new WritingSystemChangeLogDataMapper(e.GetSampleLogFilePath()));
				Assert.That(log.HasChangeFor("aaa"));
				Assert.That(log.GetChangeFor("aaa"), Is.EqualTo("ddd"));
			}
		}
		public void WritingSystemLdmlVersionGetterGetFileVersion_FileIsVersion1_Returns1()
		{
			using (_environment = new TestEnvironment())
			{
				_environment.WriteContentToWritingSystemLdmlFile(LdmlContentForTests.Version1English());
				var versionGetter = new WritingSystemLdmlVersionGetter();
				Assert.AreEqual(1, versionGetter.GetFileVersion(_environment.PathToWritingSystemLdmlFile));
			}
		}
 public void UpdateCognacy_SimilarRegularConsonant()
 {
     var env = new TestEnvironment("hɛ.lo", "he.ɬa");
     env.CognateIdentifier.SimilarSegments.IsMapped(Arg.Any<ShapeNode>(), env.SegmentPool.GetExisting("l"), Arg.Any<ShapeNode>(), Arg.Any<ShapeNode>(),
         env.SegmentPool.GetExisting("ɬ"), Arg.Any<ShapeNode>()).Returns(true);
     env.VarietyPair.CognateSoundCorrespondenceFrequencyDistribution[new SoundContext(env.SegmentPool.GetExisting("l"))].Increment(env.SegmentPool.GetExisting("ɬ"), 3);
     env.UpdateCognacy();
     Assert.That(env.WordPair.PredictedCognacy, Is.True);
     Assert.That(env.WordPair.AlignmentNotes, Is.EqualTo(new[] {"1", "2", "1", "2"}));
 }
		[Test] // ok
		public void GetTopLevelItems_OtherKnownWritingSystemsIsNull_Ok()
		{
			using (var e = new TestEnvironment())
			{
				e.SetDefinitionsInStore(new WritingSystemDefinition[] {});
				var model = e.CreateModel();
				model.Suggestor.OtherKnownWritingSystems = null;
				AssertTreeNodeLabels(model, "Add Language");
			}
		}
Exemple #28
0
		public void GetLdmlFile_BadIetfLanguageTag_Throws()
		{
			using (var environment = new TestEnvironment())
			{
				const string ietfLanguageTag = "!@#";
				string filename;
				Assert.Throws<ArgumentException>(
					() => environment.GetLdmlFile(ietfLanguageTag, out filename));
			}
		}
 public void GrepFile_ContainsPattern_ReplacesCorrectly()
 {
     using (var e = new TestEnvironment())
     {
         FileUtils.GrepFile(e.tempFile.Path, "lang", "1234567");
         Assert.That(FileUtils.GrepFile(e.tempFile.Path, "1234567"), Is.True);
         var bakPath = e.tempFile.Path + ".bak";
         File.Delete(bakPath);
     }
 }
		public void Migrate_WithVersion0LdmlFile_Migrates()
		{
			using (var e = new TestEnvironment())
			{
				e.WriteVersion0LdmlFile("en");
				var m = new GlobalWritingSystemRepositoryMigrator(e.BasePath);
				m.Migrate();

				Assert.That(e.GetMigratedFileVersion("en.ldml"), Is.EqualTo(LdmlDataMapper.CurrentLdmlVersion));
			}
		}
 public void Run()
 {
     TestEnvironment.Run(_script, _parser, _expects, null);
 }
Exemple #32
0
 public XmlTestResultParser(IEnumerable <TestCase> testCasesRun, string xmlResultFile, TestEnvironment testEnvironment, string baseDir)
 {
     this.TestEnvironment = testEnvironment;
     this.BaseDir         = baseDir;
     this.XmlResultFile   = xmlResultFile;
     this.TestCasesRun    = testCasesRun.ToList();
 }
        public void LazyWildcardExpansionDoesNotEvaluateWildCardsIfNotReferenced()
        {
            var content = @"
<Project>
   <Import Project=`foo/*.props`/>
   <ItemGroup>
      <i Include=`**/foo/**/*.cs`/>
      <i2 Include=`**/bar/**/*.cs`/>
   </ItemGroup>

   <ItemGroup>
      <ItemReference Include=`@(i)`/>
      <FullPath Include=`@(i->'%(FullPath)')`/>
      <Identity Include=`@(i->'%(Identity)')`/>
      <RecursiveDir Include=`@(i->'%(RecursiveDir)')`/>
   </ItemGroup>
</Project>
".Cleanup();

            var import = @"
<Project>
   <PropertyGroup>
      <FromImport>true</FromImport>
   </PropertyGroup>
</Project>
".Cleanup();

            using (var env = TestEnvironment.Create())
            {
                var projectFiles = env.CreateTestProjectWithFiles(content, new[] { "foo/extra.props", "foo/a.cs", "foo/b.cs", "bar/c.cs", "bar/d.cs" });

                File.WriteAllText(projectFiles.CreatedFiles[0], import);

                env.SetEnvironmentVariable("MsBuildSkipEagerWildCardEvaluationRegexes", ".*foo.*");

                EngineFileUtilities.CaptureLazyWildcardRegexes();

                var project = new Project(projectFiles.ProjectFile);

                Assert.Equal("true", project.GetPropertyValue("FromImport"));
                Assert.Equal("**/foo/**/*.cs", project.GetConcatenatedItemsOfType("i"));

                var expectedItems = "bar\\c.cs;bar\\d.cs";

                if (!NativeMethodsShared.IsWindows)
                {
                    expectedItems = expectedItems.ToSlash();
                }

                Assert.Equal(expectedItems, project.GetConcatenatedItemsOfType("i2"));

                var fullPathItems = project.GetConcatenatedItemsOfType("FullPath");
                Assert.Contains("a.cs", fullPathItems);
                Assert.Contains("b.cs", fullPathItems);

                var identityItems = project.GetConcatenatedItemsOfType("Identity");
                Assert.Contains("a.cs", identityItems);
                Assert.Contains("b.cs", identityItems);

                // direct item references do not expand the lazy wildcard
                Assert.Equal("**/foo/**/*.cs", project.GetConcatenatedItemsOfType("ItemReference"));

                // recursive dir does not work with lazy wildcards
                Assert.Equal(string.Empty, project.GetConcatenatedItemsOfType("RecursiveDir"));
            }
        }
 public void TestInitialize()
 {
     TestEnvironment.CommonTestInitialize();
     _projectItem = TestEnvironment.LoadFileIntoProject(@"Data\ExplicitAccessModifiersOnInterfaces.cs");
 }
 private IManagedTracer CreateSimpleManagedTracer(IConsumer <TraceProto> consumer) =>
 SimpleManagedTracer.Create(consumer, TestEnvironment.GetTestProjectId(), _traceIdFactory.NextId(), null);
 public void TestInitialize()
 {
     TestEnvironment.CommonTestInitialize();
     _projectItem = TestEnvironment.LoadFileIntoProject(@"Data\RegionsRemoveAndInsertWithAccessModifiers.cs");
 }
Exemple #37
0
 public void TestCleanup()
 {
     TestEnvironment.AssemblyCleanupWorker(TestType.NugetCX);
 }
Exemple #38
0
 public void TestInitialize()
 {
     TestEnvironment.CommonTestInitialize();
     _projectItem = TestEnvironment.LoadFileIntoProject(@"Data\RegionsInsertAfterReorder.cs");
 }
Exemple #39
0
 public GeoDistanceTest()
 {
     _testEnvironment = TestEnvironment.GetInstance();
 }
 public static void ClassInitialize(TestContext testContext)
 {
     TestEnvironment.Initialize(testContext);
 }
 public void TestCleanup()
 {
     TestEnvironment.RemoveFromProject(_projectItem);
 }
 public void TestInitialize()
 {
     TestEnvironment.CommonTestInitialize();
     _projectItem = TestEnvironment.LoadFileIntoProject(@"Data\LESS.less");
 }
 public void TestCleanup()
 {
     PGOManager.PGOSweepIfInstrumented(TestEnvironment.TestContext.TestName);
     TestEnvironment.AssemblyCleanupWorker(TestType.Nuget);
 }
 public void OnSkipped(TestMethod tm, TestEnvironment te, TestSite ts)
 {
     WriteMessage(null, te, ts, "Skipped", string.Format("{0} doesn't support the {1} environment", ts.Name, te.Name));
 }
Exemple #45
0
 public void TestInitialize()
 {
     TestEnvironment.CommonTestInitialize();
     _projectItem = TestEnvironment.LoadFileIntoProject(@"Data\CPlusPlus.cpp");
 }
 public void OnSuccess(TestMethod tm, TestEnvironment te, TestSite ts, TestResult tr, string requestURL, HttpStatusCode responseStatus)
 {
     WriteMessage(tm, te, ts, "Succeeded", string.Empty);
 }
Exemple #47
0
 public static void ClassInitialize(TestContext testContext)
 {
     TestEnvironment.Initialize(testContext, TestType.NugetCX);
 }
 public void OnFailure(TestMethod tm, TestEnvironment te, TestSite ts, TestResult tr, string requestURL, HttpStatusCode responseStatus)
 {
     WriteMessage(tm, te, ts, "Failed", tr.Message);
     Environment.Exit((int)ExitCode.WebTestFailed);
 }
Exemple #49
0
 public string WriteFileToProject(string fileName, string fileContent)
 {
     return(TestEnvironment.WriteFileToFolder(TargetProjectFolder, fileName, fileContent));
 }
 public void OnError(TestMethod tm, TestEnvironment te, TestSite ts, TestResult tr, string requestURL, HttpStatusCode responseStatus)
 {
     WriteMessage(tm, te, ts, "Has Errors", tr.Message);
     Environment.Exit((int)ExitCode.WebTestException);
 }
 public RpcWorkerConfigTests()
 {
     _testEnvironment = new TestEnvironment();
 }
Exemple #52
0
 public NumberBasedTestsSplitter(IEnumerable <TestCase> testcasesToRun, TestEnvironment testEnvironment)
 {
     _testEnvironment = testEnvironment;
     _testcasesToRun  = testcasesToRun;
 }
Exemple #53
0
        public async Task Subscribe_Unsubscribe()
        {
            using (var testEnvironment = new TestEnvironment())
            {
                var receivedMessagesCount = 0;

                var server = await testEnvironment.StartServerAsync();

                var c1 = await testEnvironment.ConnectClientAsync(new MqttClientOptionsBuilder().WithClientId("c1"));

                c1.UseApplicationMessageReceivedHandler(c => Interlocked.Increment(ref receivedMessagesCount));

                var c2 = await testEnvironment.ConnectClientAsync(new MqttClientOptionsBuilder().WithClientId("c2"));

                var message = new MqttApplicationMessageBuilder().WithTopic("a").WithAtLeastOnceQoS().Build();
                await c2.PublishAsync(message);

                await Task.Delay(500);

                Assert.AreEqual(0, receivedMessagesCount);

                var subscribeEventCalled = false;
                server.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate(e =>
                {
                    subscribeEventCalled = e.TopicFilter.Topic == "a" && e.ClientId == "c1";
                });

                await c1.SubscribeAsync(new TopicFilter { Topic = "a", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce });

                await Task.Delay(250);

                Assert.IsTrue(subscribeEventCalled, "Subscribe event not called.");

                await c2.PublishAsync(message);

                await Task.Delay(250);

                Assert.AreEqual(1, receivedMessagesCount);

                var unsubscribeEventCalled = false;
                server.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(e =>
                {
                    unsubscribeEventCalled = e.TopicFilter == "a" && e.ClientId == "c1";
                });

                await c1.UnsubscribeAsync("a");

                await Task.Delay(250);

                Assert.IsTrue(unsubscribeEventCalled, "Unsubscribe event not called.");

                await c2.PublishAsync(message);

                await Task.Delay(500);

                Assert.AreEqual(1, receivedMessagesCount);

                await Task.Delay(500);

                Assert.AreEqual(1, receivedMessagesCount);
            }
        }
Exemple #54
0
        private void SetAuthenticationFactory(AzureModule mode, TestEnvironment rdfeEnvironment, TestEnvironment csmEnvironment)
        {
            string           jwtToken           = null;
            X509Certificate2 certificate        = null;
            TestEnvironment  currentEnvironment = (mode == AzureModule.AzureResourceManager ? csmEnvironment : rdfeEnvironment);

            if (mode == AzureModule.AzureServiceManagement)
            {
                if (rdfeEnvironment.Credentials is TokenCloudCredentials)
                {
                    jwtToken = ((TokenCloudCredentials)rdfeEnvironment.Credentials).Token;
                }
                if (rdfeEnvironment.Credentials is CertificateCloudCredentials)
                {
                    certificate = ((CertificateCloudCredentials)rdfeEnvironment.Credentials).ManagementCertificate;
                }
            }
            else
            {
                if (csmEnvironment.Credentials is TokenCloudCredentials)
                {
                    jwtToken = ((TokenCloudCredentials)csmEnvironment.Credentials).Token;
                }
                if (csmEnvironment.Credentials is CertificateCloudCredentials)
                {
                    certificate = ((CertificateCloudCredentials)csmEnvironment.Credentials).ManagementCertificate;
                }
            }


            if (jwtToken != null)
            {
                AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory(currentEnvironment.UserName,
                                                                                        jwtToken);
            }
            else if (certificate != null)
            {
                AzureSession.AuthenticationFactory = new MockCertificateAuthenticationFactory(currentEnvironment.UserName,
                                                                                              certificate);
            }
        }
        public void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment currentEnvironment = null;

            if (mode == AzureModule.AzureResourceManager)
            {
                currentEnvironment = TestEnvironmentFactory.GetTestEnvironment();
            }
            else
            {
                throw new NotSupportedException("RDFE environment is not supported in .Net Core");
            }

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetAuthenticationFactory(mode, currentEnvironment);
            AzureEnvironment environment = new AzureEnvironment {
                Name = testEnvironmentName
            };

            Debug.Assert(currentEnvironment != null);
            environment.ActiveDirectoryAuthority = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri;
            environment.GalleryUrl           = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri;
            environment.ServiceManagementUrl = currentEnvironment.BaseUri.AbsoluteUri;
            environment.ResourceManagerUrl   = currentEnvironment.Endpoints.ResourceManagementUri.AbsoluteUri;
            environment.GraphUrl             = currentEnvironment.Endpoints.GraphUri.AbsoluteUri;
            environment.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix = currentEnvironment.Endpoints.DataLakeAnalyticsJobAndCatalogServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix
            environment.AzureDataLakeStoreFileSystemEndpointSuffix        = currentEnvironment.Endpoints.DataLakeStoreServiceUri.OriginalString.Replace("https://", "");                  // because it is just a sufix
            environment.StorageEndpointSuffix = AzureEnvironmentConstants.AzureStorageEndpointSuffix;
            if (!AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>().EnvironmentTable.ContainsKey(testEnvironmentName))
            {
                AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>().EnvironmentTable[testEnvironmentName] = environment;
            }

            if (currentEnvironment.SubscriptionId != null)
            {
                testSubscription = new AzureSubscription()
                {
                    Id   = currentEnvironment.SubscriptionId,
                    Name = testSubscriptionName,
                };

                testSubscription.SetEnvironment(testEnvironmentName);
                testSubscription.SetAccount(currentEnvironment.UserName);
                testSubscription.SetDefault();
                testSubscription.SetStorageAccount(Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT"));

                testAccount = new AzureAccount()
                {
                    Id   = currentEnvironment.UserName,
                    Type = AzureAccount.AccountType.User,
                };

                testAccount.SetSubscriptions(currentEnvironment.SubscriptionId);
                var testTenant = new AzureTenant()
                {
                    Id = Guid.NewGuid().ToString()
                };
                if (!string.IsNullOrEmpty(currentEnvironment.Tenant))
                {
                    Guid tenant;
                    if (Guid.TryParse(currentEnvironment.Tenant, out tenant))
                    {
                        testTenant.Id = currentEnvironment.Tenant;
                    }
                }
                AzureRmProfileProvider.Instance.Profile.DefaultContext = new AzureContext(testSubscription, testAccount, environment, testTenant);
            }
        }
 public void TestInitialize()
 {
     TestEnvironment.CommonTestInitialize();
     _projectItem = TestEnvironment.LoadFileIntoProject(@"Data\RegionsNewMemberOutside.cs");
 }
Exemple #57
0
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment rdfeEnvironment    = new RDFETestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment csmEnvironment     = new CSMTestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment currentEnvironment = (mode == AzureModule.AzureResourceManager ? csmEnvironment : rdfeEnvironment);

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetAuthenticationFactory(mode, rdfeEnvironment, csmEnvironment);

            AzureEnvironment environment = new AzureEnvironment {
                Name = testEnvironmentName
            };

            Debug.Assert(currentEnvironment != null);
            environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Gallery]         = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri;

            if (csmEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = csmEnvironment.BaseUri.AbsoluteUri;
            }

            if (rdfeEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = rdfeEnvironment.BaseUri.AbsoluteUri;
            }

            if (!client.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                client.AddOrSetEnvironment(environment);
            }

            if (currentEnvironment.SubscriptionId != null)
            {
                testSubscription = new AzureSubscription()
                {
                    Id          = new Guid(currentEnvironment.SubscriptionId),
                    Name        = testSubscriptionName,
                    Environment = testEnvironmentName,
                    Account     = currentEnvironment.UserName,
                    Properties  = new Dictionary <AzureSubscription.Property, string>
                    {
                        { AzureSubscription.Property.Default, "True" },
                        {
                            AzureSubscription.Property.StorageAccount,
                            Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")
                        },
                    }
                };

                testAccount = new AzureAccount()
                {
                    Id         = currentEnvironment.UserName,
                    Type       = AzureAccount.AccountType.User,
                    Properties = new Dictionary <AzureAccount.Property, string>
                    {
                        { AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId },
                    }
                };

                client.Profile.Subscriptions[testSubscription.Id] = testSubscription;
                client.Profile.Accounts[testAccount.Id]           = testAccount;
                client.SetSubscriptionAsCurrent(testSubscription.Name, testSubscription.Account);
            }
        }
 public void TestInitialize()
 {
     TestEnvironment.CommonTestInitialize();
     _projectItem = TestEnvironment.LoadFileIntoProject(@"Data\RegionsInsertEvenIfEmpty.cs");
 }
Exemple #59
0
 public void TestInitialize()
 {
     _connection = TestEnvironment.CreateConnection(TestContext);
     _connection.Open();
 }
Exemple #60
0
 public QuickOrder(TestEnvironment testEnv) : base(testEnv)
 {
 }