diff --git "a/dotnet-xharness/index/functions.json" "b/dotnet-xharness/index/functions.json" new file mode 100644--- /dev/null +++ "b/dotnet-xharness/index/functions.json" @@ -0,0 +1,11994 @@ +{ + "src/Microsoft.DotNet.XHarness.TestRunners.NUnit/NUnit3XmlOutputWriter.cs": [ + { + "name": "TerminateXmlFile", + "code": "private void TerminateXmlFile()\n {\n if (_xmlWriter == null) // should never happen, would mean a programmer's error\n {\n throw new InvalidOperationException(\"Null writer\");\n }\n\n _xmlWriter.WriteEndElement(); // test-run\n _xmlWriter.WriteEndDocument();\n _xmlWriter.Flush();\n _xmlWriter.Close();\n }", + "start_line": 146, + "end_line": 157, + "start_byte": 5626, + "end_byte": 5987 + }, + { + "name": "WriteResultElement", + "code": "private void WriteResultElement(IResultSummary result)\n {\n if (_xmlWriter == null) // should never happen, would mean a programmer's error\n {\n throw new InvalidOperationException(\"Null writer\");\n }\n\n // much simpler than in other writers, we just need to get the child nodes of each of the test-run and write\n // them. NUnit3 already gave us the xml we need to use\n foreach (var testRun in result)\n {\n for (var i = 0; i < testRun.Result.ChildNodes.Count; i++)\n {\n var node = testRun.Result.ChildNodes[i];\n if (node?.Name == \"environment\")\n {\n continue;\n }\n\n node?.WriteTo(_xmlWriter);\n }\n }\n }", + "start_line": 122, + "end_line": 144, + "start_byte": 4827, + "end_byte": 5620 + }, + { + "name": "WriteEnvironmentElement", + "code": "private void WriteEnvironmentElement()\n {\n if (_xmlWriter == null) // should never happen, would mean a programmers error\n {\n throw new InvalidOperationException(\"Null writer\");\n }\n\n _xmlWriter.WriteStartElement(\"environment\");\n\n var assembly = Assembly.GetExecutingAssembly();\n AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(assembly);\n _xmlWriter.WriteAttributeString(\"nunit-version\", assemblyName?.Version?.ToString() ?? \"unknown\");\n\n _xmlWriter.WriteAttributeString(\"clr-version\", Environment.Version.ToString());\n _xmlWriter.WriteAttributeString(\"os-version\", Environment.OSVersion.ToString());\n _xmlWriter.WriteAttributeString(\"platform\", Environment.OSVersion.Platform.ToString());\n _xmlWriter.WriteAttributeString(\"cwd\", Environment.CurrentDirectory);\n _xmlWriter.WriteAttributeString(\"machine-name\", Environment.MachineName);\n _xmlWriter.WriteAttributeString(\"user\", Environment.UserName);\n _xmlWriter.WriteAttributeString(\"user-domain\", Environment.UserDomainName);\n _xmlWriter.WriteAttributeString(\"culture\", CultureInfo.CurrentCulture.ToString());\n _xmlWriter.WriteAttributeString(\"uiculture\", CultureInfo.CurrentUICulture.ToString());\n\n _xmlWriter.WriteEndElement();\n }", + "start_line": 96, + "end_line": 120, + "start_byte": 3491, + "end_byte": 4821 + }, + { + "name": "InitializeXmlFile", + "code": "private void InitializeXmlFile(IResultSummary result)\n {\n if (_xmlWriter == null) // should never happen, would mean a programmers error\n {\n throw new InvalidOperationException(\"Null writer\");\n }\n\n _xmlWriter.WriteStartDocument(false);\n\n // In order to match the format used by NUnit 3.0, we\n // wrap the entire result from the framework in a\n // element.\n _xmlWriter.WriteStartElement(\"test-run\");\n\n _xmlWriter.WriteAttributeString(\"id\", \"2\"); // TODO: Should not be hard-coded\n _xmlWriter.WriteAttributeString(\"name\", result.Name);\n _xmlWriter.WriteAttributeString(\"fullname\", result.FullName);\n _xmlWriter.WriteAttributeString(\"testcasecount\", result.TotalTests.ToString());\n\n _xmlWriter.WriteAttributeString(\"result\", result.TestStatus.ToXmlResultValue(XmlResultJargon.NUnitV3));\n\n _xmlWriter.WriteAttributeString(\"time\", result.Duration.ToString());\n\n _xmlWriter.WriteAttributeString(\"total\", result.TotalTests.ToString());\n _xmlWriter.WriteAttributeString(\"passed\", result.PassedTests.ToString());\n _xmlWriter.WriteAttributeString(\"failed\", result.FailedTests.ToString());\n _xmlWriter.WriteAttributeString(\"inconclusive\", result.InconclusiveTests.ToString());\n _xmlWriter.WriteAttributeString(\"skipped\", result.SkippedTests.ToString());\n _xmlWriter.WriteAttributeString(\"asserts\", result.AssertCount.ToString());\n\n _xmlWriter.WriteAttributeString(\"run-date\", XmlConvert.ToString(_runStartTime, \"yyyy-MM-dd\"));\n _xmlWriter.WriteAttributeString(\"start-time\", XmlConvert.ToString(_runStartTime, \"HH:mm:ss\"));\n\n _xmlWriter.WriteAttributeString(\"random-seed\", Randomizer.InitialSeed.ToString());\n\n WriteEnvironmentElement();\n }", + "start_line": 58, + "end_line": 94, + "start_byte": 1661, + "end_byte": 3485 + }, + { + "name": "WriteXmlOutput", + "code": "private void WriteXmlOutput(IResultSummary result, XmlWriter xmlWriter)\n {\n _xmlWriter = xmlWriter;\n\n InitializeXmlFile(result);\n WriteResultElement(result);\n TerminateXmlFile();\n }", + "start_line": 49, + "end_line": 56, + "start_byte": 1440, + "end_byte": 1655 + }, + { + "name": "WriteResultFile", + "code": "public override void WriteResultFile(IResultSummary result, TextWriter writer)\n {\n var xmlWriter = new XmlTextWriter(writer)\n {\n Formatting = Formatting.Indented\n };\n\n try\n {\n WriteXmlOutput(result, xmlWriter);\n }\n finally\n {\n xmlWriter.Close();\n }\n }", + "start_line": 32, + "end_line": 47, + "start_byte": 1081, + "end_byte": 1434 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.NUnit/TestStatusExtensions.cs": [ + { + "name": "ToXmlResultValue", + "code": "public static string ToXmlResultValue(this TestStatus status, XmlResultJargon jargon) => jargon switch\n {\n XmlResultJargon.NUnitV2 => status switch\n {\n TestStatus.Failed => \"Failure\",\n TestStatus.Inconclusive => \"Inconclusive\",\n TestStatus.Passed => \"Success\",\n TestStatus.Skipped => \"Ignored\",\n _ => \"Failure\"\n },\n XmlResultJargon.NUnitV3 => status switch\n {\n TestStatus.Failed => \"Failed\",\n TestStatus.Inconclusive => \"Inconclusive\",\n TestStatus.Passed => \"Passed\",\n TestStatus.Skipped => \"Skipped\",\n _ => \"Failed\",\n },\n XmlResultJargon.xUnit => status switch\n {\n TestStatus.Failed => \"Fail\",\n TestStatus.Inconclusive => \"Skip\",\n TestStatus.Passed => \"Pass\",\n TestStatus.Skipped => \"Skip\",\n _ => \"Fail\",\n },\n _ => throw new ArgumentOutOfRangeException(nameof(status)),\n };", + "start_line": 13, + "end_line": 40, + "start_byte": 398, + "end_byte": 1413 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.NUnit/NUnitTestListener.cs": [ + { + "name": "OnTestEvent", + "code": "public void OnTestEvent(string report)\n {\n // again, not a simple api, the report string is an xml, that contains a fragment of xml\n // which depends on the event type, load the xml, do the appropriate thing.\n var doc = new XmlDocument();\n doc.LoadXml(report);\n\n var testEvent = doc.FirstChild;\n switch (testEvent.Name)\n {\n case \"start-test\":\n TestStarted(testEvent);\n break;\n\n case \"test-case\":\n TestFinished(testEvent);\n break;\n }\n }", + "start_line": 129, + "end_line": 147, + "start_byte": 4725, + "end_byte": 5304 + }, + { + "name": "TestFinished", + "code": "private void TestFinished(XmlNode testEvent)\n {\n // we need to get the status from the string. That value is stored in\n // value can be: Passed, Failed, Inconclusive or Skipped. To make things\n // 'simpler' we also need to check the label, which might have the following values: Error, Cancelled or Invalid\n var result = testEvent.GetAttribute(\"label\") ?? testEvent.GetAttribute(\"result\");\n TestStatus status = result switch\n {\n \"Passed\" => TestStatus.Passed,\n \"Failed\" => TestStatus.Failed,\n \"Inconclusive\" => TestStatus.Inconclusive,\n \"Skipped\" => TestStatus.Skipped,\n _ => TestStatus.Inconclusive // Cancelled, error or invalid\n };\n var testName = testEvent.Attributes[\"fullname\"].Value;\n var sb = new StringBuilder();\n switch (status)\n {\n case TestStatus.Passed:\n sb.Append(\"\\t[PASS] \");\n _runner.IncreasePassedTests();\n break;\n case TestStatus.Skipped:\n sb.Append(\"\\t[IGNORED] \");\n _runner.IncreaseSkippedTests();\n break;\n case TestStatus.Failed:\n sb.Append(\"\\t[FAIL] \");\n _runner.IncreaseFailedTests();\n break;\n case TestStatus.Inconclusive:\n sb.Append(\"\\t[INCONCLUSIVE] \");\n _runner.IncreaseInconclusiveTests();\n break;\n default:\n sb.Append(\"\\t[INFO] \");\n break;\n }\n\n sb.Append(testName);\n // if we skipped or we failed, add some extra info to the logging:\n if (status == TestStatus.Failed)\n {\n var messageNodes = testEvent.SelectNodes(\"failure/message\");\n if (messageNodes.Count == 1)\n {\n if (messageNodes[0].ChildNodes.Count == 1) // should not happen, but I trust no one\n {\n var cDataNode = messageNodes[0].ChildNodes[0];\n var message = cDataNode?.InnerText?.Trim();\n if (!string.IsNullOrEmpty(message))\n {\n message = message.Replace(\"\\r\\n\", \"\\\\r\\\\n\");\n sb.Append($\" : {message}\");\n }\n }\n }\n // get the stack trace, similar to the message node\n var stacktraceNodes = testEvent.SelectNodes(\"failure/stack-trace\");\n if (stacktraceNodes.Count == 1)\n {\n if (stacktraceNodes[0].ChildNodes.Count == 1) // should not happen, but I trust no one\n {\n var cDataNode = messageNodes[0].ChildNodes[0];\n var stackTrace = cDataNode?.InnerText?.Trim();\n if (!string.IsNullOrEmpty(stackTrace))\n {\n stackTrace = stackTrace.Replace(\"\\r\\n\", \"\\\\r\\\\n\");\n string[] lines = stackTrace.Split(new[] { '\\r', '\\n' }, StringSplitOptions.RemoveEmptyEntries);\n foreach (string line in lines)\n {\n sb.AppendLine($\"\\t\\t{line}\");\n }\n }\n }\n }\n\n _runner.Add(new TestFailureInfo\n {\n TestName = testName,\n Message = sb.ToString()\n });\n }\n\n _logger.OnInfo(sb.ToString());\n }", + "start_line": 42, + "end_line": 127, + "start_byte": 1171, + "end_byte": 4719 + }, + { + "name": "TestStarted", + "code": "private void TestStarted(XmlNode testEvent)\n {\n if (testEvent == null)\n {\n return;\n }\n\n if (!string.IsNullOrEmpty(_runner.TestsRootDirectory))\n {\n Environment.CurrentDirectory = _runner.TestsRootDirectory;\n }\n\n _logger.OnInfo(testEvent.Attributes[\"fullname\"].Value);\n\n }", + "start_line": 26, + "end_line": 40, + "start_byte": 818, + "end_byte": 1165 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.NUnit/INUnitTestRunner.cs": [ + { + "name": "Add", + "code": "void Add(TestFailureInfo info);", + "start_line": 23, + "end_line": 23, + "start_byte": 629, + "end_byte": 660 + }, + { + "name": "IncreaseInconclusiveTests", + "code": "void IncreaseInconclusiveTests();", + "start_line": 21, + "end_line": 21, + "start_byte": 590, + "end_byte": 623 + }, + { + "name": "IncreaseFailedTests", + "code": "void IncreaseFailedTests();", + "start_line": 19, + "end_line": 19, + "start_byte": 557, + "end_byte": 584 + }, + { + "name": "IncreaseSkippedTests", + "code": "void IncreaseSkippedTests();", + "start_line": 17, + "end_line": 17, + "start_byte": 523, + "end_byte": 551 + }, + { + "name": "IncreasePassedTests", + "code": "void IncreasePassedTests();", + "start_line": 15, + "end_line": 15, + "start_byte": 490, + "end_byte": 517 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.NUnit/OutputWriter.cs": [ + { + "name": "WriteResultFile", + "code": "public abstract void WriteResultFile(IResultSummary result, TextWriter writer);", + "start_line": 33, + "end_line": 33, + "start_byte": 1204, + "end_byte": 1283 + }, + { + "name": "WriteResultFile", + "code": "public void WriteResultFile(IResultSummary result, string outputPath)\n {\n using var writer = new StreamWriter(outputPath, false, Encoding.UTF8);\n WriteResultFile(result, writer);\n }", + "start_line": 22, + "end_line": 26, + "start_byte": 751, + "end_byte": 952 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.NUnit/XmlResultJargonExtensions.cs": [ + { + "name": "GetWriter", + "code": "public static OutputWriter GetWriter(this XmlResultJargon jargon) => jargon switch\n {\n XmlResultJargon.NUnitV2 => throw new NotImplementedException(),\n XmlResultJargon.NUnitV3 => new NUnit3XmlOutputWriter(DateTime.UtcNow),\n XmlResultJargon.xUnit => throw new NotImplementedException(),\n _ => throw new InvalidOperationException($\"Jargon {jargon} is not supported by this runner.\")\n };", + "start_line": 12, + "end_line": 18, + "start_byte": 369, + "end_byte": 787 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.NUnit/NUnitTestRunner.cs": [ + { + "name": "SkipClass", + "code": "public override void SkipClass(string className, bool _)\n => _testFilterBuilder.IgnoredClasses.Add(className);", + "start_line": 200, + "end_line": 201, + "start_byte": 5922, + "end_byte": 6039 + }, + { + "name": "SkipMethod", + "code": "public override void SkipMethod(string method, bool _)\n => _testFilterBuilder.IgnoredMethods.Add(method);", + "start_line": 197, + "end_line": 198, + "start_byte": 5804, + "end_byte": 5916 + }, + { + "name": "SkipCategories", + "code": "public override void SkipCategories(IEnumerable categories)\n => _testFilterBuilder.IgnoredCategories.AddRange(categories);", + "start_line": 194, + "end_line": 195, + "start_byte": 5661, + "end_byte": 5798 + }, + { + "name": "SkipTests", + "code": "public override void SkipTests(IEnumerable tests)\n => _testFilterBuilder.IgnoredMethods.AddRange(tests);", + "start_line": 191, + "end_line": 192, + "start_byte": 5536, + "end_byte": 5655 + }, + { + "name": "WriteResultsToFile", + "code": "public override Task WriteResultsToFile(TextWriter writer, XmlResultJargon jargon)\n {\n if (_results == null)\n {\n return Task.CompletedTask;\n }\n\n jargon.GetWriter().WriteResultFile(_results, writer);\n\n return Task.CompletedTask;\n }", + "start_line": 179, + "end_line": 189, + "start_byte": 5248, + "end_byte": 5530 + }, + { + "name": "WriteResultsToFile", + "code": "public override Task WriteResultsToFile(XmlResultJargon jargon)\n {\n if (_results == null)\n {\n return Task.FromResult(string.Empty);\n }\n\n string ret = GetResultsFilePath();\n if (string.IsNullOrEmpty(ret))\n {\n return Task.FromResult(string.Empty);\n }\n\n jargon.GetWriter().WriteResultFile(_results, ret);\n\n return Task.FromResult(ret);\n }", + "start_line": 161, + "end_line": 177, + "start_byte": 4808, + "end_byte": 5242 + }, + { + "name": "ReportFilteredAssembly", + "code": "private bool ReportFilteredAssembly(TestAssemblyInfo assemblyInfo, bool include)\n {\n if (!LogExcludedTests)\n {\n return include;\n }\n\n const string included = \"Included\";\n const string excluded = \"Excluded\";\n\n OnInfo($\"[FILTER] {(include ? included : excluded)} assembly: {assemblyInfo.FullPath}\");\n return include;\n }", + "start_line": 147, + "end_line": 159, + "start_byte": 4420, + "end_byte": 4802 + }, + { + "name": "ShouldRunAssembly", + "code": "private bool ShouldRunAssembly(TestAssemblyInfo assemblyInfo)\n {\n if (assemblyInfo == null)\n {\n return false;\n }\n\n if (AssemblyFilters == null || AssemblyFilters.Count == 0)\n {\n return true;\n }\n\n if (AssemblyFilters.TryGetValue(assemblyInfo.FullPath, out bool include))\n {\n return ReportFilteredAssembly(assemblyInfo, include);\n }\n\n string fileName = Path.GetFileName(assemblyInfo.FullPath);\n if (AssemblyFilters.TryGetValue(fileName, out include))\n {\n return ReportFilteredAssembly(assemblyInfo, include);\n }\n\n fileName = Path.GetFileNameWithoutExtension(assemblyInfo.FullPath);\n if (AssemblyFilters.TryGetValue(fileName, out include))\n {\n return ReportFilteredAssembly(assemblyInfo, include);\n }\n\n return _runAssemblyByDefault;\n }", + "start_line": 115, + "end_line": 145, + "start_byte": 3495, + "end_byte": 4414 + }, + { + "name": "Run", + "code": "public override async Task Run(IEnumerable testAssemblies)\n {\n if (testAssemblies == null)\n {\n throw new ArgumentNullException(nameof(testAssemblies));\n }\n\n if (AssemblyFilters == null || AssemblyFilters.Count == 0)\n {\n _runAssemblyByDefault = true;\n }\n else\n {\n _runAssemblyByDefault = AssemblyFilters.Values.Any(v => !v);\n }\n\n ITestEngine engine = TestEngineActivator.CreateInstance();\n TestFilter filter = _testFilterBuilder.GetFilter();\n // use the current executing assembly full name as the name of the test suit that groups all the diff assemblies\n _results = new ResultSummary(Assembly.GetExecutingAssembly().FullName!, this);\n\n TotalTests = 0;\n foreach (TestAssemblyInfo assemblyInfo in testAssemblies)\n {\n if (assemblyInfo == null || assemblyInfo.Assembly == null || !ShouldRunAssembly(assemblyInfo))\n {\n continue;\n }\n\n var testPackage = new TestPackage(assemblyInfo.FullPath);\n ITestRunner runner = engine.GetRunner(testPackage);\n TotalTests += runner.CountTestCases(filter);\n ITestRun result;\n try\n {\n OnAssemblyStart(assemblyInfo.Assembly);\n result = await Task.Run(() => runner.RunAsync(_testListener, filter)).ConfigureAwait(false);\n }\n finally\n {\n OnAssemblyFinish(assemblyInfo.Assembly);\n }\n\n if (result == null)\n {\n continue;\n }\n\n _results.Add(result);\n }\n\n FilteredTests = TotalTests - ExecutedTests;\n LogFailureSummary();\n }", + "start_line": 60, + "end_line": 113, + "start_byte": 1693, + "end_byte": 3489 + }, + { + "name": "Add", + "code": "public void Add(TestFailureInfo info)\n => FailureInfos.Add(info ?? throw new ArgumentNullException(nameof(info)));", + "start_line": 57, + "end_line": 58, + "start_byte": 1566, + "end_byte": 1687 + }, + { + "name": "IncreaseInconclusiveTests", + "code": "public void IncreaseInconclusiveTests()\n {\n InconclusiveTests++;\n ExecutedTests++;\n }", + "start_line": 51, + "end_line": 55, + "start_byte": 1455, + "end_byte": 1560 + }, + { + "name": "IncreaseFailedTests", + "code": "public void IncreaseFailedTests()\n {\n FailedTests++;\n ExecutedTests++;\n }", + "start_line": 45, + "end_line": 49, + "start_byte": 1356, + "end_byte": 1449 + }, + { + "name": "IncreaseSkippedTests", + "code": "public void IncreaseSkippedTests() => SkippedTests++;", + "start_line": 43, + "end_line": 43, + "start_byte": 1297, + "end_byte": 1350 + }, + { + "name": "IncreasePassedTests", + "code": "public void IncreasePassedTests()\n {\n PassedTests++;\n ExecutedTests++;\n }", + "start_line": 37, + "end_line": 41, + "start_byte": 1198, + "end_byte": 1291 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.NUnit/IResultSummary.cs": [], + "src/Microsoft.DotNet.XHarness.TestRunners.NUnit/ResultSummary.cs": [ + { + "name": "GetSummaryData", + "code": "private void GetSummaryData()\n {\n double duration = 0;\n long assertCount = 0;\n foreach (var result in this)\n {\n var testRunNode = result.Result.FirstChild;\n if (testRunNode.Name != \"test-run\")\n {\n continue;\n }\n\n if (double.TryParse(testRunNode.Attributes[\"time\"].Value, out var time))\n {\n duration += time;\n }\n if (long.TryParse(testRunNode.Attributes[\"asserts\"].Value, out var asserts))\n {\n assertCount += asserts;\n }\n }\n\n _duration = duration;\n _assertCount = assertCount;\n }", + "start_line": 61, + "end_line": 85, + "start_byte": 1745, + "end_byte": 2432 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.NUnit/FilterBuilder.cs": [ + { + "name": "GetFilter", + "code": "public TestFilter GetFilter()\n {\n var whereClause = BuildWhereClause();\n if (!string.IsNullOrEmpty(whereClause))\n {\n _testFilterBuilder.SelectWhere(BuildWhereClause());\n }\n\n return _testFilterBuilder.GetFilter();\n }", + "start_line": 64, + "end_line": 73, + "start_byte": 2750, + "end_byte": 3017 + }, + { + "name": "BuildWhereClause", + "code": "internal string? BuildWhereClause() // does not need to be internal, doing it so that we can test it\n {\n // not the best api to add tests, we need to build the expression to be passed to the filter builder\n // to generate the tests. First, consider the case in which we are running all the tests, in that\n // case we want to make sure that we are || and ==\n // For example:\n // test == \"My.Skipped.Test\" or cat == \"outerloop\"\n //\n // the above filter will skip any test that matches the full qualify named and the category outerloop.\n // On the other hand, when we are including them, we have to do the reverse:\n // test != \"My.Skipped.Test\" or cat != \"outerloop\"\n //\n // The above filter will skip all tests that do not have the given fully-qualified name of the category\n // build the comparison tuples, then use string.join with the or operation\n var comparisons = new List();\n var filters = new Dictionary>\n {\n [\"cat\"] = IgnoredCategories,\n [\"class\"] = IgnoredClasses,\n [\"test\"] = IgnoredMethods, // we could use AddTest, but it will not allow us to do the !isExcluded\n };\n\n foreach (string category in filters.Keys)\n {\n var filtersInCategory = filters[category];\n foreach (var filterReason in filtersInCategory)\n {\n var eq = _runAssemblyByDefault ? \"==\" : \"!=\";\n comparisons.Add($\"{category} {eq} {filterReason}\");\n }\n }\n return comparisons.Count == 0 ? null : string.Join(\" or \", comparisons);\n }", + "start_line": 30, + "end_line": 62, + "start_byte": 1060, + "end_byte": 2744 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/AndroidApplicationEntryPoint.cs": [ + { + "name": "GetTestRunner", + "code": "protected override TestRunner GetTestRunner(LogWriter logWriter)\n {\n var runner = new XUnitTestRunner(logWriter) { MaxParallelThreads = MaxParallelThreads };\n ConfigureRunnerFilters(runner, ApplicationOptions.Current);\n return runner;\n }", + "start_line": 14, + "end_line": 19, + "start_byte": 471, + "end_byte": 735 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/WasmThreadedTestRunner.cs": [ + { + "name": "WriteResultsToFile", + "code": "public override Task WriteResultsToFile(TextWriter writer, XmlResultJargon jargon)\r\n => WasmXmlResultWriter.WriteResultsToFile(ConsumeAssembliesElement());", + "start_line": 34, + "end_line": 35, + "start_byte": 1095, + "end_byte": 1257 + }, + { + "name": "Run", + "code": "public override Task Run(IEnumerable testAssemblies)\r\n {\r\n OnInfo(\"Using threaded Xunit runner\");\r\n return base.Run(testAssemblies);\r\n }", + "start_line": 28, + "end_line": 32, + "start_byte": 913, + "end_byte": 1087 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/WasmApplicationEntryPoint.cs": [ + { + "name": "Run", + "code": "public async Task Run()\n {\n await RunAsync();\n\n return LastRunHadFailedTests ? 1 : 0;\n }", + "start_line": 58, + "end_line": 63, + "start_byte": 2276, + "end_byte": 2389 + }, + { + "name": "GetTestAssemblies", + "code": "protected override IEnumerable GetTestAssemblies()\n => new[] { new TestAssemblyInfo(Assembly.LoadFrom(TestAssembly), TestAssembly) };", + "start_line": 55, + "end_line": 56, + "start_byte": 2112, + "end_byte": 2270 + }, + { + "name": "GetTestRunner", + "code": "protected override TestRunner GetTestRunner(LogWriter logWriter)\n {\n XunitTestRunnerBase runner = IsThreadless\n ? new ThreadlessXunitTestRunner(logWriter)\n : new WasmThreadedTestRunner(logWriter) { MaxParallelThreads = MaxParallelThreads };\n\n ConfigureRunnerFilters(runner, ApplicationOptions.Current);\n\n runner.RunInParallel = RunInParallel;\n\n runner.SkipCategories(ExcludedTraits);\n runner.SkipCategories(IncludedTraits, isExcluded: false);\n foreach (var cls in IncludedClasses)\n {\n runner.SkipClass(cls, false);\n }\n foreach (var method in IncludedMethods)\n {\n runner.SkipMethod(method, false);\n }\n foreach (var ns in IncludedNamespaces)\n {\n runner.SkipNamespace(ns, isExcluded: false);\n }\n return runner;\n }", + "start_line": 28, + "end_line": 53, + "start_byte": 1230, + "end_byte": 2106 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/WasmXmlResultWriter.cs": [ + { + "name": "WriteResultsToFile", + "code": "public async static Task WriteResultsToFile(XElement assembliesElement)\r\n {\r\n if (OperatingSystem.IsBrowser())\r\n {\r\n await Task.Yield();\r\n GC.Collect();\r\n await Task.Yield();\r\n GC.Collect();\r\n }\r\n\r\n using var ms = new MemoryStream();\r\n assembliesElement.Save(ms);\r\n assembliesElement = null!;\r\n\r\n\r\n if (OperatingSystem.IsBrowser())\r\n {\r\n await Task.Yield();\r\n GC.Collect();\r\n\r\n try\r\n {\r\n using JSObject globalThis = JSHost.GlobalThis;\r\n if (globalThis.HasProperty(\"fetch\") && globalThis.HasProperty(\"location\") && globalThis.HasProperty(\"document\"))\r\n {\r\n ms.Position = 0;\r\n\r\n // globalThis.location.origin\r\n using JSObject location = globalThis.GetPropertyAsJSObject(\"location\")!;\r\n var originURL = location.GetPropertyAsString(\"origin\");\r\n\r\n using var req = new HttpRequestMessage(HttpMethod.Post, originURL + \"/test-results\");\r\n req.Content = new StreamContent(ms);\r\n req.Content.Headers.ContentType = new MediaTypeHeaderValue(\"application/xml\");\r\n req.Content.Headers.ContentLength = ms.Length;\r\n\r\n using var httpClient = new HttpClient();\r\n using var response = await httpClient.SendAsync(req);\r\n if (response.IsSuccessStatusCode)\r\n {\r\n Console.WriteLine($\"Finished uploading {ms.Length} bytes of RESULTXML\");\r\n return;\r\n }\r\n // otherwise fall back to the console output\r\n }\r\n }\r\n catch (Exception)\r\n {\r\n // fall back to the console output\r\n }\r\n }\r\n\r\n ms.TryGetBuffer(out var bytes);\r\n var base64 = Convert.ToBase64String(bytes, Base64FormattingOptions.None);\r\n Console.WriteLine($\"STARTRESULTXML {bytes.Count} {base64} ENDRESULTXML\");\r\n Console.WriteLine($\"Finished writing {bytes.Count} bytes of RESULTXML\");\r\n }", + "start_line": 19, + "end_line": 75, + "start_byte": 528, + "end_byte": 2763 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/XunitTestRunnerBase.cs": [ + { + "name": "SkipNamespace", + "code": "public virtual void SkipNamespace(string namespaceName, bool isExcluded)\n => _filters.Add(XUnitFilter.CreateNamespaceFilter(namespaceName, exclude: isExcluded));", + "start_line": 84, + "end_line": 85, + "start_byte": 3105, + "end_byte": 3273 + }, + { + "name": "SkipClass", + "code": "public override void SkipClass(string className, bool isExcluded)\n => _filters.Add(XUnitFilter.CreateClassFilter(className: className, exclude: isExcluded));", + "start_line": 81, + "end_line": 82, + "start_byte": 2935, + "end_byte": 3099 + }, + { + "name": "SkipMethod", + "code": "public override void SkipMethod(string method, bool isExcluded)\n => _filters.Add(XUnitFilter.CreateSingleFilter(singleTestName: method, exclude: isExcluded));", + "start_line": 78, + "end_line": 79, + "start_byte": 2764, + "end_byte": 2929 + }, + { + "name": "SkipCategories", + "code": "public virtual void SkipCategories(IEnumerable categories, bool isExcluded)\n {\n if (categories == null)\n {\n throw new ArgumentNullException(nameof(categories));\n }\n\n foreach (var c in categories)\n {\n var traitInfo = c.Split('=');\n if (traitInfo.Length == 2)\n {\n _filters.Add(XUnitFilter.CreateTraitFilter(traitInfo[0], traitInfo[1], isExcluded));\n }\n else\n {\n _filters.Add(XUnitFilter.CreateTraitFilter(c, null, isExcluded));\n }\n }\n }", + "start_line": 57, + "end_line": 76, + "start_byte": 2150, + "end_byte": 2758 + }, + { + "name": "SkipCategories", + "code": "public override void SkipCategories(IEnumerable categories) => SkipCategories(categories, isExcluded: true);", + "start_line": 55, + "end_line": 55, + "start_byte": 2028, + "end_byte": 2144 + }, + { + "name": "SkipTests", + "code": "public override void SkipTests(IEnumerable tests)\n {\n if (tests.Any())\n {\n // create a single filter per test\n foreach (var t in tests)\n {\n if (t.StartsWith(\"KLASS:\", StringComparison.Ordinal))\n {\n var klass = t.Replace(\"KLASS:\", \"\");\n _filters.Add(XUnitFilter.CreateClassFilter(klass, true));\n }\n else if (t.StartsWith(\"KLASS32:\", StringComparison.Ordinal) && IntPtr.Size == 4)\n {\n var klass = t.Replace(\"KLASS32:\", \"\");\n _filters.Add(XUnitFilter.CreateClassFilter(klass, true));\n }\n else if (t.StartsWith(\"KLASS64:\", StringComparison.Ordinal) && IntPtr.Size == 8)\n {\n var klass = t.Replace(\"KLASS32:\", \"\");\n _filters.Add(XUnitFilter.CreateClassFilter(klass, true));\n }\n else if (t.StartsWith(\"Platform32:\", StringComparison.Ordinal) && IntPtr.Size == 4)\n {\n var filter = t.Replace(\"Platform32:\", \"\");\n _filters.Add(XUnitFilter.CreateSingleFilter(filter, true));\n }\n else\n {\n _filters.Add(XUnitFilter.CreateSingleFilter(t, true));\n }\n }\n }\n }", + "start_line": 20, + "end_line": 53, + "start_byte": 604, + "end_byte": 2022 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/XUnitFilter.cs": [ + { + "name": "ToString", + "code": "public override string ToString()\n {\n var sb = new StringBuilder(\"XUnitFilter [\");\n\n sb.Append($\"Type: {FilterType}; \");\n sb.Append(Exclude ? \"exclude\" : \"include\");\n\n if (!string.IsNullOrEmpty(AssemblyName))\n {\n sb.Append($\"; AssemblyName: {AssemblyName}\");\n }\n\n switch (FilterType)\n {\n case XUnitFilterType.Assembly:\n break;\n\n case XUnitFilterType.Namespace:\n AppendDesc(sb, \"Namespace\", SelectorValue);\n break;\n\n case XUnitFilterType.Single:\n AppendDesc(sb, \"Method\", SelectorValue);\n break;\n\n case XUnitFilterType.Trait:\n AppendDesc(sb, \"Trait name\", SelectorName);\n AppendDesc(sb, \"Trait value\", SelectorValue);\n break;\n\n case XUnitFilterType.TypeName:\n AppendDesc(sb, \"Class\", SelectorValue);\n break;\n\n default:\n sb.Append(\"; Unknown filter type\");\n break;\n }\n sb.Append(']');\n\n return sb.ToString();\n }", + "start_line": 271, + "end_line": 312, + "start_byte": 9182, + "end_byte": 10331 + }, + { + "name": "AppendDesc", + "code": "private static void AppendDesc(StringBuilder sb, string name, string? value)\n {\n if (string.IsNullOrEmpty(value))\n {\n return;\n }\n\n sb.Append($\"; {name}: {value}\");\n }", + "start_line": 261, + "end_line": 269, + "start_byte": 8965, + "end_byte": 9176 + }, + { + "name": "ReportFilteredAssembly", + "code": "private static bool ReportFilteredAssembly(TestAssemblyInfo assemblyInfo, bool excluded, Action? log = null)\n {\n if (log == null)\n {\n return excluded;\n }\n\n const string includedPrefix = \"Included\";\n const string excludedPrefix = \"Excluded\";\n\n log($\"[FILTER] {(excluded ? excludedPrefix : includedPrefix)} assembly: {assemblyInfo.FullPath}\");\n return excluded;\n }", + "start_line": 247, + "end_line": 259, + "start_byte": 8523, + "end_byte": 8959 + }, + { + "name": "ReportFilteredTest", + "code": "private bool ReportFilteredTest(ITestCase testCase, bool excluded, Action? log = null)\n {\n const string includedText = \"Included\";\n const string excludedText = \"Excluded\";\n\n if (log == null)\n {\n return excluded;\n }\n\n var selector = FilterType == XUnitFilterType.Trait ?\n $\"'{SelectorName}':'{SelectorValue}'\" : $\"'{SelectorValue}'\";\n\n log($\"[FILTER] {(excluded ? excludedText : includedText)} test (filtered by {FilterType}; {selector}): {testCase.DisplayName}\");\n return excluded;\n }", + "start_line": 230, + "end_line": 245, + "start_byte": 7941, + "end_byte": 8517 + }, + { + "name": "IsExcluded", + "code": "public bool IsExcluded(ITestCase testCase, Action? log = null)\n {\n Func? reportFilteredTest = null;\n if (log != null)\n {\n reportFilteredTest = (result) => ReportFilteredTest(testCase, result, log);\n }\n\n return FilterType switch\n {\n XUnitFilterType.Trait => ApplyTraitFilter(testCase, reportFilteredTest),\n XUnitFilterType.TypeName => ApplyTypeNameFilter(testCase, reportFilteredTest),\n XUnitFilterType.Single => ApplySingleFilter(testCase, reportFilteredTest),\n XUnitFilterType.Namespace => ApplyNamespaceFilter(testCase, reportFilteredTest),\n _ => throw new InvalidOperationException($\"Unsupported filter type {FilterType}\")\n };\n }", + "start_line": 212, + "end_line": 228, + "start_byte": 7162, + "end_byte": 7935 + }, + { + "name": "IsExcluded", + "code": "public bool IsExcluded(TestAssemblyInfo assembly, Action? reportFilteredAssembly = null)\n {\n if (FilterType != XUnitFilterType.Assembly)\n {\n throw new InvalidOperationException(\"Filter is not targeting assemblies.\");\n }\n\n Func log = (result) => ReportFilteredAssembly(assembly, result, reportFilteredAssembly);\n\n if (string.Equals(AssemblyName, assembly.FullPath, StringComparison.Ordinal))\n {\n return log(Exclude);\n }\n\n string fileName = Path.GetFileName(assembly.FullPath);\n if (string.Equals(fileName, AssemblyName, StringComparison.Ordinal))\n {\n return log(Exclude);\n }\n\n // No path of the name matched the filter, therefore return the opposite of the Exclude value\n return log(!Exclude);\n }", + "start_line": 188, + "end_line": 210, + "start_byte": 6311, + "end_byte": 7156 + }, + { + "name": "ApplyNamespaceFilter", + "code": "private bool ApplyNamespaceFilter(ITestCase testCase, Func? reportFilteredTest = null)\n {\n Func log = (result) => reportFilteredTest?.Invoke(result) ?? result;\n var testClassNamespace = testCase.GetNamespace();\n if (string.IsNullOrEmpty(testClassNamespace))\n {\n // if we exclude, since we have no namespace, we include the test\n return log(!Exclude);\n }\n\n if (string.Equals(testClassNamespace, SelectorValue, StringComparison.InvariantCultureIgnoreCase))\n {\n return log(Exclude);\n }\n\n // same logic as with no namespace\n return log(!Exclude);\n }", + "start_line": 169, + "end_line": 186, + "start_byte": 5627, + "end_byte": 6305 + }, + { + "name": "ApplySingleFilter", + "code": "private bool ApplySingleFilter(ITestCase testCase, Func? reportFilteredTest = null)\n {\n Func log = (result) => reportFilteredTest?.Invoke(result) ?? result;\n if (string.Equals(testCase.DisplayName, SelectorValue, StringComparison.InvariantCulture))\n {\n // if there is a match, return the exclude value\n return log(Exclude);\n }\n // if there is not match, return the opposite\n return log(!Exclude);\n }", + "start_line": 157, + "end_line": 167, + "start_byte": 5128, + "end_byte": 5621 + }, + { + "name": "ApplyTypeNameFilter", + "code": "private bool ApplyTypeNameFilter(ITestCase testCase, Func? reportFilteredTest = null)\n {\n Func log = (result) => reportFilteredTest?.Invoke(result) ?? result;\n var testClassName = testCase.GetTestClass();\n if (!string.IsNullOrEmpty(testClassName))\n {\n if (string.Equals(testClassName, SelectorValue, StringComparison.InvariantCulture))\n {\n return log(Exclude);\n }\n }\n\n return log(!Exclude);\n }", + "start_line": 142, + "end_line": 155, + "start_byte": 4609, + "end_byte": 5122 + }, + { + "name": "ApplyTraitFilter", + "code": "private bool ApplyTraitFilter(ITestCase testCase, Func? reportFilteredTest = null)\n {\n Func log = (result) => reportFilteredTest?.Invoke(result) ?? result;\n\n if (!testCase.HasTraits())\n {\n return log(!Exclude);\n }\n\n if (testCase.TryGetTrait(SelectorName!, out var values))\n {\n if (values == null || values.Count == 0)\n {\n // We have no values and the filter doesn't specify one - that means we match on\n // the trait name only.\n if (string.IsNullOrEmpty(SelectorValue))\n {\n return log(Exclude);\n }\n\n return log(!Exclude);\n }\n\n return values.Any(value => value.Equals(SelectorValue, StringComparison.InvariantCultureIgnoreCase)) ?\n log(Exclude) : log(!Exclude);\n }\n\n // no traits found, that means that we return the opposite of the setting of the filter\n return log(!Exclude);\n }", + "start_line": 111, + "end_line": 140, + "start_byte": 3552, + "end_byte": 4603 + }, + { + "name": "CreateTraitFilter", + "code": "public static XUnitFilter CreateTraitFilter(string traitName, string? traitValue, bool exclude)\n {\n if (string.IsNullOrEmpty(traitName))\n {\n throw new ArgumentException(\"must not be null or empty\", nameof(traitName));\n }\n\n return new XUnitFilter\n {\n AssemblyName = null,\n SelectorName = traitName,\n SelectorValue = traitValue ?? string.Empty,\n FilterType = XUnitFilterType.Trait,\n Exclude = exclude\n };\n }", + "start_line": 94, + "end_line": 109, + "start_byte": 3027, + "end_byte": 3546 + }, + { + "name": "CreateClassFilter", + "code": "public static XUnitFilter CreateClassFilter(string className, bool exclude, string? assemblyName = null)\n {\n if (string.IsNullOrEmpty(className))\n {\n throw new ArgumentException(\"must not be null or empty\", nameof(className));\n }\n\n return new XUnitFilter\n {\n AssemblyName = assemblyName,\n SelectorValue = className,\n FilterType = XUnitFilterType.TypeName,\n Exclude = exclude\n };\n }", + "start_line": 78, + "end_line": 92, + "start_byte": 2537, + "end_byte": 3021 + }, + { + "name": "CreateNamespaceFilter", + "code": "public static XUnitFilter CreateNamespaceFilter(string namespaceName, bool exclude, string? assemblyName = null)\n {\n if (string.IsNullOrEmpty(namespaceName))\n {\n throw new ArgumentException(\"must not be null or empty\", nameof(namespaceName));\n }\n\n return new XUnitFilter\n {\n AssemblyName = assemblyName,\n SelectorValue = namespaceName,\n FilterType = XUnitFilterType.Namespace,\n Exclude = exclude\n };\n }", + "start_line": 62, + "end_line": 76, + "start_byte": 2026, + "end_byte": 2531 + }, + { + "name": "CreateAssemblyFilter", + "code": "public static XUnitFilter CreateAssemblyFilter(string assemblyName, bool exclude)\n {\n if (string.IsNullOrEmpty(assemblyName))\n {\n throw new ArgumentException(\"must not be null or empty\", nameof(assemblyName));\n }\n\n // ensure that the assembly name does have one of the valid extensions\n var fileExtension = Path.GetExtension(assemblyName);\n if (fileExtension != \".dll\" && fileExtension != \".exe\")\n {\n throw new ArgumentException($\"Assembly name must have .dll or .exe as extensions. Found extension {fileExtension}\");\n }\n\n return new XUnitFilter\n {\n AssemblyName = assemblyName,\n FilterType = XUnitFilterType.Assembly,\n Exclude = exclude\n };\n }", + "start_line": 40, + "end_line": 60, + "start_byte": 1238, + "end_byte": 2020 + }, + { + "name": "CreateSingleFilter", + "code": "public static XUnitFilter CreateSingleFilter(string singleTestName, bool exclude, string? assemblyName = null)\n {\n if (string.IsNullOrEmpty(singleTestName))\n {\n throw new ArgumentException(\"must not be null or empty\", nameof(singleTestName));\n }\n\n return new XUnitFilter\n {\n AssemblyName = assemblyName,\n SelectorValue = singleTestName,\n FilterType = XUnitFilterType.Single,\n Exclude = exclude\n };\n }", + "start_line": 24, + "end_line": 38, + "start_byte": 729, + "end_byte": 1232 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/XUnitFiltersCollection.cs": [ + { + "name": "IsExcluded", + "code": "public bool IsExcluded(ITestCase testCase, Action? log = null)\n {\n // Check each type of filter separately. For conflicts within a type of filter, we want the inclusion\n // (the logic in IsExcludedInternal), but if all filters for a filter type exclude a test case, we want\n // the exclusion. For example, if a test class is included, but it contains tests that have excluded\n // traits, the behaviour should be to run all tests in that class without the excluded traits.\n foreach (IGrouping filterGroup in TestCaseFilters.GroupBy(f => f.FilterType))\n {\n if (IsExcludedInternal(filterGroup, f => f.IsExcluded(testCase, log)))\n {\n return true;\n }\n }\n\n return false;\n }", + "start_line": 64, + "end_line": 79, + "start_byte": 2373, + "end_byte": 3188 + }, + { + "name": "IsExcluded", + "code": "public bool IsExcluded(TestAssemblyInfo assembly, Action? log = null) =>\n IsExcludedInternal(AssemblyFilters, f => f.IsExcluded(assembly, log));", + "start_line": 61, + "end_line": 62, + "start_byte": 2208, + "end_byte": 2367 + }, + { + "name": "IsExcludedInternal", + "code": "private bool IsExcludedInternal(IEnumerable filters, Func isExcludedCb)\n {\n // No filters : include by default\n // Any exclude filters : include by default\n // Only include filters : exclude by default\n var isExcluded = filters.Any() && filters.All(f => !f.Exclude);\n foreach (var filter in filters)\n {\n var doesExclude = isExcludedCb(filter);\n if (filter.Exclude)\n {\n isExcluded |= doesExclude;\n }\n else\n {\n // filter does not exclude, that means that if it include, we should include and break the\n // loop, always include\n if (!doesExclude)\n {\n return false;\n }\n }\n }\n\n return isExcluded;\n }", + "start_line": 34, + "end_line": 59, + "start_byte": 1317, + "end_byte": 2202 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/EnvironmentVariables.cs": [ + { + "name": "IsLogThreadId", + "code": "public static bool IsLogThreadId() => IsTrue(\"XHARNESS_LOG_THREAD_ID\");", + "start_line": 16, + "end_line": 16, + "start_byte": 466, + "end_byte": 537 + }, + { + "name": "IsLogTestStart", + "code": "public static bool IsLogTestStart() => IsTrue(\"XHARNESS_LOG_TEST_START\");", + "start_line": 14, + "end_line": 14, + "start_byte": 385, + "end_byte": 458 + }, + { + "name": "IsTrue", + "code": "public static bool IsTrue(string varName) => Environment.GetEnvironmentVariable(varName)?.ToLower().Equals(\"true\") ?? false;", + "start_line": 12, + "end_line": 12, + "start_byte": 253, + "end_byte": 377 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/ThreadlessXunitTestRunner.cs": [ + { + "name": "OnMessage", + "code": "public bool OnMessage(IMessageSinkMessage message)\n {\n if (message is IDiagnosticMessage diagnosticMessage)\n {\n logger.OnDebug(diagnosticMessage.Message);\n }\n\n return true;\n }", + "start_line": 164, + "end_line": 172, + "start_byte": 7714, + "end_byte": 7934 + }, + { + "name": "FindWithoutThreads", + "code": "public void FindWithoutThreads(bool includeSourceInformation, IMessageSink discoveryMessageSink, ITestFrameworkDiscoveryOptions discoveryOptions)\n {\n#pragma warning disable CS0618 // SynchronousMessageBus ctor is marked obsolete\n using (var messageBus = new global::Xunit.Sdk.SynchronousMessageBus(discoveryMessageSink))\n#pragma warning restore\n {\n foreach (var type in AssemblyInfo.GetTypes(includePrivateTypes: false).Where(IsValidTestClass))\n {\n var testClass = CreateTestClass(type);\n if (!FindTestsForType(testClass, includeSourceInformation, messageBus, discoveryOptions))\n {\n break;\n }\n }\n\n messageBus.QueueMessage(new global::Xunit.Sdk.DiscoveryCompleteMessage());\n }\n }", + "start_line": 142, + "end_line": 159, + "start_byte": 6752, + "end_byte": 7580 + }, + { + "name": "WriteResultsToFile", + "code": "public override async Task WriteResultsToFile(TextWriter writer, XmlResultJargon jargon)\n {\n await WasmXmlResultWriter.WriteResultsToFile(ConsumeAssembliesElement());\n }", + "start_line": 129, + "end_line": 132, + "start_byte": 6245, + "end_byte": 6427 + }, + { + "name": "WriteResultsToFile", + "code": "public override async Task WriteResultsToFile(XmlResultJargon xmlResultJargon)\n {\n Debug.Assert(xmlResultJargon == XmlResultJargon.xUnit);\n await WriteResultsToFile(Console.Out, xmlResultJargon);\n return \"\";\n }", + "start_line": 122, + "end_line": 127, + "start_byte": 5994, + "end_byte": 6239 + }, + { + "name": "Combine", + "code": "private ExecutionSummary Combine(ExecutionSummary aggregateSummary, ExecutionSummary assemblySummary)\n {\n return new ExecutionSummary\n {\n Total = aggregateSummary.Total + assemblySummary.Total,\n Failed = aggregateSummary.Failed + assemblySummary.Failed,\n Skipped = aggregateSummary.Skipped + assemblySummary.Skipped,\n Errors = aggregateSummary.Errors + assemblySummary.Errors,\n Time = aggregateSummary.Time + assemblySummary.Time\n };\n }", + "start_line": 110, + "end_line": 120, + "start_byte": 5470, + "end_byte": 5988 + }, + { + "name": "Run", + "code": "public override async Task Run(IEnumerable testAssemblies)\n {\n OnInfo(\"Using threadless Xunit runner\");\n\n _assembliesElement = new XElement(\"assemblies\");\n\n var configuration = new TestAssemblyConfiguration() { ShadowCopy = false, ParallelizeAssembly = false, ParallelizeTestCollections = false, MaxParallelThreads = 1, PreEnumerateTheories = false };\n var discoveryOptions = TestFrameworkOptions.ForDiscovery(configuration);\n var discoverySink = new TestDiscoverySink();\n var diagnosticSink = new ConsoleDiagnosticMessageSink(Logger);\n var testOptions = TestFrameworkOptions.ForExecution(configuration);\n var testSink = new TestMessageSink();\n\n var totalSummary = new ExecutionSummary();\n foreach (var testAsmInfo in testAssemblies)\n {\n string assemblyFileName = testAsmInfo.FullPath;\n var controller = new Xunit2(AppDomainSupport.Denied, new NullSourceInformationProvider(), assemblyFileName, configFileName: null, shadowCopy: false, shadowCopyFolder: null, diagnosticMessageSink: diagnosticSink, verifyTestAssemblyExists: false);\n\n discoveryOptions.SetSynchronousMessageReporting(true);\n testOptions.SetSynchronousMessageReporting(true);\n\n OnInfo($\"Discovering: {assemblyFileName} (method display = {discoveryOptions.GetMethodDisplayOrDefault()}, method display options = {discoveryOptions.GetMethodDisplayOptionsOrDefault()})\");\n var assemblyInfo = new global::Xunit.Sdk.ReflectionAssemblyInfo(testAsmInfo.Assembly);\n var discoverer = new ThreadlessXunitDiscoverer(assemblyInfo, new NullSourceInformationProvider(), discoverySink);\n\n discoverer.FindWithoutThreads(includeSourceInformation: false, discoverySink, discoveryOptions);\n var testCasesToRun = discoverySink.TestCases.Where(t => !_filters.IsExcluded(t)).ToList();\n OnInfo($\"Discovered: {assemblyFileName} (found {testCasesToRun.Count} of {discoverySink.TestCases.Count} test cases)\");\n\n var summaryTaskSource = new TaskCompletionSource();\n var resultsXmlAssembly = new XElement(\"assembly\");\n#pragma warning disable CS0618 // Delegating*Sink types are marked obsolete, but we can't move to ExecutionSink yet: https://github.com/dotnet/arcade/issues/14375\n var resultsSink = new DelegatingXmlCreationSink(new DelegatingExecutionSummarySink(testSink), resultsXmlAssembly);\n#pragma warning restore\n var completionSink = new CompletionCallbackExecutionSink(resultsSink, summary => summaryTaskSource.SetResult(summary));\n\n if (EnvironmentVariables.IsLogTestStart())\n {\n testSink.Execution.TestStartingEvent += args => { OnInfo($\"[STRT] {args.Message.Test.DisplayName}\"); };\n }\n testSink.Execution.TestPassedEvent += args =>\n {\n OnDebug($\"[PASS] {args.Message.Test.DisplayName}\");\n PassedTests++;\n };\n testSink.Execution.TestSkippedEvent += args =>\n {\n OnDebug($\"[SKIP] {args.Message.Test.DisplayName}\");\n SkippedTests++;\n };\n testSink.Execution.TestFailedEvent += args =>\n {\n OnError($\"[FAIL] {args.Message.Test.DisplayName}{Environment.NewLine}{ExceptionUtility.CombineMessages(args.Message)}{Environment.NewLine}{ExceptionUtility.CombineStackTraces(args.Message)}\");\n FailedTests++;\n };\n testSink.Execution.TestFinishedEvent += args => ExecutedTests++;\n\n testSink.Execution.TestAssemblyStartingEvent += args => { Console.WriteLine($\"Starting: {assemblyFileName}\"); };\n testSink.Execution.TestAssemblyFinishedEvent += args => { Console.WriteLine($\"Finished: {assemblyFileName}\"); };\n\n controller.RunTests(testCasesToRun, completionSink, testOptions);\n\n totalSummary = Combine(totalSummary, await summaryTaskSource.Task);\n\n _assembliesElement.Add(resultsXmlAssembly);\n }\n TotalTests = totalSummary.Total;\n }", + "start_line": 40, + "end_line": 108, + "start_byte": 1303, + "end_byte": 5464 + }, + { + "name": "ConsumeAssembliesElement", + "code": "internal XElement ConsumeAssembliesElement()\n {\n Debug.Assert(_assembliesElement != null, \"ConsumeAssembliesElement called before Run() or after ConsumeAssembliesElement() was already called.\");\n var res = _assembliesElement;\n _assembliesElement = null;\n FailureInfos.Clear();\n return res!;\n }", + "start_line": 31, + "end_line": 38, + "start_byte": 963, + "end_byte": 1297 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/iOSApplicationEntryPoint.cs": [ + { + "name": "GetTestRunner", + "code": "protected override TestRunner GetTestRunner(LogWriter logWriter)\n {\n var runner = new XUnitTestRunner(logWriter) { MaxParallelThreads = MaxParallelThreads };\n ConfigureRunnerFilters(runner, ApplicationOptions.Current);\n return runner;\n }", + "start_line": 12, + "end_line": 17, + "start_byte": 417, + "end_byte": 681 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/CompletionCallbackExecutionSink.cs": [ + { + "name": "OnMessageWithTypes", + "code": "public bool OnMessageWithTypes(IMessageSinkMessage message, HashSet messageTypes)\n {\n var result = _innerSink.OnMessageWithTypes(message, messageTypes);\n message.Dispatch(messageTypes, args => _completionCallback(ExecutionSummary));\n return result;\n }", + "start_line": 31, + "end_line": 36, + "start_byte": 1023, + "end_byte": 1332 + }, + { + "name": "Dispose", + "code": "public void Dispose() => _innerSink.Dispose();", + "start_line": 29, + "end_line": 29, + "start_byte": 971, + "end_byte": 1017 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/TestCaseExtensions.cs": [ + { + "name": "GetNamespace", + "code": "public static string? GetNamespace(this ITestCase testCase)\n {\n var testClassName = testCase.GetTestClass();\n if (testClassName == null)\n {\n return null;\n }\n\n int dot = testClassName.LastIndexOf('.');\n return dot <= 0 ? null : testClassName.Substring(0, dot);\n }", + "start_line": 60, + "end_line": 70, + "start_byte": 2235, + "end_byte": 2556 + }, + { + "name": "GetTestClass", + "code": "public static string? GetTestClass(this ITestCase testCase) =>\n testCase.TestMethod?.TestClass?.Class?.Name?.Trim();", + "start_line": 57, + "end_line": 58, + "start_byte": 2106, + "end_byte": 2229 + }, + { + "name": "TryGetTrait", + "code": "public static bool TryGetTrait(this ITestCase testCase,\n string trait,\n [NotNullWhen(true)] out List? values,\n StringComparison comparer = StringComparison.InvariantCultureIgnoreCase)\n {\n if (trait == null)\n {\n values = null;\n return false;\n }\n\n // there is no guarantee that the dict created by xunit is case insensitive, therefore, trygetvalue might\n // not return the value we are interested in. We have to loop, which is not ideal, but will be better\n // for our use case.\n foreach (var t in testCase.Traits.Keys)\n {\n if (trait.Equals(t, comparer))\n {\n return testCase.Traits.TryGetValue(t, out values);\n }\n }\n\n values = null;\n return false;\n }", + "start_line": 26, + "end_line": 50, + "start_byte": 938, + "end_byte": 1849 + }, + { + "name": "HasTraits", + "code": "public static bool HasTraits(this ITestCase testCase) =>\n testCase.Traits != null && testCase.Traits.Count > 0;", + "start_line": 23, + "end_line": 24, + "start_byte": 814, + "end_byte": 932 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/XUnitTestRunner.cs": [ + { + "name": "Run", + "code": "private async Task Run(Assembly assembly, string assemblyPath)\n {\n using (var frontController = new XunitFrontController(AppDomainSupport, assemblyPath, null, false))\n {\n using (var discoverySink = new TestDiscoverySink())\n {\n var configuration = GetConfiguration(assembly) ?? new TestAssemblyConfiguration() { PreEnumerateTheories = false };\n ITestFrameworkDiscoveryOptions discoveryOptions = GetFrameworkOptionsForDiscovery(configuration);\n discoveryOptions.SetSynchronousMessageReporting(true);\n Logger.OnDebug($\"Starting test discovery in the '{assembly}' assembly\");\n frontController.Find(false, discoverySink, discoveryOptions);\n Logger.OnDebug($\"Test discovery in assembly '{assembly}' completed\");\n discoverySink.Finished.WaitOne();\n\n if (discoverySink.TestCases == null || discoverySink.TestCases.Count == 0)\n {\n Logger.Info(\"No test cases discovered\");\n return null;\n }\n\n TotalTests += discoverySink.TestCases.Count;\n List testCases;\n if (_filters != null && _filters.TestCaseFilters.Any())\n {\n Action log = LogExcludedTests ? (s) => do_log(s) : (Action)null;\n testCases = discoverySink.TestCases.Where(\n tc => !_filters.IsExcluded(tc, log)).ToList();\n FilteredTests += discoverySink.TestCases.Count - testCases.Count;\n }\n else\n {\n testCases = discoverySink.TestCases;\n }\n\n var summaryTaskSource = new TaskCompletionSource();\n var resultsXmlAssembly = new XElement(\"assembly\");\n#pragma warning disable CS0618 // Delegating*Sink types are marked obsolete, but we can't move to ExecutionSink yet: https://github.com/dotnet/arcade/issues/14375\n var resultsSink = new DelegatingXmlCreationSink(new DelegatingExecutionSummarySink(_messageSink), resultsXmlAssembly);\n#pragma warning restore\n var completionSink = new CompletionCallbackExecutionSink(resultsSink, summary => summaryTaskSource.SetResult(summary));\n\n ITestFrameworkExecutionOptions executionOptions = GetFrameworkOptionsForExecution(configuration);\n executionOptions.SetDisableParallelization(!RunInParallel);\n executionOptions.SetSynchronousMessageReporting(true);\n executionOptions.SetMaxParallelThreads(MaxParallelThreads);\n\n frontController.RunTests(testCases, completionSink, executionOptions);\n await summaryTaskSource.Task.ConfigureAwait(false);\n\n return resultsXmlAssembly;\n }\n }\n }", + "start_line": 1075, + "end_line": 1127, + "start_byte": 41601, + "end_byte": 44545 + }, + { + "name": "GetFrameworkOptionsForExecution", + "code": "protected virtual ITestFrameworkExecutionOptions GetFrameworkOptionsForExecution(TestAssemblyConfiguration configuration)\n {\n if (configuration == null)\n {\n throw new ArgumentNullException(nameof(configuration));\n }\n\n return TestFrameworkOptions.ForExecution(configuration);\n }", + "start_line": 1065, + "end_line": 1073, + "start_byte": 41273, + "end_byte": 41595 + }, + { + "name": "GetFrameworkOptionsForDiscovery", + "code": "protected virtual ITestFrameworkDiscoveryOptions GetFrameworkOptionsForDiscovery(TestAssemblyConfiguration configuration)\n {\n if (configuration == null)\n {\n throw new ArgumentNullException(nameof(configuration));\n }\n\n return TestFrameworkOptions.ForDiscovery(configuration);\n }", + "start_line": 1055, + "end_line": 1063, + "start_byte": 40945, + "end_byte": 41267 + }, + { + "name": "GetConfiguration", + "code": "protected virtual TestAssemblyConfiguration GetConfiguration(Assembly assembly)\n {\n if (assembly == null)\n {\n throw new ArgumentNullException(nameof(assembly));\n }\n\n Stream configStream = GetConfigurationFileStream(assembly);\n if (configStream != null)\n {\n using (configStream)\n {\n return ConfigReader.Load(configStream);\n }\n }\n\n return null;\n }", + "start_line": 1036, + "end_line": 1053, + "start_byte": 40473, + "end_byte": 40939 + }, + { + "name": "GetConfigurationFileStream", + "code": "protected virtual Stream GetConfigurationFileStream(Assembly assembly)\n {\n if (assembly == null)\n {\n throw new ArgumentNullException(nameof(assembly));\n }\n\n string path = assembly.Location?.Trim();\n if (string.IsNullOrEmpty(path))\n {\n return null;\n }\n\n path = Path.Combine(path, \".xunit.runner.json\");\n if (!File.Exists(path))\n {\n return null;\n }\n\n return File.OpenRead(path);\n }", + "start_line": 1014, + "end_line": 1034, + "start_byte": 39965, + "end_byte": 40467 + }, + { + "name": "Transform_Results", + "code": "private void Transform_Results(string xsltResourceName, XElement element, XmlWriter writer)\n {\n var xmlTransform = new System.Xml.Xsl.XslCompiledTransform();\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(xsltResourceName, StringComparison.Ordinal)).FirstOrDefault();\n if (name == null)\n {\n return;\n }\n\n using (var xsltStream = GetType().Assembly.GetManifestResourceStream(name))\n {\n if (xsltStream == null)\n {\n throw new Exception($\"Stream with name {name} cannot be found! We have {GetType().Assembly.GetManifestResourceNames()[0]}\");\n }\n // add the extension so that we can get the hash from the name of the test\n // Create an XsltArgumentList.\n var xslArg = new XsltArgumentList();\n\n var generator = new XsltIdGenerator();\n xslArg.AddExtensionObject(\"urn:hash-generator\", generator);\n\n using (var xsltReader = XmlReader.Create(xsltStream))\n using (var xmlReader = element.CreateReader())\n {\n xmlTransform.Load(xsltReader);\n xmlTransform.Transform(xmlReader, xslArg, writer);\n }\n }\n }", + "start_line": 983, + "end_line": 1012, + "start_byte": 38689, + "end_byte": 39959 + }, + { + "name": "WriteResultsToFile", + "code": "public override Task WriteResultsToFile(TextWriter writer, XmlResultJargon jargon)\n {\n if (_assembliesElement == null)\n {\n return Task.CompletedTask;\n }\n // remove all the empty nodes\n _assembliesElement.Descendants().Where(e => e.Name == \"collection\" && !e.Descendants().Any()).Remove();\n var settings = new XmlWriterSettings { Indent = true };\n using (var xmlWriter = XmlWriter.Create(writer, settings))\n {\n switch (jargon)\n {\n case XmlResultJargon.TouchUnit:\n case XmlResultJargon.NUnitV2:\n try\n {\n Transform_Results(\"NUnitXml.xslt\", _assembliesElement, xmlWriter);\n }\n catch (Exception e)\n {\n writer.WriteLine(e);\n }\n break;\n case XmlResultJargon.NUnitV3:\n try\n {\n Transform_Results(\"NUnit3Xml.xslt\", _assembliesElement, xmlWriter);\n }\n catch (Exception e)\n {\n writer.WriteLine(e);\n }\n break;\n default: // xunit as default, includes when we got Missing\n _assembliesElement.Save(xmlWriter);\n break;\n }\n }\n return Task.CompletedTask;\n }", + "start_line": 941, + "end_line": 981, + "start_byte": 37169, + "end_byte": 38683 + }, + { + "name": "WriteResultsToFile", + "code": "public override Task WriteResultsToFile(XmlResultJargon jargon)\n {\n if (_assembliesElement == null)\n {\n return Task.FromResult(string.Empty);\r\n }\n // remove all the empty nodes\n _assembliesElement.Descendants().Where(e => e.Name == \"collection\" && !e.Descendants().Any()).Remove();\n string outputFilePath = GetResultsFilePath();\n var settings = new XmlWriterSettings { Indent = true };\n using (var xmlWriter = XmlWriter.Create(outputFilePath, settings))\n {\n switch (jargon)\n {\n case XmlResultJargon.TouchUnit:\n case XmlResultJargon.NUnitV2:\n Transform_Results(\"NUnitXml.xslt\", _assembliesElement, xmlWriter);\n break;\n case XmlResultJargon.NUnitV3:\n Transform_Results(\"NUnit3Xml.xslt\", _assembliesElement, xmlWriter);\n break;\n default: // xunit as default, includes when we got Missing\n _assembliesElement.Save(xmlWriter);\n break;\n }\n }\r\n\r\n return Task.FromResult(outputFilePath);\r\n }", + "start_line": 912, + "end_line": 940, + "start_byte": 35972, + "end_byte": 37164 + }, + { + "name": "Run", + "code": "public override async Task Run(IEnumerable testAssemblies)\n {\n if (testAssemblies == null)\n {\n throw new ArgumentNullException(nameof(testAssemblies));\n }\n\n if (_filters != null && _filters.Count > 0)\n {\n do_log(\"Configured filters:\");\n foreach (XUnitFilter filter in _filters)\n {\n do_log($\" {filter}\");\n }\n }\n\n _assembliesElement = new XElement(\"assemblies\");\n Action log = LogExcludedTests ? (s) => do_log(s) : (Action)null;\n foreach (TestAssemblyInfo assemblyInfo in testAssemblies)\n {\n if (assemblyInfo == null || assemblyInfo.Assembly == null)\n {\n continue;\n }\n\n if (_filters.AssemblyFilters.Any() && _filters.IsExcluded(assemblyInfo, log))\n {\n continue;\n }\n\n if (string.IsNullOrEmpty(assemblyInfo.FullPath))\n {\n OnWarning($\"Assembly '{assemblyInfo.Assembly}' cannot be found on the filesystem. xUnit requires access to actual on-disk file.\");\n continue;\n }\n\n OnInfo($\"Assembly: {assemblyInfo.Assembly} ({assemblyInfo.FullPath})\");\n XElement assemblyElement = null;\n try\n {\n OnAssemblyStart(assemblyInfo.Assembly);\n assemblyElement = await Run(assemblyInfo.Assembly, assemblyInfo.FullPath).ConfigureAwait(false);\n }\n catch (FileNotFoundException ex)\n {\n OnWarning($\"Assembly '{assemblyInfo.Assembly}' using path '{assemblyInfo.FullPath}' cannot be found on the filesystem. xUnit requires access to actual on-disk file.\");\n OnWarning($\"Exception is '{ex}'\");\n }\n finally\n {\n OnAssemblyFinish(assemblyInfo.Assembly);\n if (assemblyElement != null)\n {\n _assembliesElement.Add(assemblyElement);\n }\n }\n }\n\n LogFailureSummary();\n TotalTests += FilteredTests; // ensure that we do have in the total run the excluded ones.\n }", + "start_line": 850, + "end_line": 910, + "start_byte": 33724, + "end_byte": 35966 + }, + { + "name": "do_log", + "code": "private void do_log(string message, Action log = null, StringBuilder sb = null)\n {\n log = EnsureLogger(log);\n\n if (sb != null)\n {\n sb.Append(message);\n }\n\n log(message);\n }", + "start_line": 838, + "end_line": 848, + "start_byte": 33486, + "end_byte": 33718 + }, + { + "name": "GetAssemblyInfo", + "code": "private static string GetAssemblyInfo(ITestAssembly assembly)\n {\n string name = assembly?.Assembly?.Name?.Trim();\n if (string.IsNullOrEmpty(name))\n {\n return name;\n }\n\n return $\" [{name}]\";\n }", + "start_line": 827, + "end_line": 836, + "start_byte": 33236, + "end_byte": 33480 + }, + { + "name": "LogSourceInformation", + "code": "private void LogSourceInformation(ISourceInformation source, Action log = null, StringBuilder sb = null)\n {\n if (source == null || string.IsNullOrEmpty(source.FileName))\n {\n return;\n }\n\n string location = source.FileName;\n if (source.LineNumber != null && source.LineNumber >= 0)\n {\n location += $\":{source.LineNumber}\";\n }\n\n do_log($\" Source: {location}\", log, sb);\n sb?.AppendLine();\n }", + "start_line": 810, + "end_line": 825, + "start_byte": 32741, + "end_byte": 33230 + }, + { + "name": "LogSummary", + "code": "private void LogSummary(ExecutionSummary summary, Action log = null, StringBuilder sb = null)\n {\n do_log($\" Time: {summary.Time}\", log, sb);\n do_log($\" Total tests run: {summary.Total}\", log, sb);\n do_log($\" Total errors: {summary.Errors}\", log, sb);\n do_log($\" Skipped tests: {summary.Skipped}\", log, sb);\n do_log($\" Failed tests: {summary.Failed}\", log, sb);\n }", + "start_line": 801, + "end_line": 808, + "start_byte": 32313, + "end_byte": 32735 + }, + { + "name": "LogSummary", + "code": "private void LogSummary(IFinishedMessage summary, Action log = null, StringBuilder sb = null)\n {\n do_log($\" Time: {summary.ExecutionTime}\", log, sb);\n do_log($\" Total tests run: {summary.TestsRun}\", log, sb);\n do_log($\" Skipped tests: {summary.TestsSkipped}\", log, sb);\n do_log($\" Failed tests: {summary.TestsFailed}\", log, sb);\n }", + "start_line": 793, + "end_line": 799, + "start_byte": 31926, + "end_byte": 32307 + }, + { + "name": "LogTestDetails", + "code": "private void LogTestDetails(ITest test, Action log = null, StringBuilder sb = null)\n {\n do_log($\" Test name: {test.DisplayName}\", log, sb);\n if (string.Compare(test.DisplayName, test.TestCase.DisplayName, StringComparison.Ordinal) != 0)\n {\n do_log($\" Test case: {test.TestCase.DisplayName}\", log, sb);\n }\n }", + "start_line": 784, + "end_line": 791, + "start_byte": 31556, + "end_byte": 31920 + }, + { + "name": "LogTestClassDetails", + "code": "private void LogTestClassDetails(ITestClass klass, Action log = null, StringBuilder sb = null)\n {\n do_log($\" Class name: {klass.Class.Name}\", log, sb);\n do_log($\" Class assembly: {klass.Class.Assembly.Name}\", OnDebug, sb);\n do_log($\" Class assembly path: {klass.Class.Assembly.AssemblyPath}\", OnDebug, sb);\n }", + "start_line": 777, + "end_line": 782, + "start_byte": 31200, + "end_byte": 31550 + }, + { + "name": "LogTestCollectionDetails", + "code": "private void LogTestCollectionDetails(ITestCollection collection, Action log = null, StringBuilder sb = null) => do_log($\" Test collection: {collection.DisplayName}\", log, sb);", + "start_line": 775, + "end_line": 775, + "start_byte": 31008, + "end_byte": 31194 + }, + { + "name": "LogTestOutput", + "code": "private void LogTestOutput(decimal executionTime, string output, Action log = null, StringBuilder sb = null)\n {\n do_log($\" Execution time: {executionTime}\", log, sb);\n if (!string.IsNullOrEmpty(output))\n {\n do_log(\" **** Output start ****\", log, sb);\n foreach (string line in output.Split('\\n'))\n {\n do_log(line, log, sb);\n }\n\n do_log(\" **** Output end ****\", log, sb);\n }\n }", + "start_line": 760, + "end_line": 773, + "start_byte": 30513, + "end_byte": 31002 + }, + { + "name": "LogTestOutput", + "code": "private void LogTestOutput(ITestResultMessage test, Action log = null, StringBuilder sb = null) => LogTestOutput(test.ExecutionTime, test.Output, log, sb);", + "start_line": 758, + "end_line": 758, + "start_byte": 30344, + "end_byte": 30507 + }, + { + "name": "LogTestOutput", + "code": "private void LogTestOutput(ITestFinished test, Action log = null, StringBuilder sb = null) => LogTestOutput(test.ExecutionTime, test.Output, log, sb);", + "start_line": 756, + "end_line": 756, + "start_byte": 30180, + "end_byte": 30338 + }, + { + "name": "LogTestMethodDetails", + "code": "private static void LogTestMethodDetails(IMethodInfo method, Action log = null, StringBuilder sb = null)\n#pragma warning restore IDE0060 // Remove unused parameter\n {\n // log = EnsureLogger(log);\n // log ($\" Test method name: {method.Type.Name}.{method.Name}\");\n }", + "start_line": 749, + "end_line": 754, + "start_byte": 29880, + "end_byte": 30174 + }, + { + "name": "EnsureLogger", + "code": "private Action EnsureLogger(Action log) => log ?? OnInfo;", + "start_line": 746, + "end_line": 746, + "start_byte": 29742, + "end_byte": 29815 + }, + { + "name": "LogFailureInformation", + "code": "private void LogFailureInformation(IFailureInformation info, Action log = null, StringBuilder sb = null)\n {\n if (info == null)\n {\n return;\n }\n\n string message = ExceptionUtility.CombineMessages(info);\n do_log($\" Exception messages: {message}\", log, sb);\n\n string traces = ExceptionUtility.CombineStackTraces(info);\n do_log($\" Exception stack traces: {traces}\", log, sb);\n }", + "start_line": 732, + "end_line": 744, + "start_byte": 29285, + "end_byte": 29736 + }, + { + "name": "LogAssemblyInformation", + "code": "private void LogAssemblyInformation(ITestAssemblyMessage message, Action log = null, StringBuilder sb = null)\n {\n if (message == null)\n {\n return;\n }\n\n do_log($\"[Assembly name: {message.TestAssembly.Assembly.Name}]\", log, sb);\n do_log($\"[Assembly path: {message.TestAssembly.Assembly.AssemblyPath}]\", OnDiagnostic, sb);\n }", + "start_line": 721, + "end_line": 730, + "start_byte": 28897, + "end_byte": 29279 + }, + { + "name": "ReportTestCase", + "code": "private void ReportTestCase(string verb, ITestCase testCase, Action log = null)\n {\n if (testCase == null)\n {\n return;\n }\n\n EnsureLogger(log)($\"{verb} test case: {testCase.DisplayName}\");\n }", + "start_line": 711, + "end_line": 719, + "start_byte": 28649, + "end_byte": 28891 + }, + { + "name": "ReportTestCases", + "code": "private void ReportTestCases(string verb, IEnumerable testCases, Action log = null, Func ignore = null)\n {\n if (testCases == null)\n {\n return;\n }\n\n foreach (ITestCase tc in testCases)\n {\n if (ignore != null && ignore(tc))\n {\n continue;\n }\n\n ReportTestCase(verb, tc, log);\n }\n }", + "start_line": 693, + "end_line": 709, + "start_byte": 28212, + "end_byte": 28643 + }, + { + "name": "ReportTestCases", + "code": "private void ReportTestCases(string verb, IEnumerable testCases, ITestCase ignoreTestCase, Action log = null) => ReportTestCases(verb, testCases, log, (ITestCase tc) => ignoreTestCase == tc);", + "start_line": 691, + "end_line": 691, + "start_byte": 27996, + "end_byte": 28206 + }, + { + "name": "RaiseTestSkippedCase", + "code": "private void RaiseTestSkippedCase(ITestResultMessage message, IEnumerable testCases, ITestCase testCase)\n {\n SkippedTests++;\n OnInfo($\"{TestStagePrefix}[IGNORED] {testCase.DisplayName}\");\n LogTestDetails(message.Test, log: OnDebug);\n LogTestOutput(message, log: OnDiagnostic);\n ReportTestCases(\" Associated\", testCases, log: OnDiagnostic);\n // notify that the test completed because it was skipped\n OnTestCompleted((\n TestName: message.Test.DisplayName,\n TestResult: TestResult.Skipped\n ));\n }", + "start_line": 677, + "end_line": 689, + "start_byte": 27400, + "end_byte": 27990 + }, + { + "name": "HandleDiscoveryTestCaseMessage", + "code": "private void HandleDiscoveryTestCaseMessage(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n ITestCase singleTestCase = args.Message.TestCase;\n ReportTestCases(\"Discovered\", args.Message.TestCases, log: OnInfo, ignore: (ITestCase tc) => tc == singleTestCase);\n ReportTestCase(\"Discovered\", singleTestCase, log: OnInfo);\n }", + "start_line": 665, + "end_line": 675, + "start_byte": 26947, + "end_byte": 27394 + }, + { + "name": "HandleDiscoveryCompleteMessage", + "code": "private void HandleDiscoveryCompleteMessage(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnInfo(\"Discovery complete\");\n }", + "start_line": 655, + "end_line": 663, + "start_byte": 26705, + "end_byte": 26941 + }, + { + "name": "HandleDiagnosticErrorMessage", + "code": "private void HandleDiagnosticErrorMessage(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n LogFailureInformation(args.Message);\n }", + "start_line": 645, + "end_line": 653, + "start_byte": 26470, + "end_byte": 26699 + }, + { + "name": "HandleDiagnosticMessage", + "code": "private void HandleDiagnosticMessage(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDiagnostic(args.Message.Message);\n }", + "start_line": 635, + "end_line": 643, + "start_byte": 26236, + "end_byte": 26464 + }, + { + "name": "HandleTestAssemblyDiscoveryFinished", + "code": "private void HandleTestAssemblyDiscoveryFinished(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnInfo($\"Discovery for assembly {args.Message.Assembly.AssemblyFilename} finished\");\n OnInfo($\" Test cases discovered: {args.Message.TestCasesDiscovered}\");\n OnInfo($\" Test cases to run: {args.Message.TestCasesToRun}\");\n }", + "start_line": 623, + "end_line": 633, + "start_byte": 25776, + "end_byte": 26230 + }, + { + "name": "HandleTestAssemblyDiscoveryStarting", + "code": "private void HandleTestAssemblyDiscoveryStarting(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnInfo($\"Discovery for assembly {args.Message.Assembly.AssemblyFilename} starting\");\n OnInfo($\" Will use AppDomain: {args.Message.AppDomain.YesNo()}\");\n }", + "start_line": 612, + "end_line": 621, + "start_byte": 25393, + "end_byte": 25770 + }, + { + "name": "HandleTestAssemblyExecutionFinished", + "code": "private void HandleTestAssemblyExecutionFinished(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnInfo($\"Execution finished for assembly {args.Message.Assembly.AssemblyFilename}\");\n LogSummary(args.Message.ExecutionSummary, log: OnDebug);\n }", + "start_line": 601, + "end_line": 610, + "start_byte": 25021, + "end_byte": 25387 + }, + { + "name": "HandleTestAssemblyExecutionStarting", + "code": "private void HandleTestAssemblyExecutionStarting(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnInfo($\"Execution starting for assembly {args.Message.Assembly.AssemblyFilename}\");\n }", + "start_line": 591, + "end_line": 599, + "start_byte": 24714, + "end_byte": 25015 + }, + { + "name": "HandleTestExecutionSummary", + "code": "private void HandleTestExecutionSummary(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnInfo(\"All tests finished\");\n OnInfo($\" Elapsed time: {args.Message.ElapsedClockTime}\");\n\n if (args.Message.Summaries == null || args.Message.Summaries.Count == 0)\n {\n return;\n }\n\n foreach (KeyValuePair summary in args.Message.Summaries)\n {\n OnInfo(string.Empty);\n OnInfo($\" Assembly: {summary.Key}\");\n LogSummary(summary.Value, log: OnDebug);\n }\n }", + "start_line": 568, + "end_line": 589, + "start_byte": 24040, + "end_byte": 24708 + }, + { + "name": "HandleAfterTestFinished", + "code": "private void HandleAfterTestFinished(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDiagnostic($\"'After' method for test '{args.Message.Test.DisplayName}' finished\");\n }", + "start_line": 558, + "end_line": 566, + "start_byte": 23757, + "end_byte": 24034 + }, + { + "name": "HandleAfterTestStarting", + "code": "private void HandleAfterTestStarting(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDiagnostic($\"'After' method for test '{args.Message.Test.DisplayName}' starting\");\n }", + "start_line": 548, + "end_line": 556, + "start_byte": 23474, + "end_byte": 23751 + }, + { + "name": "HandleBeforeTestFinished", + "code": "private void HandleBeforeTestFinished(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDiagnostic($\"'Before' method for test '{args.Message.Test.DisplayName}' finished\");\n }", + "start_line": 538, + "end_line": 546, + "start_byte": 23188, + "end_byte": 23468 + }, + { + "name": "HandleBeforeTestStarting", + "code": "private void HandleBeforeTestStarting(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n // notify that a method is starting\n OnTestStarted(args.Message.Test.DisplayName);\n OnDiagnostic($\"'Before' method for test '{args.Message.Test.DisplayName}' starting\");\n }", + "start_line": 526, + "end_line": 536, + "start_byte": 22804, + "end_byte": 23182 + }, + { + "name": "HandleTestAssemblyCleanupFailure", + "code": "private void HandleTestAssemblyCleanupFailure(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnError(\"Assembly cleanup failure\");\n LogAssemblyInformation(args.Message, OnError);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnError);\n LogFailureInformation(args.Message, log: OnError);\n }", + "start_line": 513, + "end_line": 524, + "start_byte": 22357, + "end_byte": 22798 + }, + { + "name": "HandleTestAssemblyFinished", + "code": "private void HandleTestAssemblyFinished(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n TotalTests = args.Message.TestsRun; // HACK: We are not counting correctly all the tests\n OnDebug(\"Execution process for assembly finished\");\n LogAssemblyInformation(args.Message, log: OnDebug);\n LogSummary(args.Message, log: OnDebug);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnDiagnostic);\n }", + "start_line": 499, + "end_line": 511, + "start_byte": 21811, + "end_byte": 22351 + }, + { + "name": "HandleTestAssemblyStarting", + "code": "private void HandleTestAssemblyStarting(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnInfo($\"[Test environment: {args.Message.TestEnvironment}]\");\n OnInfo($\"[Test framework: {args.Message.TestFrameworkDisplayName}]\");\n LogAssemblyInformation(args.Message, log: OnDebug);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnDebug);\n }", + "start_line": 486, + "end_line": 497, + "start_byte": 21326, + "end_byte": 21805 + }, + { + "name": "HandleTestCaseCleanupFailure", + "code": "private void HandleTestCaseCleanupFailure(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnError(\"Test case cleanup failure\");\n ReportTestCase(\" Failed\", args.Message.TestCase, log: OnError);\n ReportTestCases(\" Associated\", args.Message.TestCases, args.Message.TestCase, OnError);\n LogFailureInformation(args.Message, log: OnError);\n }", + "start_line": 473, + "end_line": 484, + "start_byte": 20849, + "end_byte": 21320 + }, + { + "name": "HandleTestCaseFinished", + "code": "private void HandleTestCaseFinished(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDebug(\"Test case finished executing\");\n ReportTestCase(\" Finished\", args.Message.TestCase, log: OnDebug);\n ReportTestCases(\" Associated\", args.Message.TestCases, args.Message.TestCase, OnDebug);\n LogSummary(args.Message, log: OnDebug);\n }", + "start_line": 460, + "end_line": 471, + "start_byte": 20390, + "end_byte": 20843 + }, + { + "name": "HandleTestCaseStarting", + "code": "private void HandleTestCaseStarting(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDiagnostic(\"Test case starting\");\n ReportTestCase(\" Starting\", args.Message.TestCase, log: OnDiagnostic);\n ReportTestCases(\" Associated\", args.Message.TestCases, args.Message.TestCase, OnDiagnostic);\n }", + "start_line": 448, + "end_line": 458, + "start_byte": 19974, + "end_byte": 20384 + }, + { + "name": "HandleTestClassCleanupFailure", + "code": "private void HandleTestClassCleanupFailure(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnError($\"Test class cleanup error{GetAssemblyInfo(args.Message.TestAssembly)}\");\n LogTestClassDetails(args.Message.TestClass, log: OnError);\n LogTestCollectionDetails(args.Message.TestCollection, log: OnError);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnError);\n LogFailureInformation(args.Message, log: OnError);\n }", + "start_line": 434, + "end_line": 446, + "start_byte": 19399, + "end_byte": 19968 + }, + { + "name": "HandleTestClassConstructionFinished", + "code": "private void HandleTestClassConstructionFinished(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDiagnostic(\"Test class construction finished\");\n LogTestDetails(args.Message.Test, log: OnDiagnostic);\n ReportTestCases(\" Associated\", args.Message.TestCases, args.Message.TestCase, OnDiagnostic);\n }", + "start_line": 422, + "end_line": 432, + "start_byte": 18962, + "end_byte": 19393 + }, + { + "name": "HandleTestClassConstructionStarting", + "code": "private void HandleTestClassConstructionStarting(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDiagnostic(\"Test class construction starting\");\n LogTestDetails(args.Message.Test, OnDiagnostic);\n ReportTestCases(\" Associated\", args.Message.TestCases, args.Message.TestCase, OnDiagnostic);\n }", + "start_line": 410, + "end_line": 420, + "start_byte": 18530, + "end_byte": 18956 + }, + { + "name": "HandleTestClassDisposeFinished", + "code": "private void HandleTestClassDisposeFinished(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDiagnostic(\"Test class dispose finished\");\n LogTestDetails(args.Message.Test, log: OnDiagnostic);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnDiagnostic);\n }", + "start_line": 398, + "end_line": 408, + "start_byte": 18126, + "end_byte": 18524 + }, + { + "name": "HandleTestClassDisposeStarting", + "code": "private void HandleTestClassDisposeStarting(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDiagnostic(\"Test class dispose starting\");\n LogTestDetails(args.Message.Test, log: OnDiagnostic);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnDiagnostic);\n }", + "start_line": 386, + "end_line": 396, + "start_byte": 17722, + "end_byte": 18120 + }, + { + "name": "HandleTestClassFinished", + "code": "private void HandleTestClassFinished(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDebug(\"Test class finished\");\n OnInfo($\"{args.Message.TestClass.Class.Name} {args.Message.ExecutionTime} ms\");\n LogTestClassDetails(args.Message.TestClass, OnDebug);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnDiagnostic);\n }", + "start_line": 373, + "end_line": 384, + "start_byte": 17257, + "end_byte": 17716 + }, + { + "name": "HandleTestClassStarting", + "code": "private void HandleTestClassStarting(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDiagnostic(\"Test class starting\");\n LogTestClassDetails(args.Message.TestClass, log: OnDiagnostic);\n }", + "start_line": 362, + "end_line": 371, + "start_byte": 16950, + "end_byte": 17251 + }, + { + "name": "HandleTestCleanupFailure", + "code": "private void HandleTestCleanupFailure(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnError($\"Test cleanup failure{GetAssemblyInfo(args.Message.TestAssembly)}\");\n LogTestDetails(args.Message.Test, log: OnError);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnError);\n LogFailureInformation(args.Message, log: OnError);\n }", + "start_line": 349, + "end_line": 360, + "start_byte": 16476, + "end_byte": 16944 + }, + { + "name": "HandleTestCollectionCleanupFailure", + "code": "private void HandleTestCollectionCleanupFailure(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnError(\"Error during test collection cleanup\");\n LogTestCollectionDetails(args.Message.TestCollection, log: OnError);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnError);\n LogFailureInformation(args.Message, log: OnError);\n }", + "start_line": 336, + "end_line": 347, + "start_byte": 15991, + "end_byte": 16470 + }, + { + "name": "HandleTestCollectionFinished", + "code": "private void HandleTestCollectionFinished(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDebug(\"Test collection finished\");\n LogSummary(args.Message, log: OnDebug);\n LogTestCollectionDetails(args.Message.TestCollection, log: OnDebug);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnDiagnostic);\n }", + "start_line": 323, + "end_line": 334, + "start_byte": 15536, + "end_byte": 15985 + }, + { + "name": "HandleTestCollectionStarting", + "code": "private void HandleTestCollectionStarting(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnInfo($\"\\n{args.Message.TestCollection.DisplayName}\");\n OnDebug(\"Test collection starting\");\n LogTestCollectionDetails(args.Message.TestCollection, log: OnDebug);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnDiagnostic);\n }", + "start_line": 310, + "end_line": 321, + "start_byte": 15065, + "end_byte": 15530 + }, + { + "name": "HandleTestFailed", + "code": "private void HandleTestFailed(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\r\n\r\n FailedTests++;\n string assemblyInfo = GetAssemblyInfo(args.Message.TestAssembly);\n var sb = new StringBuilder($\"{TestStagePrefix}[FAIL]{GetThreadIdForLog()} {args.Message.TestCase.DisplayName}\");\n LogTestDetails(args.Message.Test, OnDebug, sb);\n sb.AppendLine();\n if (!string.IsNullOrEmpty(assemblyInfo))\n {\n sb.AppendLine($\" Assembly: {assemblyInfo}\");\n }\n\n LogSourceInformation(args.Message.TestCase.SourceInformation, OnDebug, sb);\n LogFailureInformation(args.Message, OnDebug, sb);\n sb.AppendLine();\n LogTestOutput(args.Message, OnDebug, sb);\n sb.AppendLine();\n if (args.Message.TestCase.Traits != null && args.Message.TestCase.Traits.Count > 0)\n {\n foreach (var kvp in args.Message.TestCase.Traits)\n {\n string message = $\" Test trait name: {kvp.Key}\";\n OnDebug(message);\n sb.AppendLine(message);\n\n foreach (string v in kvp.Value)\n {\n message = $\" value: {v}\";\n OnDebug(message);\n sb.AppendLine(message);\n }\n }\n sb.AppendLine();\n }\n ReportTestCases(\" Associated\", args.Message.TestCases, args.Message.TestCase, OnDiagnostic);\n\n FailureInfos.Add(new TestFailureInfo\n {\n TestName = args.Message.Test?.DisplayName,\n Message = sb.ToString()\n });\n OnError($\"{TestStagePrefix}[FAIL]{GetThreadIdForLog()} {args.Message.Test.DisplayName}{Environment.NewLine}{ExceptionUtility.CombineMessages(args.Message)}{Environment.NewLine}{ExceptionUtility.CombineStackTraces(args.Message)}\");\n OnDebug(sb.ToString());\n OnTestCompleted((\n TestName: args.Message.Test.DisplayName,\n TestResult: TestResult.Failed\n ));\n }", + "start_line": 256, + "end_line": 308, + "start_byte": 12961, + "end_byte": 15059 + }, + { + "name": "HandleTestFinished", + "code": "private void HandleTestFinished(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n ExecutedTests++;\n OnDiagnostic(\"Test finished\");\n LogTestDetails(args.Message.Test, log: OnDiagnostic);\n LogTestOutput(args.Message, log: OnDiagnostic);\n ReportTestCases(\" Associated\", args.Message.TestCases, args.Message.TestCase, OnDiagnostic);\n }", + "start_line": 242, + "end_line": 254, + "start_byte": 12496, + "end_byte": 12955 + }, + { + "name": "HandleTestMethodCleanupFailure", + "code": "private void HandleTestMethodCleanupFailure(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnError($\"Test method cleanup failure{GetAssemblyInfo(args.Message.TestAssembly)}\");\n LogTestMethodDetails(args.Message.TestMethod.Method, log: OnError);\n LogTestClassDetails(args.Message.TestMethod.TestClass, log: OnError);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnDiagnostic);\n LogFailureInformation(args.Message, log: OnError);\n }", + "start_line": 228, + "end_line": 240, + "start_byte": 11901, + "end_byte": 12490 + }, + { + "name": "HandleTestMethodFinished", + "code": "private void HandleTestMethodFinished(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDebug(\"Test method finished\");\n LogTestMethodDetails(args.Message.TestMethod.Method, log: OnDebug);\n LogTestClassDetails(args.Message.TestMethod.TestClass, log: OnDebug);\n LogSummary(args.Message, log: OnDebug);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnDiagnostic);\n }", + "start_line": 214, + "end_line": 226, + "start_byte": 11381, + "end_byte": 11895 + }, + { + "name": "HandleTestMethodStarting", + "code": "private void HandleTestMethodStarting(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDebug(\"Test method starting\");\n LogTestMethodDetails(args.Message.TestMethod.Method, log: OnDebug);\n LogTestClassDetails(args.Message.TestMethod.TestClass, log: OnDebug);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnDiagnostic);\n }", + "start_line": 201, + "end_line": 212, + "start_byte": 10909, + "end_byte": 11375 + }, + { + "name": "HandleTestOutput", + "code": "private void HandleTestOutput(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n OnDebug(args.Message.Output);\n }", + "start_line": 191, + "end_line": 199, + "start_byte": 10695, + "end_byte": 10903 + }, + { + "name": "HandleTestPassed", + "code": "private void HandleTestPassed(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n PassedTests++;\n OnInfo($\"{TestStagePrefix}[PASS]{GetThreadIdForLog()} {args.Message.TestCase.DisplayName}\");\n LogTestDetails(args.Message.Test, log: OnDebug);\n LogTestOutput(args.Message, log: OnDiagnostic);\n ReportTestCases(\" Associated\", args.Message.TestCases, log: OnDiagnostic);\n // notify the completion of the test\n OnTestCompleted((\n TestName: args.Message.Test.DisplayName,\n TestResult: TestResult.Passed\n ));\n }", + "start_line": 172, + "end_line": 189, + "start_byte": 10019, + "end_byte": 10689 + }, + { + "name": "HandleTestSkipped", + "code": "private void HandleTestSkipped(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n RaiseTestSkippedCase(args.Message, args.Message.TestCases, args.Message.TestCase);\n }", + "start_line": 162, + "end_line": 170, + "start_byte": 9750, + "end_byte": 10013 + }, + { + "name": "HandleTestStarting", + "code": "private void HandleTestStarting(MessageHandlerArgs args)\n {\n if (args == null || args.Message == null)\n {\n return;\n }\n\n if (EnvironmentVariables.IsLogTestStart())\n {\n OnInfo($\"{TestStagePrefix}[STRT]{GetThreadIdForLog()} {args.Message.Test.DisplayName}\");\n }\n\n OnDebug(\"Test starting\");\n LogTestDetails(args.Message.Test, log: OnDebug);\n ReportTestCases(\" Associated\", args.Message.TestCases, args.Message.TestCase, OnDiagnostic);\n }", + "start_line": 145, + "end_line": 160, + "start_byte": 9203, + "end_byte": 9744 + }, + { + "name": "GetThreadIdForLog", + "code": "protected string GetThreadIdForLog()\r\n {\n if (EnvironmentVariables.IsLogThreadId())\r\n return $\"[{Thread.CurrentThread.ManagedThreadId}]\";\r\n\r\n return string.Empty;\r\n }", + "start_line": 137, + "end_line": 143, + "start_byte": 9000, + "end_byte": 9197 + }, + { + "name": "HandleEvent", + "code": "private void HandleEvent(string name, MessageHandlerArgs args, Action> actualHandler) where T : class, IMessageSinkMessage\n {\n try\n {\n actualHandler(args);\n }\n catch (Exception ex)\n {\n OnError($\"Handler for event {name} failed with exception\");\n OnError(ex.ToString());\n }\n }", + "start_line": 124, + "end_line": 135, + "start_byte": 8610, + "end_byte": 8994 + }, + { + "name": "SetFilters", + "code": "public void SetFilters(List newFilters)\n {\n if (newFilters == null)\n {\n _filters = null;\n return;\n }\n\n if (_filters == null)\n {\n _filters = new XUnitFiltersCollection();\n }\n\n _filters.AddRange(newFilters);\n }", + "start_line": 108, + "end_line": 122, + "start_byte": 8295, + "end_byte": 8604 + }, + { + "name": "AddFilter", + "code": "public void AddFilter(XUnitFilter filter)\n {\n if (filter != null)\n {\n _filters.Add(filter);\n }\n }", + "start_line": 101, + "end_line": 107, + "start_byte": 8155, + "end_byte": 8290 + }, + { + "name": "ConsumeAssembliesElement", + "code": "internal XElement ConsumeAssembliesElement()\r\n {\n Debug.Assert(_assembliesElement != null, \"ConsumeAssembliesElement called before Run() or after ConsumeAssembliesElement() was already called.\");\r\n var res = _assembliesElement;\r\n _assembliesElement = null;\r\n FailureInfos.Clear();\r\n return res;\r\n }", + "start_line": 39, + "end_line": 46, + "start_byte": 1087, + "end_byte": 1426 + }, + { + "name": "GenerateHash", + "code": "public int GenerateHash() => _seed++;", + "start_line": 28, + "end_line": 28, + "start_byte": 843, + "end_byte": 880 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/XUnitFilterType.cs": [], + "src/Microsoft.DotNet.XHarness.Apple/ILogger.cs": [ + { + "name": "LogCritical", + "code": "void LogCritical(string message);", + "start_line": 18, + "end_line": 18, + "start_byte": 720, + "end_byte": 753 + }, + { + "name": "LogError", + "code": "void LogError(string message);", + "start_line": 17, + "end_line": 17, + "start_byte": 685, + "end_byte": 715 + }, + { + "name": "LogWarning", + "code": "void LogWarning(string message);", + "start_line": 16, + "end_line": 16, + "start_byte": 648, + "end_byte": 680 + }, + { + "name": "LogInformation", + "code": "void LogInformation(string message);", + "start_line": 15, + "end_line": 15, + "start_byte": 607, + "end_byte": 643 + }, + { + "name": "LogDebug", + "code": "void LogDebug(string message);", + "start_line": 14, + "end_line": 14, + "start_byte": 572, + "end_byte": 602 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/DeviceLogCapturerFactory.cs": [ + { + "name": "Create", + "code": "public IDeviceLogCapturer Create(ILog mainLog, ILog deviceLog, string deviceName) => new DeviceLogCapturer(_processManager, mainLog, deviceLog, deviceName);", + "start_line": 26, + "end_line": 26, + "start_byte": 868, + "end_byte": 1024 + }, + { + "name": "Create", + "code": "IDeviceLogCapturer Create(ILog mainLog, ILog deviceLog, string deviceName);", + "start_line": 14, + "end_line": 14, + "start_byte": 466, + "end_byte": 541 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/ErrorKnowledgeBase.cs": [ + { + "name": "TryFindErrors", + "code": "private static bool TryFindErrors(IFileBackedLog log, Dictionary errorMap,\n [NotNullWhen(true)] out KnownIssue? failureMessage)\n {\n failureMessage = null;\n if (log == null)\n {\n return false;\n }\n\n if (!File.Exists(log.FullPath) || new FileInfo(log.FullPath).Length <= 0)\n {\n return false;\n }\n\n using var reader = log.GetReader();\n while (!reader.EndOfStream)\n {\n var line = reader.ReadLine();\n if (line == null)\n {\n continue;\n }\n\n //go over errors and return true as soon as we find one that matches\n foreach (var error in errorMap.Keys)\n {\n if (!line.Contains(error, StringComparison.InvariantCultureIgnoreCase))\n {\n continue;\n }\n\n failureMessage = errorMap[error];\n return true;\n }\n }\n\n return false;\n }", + "start_line": 86, + "end_line": 123, + "start_byte": 4453, + "end_byte": 5493 + }, + { + "name": "IsKnownInstallIssue", + "code": "public bool IsKnownInstallIssue(IFileBackedLog installLog, [NotNullWhen(true)] out KnownIssue? knownFailureMessage)\n => TryFindErrors(installLog, s_installErrorMaps, out knownFailureMessage);", + "start_line": 83, + "end_line": 84, + "start_byte": 4249, + "end_byte": 4447 + }, + { + "name": "IsKnownTestIssue", + "code": "public bool IsKnownTestIssue(IFileBackedLog runLog, [NotNullWhen(true)] out KnownIssue? knownFailureMessage)\n => TryFindErrors(runLog, s_testErrorMaps, out knownFailureMessage);", + "start_line": 80, + "end_line": 81, + "start_byte": 4059, + "end_byte": 4243 + }, + { + "name": "IsKnownBuildIssue", + "code": "public bool IsKnownBuildIssue(IFileBackedLog buildLog, [NotNullWhen(true)] out KnownIssue? knownFailureMessage)\n => TryFindErrors(buildLog, s_buildErrorMaps, out knownFailureMessage);", + "start_line": 77, + "end_line": 78, + "start_byte": 3863, + "end_byte": 4053 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/ExitCodeDetector.cs": [ + { + "name": "IsSignalLine", + "code": "protected override Match? IsSignalLine(AppBundleInformation appBundleInfo, string logLine)\n {\n if (base.IsSignalLine(appBundleInfo, logLine) is Match match && match.Success)\n {\n return match;\n }\n\n if (logLine.Contains(appBundleInfo.BundleIdentifier))\n {\n foreach (var regex in DeviceExitCodeRegexes)\n {\n var m = regex.Match(logLine);\n if (m.Success)\n {\n return m;\n }\n }\n }\n\n return null;\n }", + "start_line": 95, + "end_line": 115, + "start_byte": 3807, + "end_byte": 4375 + }, + { + "name": "IsAbnormalExitLine", + "code": "private static bool IsAbnormalExitLine(AppBundleInformation appBundleInfo, string logLine) =>\n logLine.Contains(AbnormalExitMessage) && (logLine.Contains(appBundleInfo.AppName) || logLine.Contains(appBundleInfo.BundleIdentifier));", + "start_line": 80, + "end_line": 81, + "start_byte": 2891, + "end_byte": 3128 + }, + { + "name": "IsStdoutExitLine", + "code": "private static bool IsStdoutExitLine(AppBundleInformation appBundleInfo, string logLine) =>\n logLine.Contains(DotnetAppExitTag) && logLine.Contains(appBundleInfo.BundleExecutable ?? appBundleInfo.BundleIdentifier);", + "start_line": 75, + "end_line": 76, + "start_byte": 2497, + "end_byte": 2718 + }, + { + "name": "IsSignalLine", + "code": "protected virtual Match? IsSignalLine(AppBundleInformation appBundleInfo, string logLine)\n {\n if (IsAbnormalExitLine(appBundleInfo, logLine) || IsStdoutExitLine(appBundleInfo, logLine))\n {\n return EoLExitCodeRegex.Match(logLine);\n }\n\n return null;\n }", + "start_line": 61, + "end_line": 69, + "start_byte": 1905, + "end_byte": 2200 + }, + { + "name": "DetectExitCode", + "code": "public int? DetectExitCode(AppBundleInformation appBundleInfo, IReadableLog log)\n {\n StreamReader reader;\n\n try\n {\n reader = log.GetReader();\n }\n catch (FileNotFoundException e)\n {\n throw new Exception(\"Failed to detect application's exit code. The log file was empty / not found at \" + e.FileName, e);\n }\n\n using (reader)\n while (!reader.EndOfStream)\n {\n if (reader.ReadLine() is string line\n && IsSignalLine(appBundleInfo, line) is Match match && match.Success\n && int.TryParse(match.Groups[\"exitCode\"].Value, out var exitCode))\n {\n return exitCode;\n }\n }\n\n return null;\n }", + "start_line": 34, + "end_line": 59, + "start_byte": 1134, + "end_byte": 1899 + }, + { + "name": "DetectExitCode", + "code": "int? DetectExitCode(AppBundleInformation appBundleInfo, IReadableLog systemLog);", + "start_line": 15, + "end_line": 15, + "start_byte": 454, + "end_byte": 534 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/DeviceFinder.cs": [ + { + "name": "FindDevice", + "code": "public async Task FindDevice(\n TestTargetOs target,\n string? deviceName,\n ILog log,\n bool includeWirelessDevices = true,\n bool pairedDevicesOnly = true,\n CancellationToken cancellationToken = default)\n {\n IDevice? device;\n IDevice? companionDevice = null;\n\n bool IsMatchingDevice(IDevice device) =>\n device.Name.Equals(deviceName, StringComparison.InvariantCultureIgnoreCase) ||\n device.UDID.Equals(deviceName, StringComparison.InvariantCultureIgnoreCase);\n\n if (target.Platform.IsSimulator())\n {\n if (deviceName == null)\n {\n (device, companionDevice) = await _simulatorLoader.FindSimulators(target, log, retryCount: 3, cancellationToken: cancellationToken);\n }\n else\n {\n await _simulatorLoader.LoadDevices(log, includeLocked: false, cancellationToken: cancellationToken);\n\n device = _simulatorLoader.AvailableDevices.FirstOrDefault(IsMatchingDevice)\n ?? throw new NoDeviceFoundException($\"Failed to find a simulator '{deviceName}'\");\n }\n }\n else\n {\n // The DeviceLoader.FindDevice will return the fist device of the type, but we want to make sure that\n // the device we use is of the correct arch, therefore, we will use the LoadDevices and handpick one\n await _deviceLoader.LoadDevices(\n log,\n includeLocked: false,\n forceRefresh: false,\n includeWirelessDevices: includeWirelessDevices,\n cancellationToken: cancellationToken);\n\n if (deviceName == null)\n {\n\n IHardwareDevice? hardwareDevice = target.Platform switch\n {\n TestTarget.Device_iOS => _deviceLoader.Connected64BitIOS.FirstOrDefault(d => !pairedDevicesOnly || d.IsPaired),\n TestTarget.Device_tvOS => _deviceLoader.ConnectedTV.FirstOrDefault(d => !pairedDevicesOnly || d.IsPaired),\n _ => throw new ArgumentOutOfRangeException(nameof(target), $\"Unrecognized device platform {target.Platform}\")\n };\n\n if (target.Platform.IsWatchOSTarget() && hardwareDevice != null)\n {\n companionDevice = await _deviceLoader.FindCompanionDevice(log, hardwareDevice, cancellationToken: cancellationToken);\n }\n\n device = hardwareDevice;\n }\n else\n {\n device = _deviceLoader.ConnectedDevices.FirstOrDefault(IsMatchingDevice)\n ?? throw new NoDeviceFoundException($\"Failed to find a device '{deviceName}'. \" +\n \"Please make sure the device is connected and unlocked.\");\n }\n }\n\n if (device == null)\n {\n throw new NoDeviceFoundException($\"Failed to find a suitable device for target {target.AsString()}\");\n }\n\n return new DevicePair(device, companionDevice);\n }", + "start_line": 41, + "end_line": 112, + "start_byte": 1403, + "end_byte": 4554 + }, + { + "name": "FindDevice", + "code": "Task FindDevice(\n TestTargetOs target,\n string? deviceName,\n ILog log,\n bool includeWirelessDevices = true,\n bool pairedDevicesOnly = true,\n CancellationToken cancellationToken = default);", + "start_line": 19, + "end_line": 25, + "start_byte": 619, + "end_byte": 861 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/Darwin.cs": [ + { + "name": "sysctl", + "code": "[DllImport(\"libc\")]\n private static extern unsafe int sysctl(\n int* name,\n uint namelen,\n byte* oldp,\n uint* oldlenp,\n IntPtr newp,\n uint newlen);", + "start_line": 65, + "end_line": 72, + "start_byte": 2290, + "end_byte": 2481 + }, + { + "name": "GetVersion", + "code": "public static string GetVersion()\n {\n var kernelRelease = GetKernelRelease();\n if (!Version.TryParse(kernelRelease, out Version? version) || version.Major < 5)\n {\n // 10.0 covers all versions prior to Darwin 5\n // Similarly, if the version is not a valid version number, but we have still detected that it is Darwin, we just assume\n // it is OS X 10.0\n return \"10.0\";\n }\n else\n {\n // Mac OS X 10.1 mapped to Darwin 5.x, and the mapping continues that way\n // So just subtract 4 from the Darwin version.\n // https://en.wikipedia.org/wiki/Darwin_%28operating_system%29\n return $\"10.{version.Major - 4}\";\n }\n }", + "start_line": 46, + "end_line": 63, + "start_byte": 1534, + "end_byte": 2284 + }, + { + "name": "GetKernelRelease", + "code": "private static string GetKernelRelease()\n {\n unsafe\n {\n const uint BUFFER_LENGTH = 32;\n\n var name = stackalloc int[2];\n name[0] = CTL_KERN;\n name[1] = KERN_OSRELEASE;\n\n var buf = stackalloc byte[(int)BUFFER_LENGTH];\n var len = stackalloc uint[1];\n *len = BUFFER_LENGTH;\n\n try\n {\n // If the buffer isn't big enough, it seems sysctl still returns 0 and just sets len to the\n // necessary buffer size. This appears to be contrary to the man page, but it's easy to detect\n // by simply checking len against the buffer length.\n if (sysctl(name, 2, buf, len, IntPtr.Zero, 0) == 0 && *len < BUFFER_LENGTH)\n {\n return Marshal.PtrToStringAnsi((IntPtr)buf, (int)*len);\n }\n }\n catch (Exception ex)\n {\n throw new PlatformNotSupportedException(\"Error reading Darwin Kernel Version\", ex);\n }\n throw new PlatformNotSupportedException(\"Unknown error reading Darwin Kernel Version\");\n }\n }", + "start_line": 14, + "end_line": 44, + "start_byte": 351, + "end_byte": 1528 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/CommunicationChannel.cs": [], + "src/Microsoft.DotNet.XHarness.Apple/CrashSnapshotReporterFactory.cs": [ + { + "name": "Create", + "code": "public ICrashSnapshotReporter Create(ILog log, ILogs logs, bool isDevice, string? deviceName) =>\n new CrashSnapshotReporter(_processManager, log, logs, isDevice, deviceName);", + "start_line": 27, + "end_line": 28, + "start_byte": 943, + "end_byte": 1124 + }, + { + "name": "Create", + "code": "ICrashSnapshotReporter Create(ILog log, ILogs logs, bool isDevice, string? deviceName);", + "start_line": 15, + "end_line": 15, + "start_byte": 517, + "end_byte": 604 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/TestTarget.cs": [ + { + "name": "IsWatchOSTarget", + "code": "public static bool IsWatchOSTarget(this TestTarget target) => target switch\n {\n TestTarget.Simulator_watchOS => true,\n TestTarget.Device_watchOS => true,\n _ => false,\n };", + "start_line": 84, + "end_line": 89, + "start_byte": 2204, + "end_byte": 2401 + }, + { + "name": "IsSimulator", + "code": "public static bool IsSimulator(this TestTarget target) => target switch\n {\n TestTarget.Simulator_iOS64 => true,\n TestTarget.Simulator_tvOS => true,\n TestTarget.Simulator_watchOS => true,\n TestTarget.Simulator_xrOS => true,\n\n TestTarget.Device_iOS => false,\n TestTarget.Device_tvOS => false,\n TestTarget.Device_watchOS => false,\n TestTarget.Device_xrOS => false,\n\n TestTarget.MacCatalyst => true,\n\n _ => throw new ArgumentOutOfRangeException($\"Unknown target: {target}\"),\n };", + "start_line": 67, + "end_line": 82, + "start_byte": 1648, + "end_byte": 2198 + }, + { + "name": "ToRunMode", + "code": "public static RunMode ToRunMode(this TestTarget target) => target switch\n {\n TestTarget.Simulator_iOS64 => RunMode.iOS,\n TestTarget.Simulator_tvOS => RunMode.TvOS,\n TestTarget.Simulator_watchOS => RunMode.WatchOS,\n TestTarget.Simulator_xrOS => RunMode.xrOS,\n\n TestTarget.Device_iOS => RunMode.iOS,\n TestTarget.Device_tvOS => RunMode.TvOS,\n TestTarget.Device_watchOS => RunMode.WatchOS,\n TestTarget.Device_xrOS => RunMode.xrOS,\n\n TestTarget.MacCatalyst => RunMode.MacOS,\n\n _ => throw new ArgumentOutOfRangeException($\"Unknown target: {target}\"),\n };", + "start_line": 50, + "end_line": 65, + "start_byte": 1018, + "end_byte": 1642 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/TestReporter.cs": [ + { + "name": "Dispose", + "code": "public void Dispose()\n {\n _crashLogs.Dispose();\n GC.SuppressFinalize(this);\n }", + "start_line": 719, + "end_line": 723, + "start_byte": 27531, + "end_byte": 27629 + }, + { + "name": "ParseResult", + "code": "public async Task<(TestExecutingResult ExecutingResult, string? ResultMessage)> ParseResult()\n {\n (TestExecutingResult ExecutingResult, string? ResultMessage) result = (ExecutingResult: TestExecutingResult.Finished, ResultMessage: null);\n var crashed = false;\n if (File.Exists(_listener.TestLog.FullPath))\n {\n WrenchLog.WriteLine(\"AddFile: {0}\", _listener.TestLog.FullPath);\n (Success, crashed, result.ResultMessage) = await TestsSucceeded(_appInfo, _listener.TestLog.FullPath, _timedout);\n }\n else if (_timedout)\n {\n WrenchLog.WriteLine(\"AddSummary: {0} never launched
\", _runMode);\n _mainLog.WriteLine(\"Test run never launched\");\n result.ResultMessage = \"Test runner never started\";\n Success = false;\n }\n else if (_launchFailure)\n {\n WrenchLog.WriteLine(\"AddSummary: {0} failed to launch
\", _runMode);\n _mainLog.WriteLine(\"Test run failed to launch\");\n result.ResultMessage = \"Test runner failed to launch\";\n Success = false;\n }\n else\n {\n WrenchLog.WriteLine(\"AddSummary: {0} crashed at startup (no log)
\", _runMode);\n _mainLog.WriteLine(\"Test run started but crashed and no test results were reported\");\n result.ResultMessage = \"No test log file was produced\";\n crashed = true;\n Success = false;\n }\n\n if (!Success.HasValue)\n {\n Success = false;\n }\n\n var crashLogWaitTime = 0;\n if (!Success.Value)\n {\n crashLogWaitTime = 5;\n }\n\n if (crashed)\n {\n crashLogWaitTime = 30;\n }\n\n await _crashReporter.EndCaptureAsync(TimeSpan.FromSeconds(crashLogWaitTime));\n\n if (_timedout)\n {\n if (TestExecutionStarted)\n {\n result.ExecutingResult = TestExecutingResult.TimedOut;\n }\n else\n {\n result.ExecutingResult = TestExecutingResult.LaunchTimedOut;\n }\n }\n else if (_launchFailure)\n {\n result.ExecutingResult = TestExecutingResult.LaunchFailure;\n }\n else if (crashed)\n {\n result.ExecutingResult = TestExecutingResult.Crashed;\n }\n else if (Success.Value)\n {\n result.ExecutingResult = TestExecutingResult.Succeeded;\n }\n else\n {\n result.ExecutingResult = TestExecutingResult.Failed;\n }\n\n // Check crash reports to see if any of them explains why the test run crashed.\n if (!Success.Value)\n {\n int pid = -1;\n string? crashReason = null;\n foreach (var crashLog in _crashLogs)\n {\n try\n {\n _logs.Add(crashLog);\n\n if (pid == -1)\n {\n // Find the pid\n pid = await GetPidFromMainLog();\n }\n\n GetCrashReason(pid, crashLog, out crashReason);\n if (crashReason != null)\n {\n break;\n }\n }\n catch (Exception e)\n {\n var message = string.Format(\"Failed to process crash report '{1}': {0}\", e.Message, crashLog.Description);\n _mainLog.WriteLine(message);\n _exceptionLogger?.Invoke(2, message);\n }\n }\n\n if (!string.IsNullOrEmpty(crashReason))\n {\n if (crashReason == \"per-process-limit\")\n {\n result.ResultMessage = \"Killed due to using too much memory (per-process-limit).\";\n }\n else\n {\n result.ResultMessage = $\"Killed by the OS ({crashReason})\";\n }\n }\n else if (_launchFailure)\n {\n // same as with a crash\n result.ResultMessage = $\"Launch failure\";\n }\n\n await GenerateXmlFailures(result.ResultMessage, crashed, crashReason);\n }\n\n return result;\n }", + "start_line": 587, + "end_line": 717, + "start_byte": 23145, + "end_byte": 27525 + }, + { + "name": "GenerateXmlFailures", + "code": "private async Task GenerateXmlFailures(string failure, bool crashed, string? crashReason)\n {\n if (!ResultsUseXml) // nothing to do\n {\n return;\n }\n\n if (!string.IsNullOrEmpty(crashReason))\n {\n _resultParser.GenerateFailure(\n _logs,\n \"crash\",\n _appInfo.AppName,\n _appInfo.Variation,\n $\"App Crash {_appInfo.AppName} {_appInfo.Variation}\",\n $\"App crashed: {failure}\",\n _mainLog.FullPath,\n _xmlJargon);\n\n return;\n }\n\n if (_launchFailure)\n {\n _resultParser.GenerateFailure(\n _logs,\n \"launch\",\n _appInfo.AppName,\n _appInfo.Variation,\n $\"App Launch {_appInfo.AppName} {_appInfo.Variation} on {_deviceName}\",\n $\"{failure} on {_deviceName}\",\n _mainLog.FullPath,\n _xmlJargon);\n\n return;\n }\n\n if (!_isSimulatorTest && crashed && string.IsNullOrEmpty(crashReason))\n {\n // this happens more that what we would like on devices, the main reason most of the time is that we have had netwoking problems and the\n // tcp connection could not be stablished. We are going to report it as an error since we have not parsed the logs, evne when the app might have\n // not crashed. We need to check the main_log to see if we do have an tcp issue or not\n if (await TcpConnectionFailed())\n {\n _resultParser.GenerateFailure(\n _logs,\n \"tcp-connection\",\n _appInfo.AppName,\n _appInfo.Variation,\n $\"TcpConnection on {_deviceName}\",\n $\"Device {_deviceName} could not reach the host over tcp.\",\n _mainLog.FullPath,\n _xmlJargon);\n }\n }\n else if (_timedout)\n {\n _resultParser.GenerateFailure(\n _logs,\n \"timeout\",\n _appInfo.AppName,\n _appInfo.Variation,\n $\"App Timeout {_appInfo.AppName} {_appInfo.Variation} on bot {_deviceName}\",\n $\"{_appInfo.AppName} {_appInfo.Variation} Test run timed out after {_timeout.TotalMinutes} minute(s) on bot {_deviceName}.\",\n _mainLog.FullPath,\n _xmlJargon);\n }\n }", + "start_line": 518, + "end_line": 585, + "start_byte": 20610, + "end_byte": 23139 + }, + { + "name": "TestsSucceeded", + "code": "private async Task<(bool Succeeded, bool Crashed, string ResultLine)> TestsSucceeded(AppBundleInformation appInfo, string test_log_path, bool timed_out)\n {\n var (resultLine, failed, crashed) = await ParseResultFile(appInfo, test_log_path, timed_out);\n // read the parsed logs in a human readable way\n if (resultLine != null)\n {\n var tests_run = resultLine.Replace(\"Tests run: \", \"\");\n if (failed)\n {\n WrenchLog.WriteLine(\"AddSummary: {0} failed: {1}
\", _runMode, tests_run);\n _mainLog.WriteLine(\"Test run failed\");\n return (false, crashed, resultLine);\n }\n else\n {\n WrenchLog.WriteLine(\"AddSummary: {0} succeeded: {1}
\", _runMode, tests_run);\n _mainLog.WriteLine(\"Test run succeeded\");\n return (true, crashed, resultLine);\n }\n }\n else if (timed_out)\n {\n WrenchLog.WriteLine(\"AddSummary: {0} timed out
\", _runMode);\n _mainLog.WriteLine(\"Test run timed out\");\n return (false, false, \"Test run timed out\");\n }\n else\n {\n WrenchLog.WriteLine(\"AddSummary: {0} crashed
\", _runMode);\n _mainLog.WriteLine(\"Test run crashed\");\n return (false, true, \"Test run crashed\");\n }\n }", + "start_line": 481, + "end_line": 513, + "start_byte": 19024, + "end_byte": 20456 + }, + { + "name": "ParseResultFile", + "code": "private async Task<(string? resultLine, bool failed, bool crashed)> ParseResultFile(AppBundleInformation appInfo, string test_log_path, bool timed_out)\n {\n (string? resultLine, bool failed, bool crashed) parseResult = (null, false, false);\n if (!File.Exists(test_log_path))\n {\n parseResult.crashed = true; // if we do not have a log file, the test crashes\n return parseResult;\n }\n // parsing the result is different if we are in jenkins or not.\n // When in Jenkins, Touch.Unit produces an xml file instead of a console log (so that we can get better test reporting).\n // However, for our own reporting, we still want the console-based log. This log is embedded inside the xml produced\n // by Touch.Unit, so we need to extract it and write it to disk. We also need to re-save the xml output, since Touch.Unit\n // wraps the NUnit xml output with additional information, which we need to unwrap so that Jenkins understands it.\n //\n // On the other hand, the nunit and xunit do not have that data and have to be parsed.\n //\n // This if statement has a small trick, we found out that internet sharing in some of the bots (VSTS) does not work, in\n // that case, we cannot do a TCP connection to xharness to get the log, this is a problem since if we did not get the xml\n // from the TCP connection, we are going to fail when trying to read it and not parse it. Therefore, we are not only\n // going to check if we are in CI, but also if the listener_log is valid.\n var path = Path.ChangeExtension(test_log_path, \"xml\");\n if (path == test_log_path)\n {\n path = Path.Combine(Path.GetDirectoryName(path)!, Path.GetFileNameWithoutExtension(path) + \"-clean.xml\");\n }\n\n _resultParser.CleanXml(test_log_path, path);\n\n if (ResultsUseXml && _resultParser.IsValidXml(path, out var xmlType))\n {\n try\n {\n var newFilename = _resultParser.GetXmlFilePath(path, xmlType);\n\n // at this point, we have the test results, but we want to be able to have attachments in vsts, so if the format is\n // the right one (NUnitV3) add the nodes. ATM only TouchUnit uses V3.\n var testRunName = $\"{appInfo.AppName} {appInfo.Variation}\";\n if (xmlType == XmlResultJargon.NUnitV3)\n {\n var logFiles = new List();\n // add our logs AND the logs of the previous task, which is the build task\n logFiles.AddRange(Directory.GetFiles(_crashLogs.Directory));\n if (_additionalLogsDirectory != null) // when using the run command, we do not have a build task, ergo, there are no logs to add.\n {\n logFiles.AddRange(Directory.GetFiles(_additionalLogsDirectory));\n }\n // add the attachments and write in the new filename\n // add a final prefix to the file name to make sure that the VSTS test uploaded just pick\n // the final version, else we will upload tests more than once\n newFilename = XmlResultParser.GetVSTSFilename(newFilename);\n _resultParser.UpdateMissingData(path, newFilename, testRunName, logFiles);\n }\n else\n {\n // rename the path to the correct value\n File.Move(path, newFilename);\n }\n path = newFilename;\n\n if (_generateHtml)\n {\n // write the human readable results in a tmp file, which we later use to step on the logs\n var humanReadableLog = _logs.CreateFile(Path.GetFileNameWithoutExtension(test_log_path) + \".log\", LogType.NUnitResult);\n (parseResult.resultLine, parseResult.failed) = _resultParser.ParseResults(path, xmlType, humanReadableLog);\n }\n else\n {\n (parseResult.resultLine, parseResult.failed) = _resultParser.ParseResults(path, xmlType, (StreamWriter?)null);\n }\n\n // we do not longer need the tmp file\n _logs.AddFile(path, LogType.XmlLog.ToString());\n return parseResult;\n\n }\n catch (Exception e)\n {\n _mainLog.WriteLine(\"Could not parse xml result file: {0}\", e);\n // print file for better debugging\n _mainLog.WriteLine(\"File data is:\");\n _mainLog.WriteLine(new string('#', 10));\n using (var stream = new StreamReader(path))\n {\n string? line;\n while ((line = await stream.ReadLineAsync()) != null)\n {\n _mainLog.WriteLine(line);\n }\n }\n _mainLog.WriteLine(new string('#', 10));\n _mainLog.WriteLine(\"End of xml results.\");\n if (timed_out)\n {\n WrenchLog.WriteLine($\"AddSummary: {_runMode} timed out
\");\n return parseResult;\n }\n else\n {\n WrenchLog.WriteLine($\"AddSummary: {_runMode} crashed
\");\n _mainLog.WriteLine(\"Test run crashed\");\n parseResult.crashed = true;\n return parseResult;\n }\n }\n\n }\n // delete not needed copy\n File.Delete(path);\n\n // not the most efficient way but this just happens when we run\n // the tests locally and we usually do not run all tests, we are\n // more interested to be efficent on the bots\n (parseResult.resultLine, parseResult.failed) = await GetResultLine(test_log_path);\n return parseResult;\n }", + "start_line": 365, + "end_line": 479, + "start_byte": 12969, + "end_byte": 19018 + }, + { + "name": "GetResultLine", + "code": "private async Task<(string? ResultLine, bool Failed)> GetResultLine(string logPath)\n {\n string? resultLine = null;\n bool failed = false;\n using var reader = new StreamReader(logPath);\n string? line = null;\n while ((line = await reader.ReadLineAsync()) != null)\n {\n if (line.Contains(\"Tests run:\"))\n {\n Console.WriteLine(line);\n resultLine = line;\n break;\n }\n else if (line.Contains(\"[FAIL]\"))\n {\n Console.WriteLine(line);\n failed = true;\n }\n }\n return (ResultLine: resultLine, Failed: failed);\n }", + "start_line": 342, + "end_line": 363, + "start_byte": 12264, + "end_byte": 12963 + }, + { + "name": "CollectDeviceResult", + "code": "public async Task CollectDeviceResult(ProcessExecutionResult runResult)\n {\n _isSimulatorTest = false;\n await CollectResult(runResult);\n }", + "start_line": 336, + "end_line": 340, + "start_byte": 12101, + "end_byte": 12258 + }, + { + "name": "CollectSimulatorResult", + "code": "public async Task CollectSimulatorResult(ProcessExecutionResult runResult)\n {\n _isSimulatorTest = true;\n await CollectResult(runResult);\n\n if (Success != null && !Success.Value)\n {\n var pid = await GetPidFromRunLog();\n if (pid > 0)\n {\n await KillAppProcess(pid, _cancellationTokenSource);\n }\n else\n {\n _mainLog.WriteLine(\"Could not find pid in mtouch output.\");\n }\n }\n }", + "start_line": 317, + "end_line": 334, + "start_byte": 11577, + "end_byte": 12095 + }, + { + "name": "LaunchCallback", + "code": "public void LaunchCallback(Task launchResult)\n {\n if (launchResult.IsFaulted)\n {\n _mainLog.WriteLine($\"Test execution failed: {launchResult.Exception}\");\n return;\n }\n\n if (launchResult.IsCanceled)\n {\n _mainLog.WriteLine(\"Test execution was cancelled\");\n return;\n }\n\n if (launchResult.Result)\n {\n _mainLog.WriteLine(\"Test execution started\");\n return;\n }\n\n _cancellationTokenSource.Cancel();\n _timedout = true;\n\n if (TestExecutionStarted)\n {\n _mainLog.WriteLine($\"Test execution timed out after {_timeoutWatch.Elapsed.TotalMinutes:0.##} minutes\");\n return;\n }\n\n _mainLog.WriteLine($\"Test failed to start in {_timeoutWatch.Elapsed.TotalMinutes:0.##} minutes\");\n }", + "start_line": 285, + "end_line": 315, + "start_byte": 10705, + "end_byte": 11571 + }, + { + "name": "CollectResult", + "code": "private async Task CollectResult(ProcessExecutionResult runResult)\n {\n if (!_waitedForExit && !runResult.TimedOut)\n {\n // mlaunch couldn't wait for exit for some reason. Let's assume the app exits when the test listener completes.\n _mainLog.WriteLine(\"Waiting for listener to complete, since mlaunch won't tell.\");\n if (!await _listener.CompletionTask.TimeoutAfter(_timeout - _timeoutWatch.Elapsed))\n {\n runResult.TimedOut = true;\n }\n }\n\n if (runResult.TimedOut)\n {\n _timedout = true;\n Success = false;\n _mainLog.WriteLine(TimeoutMessage, _timeout.TotalMinutes);\n }\n else if (runResult.Succeeded)\n {\n _mainLog.WriteLine(CompletionMessage);\n Success = true;\n }\n else\n {\n _mainLog.WriteLine(FailureMessage);\n Success = false;\n }\n }", + "start_line": 255, + "end_line": 283, + "start_byte": 9733, + "end_byte": 10699 + }, + { + "name": "KillAppProcess", + "code": "private Task KillAppProcess(int pid, CancellationTokenSource cancellationSource)\n {\n var launchTimedout = cancellationSource.IsCancellationRequested;\n var timeoutType = launchTimedout ? \"Launch\" : \"Completion\";\n _mainLog.WriteLine($\"{timeoutType} timed out after {_timeoutWatch.Elapsed.TotalSeconds} seconds\");\n return _processManager.KillTreeAsync(pid, _mainLog, true);\n }", + "start_line": 247, + "end_line": 253, + "start_byte": 9320, + "end_byte": 9727 + }, + { + "name": "TcpConnectionFailed", + "code": "private async Task TcpConnectionFailed()\n {\n using var reader = new StreamReader(_mainLog.FullPath);\n string? line;\n while ((line = await reader.ReadLineAsync()) != null)\n {\n if (line.Contains(\"Couldn't establish a TCP connection with any of the hostnames\"))\n {\n return true;\n }\n }\n return false;\n }", + "start_line": 233, + "end_line": 245, + "start_byte": 8913, + "end_byte": 9314 + }, + { + "name": "GetCrashReason", + "code": "private void GetCrashReason(int pid, IReadableLog crashLog, out string? crashReason)\n {\n crashReason = null;\n using var crashReader = crashLog.GetReader(); // dispose when we leave the method\n var text = crashReader.ReadToEnd();\n\n var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(text), new XmlDictionaryReaderQuotas());\n var doc = new XmlDocument();\n doc.Load(reader);\n foreach (XmlNode? node in doc.SelectNodes($\"/root/processes/item[pid = '\" + pid + \"']\"))\n {\n Console.WriteLine(node?.InnerXml);\n Console.WriteLine(node?.SelectSingleNode(\"reason\")?.InnerText);\n crashReason = node?.SelectSingleNode(\"reason\")?.InnerText;\n }\n }", + "start_line": 213, + "end_line": 228, + "start_byte": 8051, + "end_byte": 8810 + }, + { + "name": "GetPidFromMainLog", + "code": "private async Task GetPidFromMainLog()\n {\n int pid = -1;\n using var log_reader = _mainLog.GetReader(); // dispose when we leave the method, which is what we want\n string? line;\n while ((line = await log_reader.ReadLineAsync()) != null)\n {\n const string str = \"was launched with pid '\";\n var idx = line.IndexOf(str, StringComparison.Ordinal);\n if (idx > 0)\n {\n idx += str.Length;\n var next_idx = line.IndexOf('\\'', idx);\n if (next_idx > idx)\n {\n int.TryParse(line.Substring(idx, next_idx - idx), out pid);\n }\n }\n if (pid != -1)\n {\n return pid;\n }\n }\n return pid;\n }", + "start_line": 184, + "end_line": 208, + "start_byte": 7134, + "end_byte": 7955 + }, + { + "name": "GetPidFromRunLog", + "code": "private async Task GetPidFromRunLog()\n {\n int pid = -1;\n\n using var reader = _runLog.GetReader(); // diposed at the end of the method, which is what we want\n if (reader.Peek() == -1)\n {\n // Empty file! If the app never connected to our listener, it probably never launched\n if (!_listener.ConnectedTask.IsCompleted || !_listener.ConnectedTask.Result)\n {\n _launchFailure = true;\n }\n }\n else\n {\n while (!reader.EndOfStream)\n {\n var line = await reader.ReadLineAsync();\n\n if (line == null)\n {\n continue;\n }\n\n if (line.StartsWith(\"Application launched. PID = \", StringComparison.Ordinal))\n {\n var pidstr = line.Substring(\"Application launched. PID = \".Length);\n if (!int.TryParse(pidstr, out pid))\n {\n _mainLog.WriteLine(\"Could not parse pid: {0}\", pidstr);\n }\n }\n else if (line.Contains(\"Xamarin.Hosting: Launched \") && line.Contains(\" with pid \"))\n {\n var pidstr = line.Substring(line.LastIndexOf(' '));\n if (!int.TryParse(pidstr, out pid))\n {\n _mainLog.WriteLine(\"Could not parse pid: {0}\", pidstr);\n }\n }\n else if (line.Contains(\"error MT1008\"))\n {\n _launchFailure = true;\n }\n }\n }\n\n return pid;\n }", + "start_line": 131, + "end_line": 179, + "start_byte": 5354, + "end_byte": 7049 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/CrashSnapshotReporter.cs": [ + { + "name": "CreateCrashReportsSnapshotAsync", + "code": "private async Task> CreateCrashReportsSnapshotAsync()\n {\n var crashes = new HashSet();\n\n if (!_isDevice)\n {\n var dir = Path.Combine(Environment.GetEnvironmentVariable(\"HOME\"), \"Library\", \"Logs\", \"DiagnosticReports\");\n if (Directory.Exists(dir))\n {\n crashes.UnionWith(Directory.EnumerateFiles(dir));\n }\n }\n else\n {\n var tempFile = _tempFileProvider();\n try\n {\n var args = new MlaunchArguments(new ListCrashReportsArgument(tempFile));\n\n if (!string.IsNullOrEmpty(_deviceName))\n {\n args.Add(new DeviceNameArgument(_deviceName));\n }\n\n var result = await _processManager.ExecuteCommandAsync(args, _log, TimeSpan.FromMinutes(1));\n if (result.Succeeded)\n {\n crashes.UnionWith(File.ReadAllLines(tempFile));\n }\n }\n finally\n {\n File.Delete(tempFile);\n }\n }\n\n return crashes;\n }", + "start_line": 202, + "end_line": 239, + "start_byte": 7699, + "end_byte": 8861 + }, + { + "name": "GetSymbolicateCrashReportAsync", + "code": "private async Task GetSymbolicateCrashReportAsync(IFileBackedLog report)\n {\n if (_symbolicateCrashPath == null)\n {\n _log.WriteLine(\"Can't symbolicate {0} because the symbolicatecrash script {1} does not exist\", report.FullPath, _symbolicateCrashPath);\n return report;\n }\n\n var name = Path.GetFileName(report.FullPath);\n var symbolicated = _logs.Create(Path.ChangeExtension(name, \".symbolicated.log\"), $\"Symbolicated crash report: {name}\", timestamp: false);\n var environment = new Dictionary { { \"DEVELOPER_DIR\", Path.Combine(_processManager.XcodeRoot, \"Contents\", \"Developer\") } };\n var result = await _processManager.ExecuteCommandAsync(_symbolicateCrashPath, new[] { report.FullPath }, symbolicated, TimeSpan.FromMinutes(1), environment);\n if (result.Succeeded)\n {\n _log.WriteLine(\"Symbolicated {0} successfully.\", report.FullPath);\n return symbolicated;\n }\n else\n {\n _log.WriteLine(\"Failed to symbolicate {0}.\", report.FullPath);\n return report;\n }\n }", + "start_line": 178, + "end_line": 200, + "start_byte": 6543, + "end_byte": 7693 + }, + { + "name": "ProcessCrash", + "code": "private async Task ProcessCrash(string crashFile)\n {\n var name = Path.GetFileName(crashFile);\n var crashReportFile = _logs.Create(name, $\"Crash report: {name}\", timestamp: false);\n var args = new MlaunchArguments(\n new DownloadCrashReportArgument(crashFile),\n new DownloadCrashReportToArgument(crashReportFile.FullPath));\n\n if (!string.IsNullOrEmpty(_deviceName))\n {\n args.Add(new DeviceNameArgument(_deviceName));\n }\n\n var result = await _processManager.ExecuteCommandAsync(args, _log, TimeSpan.FromMinutes(1));\n\n if (result.Succeeded)\n {\n _log.WriteLine(\"Downloaded crash report {0} to {1}\", crashFile, crashReportFile.FullPath);\n return await GetSymbolicateCrashReportAsync(crashReportFile);\n }\n else\n {\n _log.WriteLine(\"Could not download crash report {0}\", crashFile);\n return null;\n }\n }", + "start_line": 151, + "end_line": 176, + "start_byte": 5554, + "end_byte": 6537 + }, + { + "name": "EndCaptureAsync", + "code": "public async Task EndCaptureAsync(TimeSpan timeout)\n {\n if (_initialCrashes == null)\n {\n throw new InvalidOperationException(\"CrashSnapshotReport capturing was ended without being started first!\");\n }\n\n _log.WriteLine($\"No crash reports, waiting {(int)timeout.TotalSeconds} seconds for the crash report service...\");\n\n // Check for crash reports\n var stopwatch = Stopwatch.StartNew();\n\n do\n {\n var newCrashFiles = await CreateCrashReportsSnapshotAsync();\n newCrashFiles.ExceptWith(_initialCrashes);\n\n if (newCrashFiles.Count == 0)\n {\n if (stopwatch.Elapsed.TotalSeconds > timeout.TotalSeconds)\n {\n break;\n }\n else\n {\n await Task.Delay(TimeSpan.FromSeconds(1));\n }\n\n continue;\n }\n\n _log.WriteLine(\"Found {0} new crash report(s)\", newCrashFiles.Count);\n\n IEnumerable crashReports;\n if (!_isDevice)\n {\n crashReports = new List(newCrashFiles.Count);\n foreach (var path in newCrashFiles)\n {\n // It can happen that the crash log is still being written to so we have to retry\n int retry = 1;\n while (true)\n {\n try\n {\n var fileName = Path.GetFileName(path);\n _log.WriteLine($\" - Adding {path}\");\n _logs.AddFile(path, $\"Crash report: {fileName}\");\n _log.WriteLine($\" Successfully copied {fileName}\");\n break;\n }\n catch (Exception e)\n {\n _log.WriteLine($\" Attempt {retry} to copy a crash report failed: {e.Message}\");\n }\n\n if (retry == 3)\n {\n _log.WriteLine($\" Failed to copy a crash report after {retry} retries\");\n break;\n }\n\n ++retry;\n await Task.Delay(TimeSpan.FromSeconds(2 * retry));\n }\n }\n }\n else\n {\n // Download crash reports from the device. We put them in the project directory so that they're automatically deleted on wrench\n // (if we put them in /tmp, they'd never be deleted).\n crashReports = newCrashFiles\n .Select(async crash => await ProcessCrash(crash))\n .Select(t => t.Result)\n .Where(c => c != null);\n }\n\n foreach (var cp in crashReports)\n {\n WrenchLog.WriteLine(\"AddFile: {0}\", cp.FullPath);\n _log.WriteLine(\" {0}\", cp.FullPath);\n }\n\n break;\n\n } while (true);\n }", + "start_line": 63, + "end_line": 149, + "start_byte": 2363, + "end_byte": 5548 + }, + { + "name": "StartCaptureAsync", + "code": "public async Task StartCaptureAsync() => _initialCrashes = await CreateCrashReportsSnapshotAsync();", + "start_line": 61, + "end_line": 61, + "start_byte": 2258, + "end_byte": 2357 + }, + { + "name": "StartCaptureAsync", + "code": "Task StartCaptureAsync();", + "start_line": 21, + "end_line": 21, + "start_byte": 665, + "end_byte": 690 + }, + { + "name": "EndCaptureAsync", + "code": "Task EndCaptureAsync(TimeSpan timeout);", + "start_line": 20, + "end_line": 20, + "start_byte": 621, + "end_byte": 660 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/ITestReporter.cs": [ + { + "name": "ParseResult", + "code": "Task<(TestExecutingResult ExecutingResult, string ResultMessage)> ParseResult();", + "start_line": 25, + "end_line": 25, + "start_byte": 867, + "end_byte": 947 + }, + { + "name": "CollectDeviceResult", + "code": "Task CollectDeviceResult(ProcessExecutionResult runResult);", + "start_line": 24, + "end_line": 24, + "start_byte": 803, + "end_byte": 862 + }, + { + "name": "CollectSimulatorResult", + "code": "Task CollectSimulatorResult(ProcessExecutionResult runResult);", + "start_line": 23, + "end_line": 23, + "start_byte": 736, + "end_byte": 798 + }, + { + "name": "LaunchCallback", + "code": "void LaunchCallback(Task launchResult);", + "start_line": 22, + "end_line": 22, + "start_byte": 686, + "end_byte": 731 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/ResultFileHandler.cs": [ + { + "name": "CopyResultsAsync", + "code": "public async Task CopyResultsAsync(\n RunMode runMode,\n bool isSimulator,\n string osVersion,\n string udid,\n string bundleIdentifier,\n string hostDestinationPath,\n CancellationToken token)\n {\n // This file path is set in iOSApplicationEntryPointBase\n string sourcePath = runMode == RunMode.iOS\n ? \"/Documents/test-results.xml\"\n : \"/Library/Caches/Documents/test-results.xml\";\n\n if (IsVersionSupported(osVersion, isSimulator))\n {\n string cmd;\n if (isSimulator)\n {\n cmd = $\"cp \\\"$(xcrun simctl get_app_container {udid} {bundleIdentifier} data){sourcePath}\\\" \\\"{hostDestinationPath}\\\"\";\n }\n else\n {\n cmd = $\"xcrun devicectl device copy from --device {udid} --source {sourcePath} --destination {hostDestinationPath} --user mobile --domain-type appDataContainer --domain-identifier {bundleIdentifier}\";\n }\n\n await _processManager.ExecuteCommandAsync(\n \"/bin/bash\",\n new[] { \"-c\", cmd },\n _mainLog,\n _mainLog,\n _mainLog,\n TimeSpan.FromMinutes(1),\n null,\n cancellationToken: token);\n\n if (!File.Exists(hostDestinationPath))\n {\n _mainLog.WriteLine($\"Failed to copy results file from {(isSimulator ? \"simulator\" : \"device\")}. Expected at: {hostDestinationPath}\");\n return false;\n }\n }\n\n return true;\n }", + "start_line": 64, + "end_line": 108, + "start_byte": 1918, + "end_byte": 3535 + }, + { + "name": "IsVersionSupported", + "code": "public bool IsVersionSupported(string osVersion, bool isSimulator)\n {\n if (isSimulator)\n {\n // Version format contains string like \"Simulator 18.0\".\n string[] osVersionParts = osVersion.Split(' ', StringSplitOptions.RemoveEmptyEntries);\n if (osVersionParts.Length < 2)\n {\n throw new FormatException(\"Simulator OS version is not in the expected format.\");\n }\n\n if (!Version.TryParse(osVersionParts[1], out Version osVersionParsed))\n {\n throw new FormatException(\"Simulator OS version is not in the expected format.\");\n }\n\n if (osVersionParsed.Major >= 18)\n {\n return true;\n }\n }\n else\n {\n if (!Version.TryParse(osVersion, out Version osVersionParsed))\n {\n throw new FormatException($\"Device OS version is not in the expected format.\");\n }\n\n if (osVersionParsed.Major >= 18)\n {\n return true;\n }\n }\n\n return false;\n }", + "start_line": 27, + "end_line": 62, + "start_byte": 781, + "end_byte": 1912 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/TestReporterFactory.cs": [ + { + "name": "Create", + "code": "public ITestReporter Create(IFileBackedLog mainLog,\n IReadableLog runLog,\n ILogs logs,\n ICrashSnapshotReporter crashReporter,\n ISimpleListener simpleListener,\n IResultParser parser,\n AppBundleInformation appInformation,\n RunMode runMode,\n XmlResultJargon xmlJargon,\n string? device,\n TimeSpan timeout,\n string? additionalLogsDirectory = null,\n ExceptionLogger? exceptionLogger = null,\n bool generateHtml = false) => new TestReporter(_processManager,\n mainLog,\n runLog,\n logs,\n crashReporter,\n simpleListener,\n parser,\n appInformation,\n runMode,\n xmlJargon,\n device,\n timeout,\n additionalLogsDirectory,\n exceptionLogger,\n generateHtml);", + "start_line": 44, + "end_line": 71, + "start_byte": 1450, + "end_byte": 2330 + }, + { + "name": "Create", + "code": "ITestReporter Create(IFileBackedLog mainLog,\n IReadableLog runLog,\n ILogs logs,\n ICrashSnapshotReporter crashSnapshotReporter,\n ISimpleListener simpleListener,\n IResultParser parser,\n AppBundleInformation appInformation,\n RunMode runMode,\n XmlResultJargon xmlJargon,\n string? device,\n TimeSpan timeout,\n string? additionalLogsDirectory = null,\n ExceptionLogger? exceptionLogger = null,\n bool generateHtml = false);", + "start_line": 19, + "end_line": 32, + "start_byte": 633, + "end_byte": 1138 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/SdkVersions.cs": [ + { + "name": "OverrideVersions", + "code": "public static void OverrideVersions(string xcode,\n string osx,\n string iOS,\n string watchOS,\n string tVOS,\n string minOSX,\n string miniOS,\n string minWatchOS,\n string minTVOS,\n string miniOSSimulator,\n string minWatchOSSimulator,\n string minWatchOSCompanionSimulator,\n string minTVOSSimulator,\n string maxiOSSimulator,\n string maxWatchOSSimulator,\n string maxWatchOSCompanionSimulator,\n string maxTVOSSimulator,\n string maxiOSDeploymentTarget,\n string maxWatchDeploymentTarget,\n string maxTVOSDeploymentTarget,\n string minxrOSSimulator = \"1.0\",\n string maxxrOSSimulator = \"1.0\")\n {\n Xcode = xcode;\n OSX = osx;\n SdkVersions.iOS = iOS;\n WatchOS = watchOS;\n TVOS = tVOS;\n MinOSX = minOSX;\n MiniOS = miniOS;\n MinWatchOS = minWatchOS;\n MinTVOS = minTVOS;\n MiniOSSimulator = miniOSSimulator;\n MinWatchOSSimulator = minWatchOSSimulator;\n MinWatchOSCompanionSimulator = minWatchOSCompanionSimulator;\n MinTVOSSimulator = minTVOSSimulator;\n MaxiOSSimulator = maxiOSSimulator;\n MaxWatchOSSimulator = maxWatchOSSimulator;\n MaxWatchOSCompanionSimulator = maxWatchOSCompanionSimulator;\n MaxTVOSSimulator = maxTVOSSimulator;\n MaxiOSDeploymentTarget = maxiOSDeploymentTarget;\n MaxWatchDeploymentTarget = maxWatchDeploymentTarget;\n MaxTVOSDeploymentTarget = maxTVOSDeploymentTarget;\n MinxrOSSimulator = minxrOSSimulator;\n MaxxrOSSimulator = maxxrOSSimulator;\n }", + "start_line": 36, + "end_line": 81, + "start_byte": 1801, + "end_byte": 3452 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/AppBundleInformationParser.cs": [ + { + "name": "Contains", + "code": "private static bool Contains(string haystack, string needle)\n {\n return haystack.IndexOf(needle, StringComparison.InvariantCultureIgnoreCase) > -1;\n }", + "start_line": 202, + "end_line": 205, + "start_byte": 7694, + "end_byte": 7857 + }, + { + "name": "GetPlistProperty", + "code": "private async Task GetPlistProperty(\n string plistPath,\n string propertyName,\n ILog log,\n CancellationToken cancellationToken = default,\n int attempt = 1,\n int maxAttempts = 3)\n {\n var args = new[]\n {\n \"-c\",\n $\"Print {propertyName}\",\n plistPath,\n };\n\n var commandOutput = new MemoryLog { Timestamp = false };\n var result = await _processManager.ExecuteCommandAsync(\n PlistBuddyPath,\n args,\n log,\n commandOutput,\n commandOutput,\n TimeSpan.FromSeconds(10),\n cancellationToken: cancellationToken);\n\n if (!result.Succeeded)\n {\n if (result.TimedOut && attempt < maxAttempts)\n {\n log.WriteLine($\"Attempt to get {propertyName} from {plistPath} timed out, retrying {attempt + 1} out of {maxAttempts}...\");\n return await GetPlistProperty(plistPath, propertyName, log, cancellationToken, attempt + 1, maxAttempts);\n }\n\n throw new Exception($\"Failed to get bundle information: {commandOutput}\");\n }\n\n return commandOutput.ToString().Trim();\n }", + "start_line": 162, + "end_line": 199, + "start_byte": 6348, + "end_byte": 7583 + }, + { + "name": "ParseFromAppBundle", + "code": "public async Task ParseFromAppBundle(string appPackagePath, TestTarget target, ILog log, CancellationToken cancellationToken = default)\n {\n string plistPath;\n\n if (target == TestTarget.MacCatalyst)\n {\n plistPath = Path.Combine(appPackagePath, \"Contents\", \"Info.plist\");\n }\n else\n {\n plistPath = Path.Combine(appPackagePath, \"Info.plist\");\n }\n\n if (!File.Exists(plistPath))\n {\n throw new Exception($\"Failed to find Info.plist inside the app bundle at: '{plistPath}'\");\n }\n\n var appName = await GetPlistProperty(plistPath, PListExtensions.BundleNamePropertyName, log, cancellationToken);\n var bundleIdentifier = await GetPlistProperty(plistPath, PListExtensions.BundleIdentifierPropertyName, log, cancellationToken);\n\n string supports32 = string.Empty;\n\n try\n {\n supports32 = await GetPlistProperty(plistPath, PListExtensions.RequiredDeviceCapabilities, log, cancellationToken);\n }\n catch (Exception e)\n {\n // The property might not be present\n log.WriteLine(\"Property UIRequiredDeviceCapabilities not present in Info.plist, assuming 32-bit is not supported. Error: \" + e.Message);\n }\n\n string? bundleExecutable = null;\n try\n {\n bundleExecutable = await GetPlistProperty(plistPath, PListExtensions.BundleExecutablePropertyName, log, cancellationToken);\n }\n catch (Exception e)\n {\n log.WriteLine(\"Failed to locate the bundle executable property in Info.plist: \" + e.Message);\n }\n\n string launchAppPath = target.ToRunMode() == RunMode.WatchOS\n ? Directory.GetDirectories(Path.Combine(appPackagePath, \"Watch\"), \"*.app\")[0]\n : appPackagePath;\n\n return new AppBundleInformation(\n appName: appName,\n bundleIdentifier: bundleIdentifier,\n appPath: appPackagePath,\n launchAppPath: launchAppPath,\n supports32b: Contains(supports32, Armv7),\n extension: null,\n bundleExecutable: bundleExecutable);\n }", + "start_line": 105, + "end_line": 160, + "start_byte": 4145, + "end_byte": 6342 + }, + { + "name": "ParseFromProject", + "code": "public async Task ParseFromProject(string projectFilePath, TestTarget target, string buildConfiguration)\n {\n var csproj = new XmlDocument();\n csproj.LoadWithoutNetworkAccess(projectFilePath);\n\n string projectDirectory = Path.GetDirectoryName(projectFilePath) ?? throw new DirectoryNotFoundException($\"Cannot find directory of project '{projectFilePath}'\");\n\n string appName = csproj.GetAssemblyName();\n string infoPlistPath = csproj.GetInfoPListInclude() ?? throw new InvalidOperationException(\"Couldn't locate PList include tag\");\n\n var infoPlist = new XmlDocument();\n string plistPath = Path.Combine(projectDirectory, infoPlistPath.Replace('\\\\', Path.DirectorySeparatorChar));\n infoPlist.LoadWithoutNetworkAccess(plistPath);\n\n string bundleIdentifier = infoPlist.GetCFBundleIdentifier();\n string bundleExecutable = infoPlist.GetCFBundleExecutable();\n\n Extension? extension = null;\n string extensionPointIdentifier = infoPlist.GetNSExtensionPointIdentifier();\n if (!string.IsNullOrEmpty(extensionPointIdentifier))\n {\n extension = extensionPointIdentifier.ParseFromNSExtensionPointIdentifier();\n }\n\n var platform = target.IsSimulator() ? \"iPhoneSimulator\" : \"iPhone\";\n\n string? appPath = null;\n if (_appBundleLocator != null)\n {\n appPath = await _appBundleLocator.LocateAppBundle(csproj, projectFilePath, target, buildConfiguration);\n }\n\n appPath ??= csproj.GetOutputPath(platform, buildConfiguration)?.Replace('\\\\', Path.DirectorySeparatorChar);\n\n appPath = Path.Combine(\n projectDirectory,\n appPath ?? string.Empty,\n appName + (extension != null ? \".appex\" : \".app\"));\n\n string? arch = csproj.GetMtouchArch(platform, buildConfiguration);\n\n bool supports32 = arch != null && (Contains(arch, \"ARMv7\") || Contains(arch, \"i386\"));\n\n if (!Directory.Exists(appPath))\n {\n throw new DirectoryNotFoundException($\"The app bundle directory `{appPath}` does not exist\");\n }\n\n string launchAppPath = target.ToRunMode() == RunMode.WatchOS\n ? Directory.GetDirectories(Path.Combine(appPath, \"Watch\"), \"*.app\")[0]\n : appPath;\n\n return new AppBundleInformation(\n appName,\n bundleIdentifier,\n appPath,\n launchAppPath,\n supports32,\n extension,\n bundleExecutable);\n }", + "start_line": 43, + "end_line": 103, + "start_byte": 1595, + "end_byte": 4139 + }, + { + "name": "LocateAppBundle", + "code": "Task LocateAppBundle(XmlDocument projectFile, string projectFilePath, TestTarget target, string buildConfiguration);", + "start_line": 26, + "end_line": 26, + "start_byte": 890, + "end_byte": 1015 + }, + { + "name": "ParseFromAppBundle", + "code": "Task ParseFromAppBundle(string appPackagePath, TestTarget target, ILog log, CancellationToken cancellationToken = default);", + "start_line": 21, + "end_line": 21, + "start_byte": 700, + "end_byte": 845 + }, + { + "name": "ParseFromProject", + "code": "Task ParseFromProject(string projectFilePath, TestTarget target, string buildConfiguration);", + "start_line": 19, + "end_line": 19, + "start_byte": 580, + "end_byte": 694 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/AppBundleInformation.cs": [ + { + "name": "FromBundleId", + "code": "public static AppBundleInformation FromBundleId(string bundleIdentifier) =>\n new(bundleIdentifier, bundleIdentifier, string.Empty, string.Empty, false, bundleExecutable: bundleIdentifier);", + "start_line": 43, + "end_line": 44, + "start_byte": 1513, + "end_byte": 1708 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/IResultParser.cs": [ + { + "name": "GenerateTestReport", + "code": "void GenerateTestReport(TextWriter writer, string resultsPath, XmlResultJargon xmlType);", + "start_line": 84, + "end_line": 84, + "start_byte": 4297, + "end_byte": 4385 + }, + { + "name": "ParseResults", + "code": "(string resultLine, bool failed) ParseResults(string source, XmlResultJargon xmlType, StreamWriter? textWriter = null);", + "start_line": 79, + "end_line": 79, + "start_byte": 4087, + "end_byte": 4206 + }, + { + "name": "ParseResults", + "code": "(string resultLine, bool failed) ParseResults(string source, XmlResultJargon xmlType, string? humanReadableReportDestination = null);", + "start_line": 69, + "end_line": 69, + "start_byte": 3403, + "end_byte": 3536 + }, + { + "name": "GetXmlFilePath", + "code": "string GetXmlFilePath(string path, XmlResultJargon xmlType);", + "start_line": 59, + "end_line": 59, + "start_byte": 2792, + "end_byte": 2852 + }, + { + "name": "CleanXml", + "code": "void CleanXml(string source, string destination);", + "start_line": 51, + "end_line": 51, + "start_byte": 2539, + "end_byte": 2588 + }, + { + "name": "IsValidXml", + "code": "bool IsValidXml(TextReader stream, out XmlResultJargon type);", + "start_line": 44, + "end_line": 44, + "start_byte": 2224, + "end_byte": 2285 + }, + { + "name": "IsValidXml", + "code": "bool IsValidXml(string path, out XmlResultJargon type);", + "start_line": 39, + "end_line": 39, + "start_byte": 2012, + "end_byte": 2067 + }, + { + "name": "UpdateMissingData", + "code": "void UpdateMissingData(string source, string destination, string applicationName, IEnumerable attachments);", + "start_line": 34, + "end_line": 34, + "start_byte": 1740, + "end_byte": 1855 + }, + { + "name": "GenerateFailure", + "code": "void GenerateFailure(ILogs logs, string source, string appName, string variation, string title, string message, TextReader stderrReader, XmlResultJargon jargon);", + "start_line": 29, + "end_line": 29, + "start_byte": 1378, + "end_byte": 1539 + }, + { + "name": "GenerateFailure", + "code": "void GenerateFailure(ILogs logs, string source, string appName, string? variation, string title, string message, string stderrPath, XmlResultJargon jargon);", + "start_line": 23, + "end_line": 23, + "start_byte": 931, + "end_byte": 1087 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/RunMode.cs": [], + "src/Microsoft.DotNet.XHarness.iOS.Shared/TestExecutingResult.cs": [], + "src/Microsoft.DotNet.XHarness.iOS.Shared/IErrorKnowledgeBase.cs": [ + { + "name": "IsKnownTestIssue", + "code": "bool IsKnownTestIssue(IFileBackedLog runLog, [NotNullWhen(true)] out KnownIssue? knownFailureMessage);", + "start_line": 39, + "end_line": 39, + "start_byte": 2080, + "end_byte": 2182 + }, + { + "name": "IsKnownBuildIssue", + "code": "bool IsKnownBuildIssue(IFileBackedLog buildLog, [NotNullWhen(true)] out KnownIssue? knownFailureMessage);", + "start_line": 31, + "end_line": 31, + "start_byte": 1567, + "end_byte": 1672 + }, + { + "name": "IsKnownInstallIssue", + "code": "bool IsKnownInstallIssue(IFileBackedLog installLog, [NotNullWhen(true)] out KnownIssue? knownFailureMessage);", + "start_line": 23, + "end_line": 23, + "start_byte": 1044, + "end_byte": 1153 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Extension.cs": [], + "src/Microsoft.DotNet.XHarness.iOS.Shared/IResultFileHandler.cs": [ + { + "name": "CopyResultsAsync", + "code": "Task CopyResultsAsync(\n RunMode runMode,\n bool isSimulator,\n string osVersion,\n string udid,\n string bundleIdentifier,\n string hostDestinationPath,\n CancellationToken token);", + "start_line": 21, + "end_line": 28, + "start_byte": 707, + "end_byte": 936 + }, + { + "name": "IsVersionSupported", + "code": "bool IsVersionSupported(string osVersion, bool isSimulator);", + "start_line": 16, + "end_line": 16, + "start_byte": 507, + "end_byte": 567 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/XHarnessConsoleLoggerFormatter.cs": [ + { + "name": "GetBackgroundColorEscapeCode", + "code": "private static string GetBackgroundColorEscapeCode(ConsoleColor color) => color switch\n {\n ConsoleColor.Black => \"\\x1B[40m\",\n ConsoleColor.DarkRed => \"\\x1B[41m\",\n ConsoleColor.DarkGreen => \"\\x1B[42m\",\n ConsoleColor.DarkYellow => \"\\x1B[43m\",\n ConsoleColor.DarkBlue => \"\\x1B[44m\",\n ConsoleColor.DarkMagenta => \"\\x1B[45m\",\n ConsoleColor.DarkCyan => \"\\x1B[46m\",\n ConsoleColor.Gray => \"\\x1B[47m\",\n _ => DefaultBackgroundColor // Use default background color\n };", + "start_line": 181, + "end_line": 192, + "start_byte": 6600, + "end_byte": 7125 + }, + { + "name": "GetForegroundColorEscapeCode", + "code": "private static string GetForegroundColorEscapeCode(ConsoleColor color) => color switch\n {\n ConsoleColor.Black => \"\\x1B[30m\",\n ConsoleColor.DarkRed => \"\\x1B[31m\",\n ConsoleColor.DarkGreen => \"\\x1B[32m\",\n ConsoleColor.DarkYellow => \"\\x1B[33m\",\n ConsoleColor.DarkBlue => \"\\x1B[34m\",\n ConsoleColor.DarkMagenta => \"\\x1B[35m\",\n ConsoleColor.DarkCyan => \"\\x1B[36m\",\n ConsoleColor.Gray => \"\\x1B[37m\",\n ConsoleColor.Red => \"\\x1B[1m\\x1B[31m\",\n ConsoleColor.Green => \"\\x1B[1m\\x1B[32m\",\n ConsoleColor.Yellow => \"\\x1B[1m\\x1B[33m\",\n ConsoleColor.Blue => \"\\x1B[1m\\x1B[34m\",\n ConsoleColor.Magenta => \"\\x1B[1m\\x1B[35m\",\n ConsoleColor.Cyan => \"\\x1B[1m\\x1B[36m\",\n ConsoleColor.White => \"\\x1B[1m\\x1B[37m\",\n _ => DefaultForegroundColor // default foreground color\n };", + "start_line": 161, + "end_line": 179, + "start_byte": 5731, + "end_byte": 6594 + }, + { + "name": "WriteColoredMessage", + "code": "private static void WriteColoredMessage(TextWriter textWriter, string message, ConsoleColor? background, ConsoleColor? foreground)\n {\n // Order: backgroundcolor, foregroundcolor, Message, reset foregroundcolor, reset backgroundcolor\n if (background.HasValue)\n {\n textWriter.Write(GetBackgroundColorEscapeCode(background.Value));\n }\n\n if (foreground.HasValue)\n {\n textWriter.Write(GetForegroundColorEscapeCode(foreground.Value));\n }\n\n textWriter.Write(message);\n\n if (foreground.HasValue)\n {\n textWriter.Write(DefaultForegroundColor); // reset to default foreground color\n }\n\n if (background.HasValue)\n {\n textWriter.Write(DefaultBackgroundColor); // reset to the background color\n }\n }", + "start_line": 135, + "end_line": 159, + "start_byte": 4892, + "end_byte": 5725 + }, + { + "name": "GetLogLevelConsoleColors", + "code": "private (ConsoleColor? Foreground, ConsoleColor? Background) GetLogLevelConsoleColors(LogLevel logLevel)\n {\n if (_options.ColorBehavior == LoggerColorBehavior.Disabled)\n {\n return (null, null);\n }\n\n // We must explicitly set the background color if we are setting the foreground color,\n // since just setting one can look bad on the users console.\n return logLevel switch\n {\n LogLevel.Trace => (ConsoleColor.Gray, ConsoleColor.Black),\n LogLevel.Debug => (ConsoleColor.Gray, ConsoleColor.Black),\n LogLevel.Information => (ConsoleColor.DarkGreen, ConsoleColor.Black),\n LogLevel.Warning => (ConsoleColor.Yellow, ConsoleColor.Black),\n LogLevel.Error => (ConsoleColor.Black, ConsoleColor.DarkRed),\n LogLevel.Critical => (ConsoleColor.White, ConsoleColor.DarkRed),\n _ => (null, null)\n };\n }", + "start_line": 114, + "end_line": 133, + "start_byte": 3952, + "end_byte": 4886 + }, + { + "name": "GetLogLevelString", + "code": "private static string GetLogLevelString(LogLevel logLevel) => logLevel switch\n {\n LogLevel.Trace => \"trce\",\n LogLevel.Debug => \"dbug\",\n LogLevel.Information => \"info\",\n LogLevel.Warning => \"warn\",\n LogLevel.Error => \"fail\",\n LogLevel.Critical => \"crit\",\n _ => throw new ArgumentOutOfRangeException(nameof(logLevel))\n };", + "start_line": 103, + "end_line": 112, + "start_byte": 3572, + "end_byte": 3946 + }, + { + "name": "WriteMessage", + "code": "private void WriteMessage(TextWriter textWriter, string message, bool includePadding = true)\n {\n if (message == null)\n {\n return;\n }\n\n if (includePadding)\n {\n textWriter.Write(_messagePadding);\n }\n\n textWriter.WriteLine(message.Replace(Environment.NewLine, _newLineWithMessagePadding));\n }", + "start_line": 88, + "end_line": 101, + "start_byte": 3200, + "end_byte": 3566 + }, + { + "name": "Write", + "code": "public override void Write(in LogEntry logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter)\n {\n if (logEntry.Formatter == null)\n {\n return;\n }\n\n var message = logEntry.Formatter(logEntry.State, logEntry.Exception);\n if (logEntry.Exception == null && message == null)\n {\n return;\n }\n\n LogLevel logLevel = logEntry.LogLevel;\n var logLevelColors = GetLogLevelConsoleColors(logLevel);\n var logLevelString = GetLogLevelString(logLevel);\n\n if (_options.TimestampFormat != null)\n {\n var timestamp = DateTimeOffset.Now.ToString(_options.TimestampFormat);\n textWriter.Write(timestamp);\n }\n\n WriteColoredMessage(textWriter, logLevelString, logLevelColors.Background, logLevelColors.Foreground);\n\n textWriter.Write(LoglevelPadding);\n\n WriteMessage(textWriter, message, false);\n\n // Example:\n // System.InvalidOperationException\n // at Namespace.Class.Function() in File:line X\n if (logEntry.Exception != null)\n {\n // exception message\n WriteMessage(textWriter, logEntry.Exception.ToString());\n }\n }", + "start_line": 49, + "end_line": 86, + "start_byte": 1943, + "end_byte": 3194 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Program.cs": [ + { + "name": "IsOutputSensitive", + "code": "private static bool IsOutputSensitive(string[] args)\r\n {\r\n if (args.Length > 0 && args[0] == \"version\")\r\n {\r\n return true;\r\n }\r\n\r\n if (args.Length < 2 || args.Contains(\"--help\") || args.Contains(\"-h\"))\r\n {\r\n return false;\r\n }\r\n\r\n var platform = args[0];\r\n var command = args[1];\r\n\r\n return platform switch\r\n {\r\n \"apple\" => command switch\r\n {\r\n \"device\" => true,\r\n \"state\" => args.Contains(\"--json\"),\r\n \"mlaunch\" => true,\r\n _ => false,\r\n },\r\n \"android\" => command switch\r\n {\r\n \"device\" => true,\r\n \"state\" => args.Contains(\"--json\"),\r\n \"adb\" => true,\r\n _ => false,\r\n },\r\n \"android-headless\" => command switch\r\n {\r\n \"device\" => true,\r\n \"state\" => args.Contains(\"--json\"),\r\n \"adb\" => true,\r\n _ => false,\r\n },\r\n _ => false,\r\n };\r\n }", + "start_line": 98, + "end_line": 138, + "start_byte": 3516, + "end_byte": 4638 + }, + { + "name": "GetXHarnessCommandSet", + "code": "public static CommandSet GetXHarnessCommandSet()\r\n {\r\n#pragma warning disable IDE0028 // Simplify collection initialization for DEBUG\r\n var commandSet = new CommandSet(\"xharness\");\r\n#pragma warning restore IDE0028 // Simplify collection initialization for DEBUG\r\n\r\n#if !DEBUG\r\n if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\r\n {\r\n commandSet.Add(new AppleCommandSet());\r\n }\r\n#else\r\n commandSet.Add(new AppleCommandSet());\r\n#endif\r\n\r\n commandSet.Add(new AndroidCommandSet());\r\n commandSet.Add(new AndroidHeadlessCommandSet());\r\n commandSet.Add(new WasmCommandSet());\r\n commandSet.Add(new WasiCommandSet());\r\n commandSet.Add(new XHarnessHelpCommand());\r\n commandSet.Add(new XHarnessVersionCommand());\r\n\r\n return commandSet;\r\n }", + "start_line": 70, + "end_line": 93, + "start_byte": 2511, + "end_byte": 3359 + }, + { + "name": "Main", + "code": "public static int Main(string[] args)\r\n {\r\n bool shouldOutput = !IsOutputSensitive(args);\r\n\r\n if (shouldOutput)\r\n {\r\n Console.WriteLine(\r\n $\"[{XHarnessVersionCommand.GetAssemblyVersion().ProductVersion}] \" +\r\n \"XHarness command issued: \" + string.Join(' ', args));\r\n }\r\n\r\n if (args.Length > 0)\r\n {\r\n#if !DEBUG\r\n if (args[0] == \"apple\" && !RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\r\n {\r\n // Otherwise the command would just not be found\r\n Console.Error.WriteLine(\"The 'apple' command is not available on non-OSX platforms!\");\r\n return (int)ExitCode.INVALID_ARGUMENTS;\r\n }\r\n#endif\r\n\r\n // Mono.Options wouldn't allow \"--\" so we will temporarily rename it and parse it ourselves later\r\n args = args.Select(a => a == \"--\" ? VerbatimArgumentPlaceholder : a).ToArray();\r\n }\r\n\r\n var commands = GetXHarnessCommandSet();\r\n int result = commands.Run(args);\r\n\r\n string? exitCodeName = null;\r\n if (args.Length > 0 && result != 0 && Enum.IsDefined(typeof(ExitCode), result))\r\n {\r\n exitCodeName = $\" ({(ExitCode)result})\";\r\n }\r\n\r\n if (shouldOutput)\r\n {\r\n Console.WriteLine($\"XHarness exit code: {result}{exitCodeName}\");\r\n }\r\n\r\n return result;\r\n }", + "start_line": 27, + "end_line": 68, + "start_byte": 1076, + "end_byte": 2503 + } + ], + "src/Microsoft.DotNet.XHarness.Common/CommandDiagnostics.cs": [ + { + "name": "SaveToJsonFile", + "code": "public void SaveToJsonFile(string targetFile)\n {\n _timer.Stop();\n\n var options = new JsonSerializerOptions\n {\n#if DEBUG\n WriteIndented = true,\n#else\n WriteIndented = false,\n#endif\n PropertyNamingPolicy = JsonNamingPolicy.CamelCase,\n };\n\n _logger.LogDebug(\"Saving diagnostics data to '{path}'\", targetFile);\n\n try\n {\n // Either append current data to the JSON array or create a new file\n if (File.Exists(targetFile))\n {\n var data = JsonDocument.Parse(File.ReadAllText(targetFile));\n\n var writerOptions = new JsonWriterOptions\n {\n Indented = options.WriteIndented,\n };\n\n using var fileStream = new FileStream(targetFile, FileMode.Create, FileAccess.Write);\n using var jsonWriter = new Utf8JsonWriter(fileStream, writerOptions);\n\n jsonWriter.WriteStartArray();\n\n // Copy the existing elements without going into details of what they are\n var newData = new List();\n var enumerator = data.RootElement.EnumerateArray();\n while (enumerator.MoveNext())\n {\n enumerator.Current.WriteTo(jsonWriter);\n }\n\n // New element\n JsonSerializer.Serialize(jsonWriter, this, options);\n\n jsonWriter.WriteEndArray();\n }\n else\n {\n var data = new[]\n {\n this\n };\n\n string json = JsonSerializer.Serialize(data, options);\n File.WriteAllText(targetFile, json);\n }\n }\n catch (Exception e)\n {\n _logger.LogError(\"Failed to save diagnostics data to '{pathToFile}': {error}\", targetFile, e);\n }\n }", + "start_line": 88, + "end_line": 149, + "start_byte": 2724, + "end_byte": 4687 + } + ], + "src/Microsoft.DotNet.XHarness.Common/XmlResultJargon.cs": [], + "src/Microsoft.DotNet.XHarness.Common/WasmSymbolicatorBase.cs": [ + { + "name": "Symbolicate", + "code": "public abstract string Symbolicate(string msg);", + "start_line": 49, + "end_line": 49, + "start_byte": 1664, + "end_byte": 1711 + }, + { + "name": "Create", + "code": "public static WasmSymbolicatorBase? Create(Type? symbolicatorType, string? symbolMapFile, string? symbolsPatternFile, ILogger logger)\n {\n if (symbolicatorType is null && symbolMapFile is null && symbolsPatternFile is null)\n return null;\n\n if (symbolicatorType is null)\n {\n logger.LogWarning(\"No symbolicator given\");\n return null;\n }\n\n var symbolicator = Activator.CreateInstance(symbolicatorType) as WasmSymbolicatorBase;\n if (symbolicator is null)\n {\n // should not happen\n logger.LogError($\"Symbolicator '{symbolicatorType}' is not of WasmSymbolicatorBase type.\");\n return null;\n }\n\n if (symbolicator.Init(symbolMapFile, symbolsPatternFile, logger) == true)\n return symbolicator;\n\n logger.LogDebug($\"Symbolicator '{symbolicatorType}'.Init({symbolMapFile}, {symbolsPatternFile}) returned false\");\n return null;\n }", + "start_line": 23, + "end_line": 47, + "start_byte": 683, + "end_byte": 1658 + }, + { + "name": "Init", + "code": "public virtual bool Init(string? symbolMapFile, string? symbolsPatternFile, ILogger logger)\n {\n SymbolsFile = symbolMapFile;\n SymbolsPatternFile = symbolsPatternFile;\n\n return true;\n }", + "start_line": 15, + "end_line": 21, + "start_byte": 466, + "end_byte": 677 + } + ], + "src/Microsoft.DotNet.XHarness.Common/TargetPlatform.cs": [], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/ApplicationOptions.cs": [], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/iOSApplicationEntryPointBase.cs": [ + { + "name": "RunAsync", + "code": "public override async Task RunAsync()\n {\n var options = ApplicationOptions.Current;\n\n // On iOS 18 and later, transferring results over a TCP tunnel isn\u2019t supported.\n // Instead, copy the results file from the device to the host machine.\n if (!OperatingSystem.IsMacCatalyst() && Environment.OSVersion.Version.Major >= 18)\n {\n using TextWriter? resultsFileMaybe = options.EnableXml ? System.IO.File.CreateText(TestsResultsFinalPath) : null;\n await InternalRunAsync(options, Logger, resultsFileMaybe);\n Console.WriteLine($\"Test results saved to: {TestsResultsFinalPath}\");\n }\n else\n {\n TcpTextWriter? writer;\n\n try\n {\n writer = options.UseTunnel\n ? TcpTextWriter.InitializeWithTunnelConnection(options.HostPort)\n : TcpTextWriter.InitializeWithDirectConnection(options.HostName, options.HostPort);\n }\n catch (Exception ex)\n {\n Console.WriteLine(\"Failed to initialize TCP writer. Continuing on console.\" + Environment.NewLine + ex);\n writer = null; // null means we will fall back to console output\n }\n\n using (writer)\n {\n var logger = (writer == null || options.EnableXml) ? new LogWriter(Device) : new LogWriter(Device, writer);\n logger.MinimumLogLevel = MinimumLogLevel.Info;\n\n await InternalRunAsync(options, writer, writer);\n }\n }\n }", + "start_line": 23, + "end_line": 59, + "start_byte": 820, + "end_byte": 2396 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/MinimumLogLevel.cs": [], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/IDevice.cs": [], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/TestResult.cs": [], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/TestCompletionStatus.cs": [], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/TestRunResult.cs": [], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/LogWriter.cs": [ + { + "name": "Info", + "code": "public void Info(string message)\n {\n _writer.WriteLine(message);\n _writer.Flush();\n }", + "start_line": 105, + "end_line": 109, + "start_byte": 2868, + "end_byte": 2973 + }, + { + "name": "OnInfo", + "code": "public void OnInfo(string message)\n {\n if (MinimumLogLevel < MinimumLogLevel.Info)\n {\n return;\n }\n\n _writer.WriteLine(message);\n _writer.Flush();\n }", + "start_line": 94, + "end_line": 103, + "start_byte": 2662, + "end_byte": 2862 + }, + { + "name": "OnDiagnostic", + "code": "public void OnDiagnostic(string message)\n {\n if (MinimumLogLevel < MinimumLogLevel.Verbose)\n {\n return;\n }\n\n _writer.WriteLine(message);\n _writer.Flush();\n }", + "start_line": 83, + "end_line": 92, + "start_byte": 2447, + "end_byte": 2656 + }, + { + "name": "OnDebug", + "code": "public void OnDebug(string message)\n {\n if (MinimumLogLevel < MinimumLogLevel.Debug)\n {\n return;\n }\n\n _writer.WriteLine(message);\n _writer.Flush();\n }", + "start_line": 72, + "end_line": 81, + "start_byte": 2239, + "end_byte": 2441 + }, + { + "name": "OnWarning", + "code": "public void OnWarning(string message)\n {\n if (MinimumLogLevel < MinimumLogLevel.Warning)\n {\n return;\n }\n\n _writer.WriteLine(message);\n _writer.Flush();\n }", + "start_line": 61, + "end_line": 70, + "start_byte": 2027, + "end_byte": 2233 + }, + { + "name": "OnError", + "code": "public void OnError(string message)\n {\n if (MinimumLogLevel < MinimumLogLevel.Error)\n {\n return;\n }\n\n _writer.WriteLine(message);\n _writer.Flush();\n }", + "start_line": 50, + "end_line": 59, + "start_byte": 1819, + "end_byte": 2021 + }, + { + "name": "InitLogging", + "code": "public void InitLogging()\n {\n Debug.Assert(_device is not null);\n // print some useful info\n _writer.WriteLine(\"[Runner executing:\\t{0}]\", \"Run everything\");\n _writer.WriteLine(\"[{0}:\\t{1} v{2}]\", _device.Model, _device.SystemName, _device.SystemVersion);\n _writer.WriteLine(\"[Device Name:\\t{0}]\", _device.Name);\n _writer.WriteLine(\"[Device UDID:\\t{0}]\", _device.UniqueIdentifier);\n _writer.WriteLine(\"[Device Locale:\\t{0}]\", _device.Locale);\n _writer.WriteLine(\"[Device Date/Time:\\t{0}]\", DateTime.Now); // to match earlier C.WL output\n _writer.WriteLine(\"[Bundle:\\t{0}]\", _device.BundleIdentifier);\n }", + "start_line": 38, + "end_line": 49, + "start_byte": 1142, + "end_byte": 1814 + }, + { + "name": "objc_msgSend", + "code": "[System.Runtime.InteropServices.DllImport(\"/usr/lib/libobjc.dylib\")]\n private static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector);", + "start_line": 35, + "end_line": 36, + "start_byte": 987, + "end_byte": 1136 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/AndroidApplicationEntryPointBase.cs": [ + { + "name": "RunAsync", + "code": "public override async Task RunAsync()\n {\n var options = ApplicationOptions.Current;\n using TextWriter? resultsFileMaybe = options.EnableXml ? File.CreateText(TestsResultsFinalPath) : null;\n await InternalRunAsync(options, Logger, resultsFileMaybe);\n }", + "start_line": 26, + "end_line": 31, + "start_byte": 870, + "end_byte": 1148 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/TestRunSelectorType.cs": [], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/TcpTextWriter.cs": [ + { + "name": "ValidatePort", + "code": "private static void ValidatePort(int port)\n {\n if (port < 0 || port > ushort.MaxValue)\n {\n throw new ArgumentOutOfRangeException(nameof(port), $\"Port must be between 0 and {ushort.MaxValue}\");\n }\n }", + "start_line": 192, + "end_line": 198, + "start_byte": 5432, + "end_byte": 5668 + }, + { + "name": "SelectHostName", + "code": "private static string SelectHostName(string[] names, int port)\n {\n if (names.Length == 1)\n {\n return names[0];\n }\n\n object lock_obj = new object();\n string? result = null;\n int failures = 0;\n\n using (var evt = new ManualResetEvent(false))\n {\n for (int i = names.Length - 1; i >= 0; i--)\n {\n var name = names[i];\n ThreadPool.QueueUserWorkItem((v) =>\n {\n try\n {\n var client = new TcpClient(name, port);\n using (var writer = new StreamWriter(client.GetStream()))\n {\n writer.WriteLine(\"ping\");\n }\n lock (lock_obj)\n {\n if (result == null)\n {\n result = name;\n }\n }\n evt.Set();\n }\n catch (Exception)\n {\n lock (lock_obj)\n {\n failures++;\n if (failures == names.Length)\n {\n evt.Set();\n }\n }\n }\n });\n }\n\n // Wait for 1 success or all failures\n evt.WaitOne();\n }\n\n if (result == null)\n {\n throw new InvalidOperationException(\"Couldn't connect to any of the hostnames.\");\n }\n\n return result;\n }", + "start_line": 132, + "end_line": 190, + "start_byte": 3666, + "end_byte": 5426 + }, + { + "name": "WriteLine", + "code": "public override void WriteLine()\n {\n _writer.WriteLine();\n _writer.Flush();\n }", + "start_line": 126, + "end_line": 130, + "start_byte": 3562, + "end_byte": 3660 + }, + { + "name": "Write", + "code": "public override void Write(string? value)\n {\n _writer.Write(value);\n }", + "start_line": 119, + "end_line": 122, + "start_byte": 3408, + "end_byte": 3491 + }, + { + "name": "Write", + "code": "public override void Write(char[] buffer, int index, int count)\n {\n _writer.Write(buffer, index, count);\n }", + "start_line": 114, + "end_line": 117, + "start_byte": 3282, + "end_byte": 3402 + }, + { + "name": "Write", + "code": "public override void Write(char[]? buffer)\n {\n _writer.Write(buffer);\n }", + "start_line": 109, + "end_line": 112, + "start_byte": 3191, + "end_byte": 3276 + }, + { + "name": "Write", + "code": "public override void Write(char value)\n {\n _writer.Write(value);\n }", + "start_line": 104, + "end_line": 107, + "start_byte": 3105, + "end_byte": 3185 + }, + { + "name": "Flush", + "code": "public override void Flush()\n {\n _writer.Flush();\n }", + "start_line": 98, + "end_line": 101, + "start_byte": 2935, + "end_byte": 3000 + }, + { + "name": "Dispose", + "code": "protected override void Dispose(bool disposing) => _writer?.Dispose();", + "start_line": 96, + "end_line": 96, + "start_byte": 2859, + "end_byte": 2929 + }, + { + "name": "Close", + "code": "public override void Close()\n {\n _writer.Close();\n }", + "start_line": 91, + "end_line": 94, + "start_byte": 2788, + "end_byte": 2853 + }, + { + "name": "InitializeWithDirectConnection", + "code": "public static TcpTextWriter InitializeWithDirectConnection(string hostName, int port)\n {\n if (hostName is null)\n {\n throw new ArgumentNullException(nameof(hostName));\n }\n\n ValidatePort(port);\n\n hostName = SelectHostName(hostName.Split(','), port);\n\n var client = new TcpClient(hostName, port);\n var writer = new StreamWriter(client.GetStream());\n\n return new TcpTextWriter(writer);\n }", + "start_line": 70, + "end_line": 85, + "start_byte": 2193, + "end_byte": 2650 + }, + { + "name": "InitializeWithTunnelConnection", + "code": "public static TcpTextWriter InitializeWithTunnelConnection(int port)\n {\n ValidatePort(port);\n\n var server = new TcpListener(IPAddress.Any, port);\n server.Server.ReceiveTimeout = 5000;\n server.Start();\n var watch = Stopwatch.StartNew();\n\n while (!server.Pending())\n {\n if (watch.Elapsed > s_connectionAwaitPeriod)\n {\n throw new Exception($\"No inbound TCP connection after {(int)s_connectionAwaitPeriod.TotalSeconds} seconds\");\n }\n\n Thread.Sleep(100);\n }\n\n var client = server.AcceptTcpClient();\n\n // Block until we have the ping from the client side\n byte[] buffer = new byte[16 * 1024];\n var stream = client.GetStream();\n while ((_ = stream.Read(buffer, 0, buffer.Length)) != 0)\n {\n var message = Encoding.UTF8.GetString(buffer);\n if (message.Contains(\"ping\"))\n {\n break;\n }\n }\n\n var writer = new StreamWriter(client.GetStream());\n\n return new TcpTextWriter(writer);\n }", + "start_line": 32, + "end_line": 68, + "start_byte": 1075, + "end_byte": 2187 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/TestExecutionState.cs": [ + { + "name": "Finish", + "code": "internal void Finish() => Finished = new TimeSpan(DateTime.Now.Ticks);", + "start_line": 20, + "end_line": 20, + "start_byte": 723, + "end_byte": 793 + }, + { + "name": "Start", + "code": "internal void Start() => Started = new TimeSpan(DateTime.Now.Ticks);", + "start_line": 18, + "end_line": 18, + "start_byte": 649, + "end_byte": 717 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/TestFailureInfo.cs": [], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/IgnoreFileParser.cs": [ + { + "name": "ParseContentFiles", + "code": "public static IEnumerable ParseContentFiles(string contentDir)\n {\n var ignoredTests = new List();\n foreach (var f in Directory.GetFiles(contentDir, \"*.ignore\"))\n {\n using (var reader = new StreamReader(f))\n {\n string line;\n while ((line = reader.ReadLine()) != null)\n {\n\n line = ParseLine(line);\n if (string.IsNullOrEmpty(line))\n {\n continue;\n }\n\n ignoredTests.Add(line);\n }\n }\n }\n return ignoredTests;\n }", + "start_line": 132, + "end_line": 154, + "start_byte": 4223, + "end_byte": 4896 + }, + { + "name": "ParseTraitsContentFile", + "code": "public static IEnumerable ParseTraitsContentFile(string contentDir, bool isXUnit)\n {\n var ignoredTraits = new List();\n var ignoreFile = Path.Combine(contentDir, isXUnit ? \"xunit-excludes.txt\" : \"nunit-excludes.txt\");\n using (var reader = new StreamReader(ignoreFile))\n {\n string line;\n while ((line = reader.ReadLine()) != null)\n {\n if (string.IsNullOrEmpty(line))\n {\n continue;\n }\n\n ignoredTraits.Add(line);\n }\n }\n return ignoredTraits;\n }", + "start_line": 112, + "end_line": 130, + "start_byte": 3590, + "end_byte": 4217 + }, + { + "name": "ParseTraitsContentFileAsync", + "code": "public static Task> ParseTraitsContentFileAsync(string contentDir, bool isXUnit)\n {\n var ignoreFile = Path.Combine(contentDir, isXUnit ? \"xunit-excludes.txt\" : \"nunit-excludes.txt\");\n return ParseTraitsFileAsync(ignoreFile);\n }", + "start_line": 106, + "end_line": 110, + "start_byte": 3317, + "end_byte": 3584 + }, + { + "name": "ParseTraitsFileAsync", + "code": "public static async Task> ParseTraitsFileAsync(string filePath)\n {\n var ignoredTraits = new List();\n using var reader = new StreamReader(filePath);\n string line;\n while ((line = await reader.ReadLineAsync()) != null)\n {\n if (string.IsNullOrEmpty(line))\n {\n continue;\n }\n\n ignoredTraits.Add(line);\n }\n return ignoredTraits;\n }", + "start_line": 89, + "end_line": 104, + "start_byte": 2844, + "end_byte": 3311 + }, + { + "name": "ParseContentFilesAsync", + "code": "public static async Task> ParseContentFilesAsync(string contentDir)\n {\n if (string.IsNullOrEmpty(contentDir))\n {\n return Array.Empty();\n }\n\n var ignoredTests = new List();\n foreach (var f in Directory.GetFiles(contentDir, \"*.ignore\"))\n {\n using (var reader = new StreamReader(f))\n {\n var ignored = await ParseStreamAsync(reader);\n ignoredTests.AddRange(ignored);\n }\n }\n return ignoredTests;\n }", + "start_line": 70, + "end_line": 87, + "start_byte": 2273, + "end_byte": 2838 + }, + { + "name": "ParseAssemblyResourcesAsync", + "code": "public static async Task> ParseAssemblyResourcesAsync(Assembly asm)\n {\n var ignoredTests = new List();\n // the project generator added the required resources,\n // we extract them, parse them and add the result\n foreach (var resourceName in asm.GetManifestResourceNames())\n {\n if (resourceName.EndsWith(\".ignore\", StringComparison.Ordinal))\n {\n using (var stream = asm.GetManifestResourceStream(resourceName))\n using (var reader = new StreamReader(stream))\n {\n var ignored = await ParseStreamAsync(reader);\n // we could have more than one file, lets add them\n ignoredTests.AddRange(ignored);\n }\n }\n }\n return ignoredTests;\n }", + "start_line": 49, + "end_line": 68, + "start_byte": 1410, + "end_byte": 2267 + }, + { + "name": "ParseStreamAsync", + "code": "public static async Task> ParseStreamAsync(TextReader textReader)\n {\n var ignoredMethods = new List();\n string line;\n while ((line = await textReader.ReadLineAsync()) != null)\n {\n line = ParseLine(line);\n if (string.IsNullOrEmpty(line))\n {\n continue;\n }\n\n ignoredMethods.Add(line);\n }\n return ignoredMethods;\n }", + "start_line": 32, + "end_line": 47, + "start_byte": 947, + "end_byte": 1404 + }, + { + "name": "ParseLine", + "code": "private static string ParseLine(string line)\n {\n // we have to make sure of several things, first, lets\n // remove any char after the first # which would mean\n // we have comments:\n var pos = line.IndexOf('#');\n if (pos > -1)\n {\n line = line.Remove(pos);\n }\n line = line.Trim();\n return line;\n }", + "start_line": 19, + "end_line": 31, + "start_byte": 567, + "end_byte": 942 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/TestAssemblyInfo.cs": [], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/TestRunSelector.cs": [], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/ApplicationEntryPoint.cs": [ + { + "name": "InternalRunAsync", + "code": "protected async Task InternalRunAsync(ApplicationOptions options, TextWriter? loggerWriter, TextWriter? resultsFile)\n {\n // we generate the logs in two different ways depending if the generate xml flag was\n // provided. If it was, we will write the xml file to the provided writer if present, else\n // we will write the normal console output using the LogWriter\n var logger = (loggerWriter == null || options.EnableXml) ? new LogWriter(Device) : new LogWriter(Device, loggerWriter);\n logger.MinimumLogLevel = MinimumLogLevel.Info;\n var runner = await InternalRunAsync(logger);\n\n await WriteResults(runner, options, logger, resultsFile ?? Console.Out);\n\n logger.Info($\"{Environment.NewLine}=== TEST EXECUTION SUMMARY ==={Environment.NewLine}Tests run: {runner.TotalTests} Passed: {runner.PassedTests} Inconclusive: {runner.InconclusiveTests} Failed: {runner.FailedTests} Ignored: {runner.FilteredTests} Skipped: {runner.SkippedTests}{Environment.NewLine}\");\n\n if (options.AppEndTag != null)\n {\n logger.Info(options.AppEndTag);\n }\n\n if (options.TerminateAfterExecution)\n {\n TerminateWithSuccess();\n }\n\n return runner;\n }", + "start_line": 221, + "end_line": 245, + "start_byte": 8131, + "end_byte": 9394 + }, + { + "name": "InternalRunAsync", + "code": "private async Task InternalRunAsync(LogWriter logger)\n {\n logger.MinimumLogLevel = MinimumLogLevel;\n var runner = GetTestRunner(logger);\n runner.LogExcludedTests = LogExcludedTests;\n // connect to the runner events so that we fwd them to the client\n runner.TestStarted += OnTestStarted;\n runner.TestCompleted += OnTestCompleted;\n\n // add ignored categories and specific files\n runner.SkipCategories(await GetIgnoredCategories());\n runner.SkipTests(await IgnoreFileParser.ParseContentFilesAsync(IgnoreFilesDirectory));\n\n var testAssemblies = GetTestAssemblies();\n // notify the clients we are starting\n TestsStarted?.Invoke(this, new EventArgs());\n\n await runner.Run(testAssemblies).ConfigureAwait(false);\n\n var result = new TestRunResult(runner);\n // notify the client we are done and the results, but do not expose\n // the runner.\n TestsCompleted?.Invoke(this, result);\n return runner;\n }", + "start_line": 195, + "end_line": 219, + "start_byte": 7092, + "end_byte": 8125 + }, + { + "name": "WriteResults", + "code": "private static async Task WriteResults(TestRunner runner, ApplicationOptions options, LogWriter logger, TextWriter writer)\n {\n if (options.EnableXml && writer == null)\n {\n throw new ArgumentNullException(nameof(writer));\n }\n\n if (options.EnableXml)\n {\n await runner.WriteResultsToFile(writer, options.XmlVersion);\n logger.Info(\"Xml file was written to the provided writer.\");\n }\n else\n {\n string resultsFilePath = await runner.WriteResultsToFile(options.XmlVersion);\n logger.Info($\"XML results can be found in '{resultsFilePath}'\");\n }\n }", + "start_line": 176, + "end_line": 193, + "start_byte": 6424, + "end_byte": 7086 + }, + { + "name": "ConfigureRunnerFilters", + "code": "internal static void ConfigureRunnerFilters(TestRunner runner, ApplicationOptions options)\n {\n runner.RunAllTestsByDefault = options.RunAllTestsByDefault;\n\n // Add the provided method and class filters\n if (options.SingleMethodFilters.Count != 0 || options.ClassMethodFilters.Count != 0)\n {\n // Having methods/classes explicitly specified means only those methods/classes should be run\n runner.RunAllTestsByDefault = false;\n foreach (string methodName in options.SingleMethodFilters)\n {\n runner.SkipMethod(methodName, isExcluded: false);\n }\n\n foreach (string className in options.ClassMethodFilters)\n {\n runner.SkipClass(className, isExcluded: false);\n }\n }\n }", + "start_line": 155, + "end_line": 174, + "start_byte": 5599, + "end_byte": 6418 + }, + { + "name": "GetIgnoredCategories", + "code": "private async Task> GetIgnoredCategories()\n {\n var categories = new List(); // default known category to ignore\n\n // check if the child does have an ignore files dir\n if (!string.IsNullOrEmpty(IgnoreFilesDirectory))\n {\n categories.AddRange(await IgnoreFileParser.ParseTraitsContentFileAsync(IgnoreFilesDirectory, IsXunit));\n }\n\n // check if the child provides a specific traits file.\n if (!string.IsNullOrEmpty((IgnoredTraitsFilePath)))\n {\n categories.AddRange(await IgnoreFileParser.ParseTraitsFileAsync(IgnoredTraitsFilePath));\n }\n\n return categories;\n }", + "start_line": 136, + "end_line": 153, + "start_byte": 4918, + "end_byte": 5593 + }, + { + "name": "OnTestCompleted", + "code": "private void OnTestCompleted(object? sender, (string TestName, TestResult Testresult) result) => TestCompleted?.Invoke(sender, result);", + "start_line": 134, + "end_line": 134, + "start_byte": 4777, + "end_byte": 4912 + }, + { + "name": "OnTestStarted", + "code": "private void OnTestStarted(object? sender, string testName) => TestStarted?.Invoke(sender, testName);", + "start_line": 132, + "end_line": 132, + "start_byte": 4670, + "end_byte": 4771 + }, + { + "name": "RunAsync", + "code": "public abstract Task RunAsync();", + "start_line": 125, + "end_line": 125, + "start_byte": 4441, + "end_byte": 4473 + }, + { + "name": "TerminateWithSuccess", + "code": "protected abstract void TerminateWithSuccess();", + "start_line": 120, + "end_line": 120, + "start_byte": 4307, + "end_byte": 4354 + }, + { + "name": "GetTestRunner", + "code": "protected abstract TestRunner GetTestRunner(LogWriter logWriter);", + "start_line": 79, + "end_line": 79, + "start_byte": 2480, + "end_byte": 2545 + }, + { + "name": "GetTestAssemblies", + "code": "protected abstract IEnumerable GetTestAssemblies();", + "start_line": 74, + "end_line": 74, + "start_byte": 2329, + "end_byte": 2398 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/TestRunner.cs": [ + { + "name": "OnTestCompleted", + "code": "protected virtual void OnTestCompleted((string TestName, TestResult TestResult) result) => TestCompleted?.Invoke(this, result);", + "start_line": 178, + "end_line": 178, + "start_byte": 5534, + "end_byte": 5661 + }, + { + "name": "OnTestStarted", + "code": "protected virtual void OnTestStarted(string testName) => TestStarted?.Invoke(this, testName);", + "start_line": 176, + "end_line": 176, + "start_byte": 5435, + "end_byte": 5528 + }, + { + "name": "GetResultsFilePath", + "code": "protected virtual string GetResultsFilePath()\n {\n if (string.IsNullOrEmpty(ResultsFileName))\n {\n throw new InvalidOperationException(\"Runner didn't specify a valid results file name\");\n }\n\n string resultsPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n if (!Directory.Exists(resultsPath))\n {\n Directory.CreateDirectory(resultsPath);\n }\n\n return Path.Combine(resultsPath, ResultsFileName);\n }", + "start_line": 160, + "end_line": 174, + "start_byte": 4925, + "end_byte": 5429 + }, + { + "name": "LogFailureSummary", + "code": "protected void LogFailureSummary()\n {\n if (!ShowFailureInfos || FailureInfos == null || FailureInfos.Count == 0)\n {\n return;\n }\n\n OnInfo(\"Failed tests:\");\n for (int i = 1; i <= FailureInfos.Count; i++)\n {\n TestFailureInfo info = FailureInfos[i - 1];\n if (info == null || !info.HasInfo)\n {\n continue;\n }\n\n OnInfo($\"{i}) {info.Message}\");\n }\n }", + "start_line": 140, + "end_line": 158, + "start_byte": 4441, + "end_byte": 4919 + }, + { + "name": "OnAssemblyFinish", + "code": "protected void OnAssemblyFinish(Assembly asm)\n {\n }", + "start_line": 136, + "end_line": 138, + "start_byte": 4378, + "end_byte": 4435 + }, + { + "name": "OnAssemblyStart", + "code": "protected void OnAssemblyStart(Assembly asm)\n {\n }", + "start_line": 132, + "end_line": 134, + "start_byte": 4316, + "end_byte": 4372 + }, + { + "name": "OnInfo", + "code": "protected void OnInfo(string message) => Logger.OnInfo(message);", + "start_line": 130, + "end_line": 130, + "start_byte": 4246, + "end_byte": 4310 + }, + { + "name": "OnDiagnostic", + "code": "protected void OnDiagnostic(string message) => Logger.OnDiagnostic(message);", + "start_line": 128, + "end_line": 128, + "start_byte": 4164, + "end_byte": 4240 + }, + { + "name": "OnDebug", + "code": "protected void OnDebug(string message) => Logger.OnDebug(message);", + "start_line": 126, + "end_line": 126, + "start_byte": 4092, + "end_byte": 4158 + }, + { + "name": "OnWarning", + "code": "protected void OnWarning(string message) => Logger.OnWarning(message);", + "start_line": 124, + "end_line": 124, + "start_byte": 4016, + "end_byte": 4086 + }, + { + "name": "OnError", + "code": "protected void OnError(string message) => Logger.OnError(message);", + "start_line": 122, + "end_line": 122, + "start_byte": 3944, + "end_byte": 4010 + }, + { + "name": "SkipClass", + "code": "public abstract void SkipClass(string className, bool isExcluded);", + "start_line": 120, + "end_line": 120, + "start_byte": 3872, + "end_byte": 3938 + }, + { + "name": "SkipMethod", + "code": "public abstract void SkipMethod(string method, bool isExcluded);", + "start_line": 119, + "end_line": 119, + "start_byte": 3803, + "end_byte": 3867 + }, + { + "name": "SkipCategories", + "code": "public abstract void SkipCategories(IEnumerable categories);", + "start_line": 118, + "end_line": 118, + "start_byte": 3730, + "end_byte": 3798 + }, + { + "name": "SkipTests", + "code": "public abstract void SkipTests(IEnumerable tests);", + "start_line": 117, + "end_line": 117, + "start_byte": 3667, + "end_byte": 3725 + }, + { + "name": "WriteResultsToFile", + "code": "public abstract Task WriteResultsToFile(TextWriter writer, XmlResultJargon jargon);", + "start_line": 116, + "end_line": 116, + "start_byte": 3579, + "end_byte": 3662 + }, + { + "name": "WriteResultsToFile", + "code": "public abstract Task WriteResultsToFile(XmlResultJargon xmlResultJargon);", + "start_line": 115, + "end_line": 115, + "start_byte": 3493, + "end_byte": 3574 + }, + { + "name": "Run", + "code": "public abstract Task Run(IEnumerable testAssemblies);", + "start_line": 114, + "end_line": 114, + "start_byte": 3417, + "end_byte": 3488 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/Extensions.cs": [ + { + "name": "YesNo", + "code": "public static string YesNo(this bool b) => b ? \"yes\" : \"no\";", + "start_line": 9, + "end_line": 9, + "start_byte": 311, + "end_byte": 371 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/WasmApplicationEntryPointBase.cs": [ + { + "name": "TerminateWithSuccess", + "code": "protected override void TerminateWithSuccess() => Environment.Exit(0);", + "start_line": 27, + "end_line": 27, + "start_byte": 800, + "end_byte": 870 + }, + { + "name": "RunAsync", + "code": "public override async Task RunAsync()\n {\n var options = ApplicationOptions.Current;\n var runner = await InternalRunAsync(options, null, Console.Out);\n\n LastRunHadFailedTests = runner.FailedTests != 0;\n }", + "start_line": 17, + "end_line": 23, + "start_byte": 511, + "end_byte": 741 + } + ], + "src/Microsoft.DotNet.XHarness.Android/AdbRunner.cs": [ + { + "name": "Retry", + "code": "private T Retry(Func action, Func needsRetry, TimeSpan retryInterval, TimeSpan retryPeriod)\r\n {\r\n var watch = Stopwatch.StartNew();\r\n int attempt = 0;\r\n\r\n T result;\r\n while (true)\r\n {\r\n result = action();\r\n\r\n if (!needsRetry(result))\r\n {\r\n return result;\r\n }\r\n\r\n if (watch.Elapsed > retryPeriod)\r\n {\r\n _log.LogDebug($\"All {attempt} retries of action failed\");\r\n break;\r\n }\r\n\r\n ++attempt;\r\n _log.LogDebug($\"Attempt {attempt} failed, retrying in {(int)retryInterval.TotalSeconds} seconds...\");\r\n Thread.Sleep(retryInterval);\r\n }\r\n\r\n return result;\r\n }", + "start_line": 1136, + "end_line": 1163, + "start_byte": 46453, + "end_byte": 47227 + }, + { + "name": "Retry", + "code": "private bool Retry(Func action, TimeSpan retryInterval, TimeSpan retryPeriod) =>\r\n Retry(action, result => !result, retryInterval, retryPeriod);", + "start_line": 1133, + "end_line": 1134, + "start_byte": 46288, + "end_byte": 46445 + }, + { + "name": "RunAdbCommand", + "code": "public ProcessExecutionResults RunAdbCommand(IEnumerable arguments, TimeSpan timeOut)\r\n {\r\n if (!File.Exists(_absoluteAdbExePath))\r\n {\r\n throw new FileNotFoundException($\"Provided path for adb.exe was not valid ('{_absoluteAdbExePath}')\", _absoluteAdbExePath);\r\n }\r\n\r\n return _processManager.Run(_absoluteAdbExePath, arguments, timeOut);\r\n }", + "start_line": 1123, + "end_line": 1131, + "start_byte": 45886, + "end_byte": 46280 + }, + { + "name": "RunAdbCommand", + "code": "public ProcessExecutionResults RunAdbCommand(params string[] arguments) => RunAdbCommand(arguments, TimeSpan.FromMinutes(5));", + "start_line": 1121, + "end_line": 1121, + "start_byte": 45753, + "end_byte": 45878 + }, + { + "name": "DisableChatty", + "code": "private void DisableChatty()\r\n {\r\n var result = RunAdbCommand(new[] { \"logcat\", \"-P\", \"'\\\"\\\"'\" }, TimeSpan.FromMinutes(1));\r\n\r\n if (!result.Succeeded)\r\n {\r\n _log.LogWarning($\"Unable to disable chatty. Logcat may hide what it finds to be repeating entries.\");\r\n }\r\n }", + "start_line": 1107, + "end_line": 1115, + "start_byte": 45378, + "end_byte": 45689 + }, + { + "name": "RunApkInstrumentation", + "code": "public ProcessExecutionResults RunApkInstrumentation(string apkName, string? instrumentationClassName, Dictionary args, TimeSpan timeout)\r\n {\r\n string displayName = string.IsNullOrEmpty(instrumentationClassName) ? \"{default}\" : instrumentationClassName;\r\n\r\n var adbArgs = new List\r\n {\r\n \"shell\", \"am\", \"instrument\"\r\n };\r\n\r\n adbArgs.AddRange(args.SelectMany(arg => new[] { \"-e\", arg.Key, arg.Value }));\r\n adbArgs.Add(\"-w\");\r\n\r\n if (string.IsNullOrEmpty(instrumentationClassName))\r\n {\r\n _log.LogInformation($\"Starting default instrumentation class on {apkName} (exit code 0 == success)\");\r\n adbArgs.Add(apkName);\r\n }\r\n else\r\n {\r\n _log.LogInformation($\"Starting instrumentation class '{instrumentationClassName}' on {apkName}\");\r\n adbArgs.Add($\"{apkName}/{instrumentationClassName}\");\r\n }\r\n\r\n var stopWatch = Stopwatch.StartNew();\r\n var result = RunAdbCommand(adbArgs, timeout);\r\n stopWatch.Stop();\r\n\r\n if (result.ExitCode == (int)AdbExitCodes.INSTRUMENTATION_TIMEOUT)\r\n {\r\n _log.LogWarning(\"Running instrumentation class {name} timed out after waiting {seconds} seconds\", displayName, stopWatch.Elapsed.TotalSeconds);\r\n }\r\n else\r\n {\r\n _log.LogInformation(\"Running instrumentation class {name} took {seconds} seconds\", displayName, stopWatch.Elapsed.TotalSeconds);\r\n }\r\n\r\n _log.LogDebug(result.ToString());\r\n\r\n return result;\r\n }", + "start_line": 1066, + "end_line": 1105, + "start_byte": 43776, + "end_byte": 45370 + }, + { + "name": "RunHeadlessCommand", + "code": "public ProcessExecutionResults RunHeadlessCommand(string testPath, string runtimePath, string testAssembly, string testScript, TimeSpan timeout)\r\n {\r\n var deviceTestPath = GlobalReadWriteDirectory + Path.AltDirectorySeparatorChar + new DirectoryInfo(testPath).Name + Path.AltDirectorySeparatorChar + testScript;\r\n var deviceRuntimePath = GlobalReadWriteDirectory + Path.AltDirectorySeparatorChar + \"runtime\" + Path.AltDirectorySeparatorChar + \"dotnet\";\r\n var adbArgs = new List\r\n {\r\n \"shell\",\r\n deviceTestPath,\r\n \"-r\",\r\n deviceRuntimePath,\r\n };\r\n\r\n _log.LogInformation($\"Setting executable permissions on {testScript} and runtime\");\r\n var result = RunAdbCommand(new[] { \"shell\", \"chmod\", \"a+x\", deviceTestPath, deviceRuntimePath });\r\n result.ThrowIfFailed($\"Failed setting permissions on {deviceTestPath} and {deviceRuntimePath}: {result}\");\r\n\r\n _log.LogInformation($\"Starting {testScript} from {deviceTestPath} (exit code 0 == success)\");\r\n\r\n\r\n var stopWatch = Stopwatch.StartNew();\r\n result = RunAdbCommand(adbArgs, timeout);\r\n stopWatch.Stop();\r\n\r\n if (result.ExitCode != (int)AdbExitCodes.SUCCESS)\r\n {\r\n _log.LogInformation($\"An error occurred running {testScript}\");\r\n }\r\n else\r\n {\r\n _log.LogInformation($\"Running command {testScript} took {stopWatch.Elapsed.TotalSeconds} seconds\");\r\n }\r\n\r\n _log.LogDebug(result.ToString());\r\n\r\n return result;\r\n }", + "start_line": 1029, + "end_line": 1064, + "start_byte": 42195, + "end_byte": 43768 + }, + { + "name": "SetActiveDevice", + "code": "public void SetActiveDevice(AndroidDevice? device)\r\n {\r\n _processManager.DeviceSerial = device?.DeviceSerial ?? string.Empty;\r\n _activeDevice = device;\r\n\r\n if (device is null)\r\n {\r\n _log.LogInformation($\"Active Android device unset\");\r\n }\r\n else\r\n {\r\n _log.LogInformation($\"Active Android device set to serial '{device.DeviceSerial}'\");\r\n }\r\n }", + "start_line": 1014, + "end_line": 1027, + "start_byte": 41759, + "end_byte": 42187 + }, + { + "name": "TestFileExists", + "code": "private bool TestFileExists(string path, string? deviceName = null)\r\n {\r\n var deviceTestPath = GlobalReadWriteDirectory + Path.AltDirectorySeparatorChar + new DirectoryInfo(path).Name;\r\n IEnumerable args = new string[] {\"shell\", \"stat\", deviceTestPath};\r\n\r\n if (!string.IsNullOrEmpty(deviceName))\r\n {\r\n args = new[] { \"-s\", deviceName }.Concat(args);\r\n }\r\n\r\n // Assumption: All Devices on a machine running Xharness should attempt to be online or disconnected.\r\n ProcessExecutionResults result = Retry(\r\n action: () => RunAdbCommand(args, TimeSpan.FromSeconds(30)),\r\n needsRetry: r =>\r\n {\r\n if (r.StandardError.Contains(\"device offline\", StringComparison.OrdinalIgnoreCase))\r\n {\r\n _log.LogWarning($\"Device {deviceName} is offline; retrying up to five minutes\");\r\n return true;\r\n }\r\n\r\n return false;\r\n },\r\n retryInterval: TimeSpan.FromSeconds(10),\r\n retryPeriod: TimeSpan.FromMinutes(5));\r\n\r\n if (!result.Succeeded)\r\n {\r\n _log.LogError($\"Failed to check existence of {deviceTestPath}. Check if a device is attached / emulator is started\" +\r\n Environment.NewLine + result.StandardError);\r\n\r\n return false;\r\n }\r\n\r\n return (result.ExitCode == 0);\r\n }", + "start_line": 977, + "end_line": 1012, + "start_byte": 40302, + "end_byte": 41751 + }, + { + "name": "GetDeviceProperty", + "code": "private string? GetDeviceProperty(AdbProperty property, string? deviceName = null)\r\n {\r\n IEnumerable args = s_commandList[property];\r\n\r\n if (!string.IsNullOrEmpty(deviceName))\r\n {\r\n args = new[] { \"-s\", deviceName }.Concat(args);\r\n }\r\n\r\n // Assumption: All Devices on a machine running Xharness should attempt to be online or disconnected.\r\n ProcessExecutionResults result = Retry(\r\n action: () => RunAdbCommand(args, TimeSpan.FromSeconds(30)),\r\n needsRetry: r =>\r\n {\r\n if (!r.Succeeded || r.StandardError.Contains(\"device offline\", StringComparison.OrdinalIgnoreCase))\r\n {\r\n _log.LogWarning($\"Device {deviceName} is offline; retrying up to five minutes\");\r\n return true;\r\n }\r\n\r\n return false;\r\n },\r\n retryInterval: TimeSpan.FromSeconds(10),\r\n retryPeriod: TimeSpan.FromMinutes(5));\r\n\r\n if (!result.Succeeded)\r\n {\r\n _log.LogError($\"Failed to get device's property {property}. Check if a device is attached / emulator is started\" +\r\n Environment.NewLine + result.StandardError);\r\n\r\n return null;\r\n }\r\n\r\n return result.StandardOutput.Trim();\r\n }", + "start_line": 941, + "end_line": 975, + "start_byte": 38955, + "end_byte": 40294 + }, + { + "name": "GetDevices", + "code": "private IReadOnlyCollection GetDevices(params AdbProperty[] propertiesToLoad)\r\n {\r\n string[] standardOutputLines = Array.Empty();\r\n\r\n _log.LogInformation(\"Finding attached devices/emulators...\");\r\n\r\n // Retry up to 3 mins til we get output; if the ADB server isn't started the output will come from a child process and we'll miss it.\r\n ProcessExecutionResults result = Retry(\r\n action: () => RunAdbCommand(new[] { \"devices\", \"-l\" }, TimeSpan.FromSeconds(30)),\r\n needsRetry: r =>\r\n {\r\n if (!r.Succeeded)\r\n {\r\n _log.LogDebug(\"Unexpected response from adb devices -l:\" + Environment.NewLine + r);\r\n return true;\r\n }\r\n\r\n standardOutputLines = r.StandardOutput.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);\r\n\r\n // We will keep retrying until we get something back like 'List of devices attached...{newline} {info about a device} ',\r\n // which when split on newlines ignoring empties will be at least 2 lines when there are any available devices.\r\n if (standardOutputLines.Length < 2)\r\n {\r\n _log.LogDebug(\"No attached devices found\" + Environment.NewLine + r);\r\n return true;\r\n }\r\n\r\n return false;\r\n },\r\n retryInterval: TimeSpan.FromSeconds(10),\r\n retryPeriod: TimeSpan.FromSeconds(90));\r\n\r\n result.ThrowIfFailed(\"Failed to enumerate attached devices\");\r\n\r\n // Two lines = At least one device was found. On a multi-device machine, we can't function without specifying device serial number.\r\n if (standardOutputLines.Length < 2)\r\n {\r\n // Abandon the run here, don't just guess.\r\n _log.LogWarning(\"No attached devices / emulators detected. \" +\r\n \"Check that any emulators have been started, and attached device(s) are connected via USB, powered-on, unlocked and authorized.\");\r\n return Array.Empty();\r\n }\r\n\r\n var devices = new List();\r\n\r\n _log.LogDebug($\"Found {standardOutputLines.Length - 1} possible devices\");\r\n\r\n // Start at 1 to skip first line, which is always 'List of devices attached'\r\n for (int lineNumber = 1; lineNumber < standardOutputLines.Length; lineNumber++)\r\n {\r\n _log.LogDebug($\"Evaluating output line for device serial: {standardOutputLines[lineNumber]}\");\r\n var lineParts = standardOutputLines[lineNumber].Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);\r\n\r\n var device = new AndroidDevice(lineParts[0]);\r\n\r\n foreach (var property in propertiesToLoad)\r\n {\r\n string? value = GetDeviceProperty(property, device.DeviceSerial);\r\n\r\n switch (property)\r\n {\r\n case AdbProperty.Architecture:\r\n device.Architecture = value;\r\n break;\r\n\r\n case AdbProperty.ApiVersion:\r\n device.ApiVersion = value == null ? null : int.Parse(value);\r\n break;\r\n\r\n case AdbProperty.SupportedArchitectures:\r\n device.SupportedArchitectures = value?.Split(new char[] { ',', '\\r', '\\n' });\r\n break;\r\n\r\n case AdbProperty.InstalledApps:\r\n device.InstalledApplications = value?.Split(\"\\n\");\r\n break;\r\n }\r\n }\r\n\r\n devices.Add(device);\r\n }\r\n\r\n return devices;\r\n }", + "start_line": 856, + "end_line": 939, + "start_byte": 35148, + "end_byte": 38947 + }, + { + "name": "GetDevice", + "code": "private AndroidDevice? GetDevice(\r\n bool singleDevice,\r\n bool loadArchitecture = false,\r\n bool loadApiVersion = false,\r\n string? requiredDeviceId = null,\r\n int? requiredApiVersion = null,\r\n IEnumerable? requiredArchitectures = null,\r\n string? requiredInstalledApp = null)\r\n {\r\n var devices = GetAllDevices(\r\n requiredDeviceId,\r\n requiredApiVersion,\r\n requiredArchitectures,\r\n requiredInstalledApp);\r\n\r\n if (devices.Count == 0)\r\n {\r\n _log.LogDebug($\"No suitable devices found\");\r\n\r\n if (singleDevice)\r\n {\r\n _log.LogError($\"Cannot find a suitable device, please check that a device is attached\");\r\n }\r\n\r\n return null;\r\n }\r\n\r\n if (singleDevice && devices.Count > 1)\r\n {\r\n _log.LogError($\"There is more than one suitable device. Please provide API version, device architecture or device ID\");\r\n return null;\r\n }\r\n\r\n var device = devices.First();\r\n _log.LogDebug($\"Found {devices.Count} possible devices. Using '{device.DeviceSerial}'\");\r\n\r\n SetActiveDevice(device);\r\n\r\n if (loadArchitecture && device.Architecture == null)\r\n {\r\n device.Architecture = GetDeviceProperty(AdbProperty.Architecture, device.DeviceSerial);\r\n }\r\n\r\n if (loadApiVersion && device.ApiVersion == null)\r\n {\r\n device.ApiVersion = GetDeviceApiVersion();\r\n }\r\n\r\n return device;\r\n }", + "start_line": 805, + "end_line": 854, + "start_byte": 33555, + "end_byte": 35140 + }, + { + "name": "GetAllDevices", + "code": "private IReadOnlyCollection GetAllDevices(\r\n string? requiredDeviceId = null,\r\n int? requiredApiVersion = null,\r\n IEnumerable? requiredArchitectures = null,\r\n string? requiredInstalledApp = null)\r\n {\r\n var properties = new List();\r\n\r\n if (requiredApiVersion.HasValue)\r\n {\r\n properties.Add(AdbProperty.ApiVersion);\r\n }\r\n\r\n if (requiredArchitectures?.Any() ?? false)\r\n {\r\n properties.Add(AdbProperty.SupportedArchitectures);\r\n }\r\n\r\n if (requiredInstalledApp != null)\r\n {\r\n properties.Add(AdbProperty.InstalledApps);\r\n }\r\n\r\n IReadOnlyCollection devices;\r\n\r\n try\r\n {\r\n devices = GetDevices(properties.ToArray());\r\n }\r\n catch (Exception toLog)\r\n {\r\n _log.LogError(toLog, $\"Exception thrown while trying to find compatible device\");\r\n return Array.Empty();\r\n }\r\n\r\n if (devices.Count == 0)\r\n {\r\n return Array.Empty();\r\n }\r\n\r\n if (requiredDeviceId != null)\r\n {\r\n devices = devices.Where(device => device.DeviceSerial == requiredDeviceId).ToList();\r\n\r\n if (devices.Count == 0)\r\n {\r\n _log.LogError($\"No attached device with ID {requiredDeviceId} found\");\r\n return devices;\r\n }\r\n }\r\n\r\n if (requiredApiVersion != null)\r\n {\r\n devices = devices.Where(device => device.ApiVersion == requiredApiVersion).ToList();\r\n\r\n if (devices.Count == 0)\r\n {\r\n _log.LogError($\"No attached device with API {requiredApiVersion} detected\");\r\n return devices;\r\n }\r\n }\r\n\r\n if (requiredArchitectures?.Any() ?? false)\r\n {\r\n devices = devices.Where(device => device.SupportedArchitectures?.Intersect(requiredArchitectures).Any() ?? false).ToList();\r\n\r\n if (devices.Count == 0)\r\n {\r\n _log.LogError($\"No attached device supports one of required architectures {string.Join(\", \", requiredArchitectures)}\");\r\n return devices;\r\n }\r\n }\r\n\r\n if (requiredInstalledApp != null)\r\n {\r\n if (requiredInstalledApp.StartsWith(\"package:\"))\r\n {\r\n devices = devices.Where(device => device.InstalledApplications?.Any(app => app.Contains(requiredInstalledApp)) ?? false).ToList();\r\n\r\n if (devices.Count == 0)\r\n {\r\n _log.LogError($\"No attached device with app {requiredInstalledApp} installed\");\r\n return devices;\r\n }\r\n }\r\n else if (requiredInstalledApp.StartsWith(\"filename:\"))\r\n {\r\n devices = devices.Where(device => TestFileExists(requiredInstalledApp.Substring(\"filename:\".Length), device.DeviceSerial)).ToList();\r\n\r\n if (devices.Count == 0)\r\n {\r\n _log.LogError($\"No attached device with file {requiredInstalledApp} installed\");\r\n return devices;\r\n }\r\n }\r\n else\r\n {\r\n _log.LogError($\"Could not understand required app \\\"{requiredInstalledApp}\\\"\");\r\n }\r\n }\r\n\r\n return devices;\r\n }", + "start_line": 701, + "end_line": 803, + "start_byte": 30069, + "end_byte": 33547 + }, + { + "name": "GetSingleDevice", + "code": "public AndroidDevice? GetSingleDevice(\r\n bool loadArchitecture = false,\r\n bool loadApiVersion = false,\r\n string? requiredDeviceId = null,\r\n int? requiredApiVersion = null,\r\n IEnumerable? requiredArchitectures = null,\r\n string? requiredInstalledApp = null) =>\r\n GetDevice(\r\n singleDevice: true,\r\n loadArchitecture,\r\n loadApiVersion,\r\n requiredDeviceId,\r\n requiredApiVersion,\r\n requiredArchitectures,\r\n requiredInstalledApp);", + "start_line": 677, + "end_line": 691, + "start_byte": 28871, + "end_byte": 29460 + }, + { + "name": "GetDevice", + "code": "public AndroidDevice? GetDevice(\r\n bool loadArchitecture = false,\r\n bool loadApiVersion = false,\r\n string? requiredDeviceId = null,\r\n int? requiredApiVersion = null,\r\n IEnumerable? requiredArchitectures = null,\r\n string? requiredInstalledApp = null) =>\r\n GetDevice(\r\n singleDevice: false,\r\n loadArchitecture,\r\n loadApiVersion,\r\n requiredDeviceId,\r\n requiredApiVersion,\r\n requiredArchitectures,\r\n requiredInstalledApp);", + "start_line": 651, + "end_line": 665, + "start_byte": 27496, + "end_byte": 28080 + }, + { + "name": "GetDevices", + "code": "public IReadOnlyCollection GetDevices() => GetDevices(\r\n AdbProperty.Architecture,\r\n AdbProperty.ApiVersion,\r\n AdbProperty.SupportedArchitectures);", + "start_line": 636, + "end_line": 639, + "start_byte": 26522, + "end_byte": 26705 + }, + { + "name": "HeadlessPullFiles", + "code": "public int HeadlessPullFiles(string devicePath, string localPath)\r\n {\r\n if (string.IsNullOrEmpty(localPath))\r\n {\r\n throw new ArgumentNullException(nameof(localPath));\r\n }\r\n\r\n Directory.CreateDirectory(localPath);\r\n _log.LogInformation($\"Attempting to pull contents of {devicePath} to {localPath}\");\r\n\r\n var result = RunAdbCommand(new[] { \"pull\", devicePath, localPath });\r\n\r\n if (result.ExitCode != (int)AdbExitCodes.SUCCESS)\r\n {\r\n _log.LogError($\"Failed to pull file.\");\r\n }\r\n return (int)AdbExitCodes.SUCCESS;\r\n }", + "start_line": 614, + "end_line": 631, + "start_byte": 25805, + "end_byte": 26418 + }, + { + "name": "PullFiles", + "code": "public List PullFiles(string apkPackageName, string devicePath, string localPath)\r\n {\r\n if (string.IsNullOrEmpty(localPath))\r\n {\r\n throw new ArgumentNullException(nameof(localPath));\r\n }\r\n\r\n string tempFolder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());\r\n try\r\n {\r\n Directory.CreateDirectory(tempFolder);\r\n Directory.CreateDirectory(localPath);\r\n _log.LogInformation($\"Attempting to pull contents of {devicePath} to {localPath}\");\r\n var copiedFiles = new List();\r\n\r\n var result = RunAdbCommand(new[] { \"pull\", devicePath, tempFolder });\r\n\r\n if (result.ExitCode != (int)AdbExitCodes.SUCCESS)\r\n {\r\n if (GetDeviceApiVersion() != 30)\r\n {\r\n throw new AdbFailureException($\"Failed pulling files: {result}\");\r\n }\r\n\r\n // On Android API 30 we can't use \"adb pull\" directly due to permission issues on emulators, see https://github.com/dotnet/xharness/issues/385\r\n // As a workaround we copy the files to the temp directory on the device using \"run-as\" and pull from there\r\n _log.LogInformation($\"Failed to pull file. Device is running Android API 30, trying fallback to pull {devicePath}\");\r\n\r\n result = RunAdbCommand(new[] { \"shell\", \"run-as\", apkPackageName, \"ls\", devicePath });\r\n result.ThrowIfFailed($\"Failed checking for file using fallback: {result}\");\r\n\r\n string? fileName = devicePath.Split(\"/\").LastOrDefault();\r\n if (string.IsNullOrWhiteSpace(fileName))\r\n {\r\n throw new AdbFailureException($\"Failed pulling file using fallback: Couldn't determine filename for {devicePath}\");\r\n }\r\n\r\n string deviceTempPath = $\"/data/local/tmp/{fileName}\";\r\n\r\n result = RunAdbCommand(new[] { \"shell\", \"rm\", \"-rf\", deviceTempPath });\r\n result.ThrowIfFailed($\"Failed removing {deviceTempPath} before using fallback: {result}\");\r\n\r\n result = RunAdbCommand(new[] { \"shell\", \"touch\", deviceTempPath });\r\n result.ThrowIfFailed($\"Failed touching {deviceTempPath}: {result}\");\r\n\r\n result = RunAdbCommand(new[] { \"shell\", \"run-as\", apkPackageName, \"cp\", devicePath, deviceTempPath });\r\n result.ThrowIfFailed($\"Failed copying file using fallback: {result}\");\r\n\r\n result = RunAdbCommand(new[] { \"pull\", deviceTempPath, tempFolder });\r\n result.ThrowIfFailed($\"Failed pulling file using fallback: {result}\");\r\n\r\n result = RunAdbCommand(new[] { \"shell\", \"rm\", \"-f\", deviceTempPath });\r\n result.ThrowIfFailed($\"Failed removing {deviceTempPath} after using fallback: {result}\");\r\n }\r\n\r\n var copiedToTemp = Directory.GetFiles(tempFolder, \"*\", SearchOption.AllDirectories);\r\n foreach (var filePath in copiedToTemp)\r\n {\r\n var relativePath = Path.GetRelativePath(tempFolder, filePath);\r\n var destinationPath = Path.Combine(localPath, relativePath);\r\n // if the file is already there, just warn and skip it.\r\n if (File.Exists(destinationPath))\r\n {\r\n _log.LogWarning($\"Skipping file copy as {destinationPath} already exists\");\r\n }\r\n else\r\n {\r\n Directory.CreateDirectory(Path.GetDirectoryName(destinationPath) ?? throw new ArgumentException(nameof(destinationPath)));\r\n File.Move(filePath, destinationPath);\r\n copiedFiles.Add(destinationPath);\r\n }\r\n }\r\n\r\n _log.LogDebug($\"Copied {copiedFiles.Count} files to {localPath}\");\r\n return copiedFiles;\r\n }\r\n finally\r\n {\r\n Directory.Delete(tempFolder, true);\r\n }\r\n }", + "start_line": 531, + "end_line": 611, + "start_byte": 21661, + "end_byte": 25709 + }, + { + "name": "KillProcess", + "code": "public int KillProcess(string testName)\r\n {\r\n _log.LogInformation($\"Killing all running processes for '{testName}': \");\r\n var result = RunAdbCommand(new[] { \"shell\", \"pkill\", testName });\r\n if (result.ExitCode != (int)AdbExitCodes.SUCCESS)\r\n {\r\n _log.LogError($\"Failed to kill process by name ({testName}):{Environment.NewLine}{result}\");\r\n\r\n }\r\n else\r\n {\r\n _log.LogDebug($\"Process {testName} killed!{Environment.NewLine}{result.StandardOutput}\");\r\n\r\n }\r\n return result.ExitCode;\r\n }", + "start_line": 513, + "end_line": 528, + "start_byte": 20995, + "end_byte": 21569 + }, + { + "name": "KillApk", + "code": "public int KillApk(string apkName)\r\n {\r\n _log.LogInformation($\"Killing all running processes for '{apkName}': \");\r\n var result = RunAdbCommand(new[] { \"shell\", \"am\", \"kill\", \"--user\", \"all\", apkName });\r\n if (result.ExitCode != (int)AdbExitCodes.SUCCESS)\r\n {\r\n _log.LogError($\"Error:{Environment.NewLine}{result}\");\r\n }\r\n else\r\n {\r\n _log.LogDebug($\"Success!{Environment.NewLine}{result.StandardOutput}\");\r\n }\r\n return result.ExitCode;\r\n }", + "start_line": 498, + "end_line": 511, + "start_byte": 20458, + "end_byte": 20987 + }, + { + "name": "UninstallApk", + "code": "public int UninstallApk(string apkName)\r\n {\r\n if (string.IsNullOrEmpty(apkName))\r\n {\r\n throw new ArgumentNullException(nameof(apkName));\r\n }\r\n\r\n _log.LogInformation($\"Attempting to remove apk '{apkName}'..\");\r\n var result = RunAdbCommand(new[] { \"uninstall\", apkName });\r\n\r\n // See note above in install()\r\n if (result.ExitCode == (int)AdbExitCodes.ADB_BROKEN_PIPE)\r\n {\r\n _log.LogWarning($\"Hit broken pipe error; Will make one attempt to restart ADB server, and retry the uninstallation\");\r\n\r\n KillAdbServer();\r\n StartAdbServer();\r\n result = RunAdbCommand(new[] { \"uninstall\", apkName });\r\n }\r\n\r\n if (result.ExitCode == (int)AdbExitCodes.SUCCESS)\r\n {\r\n _log.LogInformation($\"Successfully uninstalled {apkName}\");\r\n }\r\n else if (result.ExitCode == (int)AdbExitCodes.ADB_UNINSTALL_APP_NOT_ON_DEVICE ||\r\n result.ExitCode == (int)AdbExitCodes.ADB_UNINSTALL_APP_NOT_ON_EMULATOR)\r\n {\r\n _log.LogInformation($\"APK '{apkName}' was not on device\");\r\n }\r\n else\r\n {\r\n _log.LogError(message: $\"Error: {result}\");\r\n }\r\n\r\n return result.ExitCode;\r\n }", + "start_line": 460, + "end_line": 495, + "start_byte": 19074, + "end_byte": 20352 + }, + { + "name": "DeleteHeadlessFolder", + "code": "public int DeleteHeadlessFolder(string testPath)\r\n {\r\n if (string.IsNullOrEmpty(testPath))\r\n {\r\n throw new ArgumentNullException(nameof(testPath));\r\n }\r\n\r\n var fullTestPath = GlobalReadWriteDirectory + Path.AltDirectorySeparatorChar + new DirectoryInfo(testPath).Name;\r\n\r\n _log.LogInformation($\"Attempting to remove folder '{fullTestPath}'..\");\r\n var result = RunAdbCommand(new[] { \"shell\", \"rm\", \"-fr\", fullTestPath });\r\n\r\n // See note above in install()\r\n if (result.ExitCode == (int)AdbExitCodes.ADB_BROKEN_PIPE)\r\n {\r\n _log.LogWarning($\"Hit broken pipe error; Will make one attempt to restart ADB server, and retry the uninstallation\");\r\n\r\n KillAdbServer();\r\n StartAdbServer();\r\n result = RunAdbCommand(new[] { \"shell\", \"rm\", \"-fr\", fullTestPath });\r\n }\r\n\r\n if (result.ExitCode == (int)AdbExitCodes.SUCCESS)\r\n {\r\n _log.LogInformation($\"Successfully uninstalled {fullTestPath}\");\r\n }\r\n else\r\n {\r\n _log.LogError(message: $\"Failed to uninstall {fullTestPath}: {result}\");\r\n\r\n }\r\n\r\n return result.ExitCode;\r\n }", + "start_line": 425, + "end_line": 458, + "start_byte": 17854, + "end_byte": 19066 + }, + { + "name": "InstallApk", + "code": "public int InstallApk(string apkPath)\r\n {\r\n _log.LogInformation($\"Attempting to install {apkPath}\");\r\n\r\n if (string.IsNullOrEmpty(apkPath))\r\n {\r\n throw new ArgumentException($\"No value supplied for {nameof(apkPath)} \");\r\n }\r\n\r\n if (!File.Exists(apkPath))\r\n {\r\n throw new FileNotFoundException($\"Could not find {apkPath}\", apkPath);\r\n }\r\n\r\n var result = RunAdbCommand(new[] { \"install\", apkPath });\r\n\r\n // Two possible retry scenarios, theoretically both can happen on the same run:\r\n\r\n // 1. Pipe between ADB server and emulator device is broken; restarting the ADB server helps\r\n if (result.ExitCode == (int)AdbExitCodes.ADB_BROKEN_PIPE || result.StandardError.Contains(AdbInstallBrokenPipeError))\r\n {\r\n _log.LogWarning($\"Hit broken pipe error; Will make one attempt to restart ADB server, then retry the install\");\r\n KillAdbServer();\r\n StartAdbServer();\r\n result = RunAdbCommand(new[] { \"install\", apkPath });\r\n }\r\n\r\n // 2. Installation cache on device is messed up; restarting the device reliably seems to unblock this (unless the device is actually full, if so this will error the same)\r\n if (result.ExitCode != (int)AdbExitCodes.SUCCESS && result.StandardError.Contains(AdbDeviceFullInstallFailureMessage))\r\n {\r\n _log.LogWarning($\"It seems the package installation cache may be full on the device. We'll try to reboot it before trying one more time.{Environment.NewLine}Output:{result}\");\r\n RebootAndroidDevice();\r\n WaitForDevice();\r\n result = RunAdbCommand(new[] { \"install\", apkPath });\r\n }\r\n\r\n // 3. Installation timed out or failed with exception; restarting the ADB server, reboot the device and give more time for installation\r\n // installer might hang up so we need to clean it up and free memory\r\n if (result.ExitCode == (int)AdbExitCodes.INSTRUMENTATION_TIMEOUT || (result.ExitCode != (int)AdbExitCodes.SUCCESS && result.StandardError.Contains(AdbInstallException)))\r\n {\r\n _log.LogWarning($\"Installation failed; Will make one attempt to restart ADB server and the device, then retry the install\");\r\n KillAdbServer();\r\n StartAdbServer();\r\n RebootAndroidDevice();\r\n WaitForDevice();\r\n result = RunAdbCommand(new[] { \"install\", apkPath }, TimeSpan.FromMinutes(10));\r\n }\r\n\r\n if (result.ExitCode != 0)\r\n {\r\n _log.LogError($\"Error:{Environment.NewLine}{result}\");\r\n }\r\n else\r\n {\r\n _log.LogInformation($\"Successfully installed {apkPath}\");\r\n }\r\n\r\n return result.ExitCode;\r\n }", + "start_line": 365, + "end_line": 423, + "start_byte": 15056, + "end_byte": 17846 + }, + { + "name": "CopyHeadlessFolder", + "code": "public int CopyHeadlessFolder(string testPath, bool sharedRuntime = false)\r\n {\r\n _log.LogInformation($\"Attempting to install {testPath}\");\r\n\r\n if (string.IsNullOrEmpty(testPath))\r\n {\r\n throw new ArgumentException($\"No value supplied for {nameof(testPath)} \");\r\n }\r\n\r\n if (!Directory.Exists(testPath))\r\n {\r\n throw new FileNotFoundException($\"Could not find {testPath}\", testPath);\r\n }\r\n\r\n var targetDirectory = GlobalReadWriteDirectory + Path.AltDirectorySeparatorChar + new DirectoryInfo(testPath).Name;\r\n if (sharedRuntime)\r\n {\r\n targetDirectory = GlobalReadWriteDirectory + Path.AltDirectorySeparatorChar + \"runtime\";\r\n }\r\n var result = RunAdbCommand(new[] { \"push\", testPath, targetDirectory });\r\n\r\n\r\n // Two possible retry scenarios, theoretically both can happen on the same run:\r\n\r\n // 1. Pipe between ADB server and emulator device is broken; restarting the ADB server helps\r\n if (result.ExitCode == (int)AdbExitCodes.ADB_BROKEN_PIPE || result.StandardError.Contains(AdbInstallBrokenPipeError))\r\n {\r\n _log.LogWarning($\"Hit broken pipe error; Will make one attempt to restart ADB server, then retry the install\");\r\n KillAdbServer();\r\n StartAdbServer();\r\n result = RunAdbCommand(new[] { \"push\", testPath, targetDirectory });\r\n }\r\n\r\n // 2. Installation cache on device is messed up; restarting the device reliably seems to unblock this (unless the device is actually full, if so this will error the same)\r\n if (result.ExitCode != (int)AdbExitCodes.SUCCESS && result.StandardError.Contains(AdbDeviceFullInstallFailureMessage))\r\n {\r\n _log.LogWarning($\"It seems the package installation cache may be full on the device. We'll try to reboot it before trying one more time.{Environment.NewLine}Output:{result}\");\r\n RebootAndroidDevice();\r\n WaitForDevice();\r\n result = RunAdbCommand(new[] { \"push\", testPath, targetDirectory });\r\n }\r\n\r\n // 3. Installation timed out or failed with exception; restarting the ADB server, reboot the device and give more time for installation\r\n // installer might hang up so we need to clean it up and free memory\r\n if (result.ExitCode == (int)AdbExitCodes.INSTRUMENTATION_TIMEOUT || (result.ExitCode != (int)AdbExitCodes.SUCCESS && result.StandardError.Contains(AdbInstallException)))\r\n {\r\n _log.LogWarning($\"Installation failed; Will make one attempt to restart ADB server and the device, then retry the install\");\r\n KillAdbServer();\r\n StartAdbServer();\r\n RebootAndroidDevice();\r\n WaitForDevice();\r\n result = RunAdbCommand(new[] { \"push\", testPath, targetDirectory }, TimeSpan.FromMinutes(10));\r\n }\r\n\r\n if (result.ExitCode != 0)\r\n {\r\n _log.LogError($\"Error:{Environment.NewLine}{result}\");\r\n }\r\n else\r\n {\r\n _log.LogInformation($\"Successfully installed {testPath} to {targetDirectory}\");\r\n }\r\n\r\n return result.ExitCode;\r\n }", + "start_line": 299, + "end_line": 363, + "start_byte": 11847, + "end_byte": 15048 + }, + { + "name": "KillAdbServer", + "code": "public void KillAdbServer() => RunAdbCommand(new[] { \"kill-server\" }).ThrowIfFailed(\"Error killing ADB Server\");", + "start_line": 297, + "end_line": 297, + "start_byte": 11727, + "end_byte": 11839 + }, + { + "name": "StartAdbServer", + "code": "public void StartAdbServer()\r\n {\r\n bool started = Retry(\r\n () =>\r\n {\r\n var result = RunAdbCommand(new[] { \"start-server\" }, TimeSpan.FromMinutes(1));\r\n started = result.Succeeded;\r\n\r\n if (!started)\r\n {\r\n _log.LogWarning($\"Error starting the ADB server\" + Environment.NewLine + result);\r\n\r\n try\r\n {\r\n KillAdbServer();\r\n }\r\n catch (Exception e)\r\n {\r\n _log.LogError($\"Error killing ADB server after a failed start: {e.Message}\");\r\n }\r\n }\r\n else\r\n {\r\n _log.LogDebug(result.StandardOutput);\r\n }\r\n\r\n return started;\r\n },\r\n retryInterval: TimeSpan.FromSeconds(10),\r\n retryPeriod: TimeSpan.FromMinutes(5));\r\n\r\n if (!started)\r\n {\r\n throw new AdbFailureException(\"Failed to start the ADB server\");\r\n }\r\n }", + "start_line": 260, + "end_line": 295, + "start_byte": 10591, + "end_byte": 11719 + }, + { + "name": "WaitForDevice", + "code": "public bool WaitForDevice()\r\n {\r\n // This command waits for ANY kind of device to be available (emulator or real)\r\n // Needed because emulators start up asynchronously and take a while.\r\n // (Returns instantly if device is ready)\r\n // This can fail if _currentDevice is unset if there are multiple devices.\r\n _log.LogInformation(\"Waiting for device to be available (max 5 minutes)\");\r\n RunAdbCommand(new[] { \"wait-for-device\" }, TimeSpan.FromMinutes(5))\r\n .ThrowIfFailed(\"Error waiting for Android device/emulator\");\r\n\r\n // Some users will be installing the emulator and immediately calling xharness, they need to be able to expect the device is ready to load APKs.\r\n // Once wait-for-device returns, we'll give it up to TimeToWaitForBootCompletion (default 5 min) for 'adb shell getprop sys.boot_completed'\r\n // to be '1' (as opposed to empty) to make subsequent automation happy.\r\n var watch = Stopwatch.StartNew();\r\n bool bootCompleted = Retry(\r\n () =>\r\n {\r\n string? result = GetDeviceProperty(AdbProperty.BootCompletion, _activeDevice?.DeviceSerial);\r\n _log.LogDebug($\"sys.boot_completed = '{result}'\");\r\n return result?.StartsWith('1') ?? false;\r\n },\r\n retryInterval: TimeSpan.FromSeconds(10),\r\n retryPeriod: TimeToWaitForBootCompletion);\r\n\r\n if (bootCompleted)\r\n {\r\n _log.LogDebug($\"Waited {(int)watch.Elapsed.TotalSeconds} seconds for device boot completion\");\r\n return true;\r\n }\r\n else\r\n {\r\n _log.LogError($\"Did not detect boot completion variable on device; device may be in a bad state\");\r\n return false;\r\n }\r\n }", + "start_line": 224, + "end_line": 258, + "start_byte": 8781, + "end_byte": 10583 + }, + { + "name": "CheckPackageVerificationSettings", + "code": "public void CheckPackageVerificationSettings()\r\n {\r\n _log.LogDebug(\"Check current adb install and/or package verification settings\");\r\n\r\n VerifyPackageVerificationSettingValue(\"verifier_verify_adb_installs\", expectedValue: 0);\r\n VerifyPackageVerificationSettingValue(\"package_verifier_enable\", expectedValue: 0);\r\n }", + "start_line": 216, + "end_line": 222, + "start_byte": 8430, + "end_byte": 8773 + }, + { + "name": "VerifyPackageVerificationSettingValue", + "code": "private void VerifyPackageVerificationSettingValue(string settingName, int expectedValue)\r\n {\r\n var result = RunAdbCommand(new[] { \"shell\", \"settings\", \"get\", \"global\", settingName });\r\n var settingValue = GetSettingValue(result.StandardOutput.Trim());\r\n _log.LogDebug($\"{settingName} = {settingValue}\");\r\n\r\n if (settingValue != expectedValue)\r\n _log.LogWarning($\"Installing debug apks on a device might be rejected with INSTALL_FAILED_VERIFICATION_FAILURE. Make sure to set '{settingName}' to '{expectedValue}'\");\r\n }", + "start_line": 206, + "end_line": 214, + "start_byte": 7859, + "end_byte": 8422 + }, + { + "name": "GetSettingValue", + "code": "private static int? GetSettingValue (string value)\r\n {\r\n if (int.TryParse(value, out int result))\r\n {\r\n return result;\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n }", + "start_line": 194, + "end_line": 204, + "start_byte": 7625, + "end_byte": 7851 + }, + { + "name": "GetDeviceApiVersion", + "code": "public int GetDeviceApiVersion()\r\n {\r\n if (_activeDevice?.ApiVersion != null)\r\n {\r\n return _activeDevice.ApiVersion.Value;\r\n }\r\n\r\n string? output = GetDeviceProperty(AdbProperty.ApiVersion, _activeDevice?.DeviceSerial);\r\n\r\n if (output == null)\r\n {\r\n throw new Exception(\"Failed to get device's API version\");\r\n }\r\n\r\n var apiVersion = int.Parse(output);\r\n\r\n if (_activeDevice != null)\r\n {\r\n _activeDevice.ApiVersion = apiVersion;\r\n }\r\n\r\n return apiVersion;\r\n }", + "start_line": 170, + "end_line": 192, + "start_byte": 7035, + "end_byte": 7617 + }, + { + "name": "DumpBugReport", + "code": "public string DumpBugReport(string outputFilePathWithoutFormat)\r\n {\r\n var reportManager = AdbReportFactory.CreateReportManager(_log, GetDeviceApiVersion());\r\n return reportManager.DumpBugReport(this, outputFilePathWithoutFormat);\r\n }", + "start_line": 164, + "end_line": 168, + "start_byte": 6774, + "end_byte": 7027 + }, + { + "name": "TryDumpAdbLog", + "code": "public bool TryDumpAdbLog(string outputFilePath, string filterSpec = \"\")\r\n {\r\n // Workaround: Doesn't seem to have a flush() function and sometimes it doesn't have the full log on emulators.\r\n Thread.Sleep(3000);\r\n\r\n var result = RunAdbCommand(new[] { \"logcat\", \"-d\", filterSpec }, TimeSpan.FromMinutes(2));\r\n if (result.ExitCode != 0)\r\n {\r\n // Could throw here, but it would tear down a possibly otherwise acceptable execution.\r\n _log.LogError($\"Error getting ADB log:{Environment.NewLine}{result}\");\r\n return false;\r\n }\r\n else\r\n {\r\n Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath) ?? throw new ArgumentNullException(nameof(outputFilePath)));\r\n File.WriteAllText(outputFilePath, result.StandardOutput);\r\n _log.LogInformation($\"Wrote current ADB log to {outputFilePath}\");\r\n // The adb log is not directly accessible.\r\n // Hence, we duplicate the log to the main console log to simplify the UX of failure investigation.\r\n _log.LogInformation($\"ADB log output:{Environment.NewLine}{result.StandardOutput}\");\r\n return true;\r\n }\r\n }", + "start_line": 140, + "end_line": 162, + "start_byte": 5542, + "end_byte": 6766 + }, + { + "name": "EnableWifi", + "code": "public void EnableWifi(bool enable) => RunAdbCommand(\"shell\", \"svc\", \"wifi\", enable ? \"enable\" : \"disable\")\r\n .ThrowIfFailed($\"Failed to {(enable ? \"enable\" : \"disable\")} WiFi on the device\");", + "start_line": 137, + "end_line": 138, + "start_byte": 5335, + "end_byte": 5534 + }, + { + "name": "ClearAdbLog", + "code": "public void ClearAdbLog()\r\n {\r\n RunAdbCommand(\"logcat\", \"-b\", \"all\", \"-c\");\r\n\r\n // Android logs can unnecessarily hide log entries, so disable\r\n DisableChatty();\r\n }", + "start_line": 129, + "end_line": 135, + "start_byte": 5135, + "end_byte": 5327 + }, + { + "name": "RebootAndroidDevice", + "code": "public string RebootAndroidDevice()\r\n {\r\n var result = RunAdbCommand(\"reboot\");\r\n result.ThrowIfFailed(\"Failed to reboot the device\");\r\n return result.StandardOutput;\r\n }", + "start_line": 122, + "end_line": 127, + "start_byte": 4930, + "end_byte": 5127 + }, + { + "name": "GetAdbState", + "code": "public string GetAdbState() => RunAdbCommand(\"get-state\").StandardOutput;", + "start_line": 120, + "end_line": 120, + "start_byte": 4849, + "end_byte": 4922 + }, + { + "name": "GetAdbVersion", + "code": "public string GetAdbVersion()\r\n {\r\n var result = RunAdbCommand(\"version\");\r\n result.ThrowIfFailed(\"Failed to get ADB version\");\r\n return result.StandardOutput;\r\n }", + "start_line": 113, + "end_line": 118, + "start_byte": 4651, + "end_byte": 4841 + }, + { + "name": "GetCliAdbExePath", + "code": "private static string GetCliAdbExePath()\r\n {\r\n var currentAssemblyDirectory = Path.GetDirectoryName(typeof(AdbRunner).Assembly.Location);\r\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\r\n {\r\n return Path.Join(currentAssemblyDirectory, @\"..\\..\\..\\runtimes\\any\\native\\adb\\windows\\adb.exe\");\r\n }\r\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))\r\n {\r\n return Path.Join(currentAssemblyDirectory, @\"../../../runtimes/any/native/adb/linux/adb\");\r\n }\r\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\r\n {\r\n return Path.Join(currentAssemblyDirectory, @\"../../../runtimes/any/native/adb/macos/adb\");\r\n }\r\n throw new NotSupportedException(\"Cannot determine OS platform being used, thus we can not select an ADB executable\");\r\n }", + "start_line": 89, + "end_line": 105, + "start_byte": 3641, + "end_byte": 4508 + } + ], + "src/Microsoft.DotNet.XHarness.Android/AndroidDevice.cs": [], + "src/Microsoft.DotNet.XHarness.Android/AdbFailureException.cs": [], + "src/Microsoft.DotNet.XHarness.Android/ApkHelper.cs": [ + { + "name": "GetApkSupportedArchitectures", + "code": "public static List GetApkSupportedArchitectures(string apkPath)\n {\n if (string.IsNullOrEmpty(apkPath))\n {\n throw new ArgumentException(\"Please supply a value for apkPath\");\n }\n if (!File.Exists(apkPath))\n {\n throw new FileNotFoundException($\"Invalid APK Path: '{apkPath}'\", apkPath);\n }\n if (!Path.GetExtension(apkPath).Equals(\".apk\", StringComparison.OrdinalIgnoreCase))\n {\n throw new InvalidOperationException(\"Only know how to open APK files.\");\n }\n\n using (ZipArchive archive = ZipFile.Open(apkPath, ZipArchiveMode.Read))\n {\n // Enumerate all folders under /lib inside the zip\n var allLibFolders = archive.Entries.Where(e => e.FullName.StartsWith(\"lib/\"))\n .Select(e => e.FullName[4..e.FullName.IndexOf('/', 4)])\n .Distinct().ToList();\n\n return allLibFolders;\n }\n }", + "start_line": 11, + "end_line": 35, + "start_byte": 199, + "end_byte": 1224 + } + ], + "src/Microsoft.DotNet.XHarness.Android/InstrumentationRunner.cs": [ + { + "name": "ParseInstrumentationOutputs", + "code": "private IReadOnlyDictionary ParseInstrumentationOutputs(string stdout)\n {\n var outputs = new Dictionary();\n string[] lines = stdout.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);\n\n foreach (string line in lines.Where(line => line.StartsWith(InstrumentationResultPrefix)))\n {\n var subString = line.Substring(InstrumentationResultPrefix.Length);\n string[] results = subString.Trim().Split('=');\n if (results.Length == 2)\n {\n var key = results[0];\n var value = results[1];\n\n if (outputs.ContainsKey(key))\n {\n _logger.LogWarning($\"Key '{key}' defined more than once\");\n outputs[key] = value;\n }\n else\n {\n outputs.Add(key, value);\n }\n }\n else\n {\n _logger.LogWarning($\"Skipping output line due to key-value-pair parse failure: '{line}'\");\n }\n }\n\n return outputs;\n }", + "start_line": 193, + "end_line": 224, + "start_byte": 7431, + "end_byte": 8603 + }, + { + "name": "PullResultXMLs", + "code": "private bool PullResultXMLs(string apkPackageName, string outputDirectory, IReadOnlyDictionary resultValues)\n {\n bool success = false;\n\n foreach (string possibleResultKey in s_xmlOutputVariableNames)\n {\n if (!resultValues.TryGetValue(possibleResultKey, out string? resultFile))\n {\n continue;\n }\n\n _logger.LogInformation($\"Found XML result file: '{resultFile}'(key: {possibleResultKey})\");\n\n try\n {\n _runner.PullFiles(apkPackageName, resultFile, outputDirectory);\n }\n catch (Exception toLog)\n {\n _logger.LogError(toLog, \"Hit error (typically permissions) trying to pull {filePathOnDevice}\", resultFile);\n success = true;\n }\n }\n\n return success;\n }", + "start_line": 166, + "end_line": 191, + "start_byte": 6552, + "end_byte": 7425 + }, + { + "name": "ParseInstrumentationResult", + "code": "private (int? ExitCode, bool Crashed, bool FilePullFailed) ParseInstrumentationResult(string apkPackageName, string outputDirectory, string result)\n {\n // This is where test instrumentation can communicate outwardly that test execution failed\n IReadOnlyDictionary resultValues = ParseInstrumentationOutputs(result);\n\n // Pull XUnit result XMLs off the device\n bool failurePullingFiles = PullResultXMLs(apkPackageName, outputDirectory, resultValues)!;\n bool processCrashed = false;\n\n if (resultValues.TryGetValue(TestRunSummaryVariableName, out string? testRunSummary))\n {\n _logger.LogInformation($\"Test execution summary:{Environment.NewLine}{testRunSummary}\");\n }\n\n if (resultValues.TryGetValue(ShortMessageVariableName, out string? shortMessage))\n {\n _logger.LogInformation($\"Short message:{Environment.NewLine}{shortMessage}\");\n processCrashed = shortMessage.Contains(ProcessCrashedShortMessage);\n }\n\n // Due to the particulars of how instrumentations work, ADB will report a 0 exit code for crashed instrumentations\n // We'll change that to a specific value and print a message explaining why.\n int? instrumentationExitCode = null;\n if (resultValues.TryGetValue(ReturnCodeVariableName, out string? returnCode))\n {\n if (int.TryParse(returnCode, out int parsedExitCode))\n {\n _logger.LogInformation($\"Instrumentation finished normally with exit code {parsedExitCode}\");\n instrumentationExitCode = parsedExitCode;\n }\n else\n {\n _logger.LogError($\"Un-parse-able value for '{ReturnCodeVariableName}' : '{returnCode}'\");\n }\n }\n else\n {\n _logger.LogError($\"No value for '{ReturnCodeVariableName}' provided in instrumentation result. This may indicate a crashed test (see log)\");\n }\n\n return (ExitCode: instrumentationExitCode, Crashed: processCrashed, FilePullFailed: failurePullingFiles);\n }", + "start_line": 123, + "end_line": 164, + "start_byte": 4435, + "end_byte": 6546 + }, + { + "name": "RunApkInstrumentation", + "code": "public ExitCode RunApkInstrumentation(\n string apkPackageName,\n string? instrumentationName,\n Dictionary instrumentationArguments,\n string outputDirectory,\n string? deviceOutputFolder,\n TimeSpan timeout,\n int expectedExitCode)\n {\n int? instrumentationExitCode = null;\n\n // No class name = default Instrumentation\n ProcessExecutionResults result = _runner.RunApkInstrumentation(apkPackageName, instrumentationName, instrumentationArguments, timeout);\n\n bool processCrashed = false;\n bool failurePullingFiles = false;\n bool logCatSucceeded;\n\n using (_logger.BeginScope(\"Post-test copy and cleanup\"))\n {\n if (result.ExitCode == (int)ExitCode.SUCCESS)\n {\n (instrumentationExitCode, processCrashed, failurePullingFiles) = ParseInstrumentationResult(apkPackageName, outputDirectory, result.StandardOutput);\n }\n\n // Optionally copy off an entire folder\n if (!string.IsNullOrEmpty(deviceOutputFolder))\n {\n try\n {\n var logs = _runner.PullFiles(apkPackageName, deviceOutputFolder, outputDirectory);\n foreach (string log in logs)\n {\n _logger.LogDebug($\"Found output file: {log}\");\n }\n }\n catch (Exception toLog)\n {\n _logger.LogError(toLog, \"Hit error (typically permissions) trying to pull {filePathOnDevice}\", deviceOutputFolder);\n failurePullingFiles = true;\n }\n }\n\n logCatSucceeded = _runner.TryDumpAdbLog(Path.Combine(outputDirectory, $\"adb-logcat-{apkPackageName}-{(instrumentationName ?? \"default\")}.log\"));\n\n if (processCrashed)\n {\n _runner.DumpBugReport(Path.Combine(outputDirectory, $\"adb-bugreport-{apkPackageName}\"));\n }\n }\n\n // In case emulator crashes halfway through, we can tell by failing to pull ADB logs from it\n if (!logCatSucceeded)\n {\n return ExitCode.SIMULATOR_FAILURE;\n }\n\n if (result.ExitCode == (int)AdbExitCodes.INSTRUMENTATION_TIMEOUT)\n {\n return ExitCode.TIMED_OUT;\n }\n\n if (processCrashed)\n {\n return ExitCode.APP_CRASH;\n }\n\n if (failurePullingFiles)\n {\n _logger.LogError($\"Received expected instrumentation exit code ({instrumentationExitCode}), \" +\n \"but we hit errors pulling files from the device (see log for details.)\");\n return ExitCode.DEVICE_FILE_COPY_FAILURE;\n }\n\n if (!instrumentationExitCode.HasValue)\n {\n return ExitCode.RETURN_CODE_NOT_SET;\n }\n\n if (instrumentationExitCode != expectedExitCode)\n {\n _logger.LogError($\"Non-success instrumentation exit code: {instrumentationExitCode}, expected: {expectedExitCode}\");\n return ExitCode.TESTS_FAILED;\n }\n\n return ExitCode.SUCCESS;\n }", + "start_line": 35, + "end_line": 121, + "start_byte": 1250, + "end_byte": 4429 + } + ], + "src/Microsoft.DotNet.XHarness.Android/AdbExitCodes.cs": [], + "src/Microsoft.DotNet.XHarness.InstrumentationBase.Xunit/DefaultAndroidEntryPoint.cs": [ + { + "name": "GetTestRunner", + "code": "protected override TestRunner GetTestRunner(LogWriter logWriter)\n {\n var testRunner = base.GetTestRunner(logWriter);\n\n (string? Filter, Action FilterMethod, bool IsExcluded)[] filters =\n {\n (_parsedArguments.GetValueOrDefault(ExcludeMethodArgumentName), testRunner.SkipMethod, true),\n (_parsedArguments.GetValueOrDefault(ExcludeClassArgumentName), testRunner.SkipClass, true),\n (_parsedArguments.GetValueOrDefault(IncludeMethodArgumentName), testRunner.SkipMethod, false),\n (_parsedArguments.GetValueOrDefault(IncludeClassArgumentName), testRunner.SkipClass, false)\n };\n\n foreach (var t in filters)\n {\n ConfigureFilters(t.Filter, t.FilterMethod, t.IsExcluded);\n }\n\n return testRunner;\n }", + "start_line": 97, + "end_line": 115, + "start_byte": 3664, + "end_byte": 4502 + }, + { + "name": "ConfigureFilters", + "code": "private static void ConfigureFilters(string? filter, Action filterMethod, bool isExcluded)\n {\n if (filter != null)\n {\n foreach (var f in filter.Split(' '))\n {\n filterMethod(f, isExcluded);\n }\n }\n }", + "start_line": 86, + "end_line": 95, + "start_byte": 3372, + "end_byte": 3658 + }, + { + "name": "TerminateWithSuccess", + "code": "protected override void TerminateWithSuccess()\n {\n }", + "start_line": 82, + "end_line": 84, + "start_byte": 3308, + "end_byte": 3366 + }, + { + "name": "GetTestAssemblies", + "code": "protected override IEnumerable GetTestAssemblies()\n {\n foreach (var assembly in Tests)\n {\n yield return new TestAssemblyInfo(assembly, assembly.Location);\n }\n }", + "start_line": 75, + "end_line": 81, + "start_byte": 3087, + "end_byte": 3303 + } + ], + "src/Microsoft.DotNet.XHarness.Android/Execution/IReportManager.cs": [ + { + "name": "DumpBugReport", + "code": "string DumpBugReport(AdbRunner runner, string outputFilePathWithoutFormat);", + "start_line": 9, + "end_line": 9, + "start_byte": 303, + "end_byte": 378 + } + ], + "src/Microsoft.DotNet.XHarness.Android/Execution/AdbReportFactory.cs": [ + { + "name": "CreateReportManager", + "code": "internal static IReportManager CreateReportManager(ILogger log, int api)\n {\n if (api > 23) return new NewReportManager(log);\n else return new Api23AndOlderReportManager(log);\n }", + "start_line": 13, + "end_line": 17, + "start_byte": 513, + "end_byte": 710 + } + ], + "src/Microsoft.DotNet.XHarness.Android/Execution/NewReportManager.cs": [ + { + "name": "DumpBugReport", + "code": "public string DumpBugReport(AdbRunner runner, string outputFilePathWithoutFormat)\n {\n // give some time for bug report to be available\n Thread.Sleep(3000);\n\n var result = runner.RunAdbCommand(new[] { \"bugreport\", $\"{outputFilePathWithoutFormat}.zip\" }, TimeSpan.FromMinutes(5));\n\n if (result.ExitCode != 0)\n {\n // Could throw here, but it would tear down a possibly otherwise acceptable execution.\n _log.LogError($\"Error getting ADB bugreport:{Environment.NewLine}{result}\");\n return string.Empty;\n }\n else\n {\n _log.LogInformation($\"Wrote ADB bugreport to {outputFilePathWithoutFormat}.zip\");\n return $\"{outputFilePathWithoutFormat}.zip\";\n }\n }", + "start_line": 15, + "end_line": 33, + "start_byte": 289, + "end_byte": 1057 + } + ], + "src/Microsoft.DotNet.XHarness.Android/Execution/IAdbProcessManager.cs": [ + { + "name": "Run", + "code": "public ProcessExecutionResults Run(string filename, IEnumerable arguments, TimeSpan timeout);", + "start_line": 49, + "end_line": 49, + "start_byte": 1595, + "end_byte": 1696 + }, + { + "name": "ToString", + "code": "public override string ToString()\n {\n var output = new StringBuilder();\n output.AppendLine($\"Exit code: {ExitCode}\");\n output.AppendLine($\"Std out:{Environment.NewLine}{StandardOutput}{Environment.NewLine}\");\n if (!string.IsNullOrEmpty(StandardError))\n {\n output.AppendLine($\"Std err:{Environment.NewLine}{StandardError}{Environment.NewLine}\");\n }\n\n return output.ToString();\n }", + "start_line": 28, + "end_line": 39, + "start_byte": 966, + "end_byte": 1410 + }, + { + "name": "ThrowIfFailed", + "code": "public void ThrowIfFailed(string failureMessage)\n {\n if (!Succeeded)\n {\n throw new AdbFailureException(failureMessage + Environment.NewLine + this);\n }\n }", + "start_line": 20, + "end_line": 26, + "start_byte": 768, + "end_byte": 960 + } + ], + "src/Microsoft.DotNet.XHarness.Android/Execution/AdbProcessManager.cs": [ + { + "name": "Run", + "code": "public ProcessExecutionResults Run(string adbExePath, IEnumerable arguments, TimeSpan timeOut)\n {\n if (!string.IsNullOrEmpty(DeviceSerial))\n {\n arguments = arguments.Prepend(DeviceSerial).Prepend(\"-s\");\n }\n\n var processStartInfo = new ProcessStartInfo()\n {\n CreateNoWindow = true,\n UseShellExecute = false,\n WorkingDirectory = Path.GetDirectoryName(adbExePath) ?? throw new ArgumentNullException(nameof(adbExePath)),\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n FileName = adbExePath,\n };\n\n foreach (var arg in arguments)\n {\n processStartInfo.ArgumentList.Add(arg);\n }\n\n _log.LogDebug($\"Executing command: '{adbExePath} {StringUtils.FormatArguments(processStartInfo.ArgumentList)}'\");\n\n var p = new Process() { StartInfo = processStartInfo };\n\n var standardOut = new StringBuilder();\n var standardErr = new StringBuilder();\n\n p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e)\n {\n lock (standardOut)\n {\n if (e.Data != null)\n {\n standardOut.AppendLine(e.Data);\n }\n }\n };\n\n p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e)\n {\n lock (standardErr)\n {\n if (e.Data != null)\n {\n standardErr.AppendLine(e.Data);\n }\n }\n };\n\n p.Start();\n p.BeginOutputReadLine();\n p.BeginErrorReadLine();\n\n bool timedOut = false;\n int exitCode;\n\n // (int.MaxValue ms is about 24 days). Large values are effectively timeouts for the outer harness\n if (!p.WaitForExit((int)Math.Min(timeOut.TotalMilliseconds, int.MaxValue)))\n {\n _log.LogError(\"Waiting for command timed out: execution may be compromised\");\n timedOut = true;\n exitCode = (int)AdbExitCodes.INSTRUMENTATION_TIMEOUT;\n\n // try to terminate the process\n try\n {\n p.Kill();\n } catch (Exception e) {\n _log.LogError($\"Failed to kill process: {e.Message}\");\n }\n\n }\n else\n {\n // we exited normally, call WaitForExit() again to ensure redirected standard output is processed\n p.WaitForExit();\n exitCode = p.ExitCode;\n }\n\n p.Close();\n\n lock (standardOut)\n lock (standardErr)\n {\n return new ProcessExecutionResults()\n {\n ExitCode = exitCode,\n StandardOutput = standardOut.ToString(),\n StandardError = standardErr.ToString(),\n TimedOut = timedOut\n };\n }\n }", + "start_line": 23, + "end_line": 117, + "start_byte": 703, + "end_byte": 3640 + } + ], + "src/Microsoft.DotNet.XHarness.Android/Execution/Api23AndOlderReportManager.cs": [ + { + "name": "DumpBugReport", + "code": "public string DumpBugReport(AdbRunner runner, string outputFilePathWithoutFormat)\n {\n // give some time for bug report to be available\n Thread.Sleep(3000);\n\n var result = runner.RunAdbCommand(new[] { \"bugreport\" }, TimeSpan.FromMinutes(5));\n\n if (result.ExitCode != 0)\n {\n // Could throw here, but it would tear down a possibly otherwise acceptable execution.\n _log.LogError($\"Error getting ADB bugreport:{Environment.NewLine}{result}\");\n return string.Empty;\n }\n else\n {\n File.WriteAllText($\"{outputFilePathWithoutFormat}.txt\", result.StandardOutput);\n _log.LogInformation($\"Wrote ADB bugreport to {outputFilePathWithoutFormat}.txt\");\n return $\"{outputFilePathWithoutFormat}.txt\";\n }\n }", + "start_line": 21, + "end_line": 40, + "start_byte": 540, + "end_byte": 1362 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Common/Properties/AssemblyInfo.cs": [], + "src/Microsoft.DotNet.XHarness.Common/CLI/ExitCode.cs": [], + "src/Microsoft.DotNet.XHarness.Common/CLI/NoDeviceFoundException.cs": [], + "src/Microsoft.DotNet.XHarness.Common/CLI/EnvironmentVariables.cs": [ + { + "name": "IsTrue", + "code": "public static bool IsTrue(string varName) =>\n Environment.GetEnvironmentVariable(varName)?.ToLower().Equals(\"true\") ?? false;", + "start_line": 19, + "end_line": 20, + "start_byte": 668, + "end_byte": 800 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Utilities/StringUtils.cs": [ + { + "name": "QuoteForProcess", + "code": "private static string[]? QuoteForProcess(IList arguments)\n {\n if (arguments == null)\n {\n return Array.Empty();\n }\n\n return QuoteForProcess(arguments.ToArray());\n }", + "start_line": 114, + "end_line": 122, + "start_byte": 2871, + "end_byte": 3095 + }, + { + "name": "QuoteForProcess", + "code": "private static string QuoteForProcess(string f)\n {\n if (string.IsNullOrEmpty(f))\n {\n return f ?? string.Empty;\n }\n\n if (f.IndexOfAny(s_mustQuoteCharactersProcess) == -1)\n {\n return f;\n }\n\n var s = new StringBuilder();\n\n s.Append('\"');\n foreach (var c in f)\n {\n if (c == '\"')\n {\n s.Append('\\\\');\n s.Append(c).Append(c);\n }\n else if (c == '\\\\')\n {\n s.Append(c);\n }\n s.Append(c);\n }\n s.Append('\"');\n\n return s.ToString();\n }", + "start_line": 81, + "end_line": 112, + "start_byte": 2203, + "end_byte": 2865 + }, + { + "name": "Quote", + "code": "public static string Quote(string? f)\n {\n if (string.IsNullOrEmpty(f))\n {\n return f ?? string.Empty;\n }\n\n if (f.IndexOfAny(s_mustQuoteCharacters) == -1)\n {\n return f;\n }\n\n var s = new StringBuilder();\n\n s.Append(s_shellQuoteChar);\n foreach (var c in f)\n {\n if (c == '\\'' || c == '\"' || c == '\\\\')\n {\n s.Append('\\\\');\n }\n\n s.Append(c);\n }\n s.Append(s_shellQuoteChar);\n\n return s.ToString();\n }", + "start_line": 51, + "end_line": 78, + "start_byte": 1547, + "end_byte": 2117 + }, + { + "name": "QuoteForProcess", + "code": "private static string[]? QuoteForProcess(params string[] array)\n {\n if (array == null || array.Length == 0)\n {\n return array;\n }\n\n var rv = new string[array.Length];\n for (var i = 0; i < array.Length; i++)\n {\n rv[i] = QuoteForProcess(array[i]);\n }\n\n return rv;\n }", + "start_line": 35, + "end_line": 49, + "start_byte": 1194, + "end_byte": 1541 + }, + { + "name": "FormatArguments", + "code": "public static string FormatArguments(IList arguments) => string.Join(\" \", QuoteForProcess(arguments) ?? Array.Empty());", + "start_line": 33, + "end_line": 33, + "start_byte": 1053, + "end_byte": 1188 + }, + { + "name": "FormatArguments", + "code": "public static string FormatArguments(params string[] arguments) => FormatArguments((IList)arguments);", + "start_line": 31, + "end_line": 31, + "start_byte": 938, + "end_byte": 1047 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Utilities/FileUtils.cs": [ + { + "name": "TryFindExecutableInPATH", + "code": "public static bool TryFindExecutableInPATH(string filename, [NotNullWhen(true)] out string? fullPath, [NotNullWhen(false)] out string? errorMessage)\n {\n errorMessage = null;\n fullPath = null;\n if (File.Exists(filename))\n {\n fullPath = Path.GetFullPath(filename);\n return true;\n }\n\n if (Path.IsPathRooted(filename))\n {\n fullPath = filename;\n return true;\n }\n\n var path = Environment.GetEnvironmentVariable(\"PATH\");\n if (string.IsNullOrEmpty(path))\n {\n errorMessage = \"Could not find environment variable PATH\";\n return false;\n }\n\n string[] searchPaths = path.Split(new[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries);\n if (searchPaths.Length == 0)\n {\n errorMessage = $\"No paths set in environment variable PATH\";\n return false;\n }\n\n List filenamesTried = new(s_extensions.Length);\n foreach (string extn in s_extensions)\n {\n string filenameWithExtn = filename + extn;\n filenamesTried.Add(filenameWithExtn);\n foreach (string searchPath in searchPaths)\n {\n var pathToCheck = Path.Combine(searchPath, filenameWithExtn);\n if (File.Exists(pathToCheck))\n {\n fullPath = pathToCheck;\n return true;\n }\n }\n }\n\n // Could not find the path\n errorMessage = $\"Tried to look for {string.Join(\", \", filenamesTried)} in PATH: {string.Join(\", \", searchPaths)} .\";\n return false;\n }", + "start_line": 19, + "end_line": 68, + "start_byte": 706, + "end_byte": 2400 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Utilities/DisposableList.cs": [ + { + "name": "Dispose", + "code": "public void Dispose()\n {\n foreach (var item in this)\n {\n item.Dispose();\n }\n\n GC.SuppressFinalize(this);\n }", + "start_line": 12, + "end_line": 20, + "start_byte": 393, + "end_byte": 545 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Utilities/Extensions.cs": [ + { + "name": "TimeoutAfter", + "code": "public static async Task TimeoutAfter(this Task task, TimeSpan timeout)\n {\n if (timeout.Ticks < -1)\n {\n return false;\n }\n\n if (task == await Task.WhenAny(task, Task.Delay(timeout)))\n {\n return true;\n }\n else\n {\n return false;\n }\n }", + "start_line": 31, + "end_line": 46, + "start_byte": 754, + "end_byte": 1099 + }, + { + "name": "TimeoutAfter", + "code": "public static async Task TimeoutAfter(this Task task, TimeSpan timeout)\n {\n if (timeout.Ticks < -1)\n {\n return false;\n }\n\n if (task == await Task.WhenAny(task, Task.Delay(timeout)))\n {\n return true;\n }\n else\n {\n return false;\n }\n }", + "start_line": 13, + "end_line": 28, + "start_byte": 375, + "end_byte": 714 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Execution/IMacOSProcessManager.cs": [ + { + "name": "ExecuteXcodeCommandAsync", + "code": "Task ExecuteXcodeCommandAsync(\n string executable,\n IList args,\n ILog log,\n ILog stdoutLog,\n ILog stderrLog,\n TimeSpan timeout,\n CancellationToken cancellationToken = default);", + "start_line": 26, + "end_line": 33, + "start_byte": 763, + "end_byte": 1020 + }, + { + "name": "ExecuteXcodeCommandAsync", + "code": "Task ExecuteXcodeCommandAsync(\n string executable,\n IList args,\n ILog log,\n TimeSpan timeout,\n CancellationToken cancellationToken = default);", + "start_line": 19, + "end_line": 24, + "start_byte": 548, + "end_byte": 757 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Execution/ProcessManager.cs": [ + { + "name": "ToDictionary", + "code": "private static Dictionary ToDictionary(IEnumerable enumerable) =>\n enumerable.Cast().ToDictionary(v => v.Key.ToString()!, v => v.Value?.ToString(), StringComparer.Ordinal);", + "start_line": 402, + "end_line": 403, + "start_byte": 13667, + "end_byte": 13880 + }, + { + "name": "WaitForExitAsync", + "code": "private static async Task WaitForExitAsync(Process process, TimeSpan? timeout = null)\n {\n if (process.HasExited)\n {\n return true;\n }\n\n var tcs = new TaskCompletionSource();\n\n void ProcessExited(object? sender, EventArgs ea)\n {\n process.Exited -= ProcessExited;\n tcs.TrySetResult(true);\n }\n\n process.Exited += ProcessExited;\n process.EnableRaisingEvents = true;\n\n // Check if process exited again, in case it exited after we checked\n // the last time, but before we attached the event handler.\n if (process.HasExited)\n {\n process.Exited -= ProcessExited;\n tcs.TrySetResult(true);\n return true;\n }\n\n if (timeout.HasValue)\n {\n return await tcs.Task.TimeoutAfter(timeout.Value);\n }\n else\n {\n await tcs.Task;\n return true;\n }\n }", + "start_line": 364, + "end_line": 400, + "start_byte": 12681, + "end_byte": 13661 + }, + { + "name": "RunAsyncInternal", + "code": "protected static async Task RunAsyncInternal(\n Process process,\n ILog log,\n ILog stdout,\n ILog stderr,\n Action kill,\n Func> getChildProcessIds,\n TimeSpan? timeout = null,\n Dictionary? environmentVariables = null,\n CancellationToken? cancellationToken = null,\n bool? diagnostics = null)\n {\n var stdoutCompletion = new TaskCompletionSource();\n var stderrCompletion = new TaskCompletionSource();\n var result = new ProcessExecutionResult();\n\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.RedirectStandardOutput = true;\n // Make cute emojiis show up as cute emojiis in the output instead of ugly text symbols!\n process.StartInfo.StandardOutputEncoding = Encoding.UTF8;\n process.StartInfo.StandardErrorEncoding = Encoding.UTF8;\n process.StartInfo.UseShellExecute = false;\n\n if (environmentVariables != null)\n {\n foreach (var kvp in environmentVariables)\n {\n if (kvp.Value == null)\n {\n process.StartInfo.EnvironmentVariables.Remove(kvp.Key);\n }\n else\n {\n process.StartInfo.EnvironmentVariables[kvp.Key] = kvp.Value;\n }\n }\n }\n\n process.OutputDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n {\n lock (stdout)\n {\n stdout.WriteLine(e.Data);\n stdout.Flush();\n }\n }\n else\n {\n stdoutCompletion.TrySetResult(true);\n }\n };\n\n process.ErrorDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n {\n lock (stderr)\n {\n stderr.WriteLine(e.Data);\n stderr.Flush();\n }\n }\n else\n {\n stderrCompletion.TrySetResult(true);\n }\n };\n\n var sb = new StringBuilder();\n sb.Append($\"Running {StringUtils.Quote(process.StartInfo.FileName)} {process.StartInfo.Arguments}\");\n\n if (process.StartInfo.EnvironmentVariables != null)\n {\n var currentEnvironment = ToDictionary(Environment.GetEnvironmentVariables());\n var processEnvironment = ToDictionary(process.StartInfo.EnvironmentVariables);\n var allVariables = currentEnvironment.Keys.Union(processEnvironment.Keys).Distinct();\n\n bool headerShown = false;\n foreach (var variable in allVariables)\n {\n if (variable == null)\n {\n continue;\n }\n\n currentEnvironment.TryGetValue(variable, out var a);\n processEnvironment.TryGetValue(variable, out var b);\n\n if (a != b)\n {\n if (!headerShown)\n {\n sb.AppendLine().Append(\"With env vars: \");\n headerShown = true;\n }\n\n sb.AppendLine().Append($\" {variable} = '{StringUtils.Quote(b)}'\");\n }\n }\n }\n\n // Separate process calls in logs\n log.WriteLine(string.Empty);\n log.WriteLine(sb.ToString());\n\n process.Start();\n var pid = process.Id;\n\n process.BeginErrorReadLine();\n process.BeginOutputReadLine();\n\n cancellationToken?.Register(() =>\n {\n var hasExited = false;\n try\n {\n hasExited = process.HasExited;\n }\n catch (InvalidOperationException e)\n {\n // Process.HasExited can sometimes throw exceptions, so\n // just ignore those and to be safe treat it as the\n // process didn't exit (the safe option being to not leave\n // processes behind).\n stderr.WriteLine($\"Process {pid} already exited or busy: {e.Message}\");\n }\n catch (Exception e)\n {\n stderr.WriteLine($\"Unexpected error while checking process {pid}: {e.Message}\");\n }\n\n if (!hasExited)\n {\n stderr.WriteLine($\"Killing process {pid} as it was cancelled\");\n kill(pid, 9);\n }\n });\n\n if (timeout.HasValue)\n {\n if (!await WaitForExitAsync(process, timeout.Value))\n {\n log.WriteLine($\"Process {pid} didn't exit within {timeout} and will be killed\");\n\n await KillTreeAsync(pid, log, kill, getChildProcessIds, diagnostics ?? true);\n\n result.TimedOut = true;\n\n lock (stderr)\n {\n log.WriteLine($\"{pid} Execution timed out after {timeout.Value.TotalSeconds} seconds and the process was killed.\");\n }\n }\n }\n else\n {\n await WaitForExitAsync(process);\n }\n\n if (process.HasExited)\n {\n // make sure redirected output events are finished\n process.WaitForExit();\n }\n\n Task.WaitAll(new Task[] { stderrCompletion.Task, stdoutCompletion.Task }, TimeSpan.FromSeconds(1));\n\n try\n {\n result.ExitCode = process.ExitCode;\n log.WriteLine($\"Process {Path.GetFileName(process.StartInfo.FileName)} exited with {result.ExitCode}\");\n }\n catch (Exception e)\n {\n result.ExitCode = 12345678;\n log.WriteLine($\"Failed to get ExitCode: {e}\");\n }\n\n return result;\n }", + "start_line": 181, + "end_line": 362, + "start_byte": 6780, + "end_byte": 12675 + }, + { + "name": "RunAsyncInternal", + "code": "protected Task RunAsyncInternal(\n Process process,\n ILog log,\n ILog stdout,\n ILog stderr,\n TimeSpan? timeout = null,\n Dictionary? environmentVariables = null,\n CancellationToken? cancellationToken = null,\n bool? diagnostics = null) => RunAsyncInternal(\n process,\n log,\n stdout,\n stderr,\n (pid, signal) => Kill(pid, signal),\n (log, pid) => GetChildProcessIds(log, pid),\n timeout,\n environmentVariables,\n cancellationToken,\n diagnostics);", + "start_line": 161, + "end_line": 179, + "start_byte": 6132, + "end_byte": 6774 + }, + { + "name": "KillTreeAsync", + "code": "protected static async Task KillTreeAsync(\n int pid,\n ILog log,\n Action kill,\n Func> getChildProcessIds,\n bool? diagnostics = true)\n {\n log.WriteLine($\"Killing process tree of {pid}...\");\n\n var pids = getChildProcessIds(log, pid);\n log.WriteLine($\"Pids to kill: {string.Join(\", \", pids.Select((v) => v.ToString()).ToArray())}\");\n\n if (diagnostics == true)\n {\n foreach (var pidToDiagnose in pids)\n {\n log.WriteLine($\"Running lldb diagnostics for pid {pidToDiagnose}\");\n\n var template = Path.GetTempFileName();\n try\n {\n var commands = new StringBuilder();\n using (var dbg = new Process())\n {\n commands.AppendLine($\"process attach --pid {pidToDiagnose}\");\n commands.AppendLine(\"thread list\");\n commands.AppendLine(\"thread backtrace all\");\n commands.AppendLine(\"detach\");\n commands.AppendLine(\"quit\");\n\n dbg.StartInfo.FileName = \"lldb\";\n dbg.StartInfo.Arguments = StringUtils.FormatArguments(\"--source\", template);\n\n File.WriteAllText(template, commands.ToString());\n\n log.WriteLine($\"Printing backtrace for pid={pidToDiagnose}\");\n await RunAsyncInternal(\n process: dbg,\n log: new NullLog(),\n stdout: log,\n stderr: log,\n kill,\n getChildProcessIds,\n timeout: TimeSpan.FromSeconds(20),\n diagnostics: false);\n }\n }\n catch (Win32Exception e) when (e.NativeErrorCode == 2)\n {\n log.WriteLine(\"lldb was not found, skipping diagnosis..\");\n }\n catch (Exception e)\n {\n log.WriteLine(\"Failed to diagnose the process using lldb:\" + Environment.NewLine + e);\n }\n finally\n {\n try\n {\n File.Delete(template);\n }\n catch (Exception e)\n {\n log.WriteLine(e.Message);\n }\n }\n }\n }\n\n // Send SIGABRT since that produces a crash report\n // lldb may fail to attach to system processes, but crash reports will still be produced with potentially helpful stack traces.\n for (int i = 0; i < pids.Count; i++)\n {\n kill(pids[i], 6);\n }\n\n // send kill -9 anyway as a last resort\n for (int i = 0; i < pids.Count; i++)\n {\n kill(pids[i], 9);\n }\n }", + "start_line": 78, + "end_line": 159, + "start_byte": 3056, + "end_byte": 6126 + }, + { + "name": "KillTreeAsync", + "code": "public Task KillTreeAsync(int pid, ILog log, bool? diagnostics = true) => KillTreeAsync(pid, log, (pid, signal) => Kill(pid, signal), (log, pid) => GetChildProcessIds(log, pid), diagnostics);", + "start_line": 76, + "end_line": 76, + "start_byte": 2859, + "end_byte": 3050 + }, + { + "name": "KillTreeAsync", + "code": "public Task KillTreeAsync(Process process, ILog log, bool? diagnostics = true) => KillTreeAsync(process.Id, log, diagnostics);", + "start_line": 74, + "end_line": 74, + "start_byte": 2727, + "end_byte": 2853 + }, + { + "name": "RunAsync", + "code": "public Task RunAsync(\n Process process,\n ILog log,\n ILog stdout,\n ILog stderr,\n TimeSpan? timeout = null,\n Dictionary? environmentVariables = null,\n CancellationToken? cancellationToken = null,\n bool? diagnostics = null)\n => RunAsyncInternal(process, log, stdout, stderr, timeout, environmentVariables, cancellationToken, diagnostics);", + "start_line": 63, + "end_line": 72, + "start_byte": 2283, + "end_byte": 2721 + }, + { + "name": "RunAsync", + "code": "public Task RunAsync(\n Process process,\n ILog log,\n TimeSpan? timeout = null,\n Dictionary? environmentVariables = null,\n CancellationToken? cancellationToken = null,\n bool? diagnostics = null)\n => RunAsync(process, log, log, log, timeout, environmentVariables, cancellationToken, diagnostics);", + "start_line": 54, + "end_line": 61, + "start_byte": 1895, + "end_byte": 2277 + }, + { + "name": "ExecuteCommandAsync", + "code": "public async Task ExecuteCommandAsync(string filename,\n IList args,\n ILog log,\n ILog stdout,\n ILog stderr,\n TimeSpan timeout,\n Dictionary? environmentVariables = null,\n CancellationToken? cancellationToken = null)\n {\n using var p = new Process();\n p.StartInfo.FileName = filename ?? throw new ArgumentNullException(nameof(filename));\n p.StartInfo.Arguments = StringUtils.FormatArguments(args);\n return await RunAsync(p, log, stdout, stderr, timeout, environmentVariables, cancellationToken);\n }", + "start_line": 39, + "end_line": 52, + "start_byte": 1264, + "end_byte": 1889 + }, + { + "name": "ExecuteCommandAsync", + "code": "public async Task ExecuteCommandAsync(string filename,\n IList args,\n ILog log,\n TimeSpan timeout,\n Dictionary? environmentVariables = null,\n CancellationToken? cancellationToken = null)\n => await ExecuteCommandAsync(filename, args, log, log, log, timeout, environmentVariables, cancellationToken);", + "start_line": 31, + "end_line": 37, + "start_byte": 871, + "end_byte": 1258 + }, + { + "name": "GetChildProcessIds", + "code": "protected abstract List GetChildProcessIds(ILog log, int pid);", + "start_line": 25, + "end_line": 25, + "start_byte": 738, + "end_byte": 805 + }, + { + "name": "Kill", + "code": "protected abstract int Kill(int pid, int sig);", + "start_line": 24, + "end_line": 24, + "start_byte": 687, + "end_byte": 733 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Execution/IProcessManager.cs": [ + { + "name": "KillTreeAsync", + "code": "Task KillTreeAsync(int pid, ILog log, bool? diagnostics = true);", + "start_line": 63, + "end_line": 63, + "start_byte": 1990, + "end_byte": 2054 + }, + { + "name": "KillTreeAsync", + "code": "Task KillTreeAsync(Process process, ILog log, bool? diagnostics = true);", + "start_line": 62, + "end_line": 62, + "start_byte": 1913, + "end_byte": 1985 + }, + { + "name": "RunAsync", + "code": "Task RunAsync(\n Process process,\n ILog log,\n ILog stdoutLog,\n ILog stderrLog,\n TimeSpan? timeout = null,\n Dictionary? environmentVariables = null,\n CancellationToken? cancellationToken = null,\n bool? diagnostics = null);", + "start_line": 52, + "end_line": 60, + "start_byte": 1591, + "end_byte": 1907 + }, + { + "name": "RunAsync", + "code": "Task RunAsync(\n Process process,\n ILog log,\n TimeSpan? timeout = null,\n Dictionary? environmentVariables = null,\n CancellationToken? cancellationToken = null,\n bool? diagnostics = null);", + "start_line": 44, + "end_line": 50, + "start_byte": 1317, + "end_byte": 1585 + }, + { + "name": "ExecuteCommandAsync", + "code": "Task ExecuteCommandAsync(\n string filename,\n IList args,\n ILog log,\n ILog stdoutLog,\n ILog stderrLog,\n TimeSpan timeout,\n Dictionary? environmentVariables = null,\n CancellationToken? cancellationToken = null);", + "start_line": 34, + "end_line": 42, + "start_byte": 998, + "end_byte": 1311 + }, + { + "name": "ExecuteCommandAsync", + "code": "Task ExecuteCommandAsync(\n string filename,\n IList args,\n ILog log,\n TimeSpan timeout,\n Dictionary? environmentVariables = null,\n CancellationToken? cancellationToken = null);", + "start_line": 26, + "end_line": 32, + "start_byte": 727, + "end_byte": 992 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Execution/WindowsProcessManager.cs": [ + { + "name": "Kill", + "code": "protected override int Kill(int pid, int sig)\n {\n#if NET6_0_OR_GREATER\n Process.GetProcessById(pid).Kill(entireProcessTree: true);\n#else\n Process.GetProcessById(pid).Kill();\n#endif\n return 0;\n }", + "start_line": 17, + "end_line": 25, + "start_byte": 744, + "end_byte": 965 + }, + { + "name": "GetChildProcessIds", + "code": "protected override List GetChildProcessIds(ILog log, int pid) => new() { pid };", + "start_line": 15, + "end_line": 15, + "start_byte": 654, + "end_byte": 738 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Execution/UnixProcessManager.cs": [ + { + "name": "GetChildProcessIdsInternal", + "code": "protected static List GetChildProcessIdsInternal(ILog log, int pid)\n {\n var list = new List();\n\n using (var ps = new Process())\n {\n ps.StartInfo.FileName = \"ps\";\n ps.StartInfo.Arguments = \"-eo ppid,pid\";\n ps.StartInfo.UseShellExecute = false;\n ps.StartInfo.RedirectStandardOutput = true;\n ps.Start();\n\n string stdout = ps.StandardOutput.ReadToEnd();\n\n if (!ps.WaitForExit(1000))\n {\n log.WriteLine(\"ps didn't finish in a reasonable amount of time (1 second).\");\n return list;\n }\n\n if (ps.ExitCode != 0)\n {\n return list;\n }\n\n stdout = stdout.Trim();\n\n if (string.IsNullOrEmpty(stdout))\n {\n return list;\n }\n\n var dict = new Dictionary>();\n foreach (string line in stdout.Split(new char[] { '\\n', '\\r' }, StringSplitOptions.RemoveEmptyEntries))\n {\n var l = line.Trim();\n var space = l.IndexOf(' ');\n if (space <= 0)\n {\n continue;\n }\n\n var parent = l.Substring(0, space);\n var process = l.Substring(space + 1);\n\n if (int.TryParse(parent, out var parent_id) && int.TryParse(process, out var process_id))\n {\n if (!dict.TryGetValue(parent_id, out var children))\n {\n dict[parent_id] = children = new List();\n }\n\n children.Add(process_id);\n }\n }\n\n var queue = new Queue();\n queue.Enqueue(pid);\n\n do\n {\n var parent_id = queue.Dequeue();\n list.Add(parent_id);\n if (dict.TryGetValue(parent_id, out var children))\n {\n foreach (var child in children)\n {\n queue.Enqueue(child);\n }\n }\n } while (queue.Count > 0);\n }\n\n return list;\n }", + "start_line": 16, + "end_line": 90, + "start_byte": 562, + "end_byte": 2812 + }, + { + "name": "GetChildProcessIds", + "code": "protected override List GetChildProcessIds(ILog log, int pid) => GetChildProcessIdsInternal(log, pid);", + "start_line": 14, + "end_line": 14, + "start_byte": 449, + "end_byte": 556 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Execution/ProcessManagerFactory.cs": [ + { + "name": "CreateProcessManager", + "code": "public static IProcessManager CreateProcessManager()\n {\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))\n {\n return new LinuxProcessManager();\n }\n\n if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\n {\n return new MacOSProcessManager();\n }\n\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n return new WindowsProcessManager();\n }\n\n throw new InvalidOperationException(\"Unsupported OS platform detected when creating ProcessManager\");\n }", + "start_line": 12, + "end_line": 30, + "start_byte": 363, + "end_byte": 929 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Execution/LinuxProcessManager.cs": [ + { + "name": "Kill", + "code": "protected override int Kill(int pid, int sig) => kill(pid, sig);", + "start_line": 14, + "end_line": 14, + "start_byte": 440, + "end_byte": 504 + }, + { + "name": "kill", + "code": "[DllImport(\"libc\")]\n private static extern int kill(int pid, int sig);", + "start_line": 11, + "end_line": 12, + "start_byte": 361, + "end_byte": 434 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Execution/MacOSProcessManager.cs": [ + { + "name": "DetectMlaunchPath", + "code": "public static string DetectMlaunchPath()\n {\n string? pathFromEnv = Environment.GetEnvironmentVariable(EnvironmentVariables.Names.MLAUNCH_PATH);\n if (!string.IsNullOrEmpty(pathFromEnv))\n {\n return pathFromEnv;\n }\n\n // This path is where mlaunch is when the .NET tool is extracted from the .nupkg\n var assemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(MacOSProcessManager))?.Location)!;\n return Path.Combine(assemblyPath, \"..\", \"..\", \"..\", \"runtimes\", \"any\", \"native\", \"mlaunch\", \"bin\", \"mlaunch\");\n }", + "start_line": 129, + "end_line": 140, + "start_byte": 4441, + "end_byte": 5039 + }, + { + "name": "DetectXcodePath", + "code": "public static string DetectXcodePath()\n {\n using var process = new Process();\n process.StartInfo.FileName = \"xcode-select\";\n process.StartInfo.Arguments = \"-p\";\n\n var log = new MemoryLog();\n var stdout = new MemoryLog() { Timestamp = false };\n var stderr = new ConsoleLog();\n var timeout = TimeSpan.FromSeconds(30);\n\n var result = RunAsyncInternal(\n process,\n log,\n stdout,\n stderr,\n (pid, signal) => _ = kill(pid, signal),\n (log, pid) => GetChildProcessIdsInternal(log, pid),\n timeout)\n .GetAwaiter().GetResult();\n\n if (!result.Succeeded)\n {\n throw new Exception(\"Failed to detect Xcode path from xcode-select!\");\n }\n\n // Something like /Applications/Xcode114.app/Contents/Developers\n var xcodeRoot = stdout.ToString().Trim();\n\n if (string.IsNullOrEmpty(xcodeRoot))\n {\n throw new Exception(\"Failed to detect Xcode path from xcode-select!\");\n }\n\n // We need /Applications/Xcode114.app only\n // should never be null, if it is return an \"\"\n return Path.GetDirectoryName(Path.GetDirectoryName(xcodeRoot)) ?? string.Empty;\n }", + "start_line": 90, + "end_line": 127, + "start_byte": 3137, + "end_byte": 4435 + }, + { + "name": "Kill", + "code": "protected override int Kill(int pid, int sig) => kill(pid, sig);", + "start_line": 84, + "end_line": 84, + "start_byte": 3023, + "end_byte": 3087 + }, + { + "name": "kill", + "code": "[DllImport(\"/usr/lib/libc.dylib\")]\n private static extern int kill(int pid, int sig);", + "start_line": 79, + "end_line": 80, + "start_byte": 2899, + "end_byte": 2987 + }, + { + "name": "ExecuteXcodeCommandAsync", + "code": "public Task ExecuteXcodeCommandAsync(string executable, IList args, ILog log, TimeSpan timeout, CancellationToken cancellationToken = default)\n => ExecuteXcodeCommandAsync(executable, args, log, log, log, timeout, cancellationToken);", + "start_line": 74, + "end_line": 75, + "start_byte": 2605, + "end_byte": 2877 + }, + { + "name": "ExecuteXcodeCommandAsync", + "code": "public Task ExecuteXcodeCommandAsync(\n string executable,\n IList args,\n ILog log,\n ILog stdoutLog,\n ILog stderrLog,\n TimeSpan timeout,\n CancellationToken cancellationToken = default)\n {\n var filename = Path.Combine(XcodeRoot, \"Contents\", \"Developer\", \"usr\", \"bin\", executable);\n return ExecuteCommandAsync(filename, args, log, stdoutLog, stderrLog, timeout: timeout, cancellationToken: cancellationToken);\n }", + "start_line": 61, + "end_line": 72, + "start_byte": 2090, + "end_byte": 2599 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Logging/ILog.cs": [ + { + "name": "Flush", + "code": "void Flush();", + "start_line": 19, + "end_line": 19, + "start_byte": 610, + "end_byte": 623 + }, + { + "name": "WriteLine", + "code": "void WriteLine(string format, params object[] args);", + "start_line": 18, + "end_line": 18, + "start_byte": 553, + "end_byte": 605 + }, + { + "name": "WriteLine", + "code": "void WriteLine(string value);", + "start_line": 17, + "end_line": 17, + "start_byte": 519, + "end_byte": 548 + }, + { + "name": "Write", + "code": "void Write(string value);", + "start_line": 16, + "end_line": 16, + "start_byte": 489, + "end_byte": 514 + }, + { + "name": "Write", + "code": "void Write(byte[] buffer, int offset, int count);", + "start_line": 15, + "end_line": 15, + "start_byte": 435, + "end_byte": 484 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Logging/FileBackedLog.cs": [], + "src/Microsoft.DotNet.XHarness.Common/Logging/AggregatedLog.cs": [ + { + "name": "GetReader", + "code": "public StreamReader GetReader() => _defaultLog.GetReader();", + "start_line": 73, + "end_line": 73, + "start_byte": 2097, + "end_byte": 2156 + }, + { + "name": "Dispose", + "code": "public override void Dispose()\n {\n foreach (var log in _logs)\n {\n log.Dispose();\n }\n }", + "start_line": 52, + "end_line": 58, + "start_byte": 1461, + "end_byte": 1609 + }, + { + "name": "Flush", + "code": "public override void Flush()\n {\n foreach (var log in _logs)\n {\n log.Flush();\n }\n }", + "start_line": 44, + "end_line": 50, + "start_byte": 1307, + "end_byte": 1451 + }, + { + "name": "Write", + "code": "public override void Write(byte[] buffer, int offset, int count)\n {\n foreach (var log in _logs)\n {\n log.Write(buffer, offset, count);\n }\n }", + "start_line": 36, + "end_line": 42, + "start_byte": 1096, + "end_byte": 1297 + }, + { + "name": "WriteImpl", + "code": "protected override void WriteImpl(string value)\n {\n foreach (var log in _logs)\n {\n log.Write(value);\n }\n }", + "start_line": 28, + "end_line": 34, + "start_byte": 918, + "end_byte": 1086 + }, + { + "name": "CreateAggregatedLog", + "code": "public static ILog CreateAggregatedLog(params ILog[] logs) => new AggregatedLog(logs);", + "start_line": 15, + "end_line": 15, + "start_byte": 523, + "end_byte": 609 + }, + { + "name": "CreateReadableAggregatedLog", + "code": "public static IFileBackedLog CreateReadableAggregatedLog(IFileBackedLog defaultLog, params ILog[] logs) => new ReadableAggregatedLog(defaultLog, logs);", + "start_line": 13, + "end_line": 13, + "start_byte": 366, + "end_byte": 517 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Logging/ConsoleLog.cs": [ + { + "name": "Dispose", + "code": "public override void Dispose()\n {\n GC.SuppressFinalize(this);\n }", + "start_line": 41, + "end_line": 44, + "start_byte": 939, + "end_byte": 1016 + }, + { + "name": "Flush", + "code": "public override void Flush()\n {\n }", + "start_line": 37, + "end_line": 39, + "start_byte": 893, + "end_byte": 933 + }, + { + "name": "GetReader", + "code": "public override StreamReader GetReader()\n {\n lock (_captured)\n {\n var str = new MemoryStream(Encoding.GetBytes(_captured.ToString()));\n return new StreamReader(str, Encoding, false);\n }\n }", + "start_line": 28, + "end_line": 35, + "start_byte": 650, + "end_byte": 887 + }, + { + "name": "WriteImpl", + "code": "protected override void WriteImpl(string value)\n {\n lock (_captured)\n {\n _captured.Append(value);\n }\n\n Console.Write(value);\n }", + "start_line": 18, + "end_line": 26, + "start_byte": 472, + "end_byte": 644 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Logging/Log.cs": [ + { + "name": "WriteImpl", + "code": "protected abstract void WriteImpl(string value);", + "start_line": 43, + "end_line": 43, + "start_byte": 1235, + "end_byte": 1283 + }, + { + "name": "Dispose", + "code": "public abstract void Dispose();", + "start_line": 41, + "end_line": 41, + "start_byte": 1198, + "end_byte": 1229 + }, + { + "name": "Flush", + "code": "public abstract void Flush();", + "start_line": 39, + "end_line": 39, + "start_byte": 1163, + "end_byte": 1192 + }, + { + "name": "ToString", + "code": "public override string ToString() => Description ?? string.Empty;", + "start_line": 37, + "end_line": 37, + "start_byte": 1092, + "end_byte": 1157 + }, + { + "name": "WriteLine", + "code": "public void WriteLine(string format, params object[] args) => Write(string.Format(format, args) + \"\\n\");", + "start_line": 35, + "end_line": 35, + "start_byte": 982, + "end_byte": 1086 + }, + { + "name": "WriteLine", + "code": "public void WriteLine(string value) => Write(value + \"\\n\");", + "start_line": 33, + "end_line": 33, + "start_byte": 917, + "end_byte": 976 + }, + { + "name": "Write", + "code": "public void Write(string value)\n {\n if (Timestamp)\n {\n value = \"[\" + DateTime.Now.ToString(\"HH:mm:ss.fffffff\") + \"] \" + value;\n }\n\n WriteImpl(value);\n }", + "start_line": 23, + "end_line": 31, + "start_byte": 714, + "end_byte": 911 + }, + { + "name": "Write", + "code": "public virtual void Write(byte[] buffer, int offset, int count) => Write(Encoding.GetString(buffer, offset, count));", + "start_line": 21, + "end_line": 21, + "start_byte": 592, + "end_byte": 708 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Logging/ReadableLog.cs": [ + { + "name": "GetReader", + "code": "public abstract StreamReader GetReader();", + "start_line": 18, + "end_line": 18, + "start_byte": 489, + "end_byte": 530 + }, + { + "name": "GetReader", + "code": "StreamReader GetReader();", + "start_line": 11, + "end_line": 11, + "start_byte": 321, + "end_byte": 346 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Logging/MemoryLog.cs": [ + { + "name": "ToString", + "code": "public override string ToString() => _captured.ToString();", + "start_line": 35, + "end_line": 35, + "start_byte": 873, + "end_byte": 931 + }, + { + "name": "Dispose", + "code": "public override void Dispose()\n {\n GC.SuppressFinalize(this);\n }", + "start_line": 30, + "end_line": 33, + "start_byte": 790, + "end_byte": 867 + }, + { + "name": "Flush", + "code": "public override void Flush()\n {\n }", + "start_line": 26, + "end_line": 28, + "start_byte": 744, + "end_byte": 784 + }, + { + "name": "GetReader", + "code": "public override StreamReader GetReader()\n {\n var str = new MemoryStream(Encoding.GetBytes(_captured.ToString()));\n return new StreamReader(str, Encoding, false);\n }", + "start_line": 20, + "end_line": 24, + "start_byte": 554, + "end_byte": 738 + }, + { + "name": "WriteImpl", + "code": "protected override void WriteImpl(string value) => _captured.Append(value);", + "start_line": 18, + "end_line": 18, + "start_byte": 473, + "end_byte": 548 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Logging/NullLog.cs": [ + { + "name": "WriteLine", + "code": "public void WriteLine(string format, params object[] args)\n {\n }", + "start_line": 45, + "end_line": 47, + "start_byte": 890, + "end_byte": 960 + }, + { + "name": "WriteLine", + "code": "public static void WriteLine(StringBuilder value)\n {\n }", + "start_line": 41, + "end_line": 43, + "start_byte": 823, + "end_byte": 884 + }, + { + "name": "WriteLine", + "code": "public void WriteLine(string value)\n {\n }", + "start_line": 37, + "end_line": 39, + "start_byte": 770, + "end_byte": 817 + }, + { + "name": "Write", + "code": "public void Write(string value)\n {\n }", + "start_line": 33, + "end_line": 35, + "start_byte": 721, + "end_byte": 764 + }, + { + "name": "Write", + "code": "public void Write(byte[] buffer, int offset, int count)\n {\n }", + "start_line": 29, + "end_line": 31, + "start_byte": 648, + "end_byte": 715 + }, + { + "name": "Flush", + "code": "public void Flush()\n {\n }", + "start_line": 25, + "end_line": 27, + "start_byte": 611, + "end_byte": 642 + }, + { + "name": "Dispose", + "code": "public void Dispose()\n {\n GC.SuppressFinalize(this);\n }", + "start_line": 20, + "end_line": 23, + "start_byte": 537, + "end_byte": 605 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Logging/CallbackLog.cs": [ + { + "name": "WriteImpl", + "code": "protected override void WriteImpl(string value)\n {\n lock (_captured)\n {\n _captured.Append(value);\n }\n\n _onWrite(value);\n }", + "start_line": 34, + "end_line": 42, + "start_byte": 791, + "end_byte": 958 + }, + { + "name": "Flush", + "code": "public override void Flush()\n {\n }", + "start_line": 30, + "end_line": 32, + "start_byte": 745, + "end_byte": 785 + }, + { + "name": "Dispose", + "code": "public override void Dispose()\n {\n GC.SuppressFinalize(this);\n }", + "start_line": 25, + "end_line": 28, + "start_byte": 662, + "end_byte": 739 + } + ], + "src/Microsoft.DotNet.XHarness.Common/Logging/ScanLog.cs": [ + { + "name": "IsMatch", + "code": "private bool IsMatch()\n {\n if (!_hasBeenFilled)\n {\n return false;\n }\n\n for (int i = 1; i <= _buffer.Length; i++)\n {\n int index = (i + _startIndex) % _buffer.Length;\n if (_buffer[index] != _tag[i - 1])\n {\n return false;\n }\n }\n\n return true;\n }", + "start_line": 70, + "end_line": 87, + "start_byte": 1622, + "end_byte": 1989 + }, + { + "name": "Add", + "code": "private void Add(char c)\n {\n _startIndex++;\n\n if (_startIndex == _buffer.Length - 1)\n {\n _hasBeenFilled = true;\n }\n\n _startIndex %= _buffer.Length;\n _buffer[_startIndex] = c;\n }", + "start_line": 57, + "end_line": 68, + "start_byte": 1380, + "end_byte": 1616 + }, + { + "name": "Dispose", + "code": "public override void Dispose()\n {\n GC.SuppressFinalize(this);\n }", + "start_line": 52, + "end_line": 55, + "start_byte": 1297, + "end_byte": 1374 + }, + { + "name": "Flush", + "code": "public override void Flush()\n {\n }", + "start_line": 48, + "end_line": 50, + "start_byte": 1251, + "end_byte": 1291 + }, + { + "name": "WriteImpl", + "code": "protected override void WriteImpl(string value)\n {\n foreach (var c in value)\n {\n Add(c);\n\n if (IsMatch())\n {\n _tagFoundNotify();\n }\n }\n }", + "start_line": 35, + "end_line": 46, + "start_byte": 1022, + "end_byte": 1245 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/UseJsonArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/DiagnosticsArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Argument.cs": [ + { + "name": "Action", + "code": "public override void Action(string argumentValue) => _values.Add(argumentValue);", + "start_line": 323, + "end_line": 323, + "start_byte": 10225, + "end_byte": 10305 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n if (string.IsNullOrEmpty(argumentValue))\n {\n Value = _defaultValue;\n }\n else\n {\n Value = argumentValue.Equals(\"none\", StringComparison.OrdinalIgnoreCase) ? PageLoadStrategy.None :\n argumentValue.Equals(\"eager\", StringComparison.OrdinalIgnoreCase) ? PageLoadStrategy.Eager :\n argumentValue.Equals(\"normal\", StringComparison.OrdinalIgnoreCase) ? PageLoadStrategy.Normal :\n _defaultValue;\n }\n }", + "start_line": 297, + "end_line": 310, + "start_byte": 9300, + "end_byte": 9860 + }, + { + "name": "ToString", + "code": "public override string ToString() => Value ? \"true\" : \"false\";", + "start_line": 284, + "end_line": 284, + "start_byte": 8881, + "end_byte": 8943 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n if (string.IsNullOrEmpty(argumentValue))\n {\n Value = !_defaultValue;\n }\n else\n {\n Value = !argumentValue.Equals(\"false\", StringComparison.InvariantCultureIgnoreCase) &&\n !argumentValue.Equals(\"no\", StringComparison.InvariantCultureIgnoreCase) &&\n !argumentValue.Equals(\"off\", StringComparison.InvariantCultureIgnoreCase) &&\n !argumentValue.Equals(\"0\", StringComparison.InvariantCultureIgnoreCase);\n }\n }", + "start_line": 269, + "end_line": 282, + "start_byte": 8303, + "end_byte": 8875 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue) => Value = RootPath(argumentValue);", + "start_line": 256, + "end_line": 256, + "start_byte": 7925, + "end_byte": 8010 + }, + { + "name": "Validate", + "code": "public override void Validate()\n {\n if (_isRequired && string.IsNullOrEmpty(Value))\n {\n throw new ArgumentException($\"Required argument {Prototype} was not supplied\");\n }\n }", + "start_line": 241, + "end_line": 247, + "start_byte": 7519, + "end_byte": 7730 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue) => Value = RootPath(argumentValue);", + "start_line": 239, + "end_line": 239, + "start_byte": 7428, + "end_byte": 7513 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n if (int.TryParse(argumentValue, out var timeout))\n {\n Value = TimeSpan.FromSeconds(timeout);\n return;\n }\n\n if (TimeSpan.TryParse(argumentValue, out var timespan))\n {\n Value = timespan;\n return;\n }\n\n throw new ArgumentException($\"{Prototype} must be an integer - a number of seconds, or a timespan (00:30:00)\");\n }", + "start_line": 212, + "end_line": 227, + "start_byte": 6700, + "end_byte": 7166 + }, + { + "name": "Validate", + "code": "public override void Validate()\n {\n if (string.IsNullOrEmpty(Value))\n {\n throw new ArgumentException($\"Required argument {Prototype} was not supplied\");\n }\n }", + "start_line": 196, + "end_line": 202, + "start_byte": 6276, + "end_byte": 6472 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue) => Value = argumentValue;", + "start_line": 194, + "end_line": 194, + "start_byte": 6195, + "end_byte": 6270 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue) => Value = argumentValue;", + "start_line": 184, + "end_line": 184, + "start_byte": 5879, + "end_byte": 5954 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n if (int.TryParse(argumentValue, out var number))\n {\n Value = number;\n return;\n }\n\n throw new ArgumentException($\"{Prototype} must be an integer\");\n }", + "start_line": 165, + "end_line": 174, + "start_byte": 5431, + "end_byte": 5690 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n if (int.TryParse(argumentValue, out var number))\n {\n Value = number;\n return;\n }\n\n throw new ArgumentException($\"{Prototype} must be an integer\");\n }", + "start_line": 146, + "end_line": 155, + "start_byte": 4976, + "end_byte": 5235 + }, + { + "name": "ToString", + "code": "public override string ToString() => Value?.ToString() ?? base.ToString()!;", + "start_line": 136, + "end_line": 136, + "start_byte": 4692, + "end_byte": 4767 + }, + { + "name": "ParseArgument", + "code": "protected static TEnum ParseArgument(string argumentName, string? value, params TEnum[]? invalidValues) where TEnum : struct, IConvertible\n {\n if (value == null)\n {\n throw new ArgumentNullException(message: $\"Empty value supplied to {argumentName}\", null);\n }\n\n if (value.All(c => char.IsDigit(c)))\n {\n // Any int would parse into enum successfully, so we forbid that\n throw new ArgumentException(\n $\"Invalid value '{value}' supplied for {argumentName}. \" +\n $\"Valid values are:\" + GetAllowedValues(invalidValues: invalidValues));\n }\n\n var type = typeof(TEnum);\n\n if (!type.IsEnum)\n {\n throw new ArgumentException(nameof(TEnum) + \" must be an enumerated type\");\n }\n\n if (Enum.TryParse(value, ignoreCase: true, out TEnum result))\n {\n if (invalidValues != null && invalidValues.Contains(result))\n {\n throw new ArgumentException($\"{result} is an invalid value for {argumentName}\");\n }\n\n return result;\n }\n\n IEnumerable validOptions = Enum.GetValues(type).Cast();\n\n if (invalidValues != null)\n {\n validOptions = validOptions.Where(v => !invalidValues.Contains(v));\n }\n\n throw new ArgumentException(\n $\"Invalid value '{value}' supplied in {argumentName}. \" +\n $\"Valid values are:\" + GetAllowedValues(invalidValues: invalidValues));\n }", + "start_line": 79, + "end_line": 121, + "start_byte": 2808, + "end_byte": 4356 + }, + { + "name": "GetAllowedValues", + "code": "protected static string GetAllowedValues(Func? display = null, params TEnum[]? invalidValues) where TEnum : struct, IConvertible\n {\n var values = Enum.GetValues(typeof(TEnum)).Cast();\n\n if (invalidValues != null)\n {\n values = values.Where(v => !invalidValues.Contains(v));\n }\n\n var separator = Environment.NewLine + \"\\t- \";\n IEnumerable allowedValued = values.Select(t => display?.Invoke(t) ?? t.ToString());\n\n return separator + string.Join(separator, allowedValued);\n }", + "start_line": 55, + "end_line": 68, + "start_byte": 1670, + "end_byte": 2245 + }, + { + "name": "RootPath", + "code": "protected string RootPath(string path)\n {\n if (!Path.IsPathRooted(path))\n {\n path = Path.Combine(Directory.GetCurrentDirectory(), path);\n }\n\n return path;\n }", + "start_line": 38, + "end_line": 46, + "start_byte": 995, + "end_byte": 1197 + }, + { + "name": "Validate", + "code": "public virtual void Validate()\n {\n }", + "start_line": 34, + "end_line": 36, + "start_byte": 947, + "end_byte": 989 + }, + { + "name": "Action", + "code": "public abstract void Action(string argumentValue);", + "start_line": 28, + "end_line": 28, + "start_byte": 713, + "end_byte": 763 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/XHarnessCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected abstract IEnumerable GetArguments();", + "start_line": 44, + "end_line": 44, + "start_byte": 1289, + "end_byte": 1345 + }, + { + "name": "Validate", + "code": "public virtual void Validate()\n {\n foreach (var arg in GetCommandArguments())\n {\n arg.Validate();\n }\n }", + "start_line": 33, + "end_line": 39, + "start_byte": 1044, + "end_byte": 1185 + }, + { + "name": "GetCommandArguments", + "code": "public IEnumerable GetCommandArguments() => GetArguments().Concat(new Argument[]\n {\n Diagnostics,\n Verbosity,\n ShowHelp,\n });", + "start_line": 26, + "end_line": 31, + "start_byte": 876, + "end_byte": 1038 + }, + { + "name": "Validate", + "code": "void Validate();", + "start_line": 17, + "end_line": 17, + "start_byte": 580, + "end_byte": 596 + }, + { + "name": "GetCommandArguments", + "code": "IEnumerable GetCommandArguments();", + "start_line": 16, + "end_line": 16, + "start_byte": 531, + "end_byte": 575 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/HelpArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/VerbosityArgument.cs": [ + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n Value = string.IsNullOrEmpty(argumentValue) ? LogLevel.Debug : ParseArgument(\"verbosity\", argumentValue);\n }", + "start_line": 19, + "end_line": 22, + "start_byte": 656, + "end_byte": 841 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Properties/AssemblyInfo.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/Commands/XHarnessCommand.cs": [ + { + "name": "CreateLoggerFactory", + "code": "private static ILoggerFactory CreateLoggerFactory(LogLevel verbosity) => LoggerFactory.Create(builder =>\n {\n builder\n .AddConsoleFormatter(options =>\n {\n options.ColorBehavior = EnvironmentVariables.IsTrue(EnvironmentVariables.Names.DISABLE_COLOR_OUTPUT) ? LoggerColorBehavior.Disabled : LoggerColorBehavior.Default;\n options.TimestampFormat = EnvironmentVariables.IsTrue(EnvironmentVariables.Names.LOG_TIMESTAMPS) ? \"[HH:mm:ss] \" : null!;\n })\n .AddConsole(options => options.FormatterName = XHarnessConsoleLoggerFormatter.FormatterName)\n .SetMinimumLevel(verbosity);\n });", + "start_line": 166, + "end_line": 176, + "start_byte": 5563, + "end_byte": 6296 + }, + { + "name": "InvokeInternal", + "code": "protected abstract Task InvokeInternal(ILogger logger);", + "start_line": 164, + "end_line": 164, + "start_byte": 5492, + "end_byte": 5557 + }, + { + "name": "Invoke", + "code": "public sealed override int Invoke(IEnumerable arguments)\n {\n var commandArguments = Arguments.GetCommandArguments();\n var options = new OptionSet();\n\n foreach (var arg in commandArguments)\n {\n options.Add(arg.Prototype, arg.Description, arg.Action);\n }\n\n using var parseFactory = CreateLoggerFactory(Arguments.Verbosity);\n var parseLogger = parseFactory.CreateLogger(Name);\n\n try\n {\n var regularArguments = arguments.TakeWhile(arg => arg != Program.VerbatimArgumentPlaceholder);\n if (regularArguments.Count() < arguments.Count())\n {\n PassThroughArguments = arguments.Skip(regularArguments.Count() + 1);\n arguments = regularArguments;\n }\n\n var extra = options.Parse(arguments);\n\n if (extra.Count > 0)\n {\n if (_allowsExtraArgs)\n {\n ExtraArguments = extra;\n }\n else\n {\n throw new ArgumentException($\"Unknown arguments: {string.Join(\" \", extra)}\");\n }\n }\n\n if (Arguments.ShowHelp)\n {\n Console.WriteLine(\"usage: \" + CommandUsage + Environment.NewLine + Environment.NewLine + CommandDescription + Environment.NewLine);\n options.WriteOptionDescriptions(Console.Out);\n return (int)ExitCode.HELP_SHOWN;\n }\n\n Arguments.Validate();\n }\n catch (ArgumentException e)\n {\n parseLogger.LogError(e.Message);\n\n if (Arguments.ShowHelp)\n {\n options.WriteOptionDescriptions(Console.Out);\n }\n\n return (int)ExitCode.INVALID_ARGUMENTS;\n }\n catch (Exception e)\n {\n parseLogger.LogCritical(\"Unexpected failure argument: {error}\", e);\n return (int)ExitCode.GENERAL_FAILURE;\n }\n\n // Should we and where output the diagnostics data?\n string? diagnosticsPath = Arguments.Diagnostics.Value ?? Environment.GetEnvironmentVariable(EnvironmentVariables.Names.DIAGNOSTICS_PATH);\n\n try\n {\n using var factory = CreateLoggerFactory(Arguments.Verbosity);\n ILogger logger = factory.CreateLogger(Name);\n var diagnostics = new CommandDiagnostics(logger, _targetPlatform, Name);\n\n Services.TryAddSingleton(logger);\n Services.TryAddSingleton(diagnostics);\n\n var result = InvokeInternal(logger).GetAwaiter().GetResult();\n\n diagnostics.ExitCode = result;\n\n // Save diagnostic data into a file\n if (result != ExitCode.HELP_SHOWN && !string.IsNullOrEmpty(diagnosticsPath))\n {\n diagnostics.SaveToJsonFile(diagnosticsPath);\n }\n\n return (int)result;\n }\n catch (Exception e)\n {\n parseLogger.LogCritical(e.ToString());\n return (int)ExitCode.GENERAL_FAILURE;\n }\n }", + "start_line": 71, + "end_line": 162, + "start_byte": 2371, + "end_byte": 5486 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/GetStateCommand.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/Commands/XHarnessVersionCommand.cs": [ + { + "name": "GetAssemblyVersion", + "code": "public static FileVersionInfo GetAssemblyVersion() => FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);", + "start_line": 34, + "end_line": 34, + "start_byte": 1063, + "end_byte": 1190 + }, + { + "name": "Invoke", + "code": "public override int Invoke(IEnumerable arguments)\n {\n var version = GetAssemblyVersion();\n\n if (!arguments.Contains(\"-v\"))\n {\n Console.WriteLine(version.ProductVersion);\n return 0;\n }\n \n // Print the name of the tool and the version number unix style\n // Example:\n // Apple clang version 11.0.3 (clang-1103.0.32.29)\n // Target: x86_64-apple-darwin19.4.0\n // InstalledDir: /Applications/Xcode114.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin\n Console.WriteLine($\"XHarness version {version.ProductVersion} ({version.OriginalFilename})\");\n Console.WriteLine($\"InstalledDir: {version.FileName}\");\n return 0;\n }", + "start_line": 14, + "end_line": 32, + "start_byte": 303, + "end_byte": 1057 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/XHarnessHelpCommand.cs": [ + { + "name": "PrintCommandHelp", + "code": "private static void PrintCommandHelp(CommandSet commandSet, string? subcommand)\n {\n if (subcommand != null)\n {\n var command = commandSet.Where(c => c.Name == subcommand).FirstOrDefault();\n if (command != null)\n {\n command.Invoke(new string[] { \"--help\" });\n return;\n }\n\n Console.WriteLine($\"Unknown sub-command '{subcommand}'.{Environment.NewLine}\");\n }\n\n Console.WriteLine(\"All supported sub-commands:\");\n commandSet.Run(new string[] { \"help\" });\n Console.WriteLine($\"{Environment.NewLine}Run 'xharness {commandSet.Suite} {{command}} --help' for more details\");\n }", + "start_line": 82, + "end_line": 99, + "start_byte": 2683, + "end_byte": 3381 + }, + { + "name": "Invoke", + "code": "public override int Invoke(IEnumerable arguments)\n {\n string[] args = arguments.ToArray();\n\n if (args.Length == 0)\n {\n base.Invoke(arguments);\n return (int)ExitCode.HELP_SHOWN;\n }\n\n var command = args[0].ToLowerInvariant();\n\n string? subCommand = null;\n if (args.Length >= 2)\n {\n subCommand = args[1];\n }\n\n // Unfortunately, CommandSet.NestedCommandSets is not visible and we cannot go through\n // the command tree dynamically to any depth.\n switch (command)\n {\n case \"android\":\n PrintCommandHelp(new AndroidCommandSet(), subCommand);\n break;\n case \"apple\":\n#if !DEBUG\n if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\n {\n#endif\n var simulatorsSubset = new SimulatorsCommandSet();\n if (subCommand == simulatorsSubset.Suite)\n {\n PrintCommandHelp(simulatorsSubset, args.ElementAtOrDefault(2));\n }\n else\n {\n PrintCommandHelp(new AppleCommandSet(), subCommand);\n }\n#if !DEBUG\n }\n else\n {\n Console.WriteLine($\"Command '{command}' could be run on OSX only.\");\n }\n#endif\n break;\n case \"wasm\":\n PrintCommandHelp(new WasmCommandSet(), subCommand);\n break;\n case \"wasi\":\n PrintCommandHelp(new WasiCommandSet(), subCommand);\n break;\n default:\n Console.WriteLine($\"No help available for command '{command}'. Allowed commands are 'apple', 'wasm', 'wasi' and 'android'\");\n break;\n }\n\n return (int)ExitCode.HELP_SHOWN;\n }", + "start_line": 21, + "end_line": 80, + "start_byte": 745, + "end_byte": 2677 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/WebServer.cs": [ + { + "name": "FromArguments", + "code": "public static TestWebServerOptions FromArguments(IWebServerArguments arguments)\r\n {\r\n TestWebServerOptions options = new();\r\n options.UseCors = arguments.WebServerUseCors;\r\n options.UseHttps = arguments.WebServerUseHttps;\r\n options.UseCrossOriginPolicy = arguments.WebServerUseCrossOriginPolicy;\r\n options.UseDefaultFiles = arguments.WebServerUseDefaultFiles;\r\n options.WebServerUploadResults = arguments.WebServerUploadResults;\r\n options.OutputDirectory = arguments.OutputDirectory;\r\n foreach (var middlewareType in arguments.WebServerMiddlewarePathsAndTypes.GetLoadedTypes())\r\n {\r\n options.EchoServerMiddlewares.Add(middlewareType);\r\n }\r\n return options;\r\n }", + "start_line": 227, + "end_line": 241, + "start_byte": 8916, + "end_byte": 9726 + }, + { + "name": "CopyTo", + "code": "public void CopyTo(TestWebServerOptions otherOptions)\r\n {\r\n otherOptions.OnConsoleConnected = OnConsoleConnected;\r\n otherOptions.EchoServerMiddlewares = EchoServerMiddlewares;\r\n otherOptions.UseCors = UseCors;\r\n otherOptions.UseHttps = UseHttps;\r\n otherOptions.UseCrossOriginPolicy = UseCrossOriginPolicy;\r\n otherOptions.UseDefaultFiles = UseDefaultFiles;\r\n otherOptions.WebServerUploadResults = WebServerUploadResults;\r\n otherOptions.OutputDirectory = OutputDirectory;\r\n otherOptions.ContentRoot = ContentRoot;\r\n }", + "start_line": 214, + "end_line": 225, + "start_byte": 8276, + "end_byte": 8904 + }, + { + "name": "Configure", + "code": "public void Configure(IApplicationBuilder app, IOptionsMonitor optionsAccessor)\r\n {\r\n var provider = new FileExtensionContentTypeProvider();\r\n provider.Mappings[\".wasm\"] = \"application/wasm\";\r\n provider.Mappings[\".cjs\"] = \"text/javascript\";\r\n provider.Mappings[\".mjs\"] = \"text/javascript\";\r\n\r\n foreach (var extn in new string[] { \".dll\", \".pdb\", \".dat\", \".blat\", \".webcil\" })\r\n {\r\n provider.Mappings[extn] = \"application/octet-stream\";\r\n }\r\n\r\n var options = optionsAccessor.CurrentValue;\r\n\r\n if (options.UseCrossOriginPolicy)\r\n {\r\n app.Use((context, next) =>\r\n {\r\n context.Response.Headers.Append(\"Cross-Origin-Embedder-Policy\", \"require-corp\");\r\n context.Response.Headers.Append(\"Cross-Origin-Opener-Policy\", \"same-origin\");\r\n return next();\r\n });\r\n }\r\n\r\n if (options.UseDefaultFiles)\r\n {\r\n app.UseDefaultFiles(new DefaultFilesOptions\r\n {\r\n FileProvider = new PhysicalFileProvider(_hostingEnvironment.ContentRootPath)\r\n });\r\n }\r\n\r\n app.UseStaticFiles(new StaticFileOptions\r\n {\r\n FileProvider = new PhysicalFileProvider(_hostingEnvironment.ContentRootPath),\r\n ContentTypeProvider = provider,\r\n ServeUnknownFileTypes = true\r\n });\r\n\r\n if (options.UseCors)\r\n {\r\n app.UseCors(\"AnyCors\");\r\n }\r\n app.UseWebSockets();\r\n if (options.OnConsoleConnected != null)\r\n {\r\n app.UseRouter(router =>\r\n {\r\n router.MapGet(\"/console\", async context =>\r\n {\r\n if (!context.WebSockets.IsWebSocketRequest)\r\n {\r\n context.Response.StatusCode = 400;\r\n return;\r\n }\r\n\r\n var socket = await context.WebSockets.AcceptWebSocketAsync();\r\n await options.OnConsoleConnected(socket);\r\n });\r\n });\r\n }\r\n if (options.WebServerUploadResults)\r\n {\r\n app.UseRouter(router =>\r\n {\r\n router.MapPost(\"/test-results\", async context =>\r\n {\r\n var xmlResultsFilePath = Path.Combine(options.OutputDirectory!, \"testResults.xml\");\r\n\r\n await using var fileStream = File.Create(xmlResultsFilePath);\r\n await context.Request.BodyReader.CopyToAsync(fileStream);\r\n _logger.LogInformation($\"Stored {xmlResultsFilePath} results {fileStream.Position} bytes\");\r\n });\r\n });\r\n }\r\n\r\n foreach (var middleware in options.EchoServerMiddlewares)\r\n {\r\n app.UseMiddleware(middleware);\r\n _logger.LogInformation($\"Loaded {middleware.FullName} middleware\");\r\n }\r\n }", + "start_line": 118, + "end_line": 199, + "start_byte": 4405, + "end_byte": 7695 + }, + { + "name": "Start", + "code": "internal static async Task Start(TestWebServerOptions webServerOptions, ILogger logger, CancellationToken token)\r\n {\r\n var urls = webServerOptions.UseHttps\r\n ? new string[] { \"http://127.0.0.1:0\", \"https://127.0.0.1:0\" }\r\n : new string[] { \"http://127.0.0.1:0\" };\r\n\r\n var builder = new WebHostBuilder()\r\n .UseKestrel()\r\n .UseStartup()\r\n .ConfigureLogging(logging =>\r\n {\r\n logging.AddConsole().AddFilter(null, LogLevel.Warning);\r\n })\r\n .ConfigureServices((ctx, services) =>\r\n {\r\n if (webServerOptions.UseCors)\r\n {\r\n services.AddCors(o => o.AddPolicy(\"AnyCors\", builder =>\r\n {\r\n builder.AllowAnyOrigin()\r\n .AllowAnyMethod()\r\n .AllowAnyHeader()\r\n .WithExposedHeaders(\"*\");\r\n }));\r\n }\r\n services.AddRouting();\r\n services.AddSingleton(logger);\r\n services.Configure(ctx.Configuration);\r\n services.Configure(options =>\r\n {\r\n webServerOptions.CopyTo(options);\r\n });\r\n })\r\n .UseUrls(urls);\r\n\r\n if (webServerOptions.ContentRoot != null)\r\n {\r\n builder.UseContentRoot(webServerOptions.ContentRoot);\r\n }\r\n\r\n var host = builder.Build();\r\n\r\n await host.StartAsync(token);\r\n\r\n var ipAddress = host.ServerFeatures\r\n .Get()?\r\n .Addresses\r\n .Where(a => a.StartsWith(\"http:\"))\r\n .Select(a => new Uri(a))\r\n .Select(uri => $\"{uri.Host}:{uri.Port}\")\r\n .FirstOrDefault();\r\n\r\n var ipAddressSecure = webServerOptions.UseHttps\r\n ? host.ServerFeatures\r\n .Get()?\r\n .Addresses\r\n .Where(a => a.StartsWith(\"https:\"))\r\n .Select(a => new Uri(a))\r\n .Select(uri => $\"{uri.Host}:{uri.Port}\")\r\n .FirstOrDefault()\r\n : null;\r\n\r\n if (ipAddress == null || (webServerOptions.UseHttps && ipAddressSecure == null))\r\n {\r\n throw new InvalidOperationException(\"Failed to determine web server's IP address or port\");\r\n }\r\n\r\n return new ServerURLs(ipAddress, ipAddressSecure);\r\n }", + "start_line": 37, + "end_line": 105, + "start_byte": 1384, + "end_byte": 4031 + }, + { + "name": "Start", + "code": "internal static Task Start(IWebServerArguments arguments, ILogger logger, CancellationToken token, Func? onConsoleConnected = null)\r\n {\r\n var options = TestWebServerOptions.FromArguments(arguments);\r\n options.OnConsoleConnected = onConsoleConnected;\r\n return Start(options, logger, token);\r\n }", + "start_line": 30, + "end_line": 35, + "start_byte": 1027, + "end_byte": 1376 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/AppleMlaunchCommand.cs": [ + { + "name": "AsCommandLineArgument", + "code": "public override string AsCommandLineArgument() => Escape(_argument);", + "start_line": 90, + "end_line": 90, + "start_byte": 3453, + "end_byte": 3521 + }, + { + "name": "Invoke", + "code": "protected override async Task Invoke(ILogger logger)\n {\n if (!PassThroughArguments.Any())\n {\n logger.LogError(\"Please provide delimeter '--' followed by arguments for ADB:\" + Environment.NewLine +\n $\" {CommandUsage}\" + Environment.NewLine +\n $\"Example:\" + Environment.NewLine +\n $\" apple mlaunch --timeout 00:01:30 -- devices -l\");\n\n return ExitCode.INVALID_ARGUMENTS;\n }\n\n var processManager = Services.BuildServiceProvider().GetRequiredService();\n\n try\n {\n var nullLog = new CallbackLog(s => { });\n var stdout = new CallbackLog(Console.Write);\n var stderr = new CallbackLog(Console.Error.Write);\n\n var args = new MlaunchArguments(PassThroughArguments.Select(arg => new SimpleMlaunchArgument(arg)).ToArray());\n\n var cts = new CancellationTokenSource();\n cts.CancelAfter(Arguments.Timeout);\n\n var result = await processManager.ExecuteCommandAsync(\n args,\n Arguments.Verbosity < LogLevel.Information ? stdout : nullLog,\n Arguments.Verbosity <= LogLevel.Warning ? stdout : nullLog,\n stderr,\n Arguments.Timeout,\n Arguments.EnvironmentalVariables.Value.ToDictionary(t => t.Item1, t => t.Item2),\n verbosity: 0, // -v needs to be supplied by user\n cts.Token);\n\n if (result.TimedOut)\n {\n return ExitCode.TIMED_OUT;\n }\n\n return (ExitCode)result.ExitCode;\n }\n catch (Exception e)\n {\n logger.LogError(e.ToString());\n return ExitCode.GENERAL_FAILURE;\n }\n }", + "start_line": 30, + "end_line": 77, + "start_byte": 1186, + "end_byte": 2992 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/AppleResetSimulatorCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override Task InvokeInternal(ServiceProvider serviceProvider, CancellationToken cancellationToken) =>\n serviceProvider.GetRequiredService()\n .OrchestrateSimulatorReset(Arguments.Target, Arguments.DeviceName, Arguments.Timeout, cancellationToken);", + "start_line": 26, + "end_line": 28, + "start_byte": 1127, + "end_byte": 1440 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/AppleStateCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override async Task InvokeInternal(Extensions.Logging.ILogger logger)\n {\n var processManager = new MlaunchProcessManager(xcodeRoot: Arguments.XcodeRoot, mlaunchPath: Arguments.MlaunchPath);\n var deviceLoader = new HardwareDeviceLoader(processManager);\n var simulatorLoader = new SimulatorLoader(processManager);\n var log = new MemoryLog(); // do we really want to log this?\n\n var mlaunchLog = new MemoryLog { Timestamp = false };\n\n ProcessExecutionResult result;\n\n try\n {\n result = await processManager.ExecuteCommandAsync(new MlaunchArguments(new MlaunchVersionArgument()), new NullLog(), mlaunchLog, new NullLog(), TimeSpan.FromSeconds(10));\n }\n catch (Exception e)\n {\n logger.LogError($\"Failed to get mlaunch version info:{Environment.NewLine}{e}\");\n return ExitCode.GENERAL_FAILURE;\n }\n\n if (!result.Succeeded)\n {\n logger.LogError($\"Failed to get mlaunch version info:{Environment.NewLine}{mlaunchLog}\");\n return ExitCode.GENERAL_FAILURE;\n }\n\n // build the required data, then depending on the format print out\n var info = new SystemInfo(\n machineName: Environment.MachineName,\n oSName: \"Mac OS X\",\n oSVersion: Darwin.GetVersion() ?? \"\",\n oSPlatform: \"Darwin\",\n xcodePath: processManager.XcodeRoot,\n xcodeVersion: processManager.XcodeVersion.ToString(),\n mlaunchPath: processManager.MlaunchPath,\n mlaunchVersion: mlaunchLog.ToString().Trim());\n\n try\n {\n await simulatorLoader.LoadDevices(log);\n }\n catch (Exception e)\n {\n logger.LogError($\"Failed to load simulators:{Environment.NewLine}{e}\");\n logger.LogInformation($\"Execution log:{Environment.NewLine}{log}\");\n return ExitCode.GENERAL_FAILURE;\n }\n\n foreach (var sim in simulatorLoader.AvailableDevices)\n {\n info.Simulators.Add(new DeviceInfo(\n name: sim.Name,\n uDID: sim.UDID,\n type: sim.SimDeviceType.Remove(0, SimulatorPrefix.Length).Replace('-', ' '),\n oSVersion: sim.OSVersion));\n }\n\n try\n {\n await deviceLoader.LoadDevices(log, includeWirelessDevices: Arguments.IncludeWireless);\n }\n catch (Exception e)\n {\n logger.LogError($\"Failed to load connected devices:{Environment.NewLine}{e}\");\n logger.LogInformation($\"Execution log:{Environment.NewLine}{log}\");\n return ExitCode.GENERAL_FAILURE;\n }\n\n foreach (var dev in deviceLoader.ConnectedDevices)\n {\n info.Devices.Add(new DeviceInfo(\n name: dev.Name,\n uDID: dev.DeviceIdentifier,\n type: $\"{dev.DeviceClass} {dev.DevicePlatform}\",\n oSVersion: dev.OSVersion,\n isPaired: dev.IsPaired));\n }\n\n if (Arguments.UseJson)\n {\n await AsJson(info);\n }\n else\n {\n AsText(info);\n }\n\n return ExitCode.SUCCESS;\n }", + "start_line": 144, + "end_line": 233, + "start_byte": 4897, + "end_byte": 8133 + }, + { + "name": "AsText", + "code": "private void AsText(SystemInfo info)\n {\n Console.WriteLine(\"Runtime Enviroment:\");\n Console.WriteLine($\" Machine name:\\t{info.MachineName}\");\n Console.WriteLine($\" OS Name:\\t{info.OSName}\");\n Console.WriteLine($\" OS Version:\\t{info.OSVersion}\");\n Console.WriteLine($\" OS Platform:\\t{info.OSPlatform}\");\n\n Console.WriteLine();\n\n Console.WriteLine(\"Developer Tools:\");\n\n Console.WriteLine($\" Xcode:\\t{info.XcodeVersion} - {info.XcodePath}\");\n Console.WriteLine($\" Mlaunch:\\t{info.MlaunchVersion} - {info.MlaunchPath}\");\n\n Console.WriteLine();\n\n Console.WriteLine(\"Installed Simulators:\");\n\n if (info.Simulators.Any())\n {\n var maxLength = info.Simulators.Select(s => s.Name.Length).Max();\n\n foreach (var sim in info.Simulators)\n {\n var uuid = Arguments.ShowSimulatorsUUID ? $\"{sim.UDID} \" : string.Empty;\n Console.WriteLine($\" {uuid}{sim.Name.PadRight(maxLength)} {sim.OSVersion,-13} {sim.Type}\");\n }\n }\n else\n {\n Console.WriteLine(\" none\");\n }\n\n Console.WriteLine();\n\n Console.WriteLine(\"Connected Devices:\");\n\n if (info.Devices.Any())\n {\n var maxLength = info.Devices.Select(s => s.Name.Length).Max();\n\n foreach (var dev in info.Devices)\n {\n var uuid = Arguments.ShowDevicesUUID ? $\" {dev.UDID} \" : \"\";\n var notPaired = dev.IsPaired ? \"\" : \"(not paired) \";\n Console.WriteLine($\" {notPaired}{dev.Name.PadRight(maxLength)}{uuid} {dev.OSVersion,-13} {dev.Type}\");\n }\n }\n else\n {\n Console.WriteLine(\" none\");\n }\n }", + "start_line": 89, + "end_line": 142, + "start_byte": 3104, + "end_byte": 4891 + }, + { + "name": "AsJson", + "code": "private static async Task AsJson(SystemInfo info)\n {\n var options = new JsonSerializerOptions\n {\n WriteIndented = true\n };\n await JsonSerializer.SerializeAsync(Console.OpenStandardOutput(), info, options);\n Console.WriteLine();\n }", + "start_line": 79, + "end_line": 87, + "start_byte": 2816, + "end_byte": 3098 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/AppleCommandSet.cs": [ + { + "name": "GetAppleDependencies", + "code": "public static IServiceCollection GetAppleDependencies()\n {\n var services = new ServiceCollection();\n\n services.TryAddSingleton();\n services.TryAddSingleton();\n services.TryAddSingleton();\n services.TryAddSingleton();\n services.TryAddSingleton();\n services.TryAddSingleton();\n services.TryAddSingleton();\n\n services.TryAddTransient();\n services.TryAddTransient();\n services.TryAddTransient();\n services.TryAddTransient();\n services.TryAddTransient();\n services.TryAddTransient();\n\n services.TryAddTransient();\n services.TryAddTransient();\n services.TryAddTransient();\n services.TryAddTransient();\n services.TryAddTransient();\n services.TryAddTransient();\n\n services.TryAddTransient();\n services.TryAddTransient();\n services.TryAddTransient();\n services.TryAddTransient();\n services.TryAddTransient();\n services.TryAddTransient();\n services.TryAddTransient();\n\n return services;\n }", + "start_line": 43, + "end_line": 78, + "start_byte": 1598, + "end_byte": 3724 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/AppleInstallCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override Task InvokeInternal(ServiceProvider serviceProvider, CancellationToken cancellationToken) =>\n serviceProvider.GetRequiredService()\n .OrchestrateInstall(\n Arguments.Target,\n Arguments.DeviceName,\n Arguments.AppBundlePath,\n Arguments.Timeout,\n Arguments.IncludeWireless,\n Arguments.ResetSimulator,\n enableLldb: false,\n cancellationToken);", + "start_line": 27, + "end_line": 37, + "start_byte": 1169, + "end_byte": 1694 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/AppleJustTestCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override Task InvokeInternal(ServiceProvider serviceProvider, CancellationToken cancellationToken) =>\n serviceProvider.GetRequiredService()\n .OrchestrateTest(\n Arguments.BundleIdentifier,\n Arguments.Target,\n Arguments.DeviceName,\n Arguments.Timeout,\n Arguments.LaunchTimeout,\n Arguments.CommunicationChannel,\n Arguments.XmlResultJargon,\n Arguments.SingleMethodFilters.Value,\n Arguments.ClassMethodFilters.Value,\n includeWirelessDevices: Arguments.IncludeWireless,\n enableLldb: Arguments.EnableLldb,\n signalAppEnd: Arguments.SignalAppEnd,\n Arguments.EnvironmentalVariables.Value,\n PassThroughArguments,\n cancellationToken);", + "start_line": 26, + "end_line": 43, + "start_byte": 1208, + "end_byte": 2116 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/AppleAppCommand.cs": [ + { + "name": "LogCritical", + "code": "public void LogCritical(string message) => _logger.LogCritical(message);", + "start_line": 87, + "end_line": 87, + "start_byte": 4131, + "end_byte": 4203 + }, + { + "name": "LogError", + "code": "public void LogError(string message) => _logger.LogError(message);", + "start_line": 86, + "end_line": 86, + "start_byte": 4055, + "end_byte": 4121 + }, + { + "name": "LogWarning", + "code": "public void LogWarning(string message) => _logger.LogWarning(message);", + "start_line": 85, + "end_line": 85, + "start_byte": 3975, + "end_byte": 4045 + }, + { + "name": "LogInformation", + "code": "public void LogInformation(string message) => _logger.LogInformation(message);", + "start_line": 84, + "end_line": 84, + "start_byte": 3887, + "end_byte": 3965 + }, + { + "name": "LogDebug", + "code": "public void LogDebug(string message) => _logger.LogDebug(message);", + "start_line": 83, + "end_line": 83, + "start_byte": 3811, + "end_byte": 3877 + }, + { + "name": "InvokeInternal", + "code": "protected abstract Task InvokeInternal(ServiceProvider serviceProvider, CancellationToken cancellationToken);", + "start_line": 71, + "end_line": 71, + "start_byte": 3262, + "end_byte": 3381 + }, + { + "name": "Invoke", + "code": "protected sealed override async Task Invoke(Extensions.Logging.ILogger logger)\r\n {\r\n var targetName = Arguments.Target.Value.AsString();\r\n\r\n logger.LogInformation(\"Preparing run for {target}\", targetName + (!string.IsNullOrEmpty(Arguments.DeviceName.Value) ? \" targeting \" + Arguments.DeviceName.Value : null));\r\n\r\n // Create main log file for the run\r\n using ILogs logs = new Logs(Arguments.OutputDirectory);\r\n string logFileName = $\"{Name}-{targetName}{(!string.IsNullOrEmpty(Arguments.DeviceName.Value) ? \"-\" + Arguments.DeviceName.Value : null)}.log\";\r\n IFileBackedLog runLog = logs.Create(logFileName, LogType.ExecutionLog.ToString(), timestamp: true);\r\n\r\n // Pipe the execution log to the debug output of XHarness effectively making \"-v\" turn this on\r\n CallbackLog debugLog = new(message => logger.LogDebug(message.Trim()));\r\n using var mainLog = Log.CreateReadableAggregatedLog(runLog, debugLog);\r\n\r\n Services.TryAddSingleton(logs);\r\n Services.TryAddTransient();\r\n\r\n Services.TryAddSingleton(mainLog);\r\n Services.TryAddSingleton(mainLog);\r\n Services.TryAddSingleton(mainLog);\r\n\r\n var serviceProvider = Services.BuildServiceProvider();\r\n\r\n var diagnosticsData = serviceProvider.GetRequiredService();\r\n diagnosticsData.Target = Arguments.Target.Value.AsString();\r\n diagnosticsData.IsDevice = !Arguments.Target.Value.Platform.IsSimulator();\r\n\r\n var cts = new CancellationTokenSource();\r\n cts.CancelAfter(Arguments.Timeout);\r\n cts.Token.Register(() =>\r\n {\r\n logger.LogError(\"Run timed out after {timeout} seconds\", Math.Ceiling(Arguments.Timeout.Value.TotalSeconds));\r\n });\r\n\r\n return await InvokeInternal(serviceProvider, cts.Token);\r\n }", + "start_line": 33, + "end_line": 69, + "start_byte": 1341, + "end_byte": 3254 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/AppleUninstallCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override Task InvokeInternal(ServiceProvider serviceProvider, CancellationToken cancellationToken) =>\n serviceProvider.GetRequiredService()\n .OrchestrateAppUninstall(\n Arguments.BundleIdentifier,\n Arguments.Target,\n Arguments.DeviceName,\n Arguments.Timeout,\n Arguments.IncludeWireless,\n resetSimulator: false,\n enableLldb: false,\n cancellationToken);", + "start_line": 26, + "end_line": 36, + "start_byte": 1184, + "end_byte": 1716 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/AppleRunCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override Task InvokeInternal(ServiceProvider serviceProvider, CancellationToken cancellationToken) =>\n serviceProvider.GetRequiredService()\n .OrchestrateRun(\n appBundlePath: Arguments.AppBundlePath,\n target: Arguments.Target,\n deviceName: Arguments.DeviceName,\n timeout: Arguments.Timeout,\n launchTimeout: Arguments.LaunchTimeout,\n expectedExitCode: Arguments.ExpectedExitCode,\n includeWirelessDevices: Arguments.IncludeWireless,\n resetSimulator: Arguments.ResetSimulator,\n enableLldb: Arguments.EnableLldb,\n signalAppEnd: Arguments.SignalAppEnd,\n waitForExit: !Arguments.NoWait,\n environmentalVariables: Arguments.EnvironmentalVariables.Value,\n passthroughArguments: PassThroughArguments,\n cancellationToken);", + "start_line": 30, + "end_line": 46, + "start_byte": 1362, + "end_byte": 2338 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/AppleJustRunCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override Task InvokeInternal(ServiceProvider serviceProvider, CancellationToken cancellationToken) =>\n serviceProvider.GetRequiredService()\n .OrchestrateRun(\n bundleIdentifier: Arguments.BundleIdentifier,\n target: Arguments.Target,\n deviceName: Arguments.DeviceName,\n timeout: Arguments.Timeout,\n launchTimeout: Arguments.Timeout,\n expectedExitCode: Arguments.ExpectedExitCode,\n includeWirelessDevices: Arguments.IncludeWireless,\n enableLldb: Arguments.EnableLldb,\n signalAppEnd: Arguments.SignalAppEnd,\n waitForExit: !Arguments.NoWait,\n environmentalVariables: Arguments.EnvironmentalVariables.Value,\n passthroughArguments: PassThroughArguments,\n cancellationToken);", + "start_line": 27, + "end_line": 42, + "start_byte": 1249, + "end_byte": 2171 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/AppleCommand.cs": [ + { + "name": "Invoke", + "code": "protected abstract Task Invoke(ILogger logger);", + "start_line": 34, + "end_line": 34, + "start_byte": 1441, + "end_byte": 1498 + }, + { + "name": "InvokeInternal", + "code": "protected sealed override Task InvokeInternal(ILogger logger)\n {\n var processManager = new MlaunchProcessManager(Arguments.XcodeRoot, Arguments.MlaunchPath);\n Services.TryAddSingleton(processManager);\n Services.TryAddSingleton(processManager);\n Services.TryAddSingleton(processManager);\n\n return Invoke(logger);\n }", + "start_line": 24, + "end_line": 32, + "start_byte": 1007, + "end_byte": 1435 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/AppleTestCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override Task InvokeInternal(ServiceProvider serviceProvider, CancellationToken cancellationToken) =>\n serviceProvider.GetRequiredService()\n .OrchestrateTest(\n Arguments.AppBundlePath,\n Arguments.Target,\n Arguments.DeviceName,\n Arguments.Timeout,\n Arguments.LaunchTimeout,\n Arguments.CommunicationChannel,\n Arguments.XmlResultJargon,\n Arguments.SingleMethodFilters.Value,\n Arguments.ClassMethodFilters.Value,\n includeWirelessDevices: Arguments.IncludeWireless,\n resetSimulator: Arguments.ResetSimulator,\n enableLldb: Arguments.EnableLldb,\n signalAppEnd: Arguments.SignalAppEnd,\n Arguments.EnvironmentalVariables.Value,\n PassThroughArguments,\n cancellationToken);", + "start_line": 30, + "end_line": 48, + "start_byte": 1361, + "end_byte": 2320 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/AppleDeviceCommand.cs": [ + { + "name": "ParseTarget", + "code": "private TestTargetOs ParseTarget()\n {\n if (ExtraArguments.Count() != 1)\n {\n throw new ArgumentException(\"You have to specify one target platform\");\n }\n\n var target = new TargetArgument();\n target.Action(ExtraArguments.First());\n target.Validate();\n\n if (target.Value.Platform == TestTarget.MacCatalyst)\n {\n throw new ArgumentException(\"Target maccatalyst is not supported for this command\");\n }\n\n return target.Value;\n }", + "start_line": 76, + "end_line": 93, + "start_byte": 2569, + "end_byte": 3087 + }, + { + "name": "Invoke", + "code": "protected override async Task Invoke(Extensions.Logging.ILogger logger)\n {\n var log = new CallbackLog(m => logger.LogDebug(m));\n TestTargetOs target;\n\n try\n {\n target = ParseTarget();\n }\n catch (Exception e)\n {\n logger.LogError(e.Message);\n return ExitCode.INVALID_ARGUMENTS;\n }\n\n var serviceProvider = Services.BuildServiceProvider();\n var deviceFinder = serviceProvider.GetRequiredService();\n var diagnosticsData = serviceProvider.GetRequiredService();\n diagnosticsData.Target = target.AsString();\n\n try\n {\n var device = (await deviceFinder.FindDevice(target, Arguments.DeviceName, log, Arguments.IncludeWireless)).Device;\n\n diagnosticsData.TargetOS = device.OSVersion.Split(' ', 2).Last();\n diagnosticsData.Device = device.Name ?? device.UDID;\n diagnosticsData.IsDevice = !target.Platform.IsSimulator();\n\n Console.WriteLine(device.UDID);\n }\n catch (Exception e)\n {\n logger.LogError(e.ToString());\n return ExitCode.DEVICE_NOT_FOUND;\n }\n\n return ExitCode.SUCCESS;\n }", + "start_line": 37, + "end_line": 74, + "start_byte": 1304, + "end_byte": 2563 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/WASM/WasmTestMessagesProcessor.cs": [ + { + "name": "ProcessErrorMessage", + "code": "public void ProcessErrorMessage(string message) => Invoke(message, isError: true);", + "start_line": 259, + "end_line": 259, + "start_byte": 8762, + "end_byte": 8844 + }, + { + "name": "ScanMessageForErrorPatterns", + "code": "private void ScanMessageForErrorPatterns(string message)\n {\n if (LineThatMatchedErrorPattern != null || _errorScanner == null)\n return;\n\n if (_errorScanner.Value.IsError(message, out string? _))\n LineThatMatchedErrorPattern = message;\n }", + "start_line": 250, + "end_line": 257, + "start_byte": 8477, + "end_byte": 8756 + }, + { + "name": "Symbolicate", + "code": "private string Symbolicate(string msg)\n {\n if (_symbolicator is null)\n return msg;\n\n return _symbolicator.Symbolicate(msg);\n }", + "start_line": 242, + "end_line": 248, + "start_byte": 8314, + "end_byte": 8471 + }, + { + "name": "ProcessMessage", + "code": "private void ProcessMessage(string message, bool isError = false)\n {\n WasmLogMessage? logMessage = null;\n string line;\n\n if (message.StartsWith(\"{\"))\n {\n try\n {\n logMessage = JsonSerializer.Deserialize(message);\n if (logMessage != null)\n {\n line = logMessage.payload + \" \" + string.Join(\" \", logMessage.arguments ?? Enumerable.Empty());\n }\n else\n {\n line = message;\n }\n }\n catch (JsonException e)\n {\n _logger.LogError(e.Message);\n line = message;\n }\n }\n else\n {\n line = message;\n }\n\n line = line.TrimEnd();\n\n var match = xmlRx.Match(line);\n if (match.Success)\n {\n var expectedLength = Int32.Parse(match.Groups[1].Value);\n using (var stream = new FileStream(_xmlResultsFilePath, FileMode.Create))\n {\n var bytes = System.Convert.FromBase64String(match.Groups[2].Value);\n stream.Write(bytes);\n if (bytes.Length == expectedLength)\n {\n _logger.LogInformation($\"Received expected {bytes.Length} of {_xmlResultsFilePath}\");\n }\n else\n {\n _logger.LogInformation($\"Received {bytes.Length} of {_xmlResultsFilePath} but expected {expectedLength}\");\n }\n }\n }\n else\n {\n ScanMessageForErrorPatterns(line);\n line = Symbolicate(line);\n\n switch (logMessage?.method?.ToLowerInvariant())\n {\n case \"console.debug\": _logger.LogDebug(line); break;\n case \"console.error\": _logger.LogError(line); break;\n case \"console.warn\": _logger.LogWarning(line); break;\n case \"console.trace\": _logger.LogTrace(line); break;\n case \"console.log\":\n default: _logger.LogInformation(line); break;\n }\n\n if (_stdoutFileWriter.BaseStream.CanWrite)\n _stdoutFileWriter.WriteLine(line);\n }\n\n // the test runner writes this as the last line,\n // after the tests have run, and the xml results file\n // has been written to the console\n if (line.StartsWith(\"WASM EXIT\"))\n {\n _logger.LogDebug(\"Reached wasm exit\");\n\n // until WASI can work with unix exit code https://github.com/WebAssembly/wasi-cli/pull/44\n if (line.Length > 10)\n {\n // the message on WASI looks like WASM EXIT 123\n // here we strip the first 10 characters and parse the rest\n ForwardedExitCode = int.Parse(line.Substring(10));\n }\n if (!WasmExitReceivedTcs.TrySetResult())\n _logger.LogDebug(\"Got a duplicate exit message.\");\n }\n }", + "start_line": 154, + "end_line": 240, + "start_byte": 5229, + "end_byte": 8308 + }, + { + "name": "CompleteAndFlushAsync", + "code": "public async Task CompleteAndFlushAsync(TimeSpan? timeout = null)\n {\n timeout ??= s_logMessagesTimeout;\n _logger.LogInformation($\"Waiting to flush log messages with a timeout of {timeout.Value.TotalSeconds} secs ..\");\n\n try\n {\n _channelWriter.TryComplete();\n await _completed.Task.WaitAsync(timeout.Value);\n return ExitCode.SUCCESS;\n }\n catch (TimeoutException)\n {\n _logger.LogError($\"Flushing log messages timed out after {s_logMessagesTimeout.TotalSeconds}secs\");\n return ExitCode.TIMED_OUT;\n }\n catch (Exception ex)\n {\n _logger.LogError($\"Flushing log messages failed with: {ex}. Ignoring.\");\n return ExitCode.GENERAL_FAILURE;\n }\n }", + "start_line": 131, + "end_line": 152, + "start_byte": 4418, + "end_byte": 5223 + }, + { + "name": "LogMessage", + "code": "private void LogMessage(string message, bool isError)\n {\n if (isError)\n _logger.LogError(message);\n else\n _logger.LogInformation(message);\n }", + "start_line": 123, + "end_line": 129, + "start_byte": 4229, + "end_byte": 4412 + }, + { + "name": "WarnOnceIfStopped", + "code": "private void WarnOnceIfStopped()\n {\n if (!_isRunning && !_loggedProcessorStopped)\n {\n _logger.LogWarning($\"Message processor is not running anymore.\");\n _loggedProcessorStopped = true;\n }\n }", + "start_line": 114, + "end_line": 121, + "start_byte": 3984, + "end_byte": 4223 + }, + { + "name": "InvokeAsync", + "code": "public Task InvokeAsync(string message, CancellationToken token, bool isError = false)\n {\n string? logMsg;\n try\n {\n WarnOnceIfStopped();\n if (_isRunning)\n return _channelWriter.WriteAsync((message, isError), token).AsTask();\n\n logMsg = message.TrimEnd();\n }\n catch (ChannelClosedException cce)\n {\n logMsg = $\"Failed to write to the channel - {cce.Message}. Message: {message}\";\n }\n\n LogMessage(logMsg, isError);\n return Task.CompletedTask;\n }", + "start_line": 94, + "end_line": 112, + "start_byte": 3408, + "end_byte": 3978 + }, + { + "name": "Invoke", + "code": "public void Invoke(string message, bool isError = false)\n {\n WarnOnceIfStopped();\n\n if (_isRunning && _channelWriter.TryWrite((message, isError)))\n return;\n\n LogMessage(message.TrimEnd(), isError);\n }", + "start_line": 84, + "end_line": 92, + "start_byte": 3164, + "end_byte": 3402 + }, + { + "name": "RunAsync", + "code": "public async Task RunAsync(CancellationToken token)\n {\n try\n {\n await foreach ((string line, bool isError) in _channelReader.ReadAllAsync(token))\n {\n ProcessMessage(line, isError);\n }\n _completed.SetResult();\n }\n catch (Exception ex)\n {\n _channelWriter.TryComplete(ex);\n\n // surface the exception from task for this method\n // and from _completed\n _completed.SetException(ex);\n throw;\n }\n }", + "start_line": 63, + "end_line": 82, + "start_byte": 2606, + "end_byte": 3158 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/WASM/WasmLogMessage.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/Commands/WASM/WasmCommandSet.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/Commands/WASM/WebServerCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override async Task InvokeInternal(ILogger logger)\n {\n var cts = new CancellationTokenSource();\n var webServerOptions = WebServer.TestWebServerOptions.FromArguments(Arguments);\n webServerOptions.ContentRoot = Arguments.AppPackagePath;\n ServerURLs serverURLs = await WebServer.Start(\n webServerOptions,\n logger,\n cts.Token);\n\n logger.LogInformation($\"Now listening on: http://{serverURLs.Http}\");\n if (!string.IsNullOrEmpty(serverURLs.Https))\n logger.LogInformation($\"Now listening on: https://{serverURLs.Https}\");\n\n await Task.Delay(Arguments.Timeout, cts.Token);\n if (cts.Token.IsCancellationRequested)\n {\n logger.LogError(\"Token cancelled for unknown reasons, exiting.\");\n return ExitCode.GENERAL_FAILURE;\n }\n else\n {\n logger.LogInformation($\"Stopping the webserver after the timeout of {Arguments.Timeout}\");\n return ExitCode.SUCCESS;\n }\n }", + "start_line": 30, + "end_line": 55, + "start_byte": 1123, + "end_byte": 2172 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/WASM/ErrorPatternScanner.cs": [ + { + "name": "IsError", + "code": "public bool IsError(string line, out string? matchedPattern)\n {\n matchedPattern = null;\n if (_empty)\n return false;\n\n string? patternString = _errorPatternStrings.FirstOrDefault(pattern => line.Contains(pattern, StringComparison.InvariantCultureIgnoreCase));\n if (patternString != null)\n {\n matchedPattern = patternString;\n return true;\n }\n\n Regex? matchedRegex = _errorPatternRegexes.FirstOrDefault(regex => regex.IsMatch(line));\n if (matchedRegex != null)\n {\n matchedPattern = matchedRegex.ToString();\n return true;\n }\n\n return false;\n }", + "start_line": 66, + "end_line": 87, + "start_byte": 2146, + "end_byte": 2823 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Android/AndroidStateCommand.cs": [ + { + "name": "GetStateData", + "code": "private static StateData GetStateData(ILogger logger)\n {\n var runner = new AdbRunner(logger);\n\n logger.LogDebug(\"Getting state of ADB and attached Android device(s)\");\n\n var adbVersion = runner.GetAdbVersion()\n .Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);\n\n var state = runner.GetAdbState().Trim();\n\n IReadOnlyCollection allDevices = runner.GetDevices();\n\n var emulators = allDevices.Where(d => d.DeviceSerial.StartsWith(\"emulator\"));\n var devices = allDevices.Except(emulators);\n\n return new StateData(state, adbVersion, emulators, devices);\n }", + "start_line": 94, + "end_line": 111, + "start_byte": 3408, + "end_byte": 4097 + }, + { + "name": "InvokeInternal", + "code": "protected override Task InvokeInternal(ILogger logger)\n {\n try\n {\n var data = GetStateData(Arguments.UseJson ? NullLogger.Instance : logger);\n\n if (Arguments.UseJson)\n {\n var options = new JsonSerializerOptions\n {\n DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,\n WriteIndented = true,\n };\n\n JsonSerializer.Serialize(Console.OpenStandardOutput(), data, options);\n return Task.FromResult(ExitCode.SUCCESS);\n }\n\n var state = data.DeviceState switch\n {\n \"device\" => \"Device/emulator is ready\",\n null or \"\" => \"No device attached\",\n _ => data.DeviceState,\n };\n\n void PrintAndroidDevice(AndroidDevice device)\n {\n logger.LogInformation($\"{device.DeviceSerial}:{Environment.NewLine}\" +\n $\" Architecture: {device.Architecture}{Environment.NewLine}\" +\n $\" API version: {device.ApiVersion}{Environment.NewLine}\" +\n $\" Supported architectures: {string.Join(\", \", device?.SupportedArchitectures ?? Array.Empty())}\");\n }\n\n logger.LogInformation($\"ADB Version info:{Environment.NewLine}{string.Join(Environment.NewLine, data.AdbVersion)}\");\n logger.LogInformation($\"ADB State:{Environment.NewLine}{state}\");\n\n if (data.Emulators.Any())\n {\n logger.LogInformation($\"List of emulators:\");\n foreach (AndroidDevice emulator in data.Emulators)\n {\n PrintAndroidDevice(emulator);\n }\n }\n\n if (data.Devices.Any())\n {\n logger.LogInformation($\"List of devices:\");\n foreach (AndroidDevice device in data.Devices)\n {\n PrintAndroidDevice(device);\n }\n }\n\n return Task.FromResult(ExitCode.SUCCESS);\n }\n catch (Exception toLog)\n {\n logger.LogCritical(toLog, $\"Error: {toLog.Message}\");\n return Task.FromResult(ExitCode.GENERAL_FAILURE);\n }\n }", + "start_line": 31, + "end_line": 92, + "start_byte": 1090, + "end_byte": 3402 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Android/AndroidAdbCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override Task InvokeInternal(ILogger logger)\n {\n if (!PassThroughArguments.Any())\n {\n logger.LogError(\"Please provide delimeter '--' followed by arguments for ADB:\" + Environment.NewLine +\n $\" {CommandUsage}\" + Environment.NewLine +\n $\"Example:\" + Environment.NewLine +\n $\" android adb --timeout 00:01:30 -- devices -l\");\n\n return Task.FromResult(ExitCode.INVALID_ARGUMENTS);\n }\n\n var runner = new AdbRunner(logger);\n\n try\n {\n var result = runner.RunAdbCommand(PassThroughArguments, Arguments.Timeout);\n\n Console.Write(result.StandardOutput);\n Console.Error.Write(result.StandardError);\n\n return Task.FromResult((ExitCode)result.ExitCode);\n }\n catch (Exception toLog)\n {\n logger.LogCritical(toLog, $\"Error: {toLog.Message}\");\n return Task.FromResult(ExitCode.GENERAL_FAILURE);\n }\n }", + "start_line": 29, + "end_line": 57, + "start_byte": 1138, + "end_byte": 2155 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Android/AndroidTestCommand.cs": [ + { + "name": "InvokeCommand", + "code": "protected override ExitCode InvokeCommand(ILogger logger)\n {\n var runner = new AdbRunner(logger);\n\n var exitCode = AndroidInstallCommand.InvokeHelper(\n logger: logger,\n apkPackageName: Arguments.PackageName,\n appPackagePath: Arguments.AppPackagePath,\n requestedArchitectures: Arguments.DeviceArchitecture.Value.ToList(),\n deviceId: Arguments.DeviceId.Value,\n apiVersion: Arguments.ApiVersion.Value,\n bootTimeoutSeconds: Arguments.LaunchTimeout,\n runner,\n DiagnosticsData);\n\n if (Arguments.Wifi != WifiStatus.Unknown)\n {\n runner.EnableWifi(Arguments.Wifi == WifiStatus.Enable);\n }\n\n try\n {\n if (exitCode == ExitCode.SUCCESS)\n {\n runner.ClearAdbLog();\n\n var instrumentationRunner = new InstrumentationRunner(logger, runner);\n exitCode = instrumentationRunner.RunApkInstrumentation(\n Arguments.PackageName,\n Arguments.InstrumentationName,\n Arguments.InstrumentationArguments,\n Arguments.OutputDirectory,\n Arguments.DeviceOutputFolder,\n Arguments.Timeout,\n Arguments.ExpectedExitCode);\n }\n }\n finally\n {\n runner.UninstallApk(Arguments.PackageName);\n }\n\n return exitCode;\n }", + "start_line": 38, + "end_line": 81, + "start_byte": 1470, + "end_byte": 2961 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Android/AndroidRunCommand.cs": [ + { + "name": "InvokeCommand", + "code": "protected override ExitCode InvokeCommand(ILogger logger)\n {\n var runner = new AdbRunner(logger);\n\n // Make sure the adb server is started\n runner.StartAdbServer();\n\n var device = string.IsNullOrEmpty(Arguments.DeviceId.Value)\n ? runner.GetSingleDevice(loadArchitecture: true, loadApiVersion: true, requiredInstalledApp: \"package:\" + Arguments.PackageName)\n : runner.GetSingleDevice(loadArchitecture: true, loadApiVersion: true, requiredDeviceId: Arguments.DeviceId.Value);\n\n if (device is null)\n {\n return ExitCode.DEVICE_NOT_FOUND;\n }\n\n DiagnosticsData.CaptureDeviceInfo(device);\n\n runner.TimeToWaitForBootCompletion = Arguments.LaunchTimeout;\n\n // Wait till at least device(s) are ready\n if (!runner.WaitForDevice())\n {\n return ExitCode.DEVICE_NOT_FOUND;\n }\n\n logger.LogDebug($\"Working with API {runner.GetAdbVersion()}\");\n\n // Empty log as we'll be uploading the full logcat for this execution\n runner.ClearAdbLog();\n \n if (Arguments.Wifi != WifiStatus.Unknown)\n {\n runner.EnableWifi(Arguments.Wifi == WifiStatus.Enable);\n }\n\n var instrumentationRunner = new InstrumentationRunner(logger, runner);\n return instrumentationRunner.RunApkInstrumentation(\n Arguments.PackageName,\n Arguments.InstrumentationName,\n Arguments.InstrumentationArguments,\n Arguments.OutputDirectory,\n Arguments.DeviceOutputFolder,\n Arguments.Timeout,\n Arguments.ExpectedExitCode);\n }", + "start_line": 35, + "end_line": 80, + "start_byte": 1337, + "end_byte": 2988 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Android/AndroidInstallCommand.cs": [ + { + "name": "InvokeHelper", + "code": "public static ExitCode InvokeHelper(\n ILogger logger,\n string apkPackageName,\n string appPackagePath,\n IReadOnlyCollection requestedArchitectures,\n string? deviceId,\n int? apiVersion,\n TimeSpan bootTimeoutSeconds,\n AdbRunner runner,\n IDiagnosticsData diagnosticsData)\n {\n using (logger.BeginScope(\"Initialization and setup of APK on device\"))\n {\n IReadOnlyCollection requiredArchitectures;\n var apkSupportedArchitectures = ApkHelper.GetApkSupportedArchitectures(appPackagePath);\n\n if (requestedArchitectures.Any())\n {\n if (!apkSupportedArchitectures.Intersect(requestedArchitectures).Any())\n {\n logger.LogError(\"The APK at {appPackagePath} supports {apkSupportedArchitectures} architectures \" +\n \"which does not match any of the specified architectures ({requestedArchitectures})\",\n appPackagePath,\n string.Join(\", \", apkSupportedArchitectures),\n string.Join(\", \", requestedArchitectures));\n return ExitCode.INVALID_ARGUMENTS;\n }\n\n requiredArchitectures = requestedArchitectures;\n }\n else\n {\n requiredArchitectures = apkSupportedArchitectures;\n }\n\n logger.LogInformation(\"Will attempt to find device supporting architectures: '{requiredArchitectures}'\",\n string.Join(\"', '\", requiredArchitectures));\n\n // Make sure the adb server is started\n runner.StartAdbServer();\n\n AndroidDevice? device = runner.GetDevice(\n loadArchitecture: true,\n loadApiVersion: true,\n deviceId,\n apiVersion,\n requiredArchitectures);\n\n if (device is null)\n {\n throw new NoDeviceFoundException($\"Failed to find compatible device: {string.Join(\", \", requiredArchitectures)}\");\n }\n\n diagnosticsData.CaptureDeviceInfo(device);\n\n runner.TimeToWaitForBootCompletion = bootTimeoutSeconds;\n\n // Wait till at least device(s) are ready\n if (!runner.WaitForDevice())\n {\n return ExitCode.DEVICE_NOT_FOUND;\n }\n\n logger.LogDebug($\"Working with {device.DeviceSerial} (API {device.ApiVersion})\");\n\n runner.CheckPackageVerificationSettings();\n\n // If anything changed about the app, Install will fail; uninstall it first.\n // (we'll ignore if it's not present)\n // This is where mismatched architecture APKs fail.\n runner.UninstallApk(apkPackageName);\n if (runner.InstallApk(appPackagePath) != 0)\n {\n logger.LogCritical(\"Install failure: Test command cannot continue\");\n runner.UninstallApk(apkPackageName);\n return ExitCode.PACKAGE_INSTALLATION_FAILURE;\n }\n\n runner.KillApk(apkPackageName);\n }\n return ExitCode.SUCCESS;\n }", + "start_line": 53, + "end_line": 134, + "start_byte": 1752, + "end_byte": 4956 + }, + { + "name": "InvokeCommand", + "code": "protected override ExitCode InvokeCommand(ILogger logger)\n {\n if (!File.Exists(Arguments.AppPackagePath))\n {\n logger.LogCritical($\"Couldn't find {Arguments.AppPackagePath}!\");\n return ExitCode.PACKAGE_NOT_FOUND;\n }\n\n var runner = new AdbRunner(logger);\n\n return InvokeHelper(\n logger: logger,\n apkPackageName: Arguments.PackageName,\n appPackagePath: Arguments.AppPackagePath,\n requestedArchitectures: Arguments.DeviceArchitecture.Value.ToList(),\n deviceId: Arguments.DeviceId,\n apiVersion: Arguments.ApiVersion.Value,\n bootTimeoutSeconds: Arguments.LaunchTimeout,\n runner: runner,\n DiagnosticsData);\n }", + "start_line": 31, + "end_line": 51, + "start_byte": 982, + "end_byte": 1746 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Android/AndroidUninstallCommand.cs": [ + { + "name": "InvokeCommand", + "code": "protected override ExitCode InvokeCommand(ILogger logger)\n {\n using (logger.BeginScope(\"Find device where to uninstall APK\"))\n {\n // Make sure the adb server is started\n var runner = new AdbRunner(logger);\n runner.StartAdbServer();\n\n AndroidDevice? device = runner.GetSingleDevice(\n loadArchitecture: true,\n loadApiVersion: true,\n requiredDeviceId: Arguments.DeviceId,\n requiredInstalledApp: \"package:\" + Arguments.PackageName);\n\n if (device is null)\n {\n return ExitCode.DEVICE_NOT_FOUND;\n }\n\n DiagnosticsData.CaptureDeviceInfo(device);\n\n logger.LogDebug($\"Working with {device.DeviceSerial} (API {device.ApiVersion})\");\n\n runner.UninstallApk(Arguments.PackageName);\n return ExitCode.SUCCESS;\n }\n }", + "start_line": 30, + "end_line": 56, + "start_byte": 1049, + "end_byte": 1970 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Android/AndroidCommandSet.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Android/AndroidDeviceCommand.cs": [ + { + "name": "InvokeCommand", + "code": "protected override ExitCode InvokeCommand(ILogger logger)\n {\n IEnumerable? apkRequiredArchitecture = null;\n\n if (Arguments.DeviceArchitecture.Value.Any())\n {\n apkRequiredArchitecture = Arguments.DeviceArchitecture.Value;\n }\n else if (!string.IsNullOrEmpty(Arguments.AppPackagePath.Value))\n {\n if (!File.Exists(Arguments.AppPackagePath.Value))\n {\n logger.LogCritical($\"Couldn't find {Arguments.AppPackagePath.Value}!\");\n return ExitCode.PACKAGE_NOT_FOUND;\n }\n\n apkRequiredArchitecture = ApkHelper.GetApkSupportedArchitectures(Arguments.AppPackagePath.Value);\n }\n\n // Make sure the adb server is started\n var runner = new AdbRunner(logger);\n runner.StartAdbServer();\n\n // enumerate the devices attached and their architectures\n // Tell ADB to only use that one (will always use the present one for systems w/ only 1 machine)\n var device = runner.GetDevice(\n loadApiVersion: true,\n loadArchitecture: true,\n requiredApiVersion: Arguments.ApiVersion.Value,\n requiredArchitectures: apkRequiredArchitecture);\n\n if (device is null)\n {\n return ExitCode.DEVICE_NOT_FOUND;\n }\n\n DiagnosticsData.CaptureDeviceInfo(device);\n\n Console.WriteLine(device.DeviceSerial);\n\n return ExitCode.SUCCESS;\n }", + "start_line": 38, + "end_line": 79, + "start_byte": 1244, + "end_byte": 2712 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Android/AndroidCommand.cs": [ + { + "name": "InvokeCommand", + "code": "protected abstract ExitCode InvokeCommand(ILogger logger);", + "start_line": 52, + "end_line": 52, + "start_byte": 1898, + "end_byte": 1956 + }, + { + "name": "InvokeInternal", + "code": "protected sealed override Task InvokeInternal(ILogger logger)\n {\n try\n {\n return Task.FromResult(InvokeCommand(logger));\n }\n catch (NoDeviceFoundException noDevice)\n {\n logger.LogCritical(noDevice.Message);\n return Task.FromResult(ExitCode.DEVICE_NOT_FOUND);\n }\n catch (AdbFailureException adbFailure)\n {\n logger.LogCritical(adbFailure, adbFailure.Message);\n return Task.FromResult(ExitCode.ADB_FAILURE);\n }\n catch (Exception toLog)\n {\n logger.LogCritical(toLog, toLog.Message);\n }\n\n return Task.FromResult(ExitCode.GENERAL_FAILURE);\n }", + "start_line": 28, + "end_line": 50, + "start_byte": 1183, + "end_byte": 1892 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Android/IDiagnosticDataExtensions.cs": [ + { + "name": "CaptureDeviceInfo", + "code": "public static void CaptureDeviceInfo(this IDiagnosticsData data, AndroidDevice device)\n {\n data.Target = device.Architecture;\n data.TargetOS = \"API \" + device.ApiVersion;\n data.Device = device.DeviceSerial;\n data.IsDevice = !device.DeviceSerial.ToLowerInvariant().StartsWith(\"emulator\");\n }", + "start_line": 12, + "end_line": 18, + "start_byte": 393, + "end_byte": 717 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/AndroidHeadless/AndroidHeadlessTestCommand.cs": [ + { + "name": "InvokeCommand", + "code": "protected override ExitCode InvokeCommand(ILogger logger)\n {\n if (!Directory.Exists(Arguments.TestPath))\n {\n logger.LogCritical($\"Couldn't find test {Arguments.TestPath}!\");\n return ExitCode.PACKAGE_NOT_FOUND;\n }\n if (!Directory.Exists(Arguments.RuntimePath))\n {\n logger.LogCritical($\"Couldn't find shared runtime {Arguments.RuntimePath}!\");\n return ExitCode.PACKAGE_NOT_FOUND;\n }\n\n IEnumerable testRequiredArchitecture = Arguments.DeviceArchitecture.Value;\n\n logger.LogInformation($\"Required architecture: '{string.Join(\"', '\", testRequiredArchitecture)}'\");\n\n var runner = new AdbRunner(logger);\n\n var exitCode = AndroidHeadlessInstallCommand.InvokeHelper(\n logger: logger,\n testPath: Arguments.TestPath,\n runtimePath: Arguments.RuntimePath,\n testRequiredArchitecture: testRequiredArchitecture,\n deviceId: Arguments.DeviceId.Value,\n apiVersion: Arguments.ApiVersion.Value,\n bootTimeoutSeconds: Arguments.LaunchTimeout,\n runner,\n DiagnosticsData);\n\n if (exitCode == ExitCode.SUCCESS)\n {\n exitCode = AndroidHeadlessRunCommand.InvokeHelper(\n logger: logger,\n testPath: Arguments.TestPath,\n runtimePath: Arguments.RuntimePath,\n testAssembly: Arguments.TestAssembly,\n testScript: Arguments.TestScript,\n outputDirectory: Arguments.OutputDirectory,\n timeout: Arguments.Timeout,\n expectedExitCode: Arguments.ExpectedExitCode,\n wifi: Arguments.Wifi,\n runner: runner);\n }\n\n runner.DeleteHeadlessFolder(Arguments.TestPath);\n runner.DeleteHeadlessFolder(\"runtime\");\n return exitCode;\n }", + "start_line": 33, + "end_line": 81, + "start_byte": 1283, + "end_byte": 3189 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/AndroidHeadless/AndroidHeadlessCommandSet.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/Commands/AndroidHeadless/AndroidHeadlessUninstallCommand.cs": [ + { + "name": "InvokeCommand", + "code": "protected override ExitCode InvokeCommand(ILogger logger)\n {\n using (logger.BeginScope(\"Find device where to uninstall folder\"))\n {\n // Make sure the adb server is started\n var runner = new AdbRunner(logger);\n runner.StartAdbServer();\n\n AndroidDevice? device = runner.GetSingleDevice(\n loadArchitecture: true,\n loadApiVersion: true,\n requiredDeviceId: Arguments.DeviceId,\n requiredInstalledApp: \"filename:\" + Arguments.TestPath);\n\n if (device is null)\n {\n return ExitCode.DEVICE_NOT_FOUND;\n }\n\n DiagnosticsData.CaptureDeviceInfo(device);\n\n logger.LogDebug($\"Working with {device.DeviceSerial} (API {device.ApiVersion})\");\n\n runner.DeleteHeadlessFolder(Arguments.TestPath);\n runner.DeleteHeadlessFolder(\"runtime\");\n return ExitCode.SUCCESS;\n }\n }", + "start_line": 32, + "end_line": 59, + "start_byte": 1226, + "end_byte": 2205 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/AndroidHeadless/AndroidHeadlessInstallCommand.cs": [ + { + "name": "InvokeHelper", + "code": "public static ExitCode InvokeHelper(\n ILogger logger,\n string testPath,\n string runtimePath,\n IEnumerable testRequiredArchitecture,\n string? deviceId,\n int? apiVersion,\n TimeSpan bootTimeoutSeconds,\n AdbRunner runner,\n IDiagnosticsData diagnosticsData)\n {\n using (logger.BeginScope(\"Initialization and setup of test on device\"))\n {\n // Make sure the adb server is started\n runner.StartAdbServer();\n\n AndroidDevice? device = runner.GetDevice(\n loadArchitecture: true,\n loadApiVersion: true,\n deviceId,\n apiVersion,\n testRequiredArchitecture);\n\n if (device is null)\n {\n throw new NoDeviceFoundException($\"Failed to find compatible device: {string.Join(\", \", testRequiredArchitecture)}\");\n }\n\n diagnosticsData.CaptureDeviceInfo(device);\n\n runner.TimeToWaitForBootCompletion = bootTimeoutSeconds;\n\n // Wait till at least device(s) are ready\n if (!runner.WaitForDevice())\n {\n return ExitCode.DEVICE_NOT_FOUND;\n }\n\n logger.LogDebug($\"Working with {device.DeviceSerial} (API {device.ApiVersion})\");\n\n // If anything changed about the app, Install will fail; uninstall it first.\n // (we'll ignore if it's not present)\n // This is where mismatched architecture APKs fail.\n runner.DeleteHeadlessFolder(testPath);\n runner.DeleteHeadlessFolder(\"runtime\");\n if (runner.CopyHeadlessFolder(testPath) != 0)\n {\n logger.LogCritical(\"Install failure: Test command cannot continue\");\n runner.DeleteHeadlessFolder(testPath);\n return ExitCode.PACKAGE_INSTALLATION_FAILURE;\n }\n if (runner.CopyHeadlessFolder(runtimePath, true) != 0)\n {\n logger.LogCritical(\"Install failure: Test command cannot continue\");\n runner.DeleteHeadlessFolder(\"runtime\");\n return ExitCode.PACKAGE_INSTALLATION_FAILURE;\n }\n }\n return ExitCode.SUCCESS;\n }", + "start_line": 73, + "end_line": 132, + "start_byte": 2597, + "end_byte": 4866 + }, + { + "name": "InvokeCommand", + "code": "protected override ExitCode InvokeCommand(ILogger logger)\n {\n if (!Directory.Exists(Arguments.TestPath))\n {\n logger.LogCritical($\"Couldn't find test {Arguments.TestPath}!\");\n return ExitCode.PACKAGE_NOT_FOUND;\n }\n\n if (!Directory.Exists(Arguments.RuntimePath))\n {\n logger.LogCritical($\"Couldn't find shared runtime {Arguments.RuntimePath}!\");\n return ExitCode.PACKAGE_NOT_FOUND;\n }\n\n var runner = new AdbRunner(logger);\n\n List testRequiredArchitecture = new();\n\n if (string.IsNullOrEmpty(Arguments.DeviceId))\n {\n // trying to choose suitable device\n if (Arguments.DeviceArchitecture.Value.Any())\n {\n testRequiredArchitecture = Arguments.DeviceArchitecture.Value.ToList();\n logger.LogInformation($\"Will attempt to run device on specified architecture: '{string.Join(\"', '\", testRequiredArchitecture)}'\");\n }\n }\n\n return InvokeHelper(\n logger: logger,\n testPath: Arguments.TestPath,\n runtimePath: Arguments.RuntimePath,\n testRequiredArchitecture: testRequiredArchitecture,\n deviceId: Arguments.DeviceId,\n apiVersion: Arguments.ApiVersion.Value,\n bootTimeoutSeconds: Arguments.LaunchTimeout,\n runner: runner,\n DiagnosticsData);\n }", + "start_line": 33, + "end_line": 71, + "start_byte": 1149, + "end_byte": 2591 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/AndroidHeadless/AndroidHeadlessRunCommand.cs": [ + { + "name": "InvokeHelper", + "code": "public static ExitCode InvokeHelper(\n ILogger logger,\n string testPath,\n string runtimePath,\n string testAssembly,\n string testScript,\n string outputDirectory,\n TimeSpan timeout,\n int expectedExitCode,\n WifiStatus wifi,\n AdbRunner runner)\n {\n logger.LogDebug($\"Working with API {runner.GetAdbVersion()}\");\n\n // Empty log as we'll be uploading the full logcat for this execution\n runner.ClearAdbLog();\n\n if (wifi != WifiStatus.Unknown)\n {\n runner.EnableWifi(wifi == WifiStatus.Enable);\n }\n\n // No class name = default Instrumentation\n ProcessExecutionResults? result = runner.RunHeadlessCommand(\n testPath,\n runtimePath,\n testAssembly,\n testScript,\n timeout);\n\n bool failurePullingFiles = false;\n\n using (logger.BeginScope(\"Post-test copy and cleanup\"))\n {\n // Optionally copy off an entire folder\n if (!string.IsNullOrEmpty(outputDirectory))\n {\n var testResultPath = AdbRunner.GlobalReadWriteDirectory + Path.AltDirectorySeparatorChar + new DirectoryInfo(testPath).Name + Path.AltDirectorySeparatorChar + \"testResults.xml\";\n\n try\n {\n var logs = runner.HeadlessPullFiles(testResultPath, outputDirectory);\n logger.LogDebug($\"Found log file testResults.xml\");\n }\n catch (Exception toLog)\n {\n logger.LogError(toLog, \"Hit error (typically permissions) trying to pull {testResultPath}\", outputDirectory);\n failurePullingFiles = true;\n }\n }\n\n runner.TryDumpAdbLog(Path.Combine(outputDirectory, $\"adb-logcat-{testAssembly}-default.log\"));\n }\n\n if (failurePullingFiles)\n {\n logger.LogError($\"Received expected exit code ({ExitCode.SUCCESS}), \" +\n \"but we hit errors pulling files from the device (see log for details.)\");\n return ExitCode.DEVICE_FILE_COPY_FAILURE;\n }\n\n if (result.ExitCode != expectedExitCode)\n {\n logger.LogError($\"Non-success exit code: {result.ExitCode}, expected: {expectedExitCode}\");\n if (result.ExitCode != (int)ExitCode.TESTS_FAILED)\n {\n logger.LogError($\"Unexpected test run failure, extracting detailed diagnostics\");\n runner.DumpBugReport(Path.Combine(outputDirectory, $\"adb-bugreport-{testAssembly}\"));\n }\n return (ExitCode)result.ExitCode;\n }\n\n return ExitCode.SUCCESS;\n }", + "start_line": 73, + "end_line": 146, + "start_byte": 2520, + "end_byte": 5259 + }, + { + "name": "InvokeCommand", + "code": "protected override ExitCode InvokeCommand(ILogger logger)\n {\n var runner = new AdbRunner(logger);\n\n // Make sure the adb server is started\n runner.StartAdbServer();\n\n var device = string.IsNullOrEmpty(Arguments.DeviceId.Value)\n ? runner.GetSingleDevice(loadArchitecture: true, loadApiVersion: true, requiredInstalledApp: \"filename:\" + Arguments.TestPath)\n : runner.GetSingleDevice(loadArchitecture: true, loadApiVersion: true, requiredDeviceId: Arguments.DeviceId.Value);\n\n if (device is null)\n {\n return ExitCode.DEVICE_NOT_FOUND;\n }\n\n DiagnosticsData.CaptureDeviceInfo(device);\n\n runner.TimeToWaitForBootCompletion = Arguments.LaunchTimeout;\n\n // Wait till at least device(s) are ready\n if (!runner.WaitForDevice())\n {\n return ExitCode.DEVICE_NOT_FOUND;\n }\n\n return InvokeHelper(\n logger,\n Arguments.TestPath,\n Arguments.RuntimePath,\n Arguments.TestAssembly,\n Arguments.TestScript,\n Arguments.OutputDirectory,\n Arguments.Timeout,\n Arguments.ExpectedExitCode,\n Arguments.Wifi,\n runner);\n }", + "start_line": 34, + "end_line": 71, + "start_byte": 1266, + "end_byte": 2514 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/WASI/WasiCommandSet.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/Commands/WASI/Engine/WasiTestCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override async Task InvokeInternal(ILogger logger)\n {\n var processManager = ProcessManagerFactory.CreateProcessManager();\n\n string engineBinary = Arguments.Engine.Value switch\n {\n WasmEngine.WasmTime => \"wasmtime\",\n _ => throw new ArgumentException(\"Engine not set\")\n };\n\n if (!string.IsNullOrEmpty(Arguments.EnginePath.Value))\n {\n engineBinary = Arguments.EnginePath.Value;\n if (Path.IsPathRooted(engineBinary) && !File.Exists(engineBinary))\n throw new ArgumentException($\"Could not find wasi engine at the specified path - {engineBinary}\");\n }\n else\n {\n if (!FileUtils.TryFindExecutableInPATH(engineBinary, out string? foundBinary, out string? errorMessage))\n {\n logger.LogCritical($\"The engine binary `{engineBinary}` was not found. {errorMessage}\");\n return ExitCode.APP_LAUNCH_FAILURE;\n }\n engineBinary = foundBinary;\n }\n\n var cts = new CancellationTokenSource();\n try\n {\n logger.LogInformation($\"Using wasm engine {Arguments.Engine.Value} from path {engineBinary}\");\n await PrintVersionAsync(Arguments.Engine.Value.Value, engineBinary);\n\n ServerURLs? serverURLs = null;\n if (Arguments.IsWebServerEnabled)\n {\n serverURLs = await WebServer.Start(\n Arguments,\n logger,\n cts.Token);\n }\n\n var engineArgs = new List();\n engineArgs.AddRange(Arguments.EngineArgs.Value);\n\n if (Arguments.IsWebServerEnabled)\n {\n foreach (var envVariable in Arguments.WebServerHttpEnvironmentVariables.Value)\n {\n engineArgs.Add($\"--env\");\n engineArgs.Add($\"{envVariable}={serverURLs!.Http}\");\n }\n if (Arguments.WebServerUseHttps)\n {\n foreach (var envVariable in Arguments.WebServerHttpsEnvironmentVariables.Value)\n {\n engineArgs.Add($\"--env\");\n engineArgs.Add($\"{envVariable}={serverURLs!.Https}\");\n }\n }\n }\n \n engineArgs.AddRange(PassThroughArguments);\n\n var xmlResultsFilePath = Path.Combine(Arguments.OutputDirectory, \"testResults.xml\");\n File.Delete(xmlResultsFilePath);\n\n var stdoutFilePath = Path.Combine(Arguments.OutputDirectory, \"wasi-console.log\");\n File.Delete(stdoutFilePath);\n\n var logProcessor = new WasmTestMessagesProcessor(xmlResultsFilePath,\n stdoutFilePath,\n logger);\n var logProcessorTask = Task.Run(() => logProcessor.RunAsync(cts.Token));\n\n var processTask = processManager.ExecuteCommandAsync(\n engineBinary,\n engineArgs,\n log: new CallbackLog(m => logger.LogInformation(m.Trim())),\n stdoutLog: new CallbackLog(msg => logProcessor.Invoke(msg)),\n stderrLog: new CallbackLog(logProcessor.ProcessErrorMessage),\n Arguments.Timeout);\n\n var tasks = new Task[]\n {\n logProcessorTask,\n processTask,\n Task.Delay(Arguments.Timeout)\n };\n\n var task = await Task.WhenAny(tasks).ConfigureAwait(false);\n if (task == tasks[^1] || cts.IsCancellationRequested || task.IsCanceled)\n {\n logger.LogError($\"Tests timed out after {((TimeSpan)Arguments.Timeout).TotalSeconds}secs\");\n if (!cts.IsCancellationRequested)\n cts.Cancel();\n\n return ExitCode.TIMED_OUT;\n }\n\n if (task.IsFaulted)\n {\n logger.LogError($\"task faulted {task.Exception}\");\n throw task.Exception!;\n }\n\n // if the log processor completed without errors, then the\n // process should be done too, or about to be done!\n var result = await processTask;\n ExitCode logProcessorExitCode = await logProcessor.CompleteAndFlushAsync();\n if (logProcessor.ForwardedExitCode != null)\n {\n // until WASI can work with unix exit code https://github.com/WebAssembly/wasi-cli/pull/44\n result.ExitCode = logProcessor.ForwardedExitCode.Value;\n }\n\n if (result.ExitCode != Arguments.ExpectedExitCode)\n {\n logger.LogError($\"Application has finished with exit code {result.ExitCode} but {Arguments.ExpectedExitCode} was expected\");\n return ExitCode.GENERAL_FAILURE;\n }\n else\n {\n logger.LogInformation(\"Application has finished with exit code: \" + result.ExitCode);\n // return SUCCESS if logProcess also returned SUCCESS\n return logProcessorExitCode;\n }\n }\n catch (Win32Exception e) when (e.NativeErrorCode == 2)\n {\n logger.LogCritical($\"The engine binary `{engineBinary}` was not found\");\n return ExitCode.APP_LAUNCH_FAILURE;\n }\n finally\n {\n if (!cts.IsCancellationRequested)\n {\n cts.Cancel();\n }\n }\n\n Task PrintVersionAsync(WasmEngine engine, string engineBinary)\n {\n return processManager.ExecuteCommandAsync(\n engineBinary,\n new[] { \"--version\" },\n log: new CallbackLog(m => logger.LogDebug(m.Trim())),\n stdoutLog: new CallbackLog(msg => logger.LogInformation(msg.Trim())),\n stderrLog: new CallbackLog(msg => logger.LogError(msg.Trim())),\n TimeSpan.FromSeconds(10));\n }\n }", + "start_line": 36, + "end_line": 186, + "start_byte": 1431, + "end_byte": 7602 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/WASM/JS/WasmTestCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override async Task InvokeInternal(ILogger logger)\n {\n var processManager = ProcessManagerFactory.CreateProcessManager();\n\n string engineBinary = Arguments.Engine.Value switch\n {\n JavaScriptEngine.V8 => \"v8\",\n JavaScriptEngine.JavaScriptCore => \"jsc\",\n JavaScriptEngine.SpiderMonkey => \"sm\",\n JavaScriptEngine.NodeJS => \"node\",\n _ => throw new ArgumentException(\"Engine not set\")\n };\n\n if (!string.IsNullOrEmpty(Arguments.EnginePath.Value))\n {\n engineBinary = Arguments.EnginePath.Value;\n if (Path.IsPathRooted(engineBinary) && !File.Exists(engineBinary))\n throw new ArgumentException($\"Could not find js engine at the specified path - {engineBinary}\");\n }\n else\n {\n if (!FileUtils.TryFindExecutableInPATH(engineBinary, out string? foundBinary, out string? errorMessage))\n {\n logger.LogCritical($\"The engine binary `{engineBinary}` was not found. {errorMessage}\");\n return ExitCode.APP_LAUNCH_FAILURE;\n }\n engineBinary = foundBinary;\n }\n\n var serviceProvider = Services.BuildServiceProvider();\n var diagnosticsData = serviceProvider.GetRequiredService();\n diagnosticsData.Target = engineBinary;\n\n var cts = new CancellationTokenSource();\n try\n {\n logger.LogInformation($\"Using js engine {Arguments.Engine.Value} from path {engineBinary}\");\n string? versionString = await GetVersionAsync(Arguments.Engine.Value.Value, engineBinary);\n diagnosticsData.TargetOS = versionString;\n\n ServerURLs? serverURLs = null;\n if (Arguments.IsWebServerEnabled)\n {\n serverURLs = await WebServer.Start(\n Arguments,\n logger,\n cts.Token);\n }\n\n var engineArgs = new List();\n\n if (Arguments.Engine == JavaScriptEngine.V8)\n {\n // v8 needs this flag to enable WASM support\n engineArgs.Add(\"--expose_wasm\");\n }\n\n engineArgs.AddRange(Arguments.EngineArgs.Value);\n engineArgs.Add(Arguments.JSFile);\n\n if (Arguments.Engine == JavaScriptEngine.V8 || Arguments.Engine == JavaScriptEngine.JavaScriptCore)\n {\n // v8/jsc want arguments to the script separated by \"--\", others don't\n engineArgs.Add(\"--\");\n }\n\n if (Arguments.IsWebServerEnabled)\n {\n foreach (var envVariable in Arguments.WebServerHttpEnvironmentVariables.Value)\n {\n engineArgs.Add($\"--setenv={envVariable}={serverURLs!.Http}\");\n }\n if (Arguments.WebServerUseHttps)\n {\n foreach (var envVariable in Arguments.WebServerHttpsEnvironmentVariables.Value)\n {\n engineArgs.Add($\"--setenv={envVariable}={serverURLs!.Https}\");\n }\n }\n }\n\n engineArgs.AddRange(PassThroughArguments);\n\n var xmlResultsFilePath = Path.Combine(Arguments.OutputDirectory, \"testResults.xml\");\n File.Delete(xmlResultsFilePath);\n\n var stdoutFilePath = Path.Combine(Arguments.OutputDirectory, \"wasm-console.log\");\n File.Delete(stdoutFilePath);\n\n var symbolicator = WasmSymbolicatorBase.Create(Arguments.SymbolicatorArgument.GetLoadedTypes().FirstOrDefault(),\n Arguments.SymbolMapFileArgument,\n Arguments.SymbolicatePatternsFileArgument,\n logger);\n\n var logProcessor = new WasmTestMessagesProcessor(xmlResultsFilePath,\n stdoutFilePath,\n logger,\n Arguments.ErrorPatternsFile,\n symbolicator);\n var logProcessorTask = Task.Run(() => logProcessor.RunAsync(cts.Token));\n\n var processTask = processManager.ExecuteCommandAsync(\n engineBinary,\n engineArgs,\n log: new CallbackLog(m => logger.LogInformation(m)),\n stdoutLog: new CallbackLog(msg => logProcessor.Invoke(msg)),\n stderrLog: new CallbackLog(logProcessor.ProcessErrorMessage),\n Arguments.Timeout,\n // Node respects LANG only, ignores LANGUAGE\n environmentVariables: Arguments.Engine.Value == JavaScriptEngine.NodeJS ?\n new Dictionary() { {\"LANG\", Arguments.Locale} } :\n null);\n\n TaskCompletionSource wasmExitReceivedTcs = logProcessor.WasmExitReceivedTcs;\n var tasks = new Task[]\n {\n wasmExitReceivedTcs.Task,\n logProcessorTask,\n processTask,\n Task.Delay(Arguments.Timeout)\n };\n\n var task = await Task.WhenAny(tasks).ConfigureAwait(false);\n if (task == tasks[^1] || cts.IsCancellationRequested || task.IsCanceled)\n {\n logger.LogError($\"Tests timed out after {((TimeSpan)Arguments.Timeout).TotalSeconds}secs\");\n if (!cts.IsCancellationRequested)\n cts.Cancel();\n\n return ExitCode.TIMED_OUT;\n }\n\n if (task.IsFaulted)\n {\n logger.LogError($\"task faulted {task.Exception}\");\n throw task.Exception!;\n }\n\n // if the log processor completed without errors, then the\n // process should be done too, or about to be done!\n var result = await processTask;\n ExitCode logProcessorExitCode = await logProcessor.CompleteAndFlushAsync();\n\n // give messages bit more time\n if (!wasmExitReceivedTcs.Task.IsCompleted)\n {\n await Task.WhenAny(new Task[] { wasmExitReceivedTcs.Task, Task.Delay(200) }).ConfigureAwait(false);\n }\n\n if (result.ExitCode != Arguments.ExpectedExitCode)\n {\n logger.LogError($\"Application has finished with exit code {result.ExitCode} but {Arguments.ExpectedExitCode} was expected\");\n return ExitCode.GENERAL_FAILURE;\n }\n else\n {\n if(!wasmExitReceivedTcs.Task.IsCompletedSuccessfully)\n {\n logger.LogError(\"Application exited without sending a wasm exit message.\");\n // TODO return RETURN_CODE_NOT_SET when we are more confident that it doesn't happen very often\n // return ExitCode.RETURN_CODE_NOT_SET;\n }\n if (logProcessor.LineThatMatchedErrorPattern != null)\n {\n logger.LogError(\"Application exited with the expected exit code: {result.ExitCode}.\"\n + $\" But found a line matching an error pattern: {logProcessor.LineThatMatchedErrorPattern}\");\n return ExitCode.APP_CRASH;\n }\n\n logger.LogInformation(\"Application has finished with exit code: \" + result.ExitCode);\n // return SUCCESS if logProcess also returned SUCCESS\n return logProcessorExitCode;\n }\n }\n catch (Win32Exception e) when (e.NativeErrorCode == 2)\n {\n logger.LogCritical($\"The engine binary `{engineBinary}` was not found\");\n return ExitCode.APP_LAUNCH_FAILURE;\n }\n finally\n {\n if (!cts.IsCancellationRequested)\n {\n cts.Cancel();\n }\n }\n\n async Task GetVersionAsync(JavaScriptEngine engine, string engineBinary)\n {\n string[] args;\n switch (engine)\n {\n case JavaScriptEngine.V8:\n args = new[] { \"-e\", \"console.log(this.version())\" };\n break;\n case JavaScriptEngine.NodeJS:\n args = new[] { \"--version\" };\n break;\n default:\n return null;\n };\n\n StringBuilder output = new();\n await processManager.ExecuteCommandAsync(\n engineBinary,\n args,\n log: new CallbackLog(m => logger.LogDebug(m.Trim())),\n stdoutLog: new CallbackLog(msg =>\n {\n logger.LogInformation(msg.Trim());\n output.Append(msg.Trim());\n }),\n stderrLog: new CallbackLog(msg => logger.LogError(msg.Trim())),\n TimeSpan.FromSeconds(10));\n\n return output.ToString();\n }\n }", + "start_line": 37, + "end_line": 254, + "start_byte": 1414, + "end_byte": 10766 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/WASM/Browser/WasmTestBrowserCommand.cs": [ + { + "name": "CreateWebDriver", + "code": "private static (DriverService, IWebDriver) CreateWebDriver(Func getDriverService, Func getDriver)\n where TDriverService : DriverService\n {\n var driverService = getDriverService();\n try\n {\n return (driverService, getDriver(driverService));\n }\n catch\n {\n driverService?.Dispose();\n throw;\n }\n }", + "start_line": 347, + "end_line": 360, + "start_byte": 14758, + "end_byte": 15205 + }, + { + "name": "GetChromiumDriver", + "code": "private (DriverService, IWebDriver) GetChromiumDriver(\n string driverName, string sessionLanguage, Func getDriverService, ILogger logger)\n where TDriver : ChromiumDriver\n where TDriverOptions : ChromiumOptions\n where TDriverService : ChromiumDriverService\n {\n var options = Activator.CreateInstance();\n options.SetLoggingPreference(LogType.Browser, SeleniumLogLevel.All);\n\n if (!string.IsNullOrEmpty(Arguments.BrowserLocation))\n {\n options.BinaryLocation = Arguments.BrowserLocation;\n logger.LogInformation($\"Using Chrome from {Arguments.BrowserLocation}\");\n }\n\n options.AddArguments(Arguments.BrowserArgs.Value);\n\n if (!Arguments.NoHeadless && !Arguments.BackgroundThrottling)\n options.AddArguments(\"--headless\");\n\n if (Arguments.DebuggerPort.Value != null)\n options.AddArguments($\"--remote-debugging-port={Arguments.DebuggerPort}\");\n\n if (!Arguments.NoIncognito)\n options.AddArguments(\"--incognito\");\n\n if (!Arguments.BackgroundThrottling)\n {\n options.AddArguments(new[]\n {\n \"--disable-background-timer-throttling\",\n \"--disable-backgrounding-occluded-windows\",\n \"--disable-renderer-backgrounding\",\n \"--enable-features=NetworkService,NetworkServiceInProcess\",\n });\n }\n else\n {\n options.AddArguments(@\"--enable-features=IntensiveWakeUpThrottling:grace_period_seconds/1\");\n }\n\n options.AddArguments(new[]\n {\n // added based on https://github.com/puppeteer/puppeteer/blob/main/src/node/Launcher.ts#L159-L181\n \"--allow-insecure-localhost\",\n \"--disable-breakpad\",\n \"--disable-component-extensions-with-background-pages\",\n \"--disable-dev-shm-usage\",\n \"--disable-extensions\",\n \"--disable-features=TranslateUI\",\n \"--disable-ipc-flooding-protection\",\n \"--force-color-profile=srgb\",\n \"--metrics-recording-only\"\n });\n\n if (File.Exists(\"/.dockerenv\"))\n {\n // Use --no-sandbox for containers, and codespaces\n options.AddArguments(\"--no-sandbox\");\n }\n\n if (Arguments.NoQuit)\n options.LeaveBrowserRunning = true;\n\n if (options is ChromeOptions chromeOptions)\n chromeOptions.PageLoadStrategy = Arguments.PageLoadStrategy.Value;\n if (options is EdgeOptions edgeOptions)\n edgeOptions.PageLoadStrategy = Arguments.PageLoadStrategy.Value;\n\n logger.LogInformation($\"Starting {driverName} with args: {string.Join(' ', options.Arguments)} and load strategy: {Arguments.PageLoadStrategy.Value}\");\n\n // We want to explicitly specify a timeout here. This is for for the\n // driver commands, like getLog. The default is 60s, which ends up\n // timing out when getLog() is waiting, and doesn't receive anything\n // for 60s.\n //\n // Since, we almost all the output gets written via the websocket now,\n // getLog() might not see anything for long durations!\n //\n // So -> use a larger timeout!\n\n string[] err_snippets = new[]\n {\n \"exited abnormally\",\n \"Cannot start the driver service\",\n \"failed to start\"\n };\n\n foreach (var file in Directory.EnumerateFiles(Arguments.OutputDirectory, $\"{driverName}-*.log\"))\n File.Delete(file);\n\n int max_retries = 3;\n int retry_num = 0;\n while (true)\n {\n TDriverService? driverService = null;\n try\n {\n driverService = getDriverService(options);\n driverService.DriverProcessStarting += (object? sender, DriverProcessStartingEventArgs e) =>\n {\n // Browser respects LANGUAGE in the first place, only if empty it checks LANG\n e.DriverServiceProcessStartInfo.EnvironmentVariables[\"LANGUAGE\"] = sessionLanguage;\n };\n\n driverService.EnableAppendLog = false;\n driverService.EnableVerboseLogging = true;\n driverService.LogPath = Path.Combine(Arguments.OutputDirectory, $\"{driverName}-{retry_num}.log\");\n\n if (Activator.CreateInstance(typeof(TDriver), driverService, options, Arguments.Timeout.Value) is not TDriver driver)\n {\n throw new ArgumentException($\"Failed to create instance of {typeof(TDriver)}\");\n }\n\n return (driverService, driver);\n }\n catch (TargetInvocationException tie) when\n (tie.InnerException is WebDriverException wde\n && err_snippets.Any(s => wde.ToString().Contains(s)) && retry_num < max_retries - 1)\n {\n // chrome can sometimes crash on startup when launching from chromedriver.\n // As a *workaround*, let's retry that a few times\n // Example error seen:\n // [12:41:07] crit: OpenQA.Selenium.WebDriverException: unknown error: Chrome failed to start: exited abnormally.\n // (chrome not reachable)\n\n // Log on max-1 tries, and rethrow on the last one\n logger.LogWarning($\"Failed to start the browser, attempt #{retry_num}: {wde}\");\n\n driverService?.Dispose();\n }\n catch\n {\n driverService?.Dispose();\n throw;\n }\n\n retry_num++;\n }\n }", + "start_line": 206, + "end_line": 345, + "start_byte": 8924, + "end_byte": 14752 + }, + { + "name": "GetEdgeDriver", + "code": "private (DriverService, IWebDriver) GetEdgeDriver(string sessionLanguage, ILogger logger)\n => GetChromiumDriver(\n \"edgedriver\",\n sessionLanguage,\n options =>\n {\n options.UseChromium = true;\n return EdgeDriverService.CreateDefaultServiceFromOptions(options);\n }, logger);", + "start_line": 196, + "end_line": 204, + "start_byte": 8456, + "end_byte": 8918 + }, + { + "name": "GetChromeDriver", + "code": "private (DriverService, IWebDriver) GetChromeDriver(string sessionLanguage, ILogger logger)\n => GetChromiumDriver(\n \"chromedriver\",\n sessionLanguage,\n options => ChromeDriverService.CreateDefaultService(),\n logger);", + "start_line": 189, + "end_line": 194, + "start_byte": 8102, + "end_byte": 8450 + }, + { + "name": "GetFirefoxDriver", + "code": "private (DriverService, IWebDriver) GetFirefoxDriver(ILogger logger)\n {\n var options = new FirefoxOptions();\n options.SetLoggingPreference(LogType.Browser, SeleniumLogLevel.All);\n\n if (!string.IsNullOrEmpty(Arguments.BrowserLocation))\n {\n options.BrowserExecutableLocation = Arguments.BrowserLocation;\n logger.LogInformation($\"Using Firefox from {Arguments.BrowserLocation}\");\n }\n\n options.AddArguments(Arguments.BrowserArgs.Value);\n if (!Arguments.NoHeadless)\n options.AddArguments(\"--headless\");\n\n if (!Arguments.NoIncognito)\n options.AddArguments(\"-private-window\");\n\n options.PageLoadStrategy = Arguments.PageLoadStrategy.Value;\n\n logger.LogInformation($\"Starting Firefox with args: {string.Join(' ', options.ToCapabilities())} and load strategy: {Arguments.PageLoadStrategy.Value}\");\n\n return CreateWebDriver(\n () => FirefoxDriverService.CreateDefaultService(),\n (driverService) => new FirefoxDriver(driverService, options, Arguments.Timeout));\n }", + "start_line": 162, + "end_line": 187, + "start_byte": 6979, + "end_byte": 8096 + }, + { + "name": "GetSafariDriver", + "code": "private (DriverService, IWebDriver) GetSafariDriver(ILogger logger)\n {\n var options = new SafariOptions();\n options.SetLoggingPreference(LogType.Browser, SeleniumLogLevel.All);\n\n logger.LogInformation(\"Starting Safari\");\n\n return CreateWebDriver(\n () => SafariDriverService.CreateDefaultService(),\n driverService => new SafariDriver(driverService, options, Arguments.Timeout));\n }", + "start_line": 150, + "end_line": 160, + "start_byte": 6521, + "end_byte": 6973 + }, + { + "name": "InvokeInternal", + "code": "protected override async Task InvokeInternal(ILogger logger)\n {\n var xmlResultsFilePath = Path.Combine(Arguments.OutputDirectory, \"testResults.xml\");\n File.Delete(xmlResultsFilePath);\n\n var stdoutFilePath = Path.Combine(Arguments.OutputDirectory, \"wasm-console.log\");\n File.Delete(stdoutFilePath);\n\n var symbolicator = WasmSymbolicatorBase.Create(Arguments.SymbolicatorArgument.GetLoadedTypes().FirstOrDefault(),\n Arguments.SymbolMapFileArgument,\n Arguments.SymbolicatePatternsFileArgument,\n logger);\n\n var serviceProvider = Services.BuildServiceProvider();\n var diagnosticsData = serviceProvider.GetRequiredService();\n\n var logProcessor = new WasmTestMessagesProcessor(xmlResultsFilePath,\n stdoutFilePath,\n logger,\n Arguments.ErrorPatternsFile,\n symbolicator);\n var runner = new WasmBrowserTestRunner(\n Arguments,\n PassThroughArguments,\n logProcessor,\n logger);\n\n diagnosticsData.Target = Arguments.Browser.Value.ToString();\n (DriverService driverService, IWebDriver driver) = Arguments.Browser.Value switch\n {\n Browser.Chrome => GetChromeDriver(Arguments.Locale, logger),\n Browser.Safari => GetSafariDriver(logger),\n Browser.Firefox => GetFirefoxDriver(logger),\n Browser.Edge => GetEdgeDriver(Arguments.Locale, logger),\n\n // shouldn't reach here\n _ => throw new ArgumentException($\"Unknown browser : {Arguments.Browser}\")\n };\n\n try\n {\n var exitCode = await runner.RunTestsWithWebDriver(driverService, driver);\n if ((int)exitCode != Arguments.ExpectedExitCode)\n {\n logger.LogError($\"Application has finished with exit code {exitCode} but {Arguments.ExpectedExitCode} was expected\");\n return ExitCode.GENERAL_FAILURE;\n }\n\n if (logProcessor.LineThatMatchedErrorPattern != null)\n {\n logger.LogError(\"Application exited with the expected exit code: {exitCode}.\"\n + $\" But found a line matching an error pattern: {logProcessor.LineThatMatchedErrorPattern}\");\n return ExitCode.APP_CRASH;\n }\n\n return ExitCode.SUCCESS;\n }\n finally\n {\n if (Arguments.NoQuit)\n {\n logger.LogInformation(\"Tests are done. Press Ctrl+C to exit\");\n var token = new CancellationToken(false);\n token.WaitHandle.WaitOne();\n }\n\n // close all tabs before quit is a workaround for broken Selenium - GeckoDriver communication in Firefox\n // https://github.com/dotnet/runtime/issues/101617\n var cts = new CancellationTokenSource();\n cts.CancelAfter(10000);\n try\n {\n logger.LogInformation($\"Closing {driver.WindowHandles.Count} browser tabs before setting the main tab to config page and quitting.\");\n while (driver.WindowHandles.Count > 1 && driverService.IsRunning)\n {\n if (cts.IsCancellationRequested)\n {\n logger.LogInformation($\"Timeout while trying to close tabs, {driver.WindowHandles.Count} is left open before quitting.\");\n break;\n }\n driver.Navigate().GoToUrl(\"about:config\");\n driver.Navigate().GoToUrl(\"about:blank\");\n driver.Close(); //Close Tab\n\n var lastWindowHandle = driver.WindowHandles.LastOrDefault();\n if (lastWindowHandle != null)\n {\n driver.SwitchTo().Window(lastWindowHandle);\n }\n }\n await Task.Delay(TimeSpan.FromSeconds(1), cts.Token);\n if (driverService.IsRunning)\n {\n if (!cts.IsCancellationRequested && driver.WindowHandles.Count != 0)\n {\n driver.Navigate().GoToUrl(\"about:config\");\n driver.Navigate().GoToUrl(\"about:blank\");\n }\n driver.Quit(); // Firefox driver hangs if Quit is not issued.\n driver.Dispose();\n driverService.Dispose();\n }\n }\n catch (Exception e)\n {\n logger.LogError($\"Error while closing browser: {e}\");\n }\n }\n }", + "start_line": 40, + "end_line": 148, + "start_byte": 1448, + "end_byte": 6515 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/WASM/Browser/WasmBrowserTestRunner.cs": [ + { + "name": "VerbosityToString", + "code": "private string VerbosityToString() => _arguments.Verbosity.Value switch\n {\n LogLevel.Trace => \"Verbose\",\n LogLevel.Debug => \"Debug\",\n LogLevel.Information => \"Info\",\n LogLevel.Warning => \"Warning\",\n LogLevel.Error => \"Error\",\n LogLevel.Critical => \"Critical\",\n LogLevel.None => \"Critical\",\n _ => throw new NotSupportedException($\"The value '{_arguments.Verbosity.Value}' is not supported in conversion to MinimumLogLevel\")\n };", + "start_line": 303, + "end_line": 313, + "start_byte": 11492, + "end_byte": 11980 + }, + { + "name": "BuildUrl", + "code": "private string BuildUrl(ServerURLs serverURLs)\n {\n var uriBuilder = new UriBuilder($\"{serverURLs.Http}/{_arguments.HTMLFile}\");\n var sb = new StringBuilder();\n\n if (_arguments.DebuggerPort.Value != null)\n sb.Append($\"arg=--debug\");\n\n foreach (var envVariable in _arguments.WebServerHttpEnvironmentVariables.Value)\n {\n if (sb.Length > 0)\n sb.Append('&');\n sb.Append($\"arg={HttpUtility.UrlEncode($\"--setenv={envVariable}={serverURLs!.Http}\")}\");\n }\n\n if (_arguments.WebServerUseHttps)\n {\n foreach (var envVariable in _arguments.WebServerHttpsEnvironmentVariables.Value)\n {\n if (sb.Length > 0)\n sb.Append('&');\n sb.Append($\"arg={HttpUtility.UrlEncode($\"--setenv={envVariable}={serverURLs!.Https}\")}\");\n }\n }\n\n foreach (var arg in _passThroughArguments)\n {\n if (sb.Length > 0)\n sb.Append('&');\n\n sb.Append($\"arg={HttpUtility.UrlEncode(arg)}\");\n }\n\n if (sb.Length > 0)\n sb.Append('&');\n\n sb.Append($\"arg=-verbosity&arg={VerbosityToString()}\");\n\n uriBuilder.Query = sb.ToString();\n return uriBuilder.ToString();\n }", + "start_line": 255, + "end_line": 295, + "start_byte": 9997, + "end_byte": 11301 + }, + { + "name": "RunSeleniumLogMessagePump", + "code": "private void RunSeleniumLogMessagePump(IWebDriver driver, CancellationToken token)\n {\n try\n {\n ILogs logs = driver.Manage().Logs;\n while (!token.IsCancellationRequested)\n {\n foreach (var logType in logs.AvailableLogTypes)\n {\n foreach (var logEntry in logs.GetLog(logType))\n {\n if (logEntry.Level == SeleniumLogLevel.Severe)\n {\n // These are errors from the browser, some of which might be\n // thrown as part of tests. So, we can't differentiate when\n // it is an error that we can ignore, vs one that should stop\n // the execution completely.\n //\n // Note: these could be received out-of-order as compared to\n // console messages via the websocket.\n //\n // (see commit message for more info)\n _logger.LogError($\"[out of order message from the {logType}]: {logEntry.Message}\");\n continue;\n }\n\n var match = s_consoleLogRegex.Match(Regex.Unescape(logEntry.Message));\n string msg = match.Success ? match.Groups[1].Value : logEntry.Message;\n _messagesProcessor.Invoke(msg);\n }\n }\n }\n }\n catch (WebDriverException wde) when (wde.Message.Contains(\"timed out after\"))\n {\n _logger.LogDebug(wde.Message);\n }\n catch (Exception ex)\n {\n _logger.LogDebug($\"Failed trying to read log messages via selenium: {ex}\");\n throw;\n }\n }", + "start_line": 211, + "end_line": 253, + "start_byte": 8095, + "end_byte": 9991 + }, + { + "name": "RunConsoleMessagesPump", + "code": "private async Task RunConsoleMessagesPump(WebSocket socket, CancellationToken token)\n {\n byte[] buff = new byte[4000];\n var mem = new MemoryStream();\n try\n {\n while (!token.IsCancellationRequested)\n {\n if (socket.State != WebSocketState.Open)\n {\n _logger.LogError($\"DevToolsProxy: Socket is no longer open.\");\n return;\n }\n\n WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment(buff), token).ConfigureAwait(false);\n if (result.MessageType == WebSocketMessageType.Close)\n return;\n\n mem.Write(buff, 0, result.Count);\n\n if (result.EndOfMessage)\n {\n var line = Encoding.UTF8.GetString(mem.GetBuffer(), 0, (int)mem.Length);\n line += Environment.NewLine;\n\n await _messagesProcessor.InvokeAsync(line, token);\n mem.SetLength(0);\n mem.Seek(0, SeekOrigin.Begin);\n }\n }\n }\n catch (WebSocketException wse)\n {\n // this could happen when WebWorker is closed or when browser died\n _logger.LogDebug($\"RunConsoleMessagesPump failed: {wse}\");\n }\n catch (OperationCanceledException oce)\n {\n if (!token.IsCancellationRequested)\n _logger.LogDebug($\"RunConsoleMessagesPump cancelled: {oce}\");\n }\n finally\n {\n _logger.LogDebug($\"Reading console messages from websocket stopped\");\n }\n }", + "start_line": 160, + "end_line": 205, + "start_byte": 6155, + "end_byte": 7827 + }, + { + "name": "RunTestsWithWebDriver", + "code": "public async Task RunTestsWithWebDriver(DriverService driverService, IWebDriver driver)\n {\n var htmlFilePath = Path.Combine(_arguments.AppPackagePath, _arguments.HTMLFile.Value);\n if (!File.Exists(htmlFilePath))\n {\n _logger.LogError($\"Could not find html file {htmlFilePath}\");\n return ExitCode.GENERAL_FAILURE;\n }\n\n var cts = new CancellationTokenSource();\n try\n {\n var consolePumpTcs = new TaskCompletionSource();\n var logProcessorTask = Task.Run(() => _messagesProcessor.RunAsync(cts.Token));\n\n var webServerOptions = WebServer.TestWebServerOptions.FromArguments(_arguments);\n webServerOptions.ContentRoot = _arguments.AppPackagePath;\n webServerOptions.OnConsoleConnected = socket => RunConsoleMessagesPump(socket, cts.Token);\n ServerURLs serverURLs = await WebServer.Start(\n webServerOptions,\n _logger,\n cts.Token);\n\n string testUrl = BuildUrl(serverURLs);\n\n var seleniumLogMessageTask = Task.Run(() => RunSeleniumLogMessagePump(driver, cts.Token), cts.Token);\n cts.CancelAfter(_arguments.Timeout);\n\n _logger.LogDebug($\"Opening in browser: {testUrl}\");\n driver.Navigate().GoToUrl(testUrl);\n\n TaskCompletionSource wasmExitReceivedTcs = _messagesProcessor.WasmExitReceivedTcs;\n var tasks = new Task[]\n {\n wasmExitReceivedTcs.Task,\n consolePumpTcs.Task,\n seleniumLogMessageTask,\n logProcessorTask,\n Task.Delay(_arguments.Timeout)\n };\n\n if (_arguments.BackgroundThrottling)\n {\n // throttling only happens when the page is not visible\n driver.Manage().Window.Minimize();\n }\n\n var task = await Task.WhenAny(tasks).ConfigureAwait(false);\n\n ExitCode logProcessorExitCode = ExitCode.SUCCESS;\n if (task != logProcessorTask && !task.IsFaulted)\n logProcessorExitCode = await _messagesProcessor.CompleteAndFlushAsync();\n\n if (task == tasks[^1] || cts.IsCancellationRequested)\n {\n if (driverService.IsRunning)\n {\n // Selenium isn't able to kill chrome in this case :/\n int pid = driverService.ProcessId;\n var p = Process.GetProcessById(pid);\n if (p != null)\n {\n _logger.LogError($\"Tests timed out. Killing driver service pid {pid}\");\n p.Kill(true);\n }\n }\n\n // timed out\n if (!cts.IsCancellationRequested)\n cts.Cancel();\n return ExitCode.TIMED_OUT;\n }\n\n if (task == wasmExitReceivedTcs.Task && wasmExitReceivedTcs.Task.IsCompletedSuccessfully)\n {\n _logger.LogTrace($\"Looking for `tests_done` element, to get the exit code\");\n var testsDoneElement = new WebDriverWait(driver, TimeSpan.FromSeconds(30))\n .Until(e => e.FindElement(By.Id(\"tests_done\")));\n\n if (int.TryParse(testsDoneElement.Text, out var code))\n {\n var appExitCode = (ExitCode)Enum.ToObject(typeof(ExitCode), code);\n if (logProcessorExitCode != ExitCode.SUCCESS)\n {\n _logger.LogInformation($\"Application has finished with exit code {appExitCode}. But the log processor failed with {logProcessorExitCode}.\");\n return logProcessorExitCode;\n }\n\n return appExitCode;\n }\n\n return ExitCode.RETURN_CODE_NOT_SET;\n }\n\n if (task.IsFaulted)\n {\n _logger.LogDebug($\"task faulted {task.Exception}\");\n throw task.Exception!;\n }\n\n return ExitCode.TIMED_OUT;\n }\n finally\n {\n if (!cts.IsCancellationRequested)\n {\n cts.Cancel();\n }\n }\n }", + "start_line": 49, + "end_line": 158, + "start_byte": 1811, + "end_byte": 6149 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/Simulators/ListCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override async Task InvokeInternal(ILogger logger)\n {\n Logger = logger;\n\n var simulators = await GetAvailableSimulators();\n\n foreach (var simulator in simulators)\n {\n var output = new StringBuilder();\n output.AppendLine(simulator.Name);\n output.Append($\" Version: {simulator.Version}\");\n\n string? installStatus = null;\n var installedVersion = await IsInstalled(simulator);\n if (installedVersion == null)\n {\n if (Arguments.ListInstalledOnly)\n {\n Logger.LogDebug($\"The simulator '{simulator.Name}' is not installed\");\n continue;\n }\n\n installStatus = \"not installed\";\n }\n else\n {\n if (installedVersion >= Version.Parse(simulator.Version))\n {\n if (!Arguments.ListInstalledOnly)\n {\n installStatus = \"installed\";\n }\n }\n else\n {\n output.AppendLine();\n installStatus = $\"an earlier version is installed: {installedVersion}\";\n }\n }\n\n output.AppendLine($\" ({installStatus})\");\n output.AppendLine($\" Source: {simulator.Source}\");\n output.AppendLine($\" Identifier: {simulator.Identifier}\");\n output.AppendLine($\" InstallPrefix: {simulator.InstallPrefix}\");\n\n Logger.LogInformation(output.ToString());\n }\n\n return ExitCode.SUCCESS;\n }", + "start_line": 29, + "end_line": 78, + "start_byte": 937, + "end_byte": 2612 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/Simulators/InstallCommand.cs": [ + { + "name": "InstallSimulator", + "code": "private async Task InstallSimulator(Simulator simulator, string downloadPath, string filename)\n {\n if (simulator.IsDmgFormat)\n {\n Logger.LogInformation($\"Installing simulator '{downloadPath}' using simctl...\");\n var (succeeded, stdout) = await ExecuteCommand(\"xcrun\", TimeSpan.FromMinutes(15), \"simctl\", \"runtime\", \"add\", downloadPath);\n if (!succeeded)\n {\n Logger.LogError(\"Installation failure!\" + Environment.NewLine + stdout);\n return false;\n }\n\n File.Delete(downloadPath);\n return true;\n }\n else\n {\n var mount_point = Path.Combine(TempDirectory, filename + \"-mount\");\n Directory.CreateDirectory(mount_point);\n try\n {\n Logger.LogInformation($\"Mounting '{downloadPath}' into '{mount_point}'...\");\n var (succeeded, stdout) = await ExecuteCommand(\"hdiutil\", TimeSpan.FromMinutes(1), \"attach\", downloadPath, \"-mountpoint\", mount_point, \"-quiet\", \"-nobrowse\");\n if (!succeeded)\n {\n Logger.LogError(\"Mount failure!\" + Environment.NewLine + stdout);\n return false;\n }\n\n try\n {\n var packages = Directory.GetFiles(mount_point, \"*.pkg\");\n if (packages.Length == 0)\n {\n Logger.LogError(\"Found no *.pkg files in the dmg.\");\n return false;\n }\n else if (packages.Length > 1)\n {\n Logger.LogError(\"Found more than one *.pkg file in the dmg:\\n\\t{0}\", string.Join(\"\\n\\t\", packages));\n return false;\n }\n\n // According to the package manifest, the package's install location is /.\n // That's obviously not where it's installed, but I have no idea how Apple does it\n // So instead decompress the package, modify the package manifest, re-create the package, and then install it.\n var expanded_path = Path.Combine(TempDirectory + \"-expanded-pkg\");\n if (Directory.Exists(expanded_path))\n {\n Directory.Delete(expanded_path, true);\n }\n\n Logger.LogInformation($\"Expanding '{packages[0]}' into '{expanded_path}'...\");\n (succeeded, stdout) = await ExecuteCommand(\"pkgutil\", TimeSpan.FromMinutes(1), \"--expand\", packages[0], expanded_path);\n if (!succeeded)\n {\n Logger.LogError($\"Failed to expand {packages[0]}:\" + Environment.NewLine + stdout);\n return false;\n }\n\n try\n {\n var packageInfoPath = Path.Combine(expanded_path, \"PackageInfo\");\n var packageInfoDoc = new XmlDocument();\n packageInfoDoc.Load(packageInfoPath);\n // Add the install-location attribute to the pkg-info node\n var attr = packageInfoDoc.CreateAttribute(\"install-location\");\n attr.Value = simulator.InstallPrefix;\n packageInfoDoc.SelectSingleNode(\"/pkg-info\")?.Attributes?.Append(attr);\n packageInfoDoc.Save(packageInfoPath);\n\n var fixed_path = Path.Combine(Path.GetDirectoryName(downloadPath)!, Path.GetFileNameWithoutExtension(downloadPath) + \"-fixed.pkg\");\n if (File.Exists(fixed_path))\n {\n File.Delete(fixed_path);\n }\n\n try\n {\n Logger.LogInformation($\"Creating fixed package '{fixed_path}' from '{expanded_path}'...\");\n\n (succeeded, stdout) = await ExecuteCommand(\"pkgutil\", TimeSpan.FromMinutes(2), \"--flatten\", expanded_path, fixed_path);\n if (!succeeded)\n {\n Logger.LogError(\"Failed to create fixed package:\" + Environment.NewLine + stdout);\n return false;\n }\n\n Logger.LogInformation($\"Installing '{fixed_path}'...\");\n (succeeded, stdout) = await ExecuteCommand(\"sudo\", TimeSpan.FromMinutes(15), \"installer\", \"-pkg\", fixed_path, \"-target\", \"/\", \"-verbose\", \"-dumplog\");\n if (!succeeded)\n {\n Logger.LogError(\"Failed to install package:\" + Environment.NewLine + stdout);\n return false;\n }\n }\n finally\n {\n if (File.Exists(fixed_path))\n {\n File.Delete(fixed_path);\n }\n }\n }\n finally\n {\n Directory.Delete(expanded_path, true);\n }\n }\n finally\n {\n await ExecuteCommand(\"hdiutil\", TimeSpan.FromMinutes(5), \"detach\", mount_point, \"-quiet\");\n }\n }\n finally\n {\n Directory.Delete(mount_point, true);\n }\n\n File.Delete(downloadPath);\n return true;\n }\n }", + "start_line": 304, + "end_line": 426, + "start_byte": 12466, + "end_byte": 18269 + }, + { + "name": "DownloadSimulator", + "code": "private async Task DownloadSimulator(Simulator simulator, string downloadPath)\n {\n var watch = Stopwatch.StartNew();\n var httpClient = s_client;\n\n if (simulator.IsDmgFormat)\n {\n CookieContainer cookies = new();\n\n // we need to first get the cookie from ADC\n var path = Uri.TryCreate(simulator.Source, UriKind.Absolute, out var simulatorUri)\n ? simulatorUri.AbsolutePath\n : throw new InvalidOperationException($\"Could not parse the simulator URL: {simulator.Source}\");\n\n httpClient = new HttpClient(new HttpClientHandler() { CookieContainer = cookies, CheckCertificateRevocationList = true });\n httpClient.DefaultRequestHeaders.Add(\"User-Agent\", $\"dotnet/xharness {XHarnessVersionCommand.GetAssemblyVersion().ProductVersion}\"); // otherwise we get a 401 Unauthorized\n\n var adcDownloadUrl = $\"https://developerservices2.apple.com/services/download?path={path}\";\n using (var response = await httpClient.GetAsync(adcDownloadUrl, HttpCompletionOption.ResponseHeadersRead))\n {\n response.EnsureSuccessStatusCode();\n\n foreach (Cookie cookie in cookies.GetAllCookies())\n {\n if (cookie.Name == \"ADCDownloadAuth\")\n {\n // transfer this cookie to the simulator download URI\n cookies.Add(simulatorUri, new Cookie(cookie.Name, cookie.Value));\n }\n }\n }\n }\n\n using (var response = await httpClient.GetAsync(simulator.Source, HttpCompletionOption.ResponseHeadersRead))\n {\n response.EnsureSuccessStatusCode();\n\n using var fileStream = File.Create(downloadPath);\n\n if (Arguments.HideProgress)\n {\n await response.Content.CopyToAsync(fileStream);\n }\n else\n {\n var progressMessage = $\"Starting the download..\";\n Console.Write(progressMessage);\n\n void ShowProgress(long totalBytesDownloaded)\n {\n var previousLength = progressMessage.Length;\n progressMessage = $\"[{watch.Elapsed:hh\\\\:mm\\\\:ss}] {totalBytesDownloaded / 1024.0 / 1024.0:N2} / {simulator.FileSize / 1024.0 / 1024.0:N2} MB\\t\\t{(int)(100 * totalBytesDownloaded / simulator.FileSize),3}%\";\n Console.Write(\"\\r\" + progressMessage.PadRight(previousLength));\n }\n\n var totalBytesDownloaded = 0L;\n var buffer = new byte[8192];\n var lastUpdate = DateTime.Now;\n var updateFrequency = TimeSpan.FromMilliseconds(400);\n\n using var responseStream = await response.Content.ReadAsStreamAsync();\n while (true)\n {\n var bytesRead = await responseStream.ReadAsync(buffer);\n if (bytesRead == 0)\n {\n Console.Write(\"\\r\" + \" \".PadRight(progressMessage.Length) + \"\\r\");\n break;\n }\n\n await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead));\n\n totalBytesDownloaded += bytesRead;\n\n if (DateTime.Now - lastUpdate > updateFrequency)\n {\n ShowProgress(totalBytesDownloaded);\n lastUpdate = DateTime.Now;\n }\n }\n }\n }\n\n watch.Stop();\n\n var size = new FileInfo(downloadPath).Length;\n Logger.LogInformation($\"Downloaded {size / 1024.0 / 1024.0:N1} MB in {watch.Elapsed:hh\\\\:mm\\\\:ss}\");\n }", + "start_line": 215, + "end_line": 302, + "start_byte": 8676, + "end_byte": 12460 + }, + { + "name": "CanXcodeDownloadSimulatorsUsingCLI", + "code": "private static bool CanXcodeDownloadSimulatorsUsingCLI(Version xcodeVersion)\n {\n // -buildVersion is only supported in Xcode 16.1 and later\n return (xcodeVersion.Major == 16 && xcodeVersion.Minor >= 1) || xcodeVersion.Major > 16;\n }", + "start_line": 209, + "end_line": 213, + "start_byte": 8418, + "end_byte": 8670 + }, + { + "name": "CanSimulatorBeInstalledUsingXcodeCLI", + "code": "private static bool CanSimulatorBeInstalledUsingXcodeCLI(Simulator simulator)\n {\n var simulatorVersion = Version.Parse(simulator.Version);\n\n return simulator.Platform switch\n {\n \"iOS\" => simulatorVersion.Major >= 16,\n \"tvOS\" => simulatorVersion.Major >= 16,\n \"watchOS\" => simulatorVersion.Major >= 9,\n \"visionOS\" => simulatorVersion.Major >= 1,\n _ => false,\n };\n }", + "start_line": 195, + "end_line": 207, + "start_byte": 7959, + "end_byte": 8412 + }, + { + "name": "Install", + "code": "private async Task Install(Simulator simulator)\n {\n var xcodeVersion = await GetXcodeVersion();\n\n if (CanXcodeDownloadSimulatorsUsingCLI(xcodeVersion) && CanSimulatorBeInstalledUsingXcodeCLI(simulator))\n {\n Logger.LogInformation($\"Downloading and installing simulator: {simulator.Name} through xcodebuild with Xcode: {xcodeVersion}\");\n var (succeeded, stdout) = await ExecuteCommand(\"xcodebuild\", TimeSpan.FromMinutes(15), \"-downloadPlatform\", simulator.Platform, \"-buildVersion\", simulator.BuildUpdate, \"-verbose\");\n if (!succeeded)\n {\n Logger.LogError($\"Download and installation failed through xcodebuild for simulator: {simulator.Name} with Xcode: {xcodeVersion}!\" + Environment.NewLine + stdout);\n return false;\n }\n else\n {\n Logger.LogDebug(stdout);\n return true;\n }\n }\n // Xcode 16.0 trying to install new simulators (e.g. iOS 18) path\n else if (xcodeVersion.Major == 16 && xcodeVersion.Minor == 0 && simulator.Source is null)\n {\n Logger.LogWarning($\"Xcode {xcodeVersion} does not support selecting simulator versions using CLI. It will always default to the latest version. Consider upgrading to Xcode 16.1 or later.\");\n Logger.LogInformation($\"Downloading and installing the latest {simulator.Platform} simulator through xcodebuild with Xcode: {xcodeVersion}\");\n var (succeeded, stdout) = await ExecuteCommand(\"xcodebuild\", TimeSpan.FromMinutes(15), \"-downloadPlatform\", simulator.Platform, \"-verbose\");\n if (!succeeded)\n {\n Logger.LogError($\"Download and installation failed through xcodebuild for the latest {simulator.Platform} simulator with Xcode: {xcodeVersion}!\" + Environment.NewLine + stdout);\n return false;\n }\n else\n {\n Logger.LogDebug(stdout);\n return true;\n }\n }\n else if (simulator.Source is not null)\n {\n var filename = Path.GetFileName(simulator.Source);\n var downloadPath = Path.Combine(TempDirectory, filename);\n var download = true;\n\n if (!File.Exists(downloadPath))\n {\n Logger.LogInformation(\n $\"Downloading '{simulator.Source}' to '{downloadPath}' \" +\n $\"(size: {simulator.FileSize} bytes = {simulator.FileSize / 1024.0 / 1024.0:N2} MB)...\");\n }\n else if (new FileInfo(downloadPath).Length != simulator.FileSize)\n {\n Logger.LogInformation(\n $\"Downloading '{simulator.Source}' to '{downloadPath}' because the existing file's \" +\n $\"size {new FileInfo(downloadPath).Length} does not match the expected size {simulator.FileSize}...\");\n }\n else\n {\n download = false;\n }\n\n if (download)\n {\n await DownloadSimulator(simulator, downloadPath);\n }\n\n return await InstallSimulator(simulator, downloadPath, filename);\n }\n else\n {\n throw new Exception($\"Cannot download simulator: {simulator.Name} from source nor through Xcode: {xcodeVersion}\");\n }\n }", + "start_line": 122, + "end_line": 192, + "start_byte": 4448, + "end_byte": 7857 + }, + { + "name": "InvokeInternal", + "code": "protected override async Task InvokeInternal(ILogger logger)\n {\n Logger = logger;\n\n var simulatorIds = ParseSimulatorIds();\n\n var simulators = await GetAvailableSimulators();\n var exitCode = ExitCode.SUCCESS;\n\n if (!simulatorIds.Any())\n {\n logger.LogError(\"You have to specify at least one simulator to install!\");\n return ExitCode.INVALID_ARGUMENTS;\n }\n\n var unknownSimulators = simulatorIds.Where(identifier =>\n !simulators.Any(sim => sim.Identifier.Equals(identifier, StringComparison.InvariantCultureIgnoreCase)));\n\n if (unknownSimulators.Any())\n {\n Logger.LogError(\"Unknown simulators: \" + string.Join(\", \", unknownSimulators));\n return ExitCode.DEVICE_NOT_FOUND;\n }\n\n foreach (var simulator in simulators)\n {\n if (!simulatorIds.Any(identifier => simulator.Identifier.Equals(identifier, StringComparison.InvariantCultureIgnoreCase)))\n {\n Logger.LogDebug($\"Skipping '{simulator.Identifier}'\");\n continue;\n }\n\n var installedVersion = await IsInstalled(simulator);\n var shouldInstall = false;\n\n if (installedVersion == null)\n {\n Logger.LogInformation($\"The simulator '{simulator.Name}' is missing and will be installed\");\n shouldInstall = true;\n }\n else\n {\n if (installedVersion >= Version.Parse(simulator.Version))\n {\n if (Arguments.Force)\n {\n Logger.LogInformation($\"The simulator '{simulator.Name}' is installed but --force was supplied so reinstalling\");\n shouldInstall = true;\n }\n else\n {\n Logger.LogInformation($\"The simulator '{simulator.Name}' is already installed ({simulator.Version})\");\n }\n }\n else\n {\n Logger.LogInformation($\"The simulator '{simulator.Name}' is installed, but an update is available ({simulator.Version}).\");\n }\n }\n\n if (shouldInstall)\n {\n Logger.LogInformation($\"Installing '{simulator.Name}' ({simulator.Version})...\");\n\n try\n {\n if (await Install(simulator))\n {\n Logger.LogInformation($\"Installed '{simulator.Name}' successfully\");\n }\n else\n {\n Logger.LogError($\"Failed to install '{simulator.Name}'\");\n exitCode = ExitCode.GENERAL_FAILURE;\n }\n }\n catch (Exception e)\n {\n Logger.LogError($\"Failed to install '{simulator.Name}':{Environment.NewLine}{e}\");\n exitCode = ExitCode.GENERAL_FAILURE;\n }\n }\n }\n\n return exitCode;\n }", + "start_line": 35, + "end_line": 120, + "start_byte": 1277, + "end_byte": 4442 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/Simulators/SimulatorsCommandSet.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/Simulators/FindCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override async Task InvokeInternal(ILogger logger)\n {\n Logger = logger;\n\n var searchedSimulators = ParseSimulatorIds();\n\n var simulators = await GetAvailableSimulators();\n var exitCode = ExitCode.SUCCESS;\n\n var unknownSimulators = searchedSimulators.Where(identifier =>\n !simulators.Any(sim => sim.Identifier.Equals(identifier, StringComparison.InvariantCultureIgnoreCase)));\n\n if (unknownSimulators.Any())\n {\n // This output is actually matched in some tools, so please don't change\n var message = \"Unknown simulators: \" + string.Join(\", \", unknownSimulators);\n\n if (Arguments.Verbosity == LogLevel.Debug)\n {\n Logger.LogDebug(message);\n\n }\n else\n {\n // For parsing\n Console.WriteLine(message);\n }\n return ExitCode.DEVICE_NOT_FOUND;\n }\n\n // We output a list of simulators that were supplied and not installed\n foreach (var simulator in simulators)\n {\n var installedVersion = await IsInstalled(simulator);\n\n if (installedVersion == null && searchedSimulators.Any(identifier => simulator.Identifier.Equals(identifier, StringComparison.InvariantCultureIgnoreCase)))\n {\n if (Arguments.Verbosity == LogLevel.Debug)\n {\n Logger.LogDebug($\"The simulator '{simulator.Name}' is not installed\");\n\n }\n else\n {\n // For parsing\n Console.WriteLine(simulator.Identifier);\n }\n\n exitCode = ExitCode.DEVICE_NOT_FOUND;\n continue;\n }\n\n if (installedVersion >= Version.Parse(simulator.Version))\n {\n Logger.LogDebug($\"The simulator {simulator.Version} is installed ({simulator.Version})\");\n }\n else\n {\n Logger.LogDebug($\"The simulator {simulator.Name} is installed, but an update is available ({simulator.Version}).\");\n }\n }\n\n return exitCode;\n }", + "start_line": 29, + "end_line": 92, + "start_byte": 1125, + "end_byte": 3337 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/Simulators/SimulatorsCommand.cs": [ + { + "name": "GetXcodeUuid", + "code": "private async Task GetXcodeUuid()\n {\n if (_xcodeUuid is not null)\n {\n return _xcodeUuid;\n }\n\n string xcodeRoot = Arguments.XcodeRoot.Value ?? new MacOSProcessManager().XcodeRoot;\n var plistPath = Path.Combine(xcodeRoot, \"Contents\", \"Info.plist\");\n\n var (succeeded, xcodeUuid) = await ExecuteCommand(\"/usr/libexec/PlistBuddy\", TimeSpan.FromSeconds(5), \"-c\", \"Print :DVTPlugInCompatibilityUUID\", plistPath);\n if (!succeeded)\n {\n throw new Exception(\"Failed to detect Xcode UUID! This is only available on Xcode < 15.3.\");\n }\n\n _xcodeUuid = xcodeUuid.Trim();\n\n return _xcodeUuid;\n }", + "start_line": 436, + "end_line": 455, + "start_byte": 18218, + "end_byte": 18910 + }, + { + "name": "GetXcodeVersion", + "code": "protected async Task GetXcodeVersion()\n {\n if (_xcodeVersion is not null)\n {\n return _xcodeVersion;\n }\n\n string xcodeRoot = Arguments.XcodeRoot.Value ?? new MacOSProcessManager().XcodeRoot;\n var plistPath = Path.Combine(xcodeRoot, \"Contents\", \"Info.plist\");\n\n var (succeeded, xcodeVersion) = await ExecuteCommand(\"/usr/libexec/PlistBuddy\", TimeSpan.FromSeconds(5), \"-c\", \"Print :DTXcode\", plistPath);\n if (!succeeded)\n {\n throw new Exception(\"Failed to detect Xcode version!\");\n }\n\n xcodeVersion = xcodeVersion.Trim();\n\n // the first two digits of DTXcode are the major version, then minor and revision so e.g. 1520 would translate to 15.2.0\n xcodeVersion = xcodeVersion.Insert(xcodeVersion.Length - 2, \".\");\n xcodeVersion = xcodeVersion.Insert(xcodeVersion.Length - 1, \".\");\n\n _xcodeVersion = Version.Parse(xcodeVersion);\n\n return _xcodeVersion;\n }", + "start_line": 409, + "end_line": 434, + "start_byte": 17221, + "end_byte": 18212 + }, + { + "name": "DownloadFile", + "code": "private async Task DownloadFile(string url, string destinationPath)\n {\n try\n {\n Logger.LogInformation($\"Downloading {url}...\");\n\n var downloadTask = s_client.GetStreamAsync(url);\n using var fileStream = new FileStream(destinationPath, FileMode.Create);\n using var bodyStream = await downloadTask;\n await bodyStream.CopyToAsync(fileStream);\n return true;\n }\n catch (HttpRequestException e)\n {\n // 403 means 404\n if (e.StatusCode == HttpStatusCode.Forbidden)\n {\n // Apple's servers return a 403 if the file doesn't exist, which can be quite confusing, so show a better error.\n Logger.LogWarning($\"Failed to download {url}: Not found\");\n }\n else\n {\n Logger.LogWarning($\"Failed to download {url}: {e}\");\n }\n }\n\n return false;\n }", + "start_line": 380, + "end_line": 407, + "start_byte": 16242, + "end_byte": 17215 + }, + { + "name": "GetSimulatorIndexXml", + "code": "private async Task GetSimulatorIndexXml()\n {\n var xcodeVersion = await GetXcodeVersion();\n string indexUrl, indexName;\n\n if (xcodeVersion.Major >= 14)\n {\n /*\n * The following url was found while debugging Xcode, the \"index2\" part is actually hardcoded:\n *\n *\tDVTFoundation`-[DVTDownloadableIndexSource identifier]:\n *\t\t0x103db478d <+0>: pushq %rbp\n *\t\t0x103db478e <+1>: movq %rsp, %rbp\n *\t\t0x103db4791 <+4>: leaq 0x53f008(%rip), %rax ; @\"index2\"\n *\t\t0x103db4798 <+11>: popq %rbp\n *\t\t0x103db4799 <+12>: retq\n *\n */\n indexName = $\"index-{xcodeVersion}.dvtdownloadableindex\";\n indexUrl = \"https://devimages-cdn.apple.com/downloads/xcode/simulators/index2.dvtdownloadableindex\";\n }\n else\n {\n var xcodeUuid = await GetXcodeUuid();\n indexName = $\"index-{xcodeVersion}-{xcodeUuid}.dvtdownloadableindex\";\n\n indexUrl = $\"https://devimages-cdn.apple.com/downloads/xcode/simulators/{indexName}\";\n }\n\n var tmpfile = Path.Combine(TempDirectory, indexName);\n if (!File.Exists(tmpfile))\n {\n if (!await DownloadFile(indexUrl, tmpfile))\n return null;\n }\n else\n {\n Logger.LogInformation($\"File '{tmpfile}' already exists, skipped download\");\n }\n\n var (succeeded, xmlResult) = await ExecuteCommand(\"plutil\", TimeSpan.FromSeconds(30), \"-convert\", \"xml1\", \"-o\", \"-\", tmpfile);\n if (!succeeded)\n {\n return null;\n }\n\n return xmlResult;\n }", + "start_line": 331, + "end_line": 378, + "start_byte": 14527, + "end_byte": 16236 + }, + { + "name": "ParseSimulatorIds", + "code": "protected IEnumerable ParseSimulatorIds()\n {\n var simulators = new List();\n\n foreach (string argument in ExtraArguments)\n {\n if (argument.StartsWith(\"com.apple.pkg.\") || argument.StartsWith(\"com.apple.dmg.\"))\n {\n simulators.Add(argument);\n continue;\n }\n\n TestTargetOs target;\n try\n {\n target = argument.ParseAsAppRunnerTargetOs();\n }\n catch (ArgumentOutOfRangeException e)\n {\n throw new ArgumentException(\n $\"Failed to parse simulator '{argument}'. Available values are ios-simulator, tvos-simulator, watchos-simulator and xros-simulator.\" +\n Environment.NewLine + Environment.NewLine +\n \"You need to also specify the version. Example: ios-simulator_13.4\", e);\n }\n\n if (string.IsNullOrEmpty(target.OSVersion))\n {\n throw new ArgumentException($\"Failed to parse simulator '{argument}'. \" +\n $\"You need to specify the exact version. Example: ios-simulator_13.4\");\n }\n\n var testTargetVersion = Version.Parse(target.OSVersion);\n\n (string simulatorName, string simulatorFormat) = target.Platform switch\n {\n TestTarget.Simulator_iOS64 => (\"iPhone\", testTargetVersion.Major >= 16 ? \"dmg\" : \"pkg\"),\n TestTarget.Simulator_tvOS => (\"AppleTV\", testTargetVersion.Major >= 16 ? \"dmg\" : \"pkg\"),\n TestTarget.Simulator_watchOS => (\"Watch\", testTargetVersion.Major >= 9 ? \"dmg\" : \"pkg\"),\n TestTarget.Simulator_xrOS => (\"xrOS\", \"dmg\"),\n _ => throw new ArgumentException($\"Failed to parse simulator '{argument}'. \" +\n \"Available values are ios-simulator, tvos-simulator, watchos-simulator and xros-simulator.\" +\n Environment.NewLine + Environment.NewLine +\n \"You need to also specify the version. Example: ios-simulator_13.4\"),\n };\n\n // e.g. com.apple.pkg.AppleTVSimulatorSDK14_3\n simulators.Add($\"com.apple.{simulatorFormat}.{simulatorName}SimulatorSDK{target.OSVersion.Replace(\".\", \"_\")}\");\n }\n\n return simulators;\n }", + "start_line": 279, + "end_line": 329, + "start_byte": 12173, + "end_byte": 14521 + }, + { + "name": "IsInstalled", + "code": "protected async Task IsInstalled(Simulator simulator)\n {\n var xcodeVersion = await GetXcodeVersion();\n bool isXcode14 = xcodeVersion.Major >= 14;\n\n if (simulator.Identifier.StartsWith(\"com.apple.dmg.\") && isXcode14)\n {\n var (succeeded, json) = await ExecuteCommand($\"xcrun\", TimeSpan.FromMinutes(1), \"simctl\", \"runtime\", \"list\", \"-j\");\n if (!succeeded)\n {\n return null;\n }\n Logger.LogDebug($\"Listing runtime disk images via returned: {json}\");\n\n string simulatorRuntime = \"\";\n string simulatorVersion = \"\";\n\n if (simulator.Identifier.StartsWith(\"com.apple.dmg.iPhoneSimulatorSDK\"))\n {\n simulatorRuntime = \"com.apple.CoreSimulator.SimRuntime.iOS-\";\n simulatorVersion = simulator.Identifier.Substring(\"com.apple.dmg.iPhoneSimulatorSDK\".Length);\n }\n else if (simulator.Identifier.StartsWith(\"com.apple.dmg.AppleTVSimulatorSDK\"))\n {\n simulatorRuntime = \"com.apple.CoreSimulator.SimRuntime.tvOS-\";\n simulatorVersion = simulator.Identifier.Substring(\"com.apple.dmg.AppleTVSimulatorSDK\".Length);\n }\n else if (simulator.Identifier.StartsWith(\"com.apple.dmg.WatchSimulatorSDK\"))\n {\n simulatorRuntime = \"com.apple.CoreSimulator.SimRuntime.watchOS-\";\n simulatorVersion = simulator.Identifier.Substring(\"com.apple.dmg.WatchSimulatorSDK\".Length);\n }\n else if (simulator.Identifier.StartsWith(\"com.apple.dmg.xrSimulatorSDK\"))\n {\n simulatorRuntime = \"com.apple.CoreSimulator.SimRuntime.xrOS-\";\n simulatorVersion = simulator.Identifier.Substring(\"com.apple.dmg.xrSimulatorSDK\".Length);\n }\n else\n {\n Logger.LogWarning($\"Unknown simulator type: {simulator.Identifier}\");\n }\n\n // trim away any beta suffix\n string simulatorBetaVersion = \"\";\n if (simulatorVersion.Contains(\"_b\"))\n {\n simulatorBetaVersion = simulatorVersion.Substring(simulatorVersion.LastIndexOf(\"_b\") + \"_b\".Length);\n simulatorVersion = simulatorVersion.Substring(0, simulatorVersion.LastIndexOf(\"_b\"));\n }\n\n var runtimeIdentifier = simulatorRuntime + simulatorVersion.Replace('_', '-');\n var simulators = JsonDocument.Parse(json);\n\n foreach (JsonProperty sim in simulators.RootElement.EnumerateObject())\n {\n if (sim.Value.GetProperty(\"runtimeIdentifier\").GetString() == runtimeIdentifier)\n {\n var version = sim.Value.GetProperty(\"version\").GetString();\n if (version == null)\n return null;\n\n // make sure we have a proper major.minor.build.revision version\n // and if we have a beta version, add it to the version as the revision parameter\n if (version.Count(c => c == '.') == 1)\n version += simulatorBetaVersion == \"\" ? \".0.0\" : $\".0.{simulatorBetaVersion}\";\n else if (version.Count(c => c == '.') == 2)\n version += simulatorBetaVersion == \"\" ? \".0\" : $\".{simulatorBetaVersion}\";\n\n // TODO: the version returned by simctl and index2.dvtdownloadableindex for dmg packages is not a unique version like for pkg but just major.minor.0.0,\n // we could use the \"build\" key from simctl to compare with the \"buildUpdate\" in the index2.dvtdownloadableindex\n\n return Version.TryParse(version, out var parsedVersion) ? parsedVersion : null;\n }\n }\n\n return null;\n }\n else if (simulator.Identifier.StartsWith(\"com.apple.pkg.\"))\n {\n var (succeeded, pkgInfo) = await ExecuteCommand($\"pkgutil\", TimeSpan.FromMinutes(1), \"--pkg-info\", simulator.Identifier);\n if (!succeeded)\n {\n return null;\n }\n\n var lines = pkgInfo.Split('\\n');\n var version = lines.First(v => v.StartsWith(\"version: \", StringComparison.Ordinal)).Substring(\"version: \".Length);\n return Version.Parse(version);\n }\n\n return null;\n }", + "start_line": 186, + "end_line": 277, + "start_byte": 7738, + "end_byte": 12167 + }, + { + "name": "ReplaceStringUsingKey", + "code": "[return: NotNullIfNotNull(\"value\")]\n static string? ReplaceStringUsingKey(string? value, Dictionary replacements)\n {\n if (value is null)\n return null;\n\n foreach (var kvp in replacements)\n {\n value = value.Replace($\"$({kvp.Key})\", kvp.Value);\n }\n\n return value;\n }", + "start_line": 172, + "end_line": 184, + "start_byte": 7387, + "end_byte": 7732 + }, + { + "name": "GetAvailableSimulators", + "code": "protected async Task> GetAvailableSimulators()\n {\n\n var doc = new XmlDocument();\n doc.LoadXml(await GetSimulatorIndexXml() ?? throw new FailedToGetIndexException());\n\n var simulators = new List();\n\n var downloadables = doc.SelectNodes(\"//plist/dict/key[text()='downloadables']/following-sibling::array[1]/dict\");\n foreach (XmlNode? downloadable in downloadables!)\n {\n if (downloadable == null)\n {\n continue;\n }\n\n var nameNode = downloadable.SelectSingleNode(\"key[text()='name']/following-sibling::string\") ?? throw new Exception(\"Name node not found\");\n var versionNode = downloadable.SelectSingleNode(\"key[text()='version']/following-sibling::string\") ?? throw new Exception(\"Version node not found\");\n var identifierNode = downloadable.SelectSingleNode(\"key[text()='identifier']/following-sibling::string\") ?? throw new Exception(\"Identifier node not found\");\n var sourceNode = downloadable.SelectSingleNode(\"key[text()='source']/following-sibling::string\");\n\n var fileSizeNode = downloadable.SelectSingleNode(\"key[text()='fileSize']/following-sibling::integer|key[text()='fileSize']/following-sibling::real\");\n var installPrefixNode = downloadable.SelectSingleNode(\"key[text()='userInfo']/following-sibling::dict/key[text()='InstallPrefix']/following-sibling::string\");\n var buildUpdateNode = downloadable.SelectSingleNode(\"key[text()='simulatorVersion']/following-sibling::dict[1]/key[text()='buildUpdate']/following-sibling::string[1]\");\n\n var version = versionNode.InnerText;\n var versions = version.Split('.');\n var versionMajor = versions[0];\n var versionMinor = versions[1];\n var dict = new Dictionary() {\n { MAJOR_VERSION_PLACEHOLDER, versionMajor },\n { MINOR_VERSION_PLACEHOLDER, versionMinor },\n { VERSION_PLACEHOLDER, version },\n };\n\n var identifier = ReplaceStringUsingKey(identifierNode.InnerText, dict);\n\n dict.Add(IDENTIFIER_PLACEHOLDER, identifier);\n\n _ = double.TryParse(fileSizeNode?.InnerText, out var parsedFileSize);\n\n var name = ReplaceStringUsingKey(nameNode.InnerText, dict);\n var installPrefix = ReplaceStringUsingKey(installPrefixNode?.InnerText, dict);\n if (installPrefix is null)\n {\n // newer simulators aren't installed anymore, provide a dummy value here\n var simRuntimeName = name.Replace(\" Simulator\", \".simruntime\");\n installPrefix = $\"/Library/Developer/CoreSimulator/Profiles/Runtimes/{simRuntimeName}\";\n }\n\n var platform = name.Split(' ').FirstOrDefault();\n if (platform is null)\n {\n Logger.LogWarning($\"Platform name could not be parsed from simulator name: '{nameNode.InnerText}' version: '{versionNode.InnerText}' identifier: '{identifierNode.InnerText}' skipping...\");\n continue;\n }\n\n var source = ReplaceStringUsingKey(sourceNode?.InnerText, dict);\n\n string? buildUpdate = buildUpdateNode?.InnerText;\n if (buildUpdate is null)\n {\n Logger.LogWarning($\"Simulator with name: '{nameNode.InnerText}' version: '{versionNode.InnerText}' identifier: '{identifierNode.InnerText}' has no buildUpdate, skipping...\");\n continue;\n }\n\n simulators.Add(new Simulator(\n name: name,\n platform: platform,\n identifier: ReplaceStringUsingKey(identifierNode.InnerText, dict),\n version: versionNode.InnerText,\n source: source,\n installPrefix: installPrefix,\n fileSize: (long)parsedFileSize,\n buildUpdate: buildUpdate\n ));\n }\n\n return simulators;\n }", + "start_line": 91, + "end_line": 170, + "start_byte": 3311, + "end_byte": 7381 + }, + { + "name": "ExecuteCommand", + "code": "protected async Task<(bool Succeeded, string Stdout)> ExecuteCommand(\n string filename,\n TimeSpan? timeout = null,\n params string[] arguments)\n {\n var stdoutLog = new MemoryLog() { Timestamp = false };\n var stderrLog = new MemoryLog() { Timestamp = false };\n\n var result = await _processManager.ExecuteCommandAsync(\n filename,\n arguments,\n new CallbackLog(m => Logger.LogDebug(m)),\n stdoutLog,\n stderrLog,\n timeout ?? TimeSpan.FromSeconds(30));\n\n var stderr = stderrLog.ToString();\n if (stderr.Length > 0)\n {\n Logger.LogDebug(\"Error output:\" + Environment.NewLine + stderr);\n }\n\n return (result.Succeeded, stdoutLog.ToString());\n }", + "start_line": 66, + "end_line": 89, + "start_byte": 2514, + "end_byte": 3305 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/Commands/Apple/Simulators/Simulator.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/AppleMlaunchCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n MlaunchPath,\n XcodeRoot,\n Timeout,\n EnvironmentalVariables,\n };", + "start_line": 17, + "end_line": 23, + "start_byte": 690, + "end_byte": 865 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/AppleResetSimulatorCommandArguments.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n base.Validate();\n\n if (Target.Value.Platform == TestTarget.MacCatalyst)\n {\n throw new ArgumentException(\"This command is not supported with the maccatalyst target\");\n }\n }", + "start_line": 30, + "end_line": 38, + "start_byte": 1049, + "end_byte": 1301 + }, + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n Target,\n DeviceName,\n Timeout,\n OutputDirectory,\n XcodeRoot,\n MlaunchPath,\n };", + "start_line": 20, + "end_line": 28, + "start_byte": 839, + "end_byte": 1043 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/AppleInstallCommandArguments.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n base.Validate();\n\n if (Target.Value.Platform == TestTarget.MacCatalyst)\n {\n throw new ArgumentException(\"This command is not supported with the maccatalyst target\");\n }\n }", + "start_line": 36, + "end_line": 44, + "start_byte": 1309, + "end_byte": 1561 + }, + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n AppBundlePath,\n Target,\n OutputDirectory,\n DeviceName,\n IncludeWireless,\n Timeout,\n XcodeRoot,\n MlaunchPath,\n ResetSimulator,\n };", + "start_line": 23, + "end_line": 34, + "start_byte": 1027, + "end_byte": 1303 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/AppleDeviceCommandsArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n DeviceName,\n IncludeWireless,\n XcodeRoot,\n MlaunchPath,\n };", + "start_line": 16, + "end_line": 22, + "start_byte": 639, + "end_byte": 810 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/AppleJustRunCommandArguments.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n base.Validate();\n\n if (Target.Value.Platform == TestTarget.MacCatalyst)\n {\n throw new ArgumentException(\"This command is not supported with the maccatalyst target\");\n }\n\n if (SignalAppEnd && NoWait)\n {\n throw new ArgumentException(\"--signal-app-end cannot be used in combination with --no-wait\");\n }\n }", + "start_line": 45, + "end_line": 58, + "start_byte": 1741, + "end_byte": 2156 + }, + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n BundleIdentifier,\n Target,\n OutputDirectory,\n DeviceName,\n IncludeWireless,\n Timeout,\n ExpectedExitCode,\n XcodeRoot,\n MlaunchPath,\n EnableLldb,\n SignalAppEnd,\n NoWait,\n EnvironmentalVariables,\n };", + "start_line": 28, + "end_line": 43, + "start_byte": 1364, + "end_byte": 1735 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/AppleTestCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n AppBundlePath,\n Target,\n OutputDirectory,\n Timeout,\n LaunchTimeout,\n XcodeRoot,\n MlaunchPath,\n DeviceName,\n IncludeWireless,\n CommunicationChannel,\n XmlResultJargon,\n SingleMethodFilters,\n ClassMethodFilters,\n EnableLldb,\n SignalAppEnd,\n EnvironmentalVariables,\n ResetSimulator,\n };", + "start_line": 30, + "end_line": 49, + "start_byte": 1572, + "end_byte": 2057 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/AppleUninstallCommandArguments.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n base.Validate();\n\n if (Target.Value.Platform == TestTarget.MacCatalyst)\n {\n throw new ArgumentException(\"This command is not supported with the maccatalyst target\");\n }\n }", + "start_line": 34, + "end_line": 42, + "start_byte": 1235, + "end_byte": 1487 + }, + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n BundleIdentifier,\n Target,\n OutputDirectory,\n Timeout,\n XcodeRoot,\n MlaunchPath,\n DeviceName,\n IncludeWireless,\n };", + "start_line": 22, + "end_line": 32, + "start_byte": 974, + "end_byte": 1229 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/IAppleArguments.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/AppleRunCommandArguments.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\r\n {\r\n base.Validate();\r\n\r\n if (SignalAppEnd && NoWait)\r\n {\r\n throw new ArgumentException(\"--signal-app-end cannot be used in combination with --no-wait\");\r\n }\r\n }", + "start_line": 48, + "end_line": 56, + "start_byte": 1927, + "end_byte": 2166 + }, + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\r\n {\r\n AppBundlePath,\r\n Target,\r\n OutputDirectory,\r\n DeviceName,\r\n IncludeWireless,\r\n Timeout,\r\n LaunchTimeout,\r\n ExpectedExitCode,\r\n XcodeRoot,\r\n MlaunchPath,\r\n EnableLldb,\r\n SignalAppEnd,\r\n NoWait,\r\n ResetSimulator,\r\n EnvironmentalVariables,\r\n };", + "start_line": 29, + "end_line": 46, + "start_byte": 1487, + "end_byte": 1919 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/AppleJustTestCommandArguments.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n base.Validate();\n\n if (Target.Value.Platform == TestTarget.MacCatalyst)\n {\n throw new ArgumentException(\"This command is not supported with the maccatalyst target\");\n }\n }", + "start_line": 50, + "end_line": 58, + "start_byte": 2035, + "end_byte": 2287 + }, + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n BundleIdentifier,\n Target,\n OutputDirectory,\n Timeout,\n LaunchTimeout,\n XcodeRoot,\n MlaunchPath,\n DeviceName,\n IncludeWireless,\n CommunicationChannel,\n XmlResultJargon,\n SingleMethodFilters,\n ClassMethodFilters,\n EnableLldb,\n SignalAppEnd,\n EnvironmentalVariables,\n };", + "start_line": 30, + "end_line": 48, + "start_byte": 1565, + "end_byte": 2029 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/IAppleAppRunArguments.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/AppleStateCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n XcodeRoot,\n MlaunchPath,\n ShowSimulatorsUUID,\n ShowDevicesUUID,\n IncludeWireless,\n UseJson,\n };", + "start_line": 18, + "end_line": 26, + "start_byte": 779, + "end_byte": 1024 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/WebServerCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n AppPackagePath,\n Timeout,\n WebServerMiddlewarePathsAndTypes,\n WebServerHttpEnvironmentVariables,\n WebServerHttpsEnvironmentVariables,\n WebServerUseHttps,\n WebServerUseCors,\n WebServerUseCrossOriginPolicy,\n WebServerUseDefaultFiles,\n };", + "start_line": 28, + "end_line": 39, + "start_byte": 1406, + "end_byte": 1788 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/WasmTestCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n Engine,\n EnginePath,\n EngineArgs,\n JSFile,\n ErrorPatternsFile,\n OutputDirectory,\n Timeout,\n ExpectedExitCode,\n Locale,\n PageLoadStrategy,\n SymbolMapFileArgument,\n SymbolicatePatternsFileArgument,\n SymbolicatorArgument,\n WebServerMiddlewarePathsAndTypes,\n WebServerHttpEnvironmentVariables,\n WebServerHttpsEnvironmentVariables,\n WebServerUseHttps,\n WebServerUseCors,\n WebServerUseCrossOriginPolicy,\n WebServerUseDefaultFiles,\n };", + "start_line": 36, + "end_line": 58, + "start_byte": 2195, + "end_byte": 2927 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/WasmTestBrowserCommandArguments.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n base.Validate();\n\n if (!string.IsNullOrEmpty(BrowserLocation))\n {\n if (Browser == Wasm.Browser.Safari)\n {\n throw new ArgumentException(\"Safari driver doesn't support custom browser path\");\n }\n\n if (!File.Exists(BrowserLocation))\n {\n throw new ArgumentException($\"Could not find browser at {BrowserLocation}\");\n }\n }\n\n if (DebuggerPort.Value != null || NoQuit)\n {\n NoHeadless.Set(true);\n }\n }", + "start_line": 74, + "end_line": 95, + "start_byte": 3510, + "end_byte": 4099 + }, + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n AppPackagePath,\n Browser,\n BrowserLocation,\n BrowserArgs,\n HTMLFile,\n ErrorPatternsFile,\n ExpectedExitCode,\n OutputDirectory,\n Timeout,\n DebuggerPort,\n NoIncognito,\n NoHeadless,\n NoQuit,\n BackgroundThrottling,\n Locale,\n PageLoadStrategy,\n SymbolMapFileArgument,\n SymbolicatePatternsFileArgument,\n SymbolicatorArgument,\n WebServerMiddlewarePathsAndTypes,\n WebServerHttpEnvironmentVariables,\n WebServerHttpsEnvironmentVariables,\n WebServerUseHttps,\n WebServerUseCors,\n WebServerUseCrossOriginPolicy,\n WebServerUseDefaultFiles,\n };", + "start_line": 44, + "end_line": 72, + "start_byte": 2606, + "end_byte": 3504 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/IWebServerArguments.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/AndroidTestCommandArguments.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n base.Validate();\n\n if (!File.Exists(AppPackagePath))\n {\n throw new ArgumentException($\"Couldn't find {AppPackagePath}!\");\n }\n }", + "start_line": 44, + "end_line": 52, + "start_byte": 1766, + "end_byte": 1974 + }, + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n AppPackagePath,\n PackageName,\n OutputDirectory,\n Timeout,\n LaunchTimeout,\n DeviceArchitecture,\n DeviceId,\n ApiVersion,\n InstrumentationName,\n InstrumentationArguments,\n ExpectedExitCode,\n DeviceOutputFolder,\n Wifi,\n };", + "start_line": 27, + "end_line": 42, + "start_byte": 1367, + "end_byte": 1760 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/IAndroidAppRunArguments.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/AndroidInstallCommandArguments.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n base.Validate();\n\n if (!File.Exists(AppPackagePath))\n {\n throw new ArgumentException($\"Couldn't find {AppPackagePath}!\");\n }\n }", + "start_line": 34, + "end_line": 42, + "start_byte": 1257, + "end_byte": 1465 + }, + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n AppPackagePath,\n PackageName,\n OutputDirectory,\n Timeout,\n DeviceId,\n LaunchTimeout,\n DeviceArchitecture,\n ApiVersion,\n };", + "start_line": 22, + "end_line": 32, + "start_byte": 989, + "end_byte": 1251 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/AndroidUninstallCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n PackageName,\n DeviceId,\n };", + "start_line": 14, + "end_line": 18, + "start_byte": 507, + "end_byte": 640 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/AndroidStateCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n UseJson,\n };", + "start_line": 13, + "end_line": 16, + "start_byte": 442, + "end_byte": 545 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/AndroidRunCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n PackageName,\n OutputDirectory,\n Timeout,\n LaunchTimeout,\n DeviceId,\n ApiVersion,\n InstrumentationName,\n InstrumentationArguments,\n ExpectedExitCode,\n DeviceOutputFolder,\n Wifi,\n };", + "start_line": 24, + "end_line": 37, + "start_byte": 1214, + "end_byte": 1555 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/AndroidArchitecture.cs": [ + { + "name": "AsString", + "code": "public static string AsString(this AndroidArchitecture arch) => arch switch\n {\n AndroidArchitecture.X86 => \"x86\",\n AndroidArchitecture.X86_64 => \"x86_64\",\n AndroidArchitecture.Arm64_v8a => \"arm64-v8a\",\n AndroidArchitecture.Armeabi_v7a => \"armeabi-v7a\",\n _ => throw new ArgumentOutOfRangeException(nameof(arch))\n };", + "start_line": 24, + "end_line": 31, + "start_byte": 615, + "end_byte": 970 + }, + { + "name": "ParseAsAndroidArchitecture", + "code": "public static AndroidArchitecture ParseAsAndroidArchitecture(this string target) => target switch\n {\n \"x86\" => AndroidArchitecture.X86,\n \"x86_64\" => AndroidArchitecture.X86_64,\n \"arm64-v8a\" => AndroidArchitecture.Arm64_v8a,\n \"armeabi-v7a\" => AndroidArchitecture.Armeabi_v7a,\n _ => throw new ArgumentOutOfRangeException(nameof(target))\n };", + "start_line": 15, + "end_line": 22, + "start_byte": 230, + "end_byte": 609 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/AndroidAdbCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new[]\n {\n Timeout,\n };", + "start_line": 14, + "end_line": 17, + "start_byte": 480, + "end_byte": 574 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/AndroidDeviceCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n AppPackagePath,\n DeviceArchitecture,\n ApiVersion,\n };", + "start_line": 15, + "end_line": 20, + "start_byte": 590, + "end_byte": 748 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/AndroidHeadless/AndroidHeadlessUninstallCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n TestPath,\n RuntimePath,\n DeviceId,\n };", + "start_line": 16, + "end_line": 21, + "start_byte": 640, + "end_byte": 795 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/AndroidHeadless/IAndroidHeadlessAppRunArguments.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/AndroidHeadless/AndroidHeadlessRunCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n TestPath,\n RuntimePath,\n TestAssembly,\n TestScript,\n OutputDirectory,\n Timeout,\n LaunchTimeout,\n DeviceId,\n ApiVersion,\n ExpectedExitCode,\n DeviceOutputFolder,\n Wifi,\n };", + "start_line": 26, + "end_line": 40, + "start_byte": 1321, + "end_byte": 1659 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/AndroidHeadless/AndroidHeadlessInstallCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n TestPath,\n RuntimePath,\n TestAssembly,\n TestScript,\n OutputDirectory,\n Timeout,\n DeviceId,\n LaunchTimeout,\n DeviceArchitecture,\n ApiVersion,\n };", + "start_line": 24, + "end_line": 36, + "start_byte": 1175, + "end_byte": 1473 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/AndroidHeadless/AndroidHeadlessTestCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n TestPath,\n RuntimePath,\n TestAssembly,\n TestScript,\n OutputDirectory,\n Timeout,\n LaunchTimeout,\n DeviceArchitecture,\n DeviceId,\n ApiVersion,\n ExpectedExitCode,\n Wifi,\n };", + "start_line": 26, + "end_line": 40, + "start_byte": 1322, + "end_byte": 1660 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASI/WasiTestCommandArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\n {\n Engine,\n EnginePath,\n EngineArgs,\n OutputDirectory,\n Timeout,\n ExpectedExitCode,\n\n WebServerMiddlewarePathsAndTypes,\n WebServerHttpEnvironmentVariables,\n WebServerHttpsEnvironmentVariables,\n WebServerUseHttps,\n WebServerUseCors,\n WebServerUseCrossOriginPolicy,\n WebServerUseDefaultFiles,\n };", + "start_line": 30, + "end_line": 46, + "start_byte": 1684, + "end_byte": 2202 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/WebServerUseCorsArguments.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/SingleMethodFilters.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/WebServerHttpsEnvironmentVariables.cs": [ + { + "name": "Action", + "code": "public override void Action(string argumentValue) => Value = argumentValue.Split(',');", + "start_line": 20, + "end_line": 20, + "start_byte": 730, + "end_byte": 816 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/TypeFromAssemblyArgument.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n base.Validate();\n\n if (!_repeatable && Value.Count > 1)\n throw new ArgumentException($\"{Prototype} can only be passed once\");\n\n foreach (var (path, type) in Value)\n {\n if (string.IsNullOrWhiteSpace(path))\n {\n throw new ArgumentException($\"Empty path to assembly\");\n }\n\n if (!File.Exists(path))\n {\n throw new ArgumentException($\"Failed to find the assembly at {path}\");\n }\n\n if (string.IsNullOrEmpty(type))\n {\n throw new ArgumentException($\"No type name given with assembly {path}\");\n }\n }\n }", + "start_line": 46, + "end_line": 70, + "start_byte": 1556, + "end_byte": 2279 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n var split = argumentValue.Split(',', 2);\n var file = split[0];\n string? type = split.Length > 1 ? split[1] : null;\n\n Value.Add((file, type));\n }", + "start_line": 37, + "end_line": 44, + "start_byte": 1318, + "end_byte": 1550 + }, + { + "name": "GetLoadedTypes", + "code": "public IEnumerable GetLoadedTypes()\n {\n foreach ((string assemblyPath, string? typeName) in Value)\n {\n var extensionAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.GetFullPath(assemblyPath));\n var loadedType = extensionAssembly?.GetTypes().Where(type => type.FullName == typeName).FirstOrDefault();\n if (loadedType is null)\n throw new Exception($\"Can't find type named {typeName} in {assemblyPath}\");\n\n yield return loadedType;\n }\n }", + "start_line": 24, + "end_line": 35, + "start_byte": 770, + "end_byte": 1312 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/WebServerUploadResults.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/TimeoutArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/WebServerMiddlewareArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/WebServerUseHttpsArguments.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/AppPathArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/WebServerUseDefaultFiles.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/WebServerUseCrossOriginPolicyArguments.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/ExpectedExitCodeArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/WebServerHttpEnvironmentVariables.cs": [ + { + "name": "Action", + "code": "public override void Action(string argumentValue) => Value = argumentValue.Split(',');", + "start_line": 20, + "end_line": 20, + "start_byte": 726, + "end_byte": 812 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/OutputDirectoryArgument.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n if (!Directory.Exists(Value ?? throw new ArgumentNullException(\"You must provide an output directory where results will be stored\")))\n {\n Directory.CreateDirectory(Value);\n }\n }", + "start_line": 19, + "end_line": 25, + "start_byte": 581, + "end_byte": 832 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Arguments/ClassMethodFilters.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASI/Arguments/WasmEngineArgument.cs": [ + { + "name": "Validate", + "code": "public override void Validate() => Value ??= WasmEngine.WasmTime;", + "start_line": 20, + "end_line": 20, + "start_byte": 631, + "end_byte": 696 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue) =>\n Value = ParseArgument(\"engine\", argumentValue);", + "start_line": 16, + "end_line": 17, + "start_byte": 467, + "end_byte": 587 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASI/Arguments/WasmEngineLocationArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASI/Arguments/WasmEngineArguments.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/AndroidHeadless/Arguments/TestScriptArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/AndroidHeadless/Arguments/TestPathArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/AndroidHeadless/Arguments/RuntimePathArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/AndroidHeadless/Arguments/TestAssemblyArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/Arguments/InstrumentationArguments.cs": [ + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n var argPair = argumentValue.Split('=', 2);\n\n if (argPair.Length != 2)\n {\n throw new ArgumentException($\"The --arg argument expects 'key=value' format. Invalid format found in '{argumentValue}'\");\n }\n\n if (Value.ContainsKey(argPair[0]))\n {\n throw new ArgumentException($\"Duplicate arg name '{argPair[0]}' found\");\n }\n\n Value.Add(argPair[0].Trim(), argPair[1].Trim());\n }", + "start_line": 20, + "end_line": 35, + "start_byte": 671, + "end_byte": 1178 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/Arguments/PackageNameArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/Arguments/ApiVersionArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/Arguments/ShowAdbPathArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/Arguments/InstrumentationNameArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/Arguments/WifiArgument.cs": [ + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n Value = string.IsNullOrEmpty(argumentValue)\n ? WifiStatus.Enable\n : ParseArgument(\"wifi\", argumentValue, invalidValues: WifiStatus.Unknown);\n }", + "start_line": 17, + "end_line": 22, + "start_byte": 584, + "end_byte": 816 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/Arguments/DeviceArchitectureArgument.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n foreach (var archName in Value)\n {\n try\n {\n AndroidArchitectureHelper.ParseAsAndroidArchitecture(archName);\n }\n catch (ArgumentOutOfRangeException e)\n {\n throw new ArgumentException(\n $\"Failed to parse architecture '{archName}'. Available architectures are:\" +\n GetAllowedValues(t => t.AsString()), e);\n }\n }\n }", + "start_line": 17, + "end_line": 32, + "start_byte": 649, + "end_byte": 1178 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/Arguments/DeviceIdArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/Arguments/LaunchTimeoutArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/Arguments/DeviceOutputFolderArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/BrowserLocationArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/NoHeadlessArgument.cs": [ + { + "name": "Set", + "code": "public void Set(bool value) => Value = value;", + "start_line": 14, + "end_line": 14, + "start_byte": 440, + "end_byte": 485 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/HTMLFileArgument.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n base.Validate();\n\n if (Path.IsPathRooted(Value))\n {\n throw new ArgumentException(\"--html-file argument must be a relative path\");\n }\n }", + "start_line": 17, + "end_line": 25, + "start_byte": 548, + "end_byte": 764 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/SymbolicatePatternsFileArgument.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n base.Validate();\n\n if (Value != null && !File.Exists(Value))\n {\n throw new ArgumentException($\"Cannot find error patterns file {Value}\");\n }\n }", + "start_line": 21, + "end_line": 29, + "start_byte": 909, + "end_byte": 1133 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/ErrorPatternsFileArgument.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n base.Validate();\n\n if (Value != null && !File.Exists(Value))\n {\n throw new ArgumentException($\"Cannot find error patterns file {Value}\");\n }\n }", + "start_line": 17, + "end_line": 25, + "start_byte": 578, + "end_byte": 802 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/BrowserArgument.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n base.Validate();\n\n if (Value == Browser.Safari && !RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\n {\n throw new ArgumentException(\"Safari is only supported on OSX\");\n }\n }", + "start_line": 20, + "end_line": 28, + "start_byte": 648, + "end_byte": 902 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue) =>\n Value = ParseArgument(\"browser\", argumentValue);", + "start_line": 17, + "end_line": 18, + "start_byte": 524, + "end_byte": 642 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/BrowserArguments.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/SymbolicatorArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/JavaScriptFileArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/JavaScriptEngineArgument.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n if (Value == null)\n {\n throw new ArgumentException(\"Engine not specified\");\n }\n }", + "start_line": 19, + "end_line": 25, + "start_byte": 626, + "end_byte": 781 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue) =>\n Value = ParseArgument(\"engine\", argumentValue);", + "start_line": 16, + "end_line": 17, + "start_byte": 494, + "end_byte": 620 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/JavaScriptEngineLocationArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/PageLoadStrategyArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/NoQuitArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/NoIncognitoArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/LocaleArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/SymbolMapFileArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/JavaScriptEngineArguments.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/BackgroundThrottlingArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/DebuggerPortArgument.cs": [ + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n if (int.TryParse(argumentValue, out var number))\n {\n Value = number;\n return;\n }\n\n throw new ArgumentException($\"{Prototype} must be an integer\");\n }", + "start_line": 15, + "end_line": 24, + "start_byte": 512, + "end_byte": 771 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Simulators/InstallCommandArguments.cs": [ + { + "name": "GetAdditionalArguments", + "code": "protected override IEnumerable GetAdditionalArguments() => new Argument[]\n {\n Force,\n HideProgress,\n };", + "start_line": 15, + "end_line": 19, + "start_byte": 518, + "end_byte": 659 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Simulators/SimulatorsCommandArguments.cs": [ + { + "name": "GetAdditionalArguments", + "code": "protected abstract IEnumerable GetAdditionalArguments();", + "start_line": 20, + "end_line": 20, + "start_byte": 649, + "end_byte": 715 + }, + { + "name": "GetArguments", + "code": "protected sealed override IEnumerable GetArguments() =>\n GetAdditionalArguments().Concat(new Argument[]\n {\n XcodeRoot\n });", + "start_line": 14, + "end_line": 18, + "start_byte": 475, + "end_byte": 643 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Simulators/ListCommandArguments.cs": [ + { + "name": "GetAdditionalArguments", + "code": "protected override IEnumerable GetAdditionalArguments() => new Argument[]\n {\n ListInstalledOnly,\n };", + "start_line": 13, + "end_line": 16, + "start_byte": 459, + "end_byte": 586 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Simulators/FindCommandArguments.cs": [ + { + "name": "GetAdditionalArguments", + "code": "protected override IEnumerable GetAdditionalArguments() => Enumerable.Empty();", + "start_line": 12, + "end_line": 12, + "start_byte": 408, + "end_byte": 506 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/EnableLldbArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/HideProgressArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/ForceInstallationArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/IncludeWirelessArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/MlaunchArgument.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n if (!File.Exists(Value))\n {\n throw new ArgumentException(\n $\"Failed to find mlaunch at {Value}. \" +\n $\"Make sure you specify --mlaunch or set the {EnvironmentVariables.Names.MLAUNCH_PATH} env var. \" +\n $\"See README.md for more information\");\n }\n }", + "start_line": 24, + "end_line": 33, + "start_byte": 825, + "end_byte": 1191 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue) => Value = RootPath(argumentValue);", + "start_line": 22, + "end_line": 22, + "start_byte": 734, + "end_byte": 819 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/TargetArgument.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n if (Value == TestTargetOs.None)\n {\n throw new ArgumentException(\"No test target specified\");\n }\n }", + "start_line": 36, + "end_line": 42, + "start_byte": 1254, + "end_byte": 1426 + }, + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n try\n {\n Value = argumentValue.ParseAsAppRunnerTargetOs();\n }\n catch (ArgumentOutOfRangeException e)\n {\n throw new ArgumentException(\n $\"Failed to parse test target '{argumentValue}'. Available targets are:\" +\n GetAllowedValues(t => t.AsString(), invalidValues: TestTarget.None) +\n Environment.NewLine + Environment.NewLine +\n \"You can also specify desired OS version, e.g. ios-simulator-64_13.4\", e);\n }\n }", + "start_line": 20, + "end_line": 34, + "start_byte": 658, + "end_byte": 1248 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/DeviceNameArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/ListInstalledArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/ShowSimulatorsUUIDArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/ShowDevicesUUIDArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/XmlResultJargonArgument.cs": [ + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n Value = ParseArgument(\"xml-jargon\", argumentValue, invalidValues: XmlResultJargon.Missing);\n }", + "start_line": 19, + "end_line": 22, + "start_byte": 781, + "end_byte": 942 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/LaunchTimeoutArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/SignalAppEndArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/EnvironmentalVariablesArgument.cs": [ + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n var position = argumentValue.IndexOf('=');\n if (position == -1)\n {\n throw new ArgumentException($\"The set-env argument {argumentValue} must be in the key=value format\");\n }\n\n var key = argumentValue.Substring(0, position);\n var value = argumentValue.Substring(position + 1);\n _environmentalVariables.Add((key, value));\n }", + "start_line": 22, + "end_line": 33, + "start_byte": 815, + "end_byte": 1256 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/XcodeArgument.cs": [ + { + "name": "Validate", + "code": "public override void Validate()\n {\n if (Value != null && !Directory.Exists(Value))\n {\n throw new ArgumentException($\"Failed to find Xcode root at {Value}\");\n }\n }", + "start_line": 19, + "end_line": 25, + "start_byte": 563, + "end_byte": 763 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/CommunicationChannelArgument.cs": [ + { + "name": "Action", + "code": "public override void Action(string argumentValue)\n {\n Value = ParseArgument(\"communication-channel\", argumentValue);\n }", + "start_line": 19, + "end_line": 22, + "start_byte": 703, + "end_byte": 857 + } + ], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/NoWaitArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/BundleIdentifierArgument.cs": [], + "src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Apple/Arguments/ResetSimulatorArgument.cs": [], + "src/Microsoft.DotNet.XHarness.iOS.Shared/XmlResults/TouchUnitResultParser.cs": [ + { + "name": "ParseXml", + "code": "public (string resultLine, bool failed) ParseXml(TextReader stream, TextWriter? humanReadableOutput)\n {\n long total, errors, failed, notRun, inconclusive, ignored, skipped, invalid;\n total = errors = failed = notRun = inconclusive = ignored = skipped = invalid = 0L;\n\n using (var reader = XmlReader.Create(stream))\n {\n while (reader.Read())\n {\n if (reader.NodeType == XmlNodeType.Element && reader.Name == \"test-results\")\n {\n long.TryParse(reader[\"total\"], out total);\n long.TryParse(reader[\"errors\"], out errors);\n long.TryParse(reader[\"failures\"], out failed);\n long.TryParse(reader[\"not-run\"], out notRun);\n long.TryParse(reader[\"inconclusive\"], out inconclusive);\n long.TryParse(reader[\"ignored\"], out ignored);\n long.TryParse(reader[\"skipped\"], out skipped);\n long.TryParse(reader[\"invalid\"], out invalid);\n }\n if (humanReadableOutput != null && reader.NodeType == XmlNodeType.Element && reader.Name == \"TouchUnitExtraData\")\n {\n // move fwd to get to the CData\n if (reader.Read())\n {\n humanReadableOutput.Write(reader.Value);\n }\n }\n }\n }\n var passed = total - errors - failed - notRun - inconclusive - ignored - skipped - invalid;\n var resultLine = $\"Tests run: {total} Passed: {passed} Inconclusive: {inconclusive} Failed: {failed + errors} Ignored: {ignored + skipped + invalid}\";\n humanReadableOutput?.WriteLine(resultLine);\n return (resultLine, errors != 0 || failed != 0);\n }", + "start_line": 13, + "end_line": 47, + "start_byte": 380, + "end_byte": 2208 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/XmlResults/XUnitTestReportGenerator.cs": [ + { + "name": "GenerateTestReport", + "code": "public override void GenerateTestReport(TextWriter writer, XmlReader reader)\n {\n var failedTests = new List<(string name, string message)>();\n // xUnit is not as nice and does not provide the final result in a top node,\n // we need to look in all the collections and find all the failed tests, this is really bad :/\n while (reader.Read())\n {\n if (reader.NodeType != XmlNodeType.Element || reader.Name != \"collection\")\n {\n continue;\n }\n\n reader.ReadToDescendant(\"test\");\n do\n {\n if (reader.Name != \"test\")\n {\n break;\n }\n // read the test cases in the current node\n var status = reader[\"result\"];\n switch (status)\n {\n case \"Fail\":\n string name = reader[\"name\"] ?? throw new InvalidOperationException();\n reader.ReadToDescendant(\"message\");\n string message = reader.ReadElementContentAsString();\n failedTests.Add((name, message));\n break;\n }\n } while (reader.ReadToNextSibling(\"test\"));\n }\n\n if (failedTests.Count > 0)\n {\n writer.WriteLine(\"
\");\n writer.WriteLine(\"
    \");\n foreach (var (name, message) in failedTests)\n {\n writer.WriteLine(\"
  • \");\n writer.Write(name.AsHtml());\n if (!string.IsNullOrEmpty(message))\n {\n writer.Write(\": \");\n writer.Write(message.AsHtml());\n }\n writer.WriteLine(\"
    \");\n writer.WriteLine(\"
  • \");\n }\n writer.WriteLine(\"
\");\n writer.WriteLine(\"
\");\n }\n }", + "start_line": 53, + "end_line": 105, + "start_byte": 1866, + "end_byte": 3847 + }, + { + "name": "GenerateFailure", + "code": "public override void GenerateFailure(XmlWriter writer, string title, string message, TextReader stderr)\n {\n writer.WriteStartElement(\"assemblies\");\n writer.WriteStartElement(\"assembly\");\n WriteAttributes(writer,\n (\"name\", title),\n (\"environment\", \"64-bit .NET Standard [collection-per-class, non-parallel]\"),\n (\"test-framework\", \"xUnit.net 2.4.1.0\"),\n (\"run-date\", XmlConvert.ToString(DateTime.Now, \"yyyy-MM-dd\")),\n (\"total\", \"1\"),\n (\"passed\", \"0\"),\n (\"failed\", \"1\"),\n (\"skipped\", \"0\"),\n (\"time\", \"0\"),\n (\"errors\", \"0\"));\n writer.WriteStartElement(\"collection\");\n WriteAttributes(writer,\n (\"total\", \"1\"),\n (\"passed\", \"0\"),\n (\"failed\", \"1\"),\n (\"skipped\", \"0\"),\n (\"name\", title),\n (\"time\", \"0\"));\n writer.WriteStartElement(\"test\");\n WriteAttributes(writer,\n (\"name\", title),\n (\"type\", \"TestApp\"),\n (\"method\", \"Run\"),\n (\"time\", \"0\"),\n (\"result\", \"Fail\"));\n WriteFailure(writer, message, stderr);\n writer.WriteEndElement(); // test\n writer.WriteEndElement(); // collection\n writer.WriteEndElement(); // assembly\n writer.WriteEndElement(); // assemblies\n }", + "start_line": 16, + "end_line": 51, + "start_byte": 488, + "end_byte": 1860 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/XmlResults/NUnitV2ResultParser.cs": [ + { + "name": "ParseXml", + "code": "public (string resultLine, bool failed) ParseXml(TextReader stream, TextWriter? humanReadableOutput)\n {\n long total, errors, failed, notRun, inconclusive, ignored, skipped, invalid;\n total = errors = failed = notRun = inconclusive = ignored = skipped = invalid = 0L;\n\n var settings = new XmlReaderSettings\n {\n ValidationType = ValidationType.None\n };\n\n using (var reader = XmlReader.Create(stream, settings))\n {\n while (reader.Read())\n {\n if (reader.NodeType == XmlNodeType.Element && reader.Name == \"test-results\")\n {\n long.TryParse(reader[\"total\"], out total);\n long.TryParse(reader[\"errors\"], out errors);\n long.TryParse(reader[\"failures\"], out failed);\n long.TryParse(reader[\"not-run\"], out notRun);\n long.TryParse(reader[\"inconclusive\"], out inconclusive);\n long.TryParse(reader[\"ignored\"], out ignored);\n long.TryParse(reader[\"skipped\"], out skipped);\n long.TryParse(reader[\"invalid\"], out invalid);\n }\n\n if (humanReadableOutput != null && reader.NodeType == XmlNodeType.Element && reader.Name == \"test-suite\" && (reader[\"type\"] == \"TestFixture\" || reader[\"type\"] == \"TestCollection\"))\n {\n var testCaseName = reader[\"name\"];\n humanReadableOutput.WriteLine(testCaseName);\n var time = reader.GetAttribute(\"time\") ?? \"0\"; // some nodes might not have the time :/\n // get the first node and then move in the siblings of the same type\n reader.ReadToDescendant(\"test-case\");\n do\n {\n if (reader.Name != \"test-case\")\n {\n break;\n }\n\n // read the test cases in the current node\n var status = reader[\"result\"];\n switch (status)\n {\n case \"Success\":\n humanReadableOutput.Write(\"\\t[PASS] \");\n break;\n case \"Ignored\":\n humanReadableOutput.Write(\"\\t[IGNORED] \");\n break;\n case \"Error\":\n case \"Failure\":\n humanReadableOutput.Write(\"\\t[FAIL] \");\n break;\n case \"Inconclusive\":\n humanReadableOutput.Write(\"\\t[INCONCLUSIVE] \");\n break;\n default:\n humanReadableOutput.Write(\"\\t[INFO] \");\n break;\n }\n\n humanReadableOutput.Write(reader[\"name\"]);\n\n if (status == \"Failure\" || status == \"Error\")\n { // we need to print the message\n reader.ReadToDescendant(\"message\");\n humanReadableOutput.Write($\" : {reader.ReadElementContentAsString()}\");\n reader.ReadToNextSibling(\"stack-trace\");\n humanReadableOutput.Write($\" : {reader.ReadElementContentAsString()}\");\n }\n\n // add a new line\n humanReadableOutput.WriteLine();\n } while (reader.ReadToNextSibling(\"test-case\"));\n\n humanReadableOutput.WriteLine($\"{testCaseName} {time} ms\");\n }\n }\n }\n\n var passed = total - errors - failed - notRun - inconclusive - ignored - skipped - invalid;\n var resultLine = $\"Tests run: {total} Passed: {passed} Inconclusive: {inconclusive} Failed: {failed + errors} Ignored: {ignored + skipped + invalid}\";\n humanReadableOutput?.WriteLine(resultLine);\n\n return (resultLine, errors != 0 || failed != 0);\n }", + "start_line": 13, + "end_line": 99, + "start_byte": 378, + "end_byte": 4660 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/XmlResults/NUnitV3ResultParser.cs": [ + { + "name": "ParseNUnitV3XmlTestSuite", + "code": "private static void ParseNUnitV3XmlTestSuite(XmlReader reader, TextWriter humanReadableOutput, bool nested)\n {\n if (reader.NodeType != XmlNodeType.Element)\n {\n throw new InvalidOperationException();\n }\n\n if (reader.Name != \"test-suite\")\n {\n throw new InvalidOperationException();\n }\n\n var type = reader[\"type\"];\n var isFixture = type == \"TestFixture\" || type == \"ParameterizedFixture\";\n var testCaseName = reader[\"fullname\"];\n var time = reader.GetAttribute(\"time\") ?? \"0\"; // some nodes might not have the time :/\n\n if (isFixture)\n {\n humanReadableOutput.WriteLine(testCaseName);\n }\n\n if (reader.IsEmptyElement)\n {\n if (isFixture)\n {\n humanReadableOutput.WriteLine($\"{testCaseName} {time} ms\");\n }\n\n return;\n }\n\n while (reader.Read())\n {\n switch (reader.NodeType)\n {\n case XmlNodeType.Element:\n if (reader.Name == \"test-case\")\n {\n ParseNUnitV3XmlTestCase(reader, humanReadableOutput);\n }\n else if (reader.Name == \"test-suite\")\n {\n ParseNUnitV3XmlTestSuite(reader, humanReadableOutput, nested || isFixture);\n }\n break;\n case XmlNodeType.EndElement:\n if (reader.Name == \"test-suite\")\n {\n if (isFixture)\n {\n humanReadableOutput.WriteLine($\"{testCaseName} {time} ms\");\n }\n\n return;\n }\n break;\n }\n }\n\n throw new InvalidOperationException(\"Invalid XML: no test-suite end element\");\n }", + "start_line": 110, + "end_line": 171, + "start_byte": 3993, + "end_byte": 5947 + }, + { + "name": "ParseNUnitV3XmlTestCase", + "code": "private static void ParseNUnitV3XmlTestCase(XmlReader reader, TextWriter humanReadableOutput)\n {\n if (reader.NodeType != XmlNodeType.Element)\n {\n throw new InvalidOperationException();\n }\n\n if (reader.Name != \"test-case\")\n {\n throw new InvalidOperationException();\n }\n\n // read the test cases in the current node\n var status = reader[\"result\"];\n switch (status)\n {\n case \"Passed\":\n humanReadableOutput.Write(\"\\t[PASS] \");\n break;\n case \"Skipped\":\n humanReadableOutput.Write(\"\\t[IGNORED] \");\n break;\n case \"Error\":\n case \"Failed\":\n humanReadableOutput.Write(\"\\t[FAIL] \");\n break;\n case \"Inconclusive\":\n humanReadableOutput.Write(\"\\t[INCONCLUSIVE] \");\n break;\n default:\n humanReadableOutput.Write(\"\\t[INFO] \");\n break;\n }\n var name = reader[\"name\"];\n humanReadableOutput.Write(name);\n if (status == \"Failed\")\n { // we need to print the message\n reader.ReadToDescendant(\"failure\");\n reader.ReadToDescendant(\"message\");\n humanReadableOutput.Write($\" : {reader.ReadElementContentAsString()}\");\n if (reader.Name != \"stack-trace\")\n {\n reader.ReadToNextSibling(\"stack-trace\");\n }\n\n humanReadableOutput.Write($\" : {reader.ReadElementContentAsString()}\");\n }\n if (status == \"Skipped\")\n { // nice to have the skip reason\n reader.ReadToDescendant(\"reason\");\n reader.ReadToDescendant(\"message\");\n humanReadableOutput.Write($\" : {reader.ReadElementContentAsString()}\");\n }\n // add a new line\n humanReadableOutput.WriteLine();\n }", + "start_line": 53, + "end_line": 108, + "start_byte": 2056, + "end_byte": 3987 + }, + { + "name": "ParseXml", + "code": "public (string resultLine, bool failed) ParseXml(TextReader source, TextWriter? humanReadableOutput)\n {\n long testcasecount, passed, failed, inconclusive, skipped;\n var failedTestRun = false; // result = \"Failed\"\n testcasecount = passed = failed = inconclusive = skipped = 0L;\n\n var settings = new XmlReaderSettings\n {\n IgnoreWhitespace = true,\n IgnoreComments = true,\n IgnoreProcessingInstructions = true\n };\n\n using (var reader = XmlReader.Create(source, settings))\n {\n while (reader.Read())\n {\n if (reader.NodeType == XmlNodeType.Element && reader.Name == \"test-run\")\n {\n long.TryParse(reader[\"testcasecount\"], out testcasecount);\n long.TryParse(reader[\"passed\"], out passed);\n long.TryParse(reader[\"failed\"], out failed);\n long.TryParse(reader[\"inconclusive\"], out inconclusive);\n long.TryParse(reader[\"skipped\"], out skipped);\n failedTestRun = failed != 0;\n }\n\n if (humanReadableOutput != null && reader.NodeType == XmlNodeType.Element && reader.Name == \"test-suite\")\n {\n ParseNUnitV3XmlTestSuite(reader, humanReadableOutput, false);\n }\n }\n }\n\n var resultLine = $\"Tests run: {testcasecount} Passed: {passed} Inconclusive: {inconclusive} Failed: {failed} Ignored: {skipped + inconclusive}\";\n humanReadableOutput?.WriteLine(resultLine);\n return (resultLine, failedTestRun);\n }", + "start_line": 14, + "end_line": 51, + "start_byte": 392, + "end_byte": 2050 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/XmlResults/IXmlResultParser.cs": [ + { + "name": "ParseXml", + "code": "(string resultLine, bool failed) ParseXml(TextReader stream, TextWriter? humanReadableOutput);", + "start_line": 12, + "end_line": 12, + "start_byte": 342, + "end_byte": 436 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/XmlResults/NUnitV2TestReportGenerator.cs": [ + { + "name": "WriteNUnitV2TestCase", + "code": "private static void WriteNUnitV2TestCase(XmlWriter writer, string title, string message, TextReader stderr)\n {\n writer.WriteStartElement(\"test-case\");\n WriteAttributes(writer,\n (\"name\", title),\n (\"executed\", \"True\"),\n (\"result\", \"Failure\"),\n (\"success\", \"False\"),\n (\"time\", \"0\"),\n (\"asserts\", \"1\")\n );\n writer.WriteStartElement(\"failure\");\n writer.WriteStartElement(\"message\");\n writer.WriteCDataSafe(message);\n writer.WriteEndElement(); // message\n writer.WriteStartElement(\"stack-trace\");\n writer.WriteCDataSafe(stderr.ReadToEnd());\n writer.WriteEndElement(); // stack-trace\n writer.WriteEndElement(); // failure\n writer.WriteEndElement(); // test-case\n }", + "start_line": 149, + "end_line": 169, + "start_byte": 4687, + "end_byte": 5500 + }, + { + "name": "WriteNUnitV2TestSuiteAttributes", + "code": "private static void WriteNUnitV2TestSuiteAttributes(XmlWriter writer, string title) => WriteAttributes(writer,\n (\"name\", title),\n (\"executed\", \"True\"),\n (\"result\", \"Failure\"),\n (\"success\", \"False\"),\n (\"time\", \"0\"),\n (\"asserts\", \"1\"));", + "start_line": 141, + "end_line": 147, + "start_byte": 4405, + "end_byte": 4681 + }, + { + "name": "GenerateFailure", + "code": "public override void GenerateFailure(XmlWriter writer, string title, string message, TextReader stderr)\n {\n writer.WriteStartElement(\"test-results\");\n WriteAttributes(writer,\n (\"name\", title),\n (\"total\", \"1\"),\n (\"errors\", \"0\"),\n (\"failures\", \"1\"),\n (\"not-run\", \"0\"),\n (\"inconclusive\", \"0\"),\n (\"ignored\", \"0\"),\n (\"skipped\", \"0\"),\n (\"invalid\", \"0\"),\n (\"date\", XmlConvert.ToString(DateTime.Now, \"yyyy-MM-dd\")));\n\n // we are not writting the env and the cunture info since the VSTS uploader does not care\n writer.WriteStartElement(\"test-suite\");\n writer.WriteAttributeString(\"type\", \"Assembly\");\n WriteNUnitV2TestSuiteAttributes(writer, title);\n writer.WriteStartElement(\"results\");\n writer.WriteStartElement(\"test-suite\");\n writer.WriteAttributeString(\"type\", \"TestFixture\");\n WriteNUnitV2TestSuiteAttributes(writer, title);\n writer.WriteStartElement(\"results\");\n WriteNUnitV2TestCase(writer, title, message, stderr);\n writer.WriteEndElement(); // results\n writer.WriteEndElement(); // test-suite TextFixture\n writer.WriteEndElement(); // results\n writer.WriteEndElement(); // test-suite Assembly\n writer.WriteEndElement(); // test-results\n }", + "start_line": 109, + "end_line": 139, + "start_byte": 3025, + "end_byte": 4399 + }, + { + "name": "GenerateTestReport", + "code": "public override void GenerateTestReport(TextWriter writer, XmlReader reader)\n {\n if (!reader.ReadToFollowing(\"test-results\"))\n {\n return;\n }\n\n long.TryParse(reader[\"errors\"], out var errors);\n long.TryParse(reader[\"failures\"], out var failures);\n if (errors == 0 && failures == 0)\n {\n return;\n }\n\n writer.WriteLine(\"
\");\n writer.WriteLine(\"
    \");\n\n void write_failure()\n {\n var name = reader[\"name\"];\n string? message = null;\n var depth = reader.Depth;\n if (reader.ReadToDescendant(\"message\"))\n {\n message = reader.ReadElementContentAsString();\n // ReadToParent\n while (depth > reader.Depth && reader.Read())\n {\n }\n }\n var message_block = message?.IndexOf('\\n') >= 0;\n writer.WriteLine(\"
  • \");\n writer.Write(name.AsHtml());\n if (!string.IsNullOrEmpty(message))\n {\n writer.Write(\": \");\n if (message_block)\n {\n writer.WriteLine(\"
    \");\n }\n\n writer.Write(message.AsHtml());\n if (message_block)\n {\n writer.WriteLine(\"
    \");\n }\n }\n writer.WriteLine(\"
  • \");\n }\n\n while (reader.ReadToFollowing(\"test-suite\"))\n {\n if (reader[\"type\"] == \"Assembly\")\n {\n continue;\n }\n\n var result = reader[\"result\"];\n if (result != \"Error\" && result != \"Failure\")\n {\n continue;\n }\n\n if (result == \"Error\")\n {\n write_failure();\n }\n\n var depth = reader.Depth;\n\n while (reader.Read())\n {\n if (reader.NodeType != XmlNodeType.Element || reader.Name != \"test-case\")\n {\n continue;\n }\n\n result = reader[\"result\"];\n if (result == \"Error\" || result == \"Failure\")\n {\n write_failure();\n }\n\n if (reader.Depth < depth)\n {\n break;\n }\n }\n }\n\n writer.WriteLine(\"
\");\n writer.WriteLine(\"
\");\n }", + "start_line": 15, + "end_line": 107, + "start_byte": 456, + "end_byte": 3019 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/XmlResults/TrxTestReportGenerator.cs": [ + { + "name": "GenerateTestReport", + "code": "public override void GenerateTestReport(TextWriter writer, XmlReader reader)\n {\n var tests = TrxResultParser.ParseTrxXml(reader);\n var failedTests = tests.Where(v => v.Outcome != \"Passed\" && v.Outcome != \"NotExecuted\");\n\n if (failedTests.Any())\n {\n writer.WriteLine(\"
\");\n writer.WriteLine(\"
    \");\n foreach (var test in failedTests)\n {\n writer.WriteLine(\"
  • \");\n writer.Write($\"{test.ClassName?.AsHtml()}.{test.TestName?.AsHtml()}\");\n if (!string.IsNullOrEmpty(test.Message))\n {\n writer.Write(\": \");\n writer.Write(test.Message?.AsHtml());\n }\n writer.WriteLine(\"
    \");\n writer.WriteLine(\"
  • \");\n }\n writer.WriteLine(\"
\");\n writer.WriteLine(\"
\");\n }\n }", + "start_line": 20, + "end_line": 44, + "start_byte": 662, + "end_byte": 1621 + }, + { + "name": "GenerateFailure", + "code": "public override void GenerateFailure(XmlWriter writer, string title, string message, TextReader stderr)\n {\n // No-op - there was no implementation when we were splitting the parser up\n }", + "start_line": 15, + "end_line": 18, + "start_byte": 457, + "end_byte": 656 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/XmlResults/XmlResultParser.cs": [ + { + "name": "GetVSTSFilename", + "code": "public static string GetVSTSFilename(string filename)\n {\n if (filename == null)\n {\n throw new ArgumentNullException(nameof(filename));\n }\n\n var dirName = Path.GetDirectoryName(filename);\n return dirName == null ? $\"vsts-{Path.GetFileName(filename)}\" : Path.Combine(dirName, $\"vsts-{Path.GetFileName(filename)}\");\n }", + "start_line": 259, + "end_line": 268, + "start_byte": 10380, + "end_byte": 10747 + }, + { + "name": "GenerateFailure", + "code": "public void GenerateFailure(ILogs logs, string source, string appName, string? variation, string title,\n string message, TextReader stderrReader, XmlResultJargon jargon)\n {\n // VSTS does not provide a nice way to report build errors, create a fake\n // test result with a failure in the case the build did not work\n var failureLogXml = logs.Create($\"vsts-nunit-{source}-{s_helpers.Timestamp}.xml\", LogType.XmlLog.ToString());\n if (jargon == XmlResultJargon.NUnitV3)\n {\n var failureXmlTmp = logs.Create($\"nunit-{source}-{s_helpers.Timestamp}.tmp\", \"Failure Log tmp\");\n GenerateFailureXml(failureXmlTmp.FullPath, title, message, stderrReader, jargon);\n // add the required attachments and the info of the application that failed to install\n var failure_logs = Directory.GetFiles(logs.Directory).Where(p => !p.Contains(\"nunit\")); // all logs but ourself\n UpdateMissingData(failureXmlTmp.FullPath, failureLogXml.FullPath, $\"{appName} {variation}\", failure_logs);\n }\n else\n {\n GenerateFailureXml(failureLogXml.FullPath, title, message, stderrReader, jargon);\n }\n }", + "start_line": 239, + "end_line": 257, + "start_byte": 9174, + "end_byte": 10374 + }, + { + "name": "GenerateFailure", + "code": "public void GenerateFailure(ILogs logs, string source, string appName, string? variation, string title, string message, string stderrPath, XmlResultJargon jargon)\n {\n using var stderrReader = new StreamReader(stderrPath);\n GenerateFailure(logs, source, appName, variation, title, message, stderrReader, jargon);\n }", + "start_line": 233, + "end_line": 237, + "start_byte": 8834, + "end_byte": 9168 + }, + { + "name": "GenerateFailureXml", + "code": "private void GenerateFailureXml(string destination, string title, string message, TextReader stderrReader, XmlResultJargon jargon)\n {\n var settings = new XmlWriterSettings { Indent = true };\n using (var stream = File.CreateText(destination))\n using (var xmlWriter = XmlWriter.Create(stream, settings))\n {\n xmlWriter.WriteStartDocument();\n\n if (_xmlFormatters.TryGetValue(jargon, out var xmlFormatters))\n {\n xmlFormatters.Generator.GenerateFailure(xmlWriter, title, message, stderrReader);\n }\n\n xmlWriter.WriteEndDocument();\n }\n }", + "start_line": 216, + "end_line": 231, + "start_byte": 8188, + "end_byte": 8828 + }, + { + "name": "UpdateMissingData", + "code": "public void UpdateMissingData(string source, string destination, string applicationName, IEnumerable attachments)\n {\n // we could do this with a XmlReader and a Writer, but might be to complicated to get right, we pay with performance what we\n // cannot pay with brain cells.\n var doc = XDocument.Load(source);\n var attachmentsElement = new XElement(\"attachments\");\n foreach (var path in attachments)\n {\n // we do not add a description, VSTS ignores that :/\n attachmentsElement.Add(new XElement(\"attachment\",\n new XElement(\"filePath\", path)));\n }\n\n var testSuitesElements = doc.Descendants().Where(e => e.Name == \"test-suite\" && e.Attribute(\"type\")?.Value == \"Assembly\");\n if (!testSuitesElements.Any())\n {\n return;\n }\n\n // add the attachments to the first test-suite, this will add the attachmnets to it, which will be added to the test-run, the pipeline\n // SHOULD NOT merge runs, else this upload will be really hard to use. Also, just to one of them, else we have duplicated logs.\n testSuitesElements.FirstOrDefault().Add(attachmentsElement);\n\n foreach (var suite in testSuitesElements)\n {\n suite.SetAttributeValue(\"name\", applicationName);\n suite.SetAttributeValue(\"fullname\", applicationName); // docs say just name, but I've seen the fullname instead, docs usually lie\n // add also the attachments to all the failing tests, this will make the life of the person monitoring easier, since\n // he will see the logs directly from the attachment page\n var tests = suite.Descendants().Where(e => e.Name == \"test-case\" && e.Attribute(\"result\").Value == \"Failed\");\n foreach (var t in tests)\n {\n t.Add(attachmentsElement);\n }\n }\n\n doc.Save(destination);\n }", + "start_line": 177, + "end_line": 214, + "start_byte": 6129, + "end_byte": 8182 + }, + { + "name": "GenerateTestReport", + "code": "public void GenerateTestReport(TextWriter writer, TextReader stream, XmlResultJargon xmlType)\n {\n var reader = XmlReader.Create(stream);\n\n if (_xmlFormatters.TryGetValue(xmlType, out var xmlFormatter))\n {\n xmlFormatter.Generator.GenerateTestReport(writer, reader);\n }\n else\n {\n writer.WriteLine($\"Could not parse {xmlType}: Not supported format.
\");\n }\n }", + "start_line": 162, + "end_line": 174, + "start_byte": 5567, + "end_byte": 6045 + }, + { + "name": "GenerateTestReport", + "code": "public void GenerateTestReport(TextWriter writer, string resultsPath, XmlResultJargon xmlType)\n {\n using var stream = new StreamReader(resultsPath);\n GenerateTestReport(writer, stream, xmlType);\n }", + "start_line": 156, + "end_line": 160, + "start_byte": 5344, + "end_byte": 5561 + }, + { + "name": "ParseResults", + "code": "public (string resultLine, bool failed) ParseResults(string source, XmlResultJargon xmlType, StreamWriter? humanReadableReportDestination = null)\n {\n var reader = new StreamReader(source);\n var parsedData = (\"\", true);\n\n if (_xmlFormatters.TryGetValue(xmlType, out var xmlFormatter))\n {\n parsedData = xmlFormatter.Parser.ParseXml(reader, humanReadableReportDestination);\n }\n\n return parsedData;\n }", + "start_line": 143, + "end_line": 154, + "start_byte": 4882, + "end_byte": 5338 + }, + { + "name": "ParseResults", + "code": "public (string resultLine, bool failed) ParseResults(string source, XmlResultJargon xmlType, string? humanReadableReportDestination = null)\n {\n StreamWriter? writer = null;\n if (humanReadableReportDestination != null)\n {\n writer = new StreamWriter(humanReadableReportDestination, true);\n }\n\n var result = ParseResults(source, xmlType, writer);\n writer?.Dispose();\n return result;\n }", + "start_line": 130, + "end_line": 141, + "start_byte": 4428, + "end_byte": 4876 + }, + { + "name": "CleanXml", + "code": "public void CleanXml(string source, string destination)\n {\n using (var reader = new StreamReader(source))\n using (var writer = new StreamWriter(destination))\n {\n string? line;\n while ((line = reader.ReadLine()) != null)\n {\n if (line.StartsWith(\"ping\", StringComparison.Ordinal) || line.Contains(\"TouchUnitTestRun\") || line.Contains(\"NUnitOutput\") || line.Contains(\"\")\n {\n Log.WriteLine(\"Tests have finished executing\");\n break;\n }\n }\n }\n }\n TestLog.Flush();\n Finished();\n }", + "start_line": 42, + "end_line": 72, + "start_byte": 1159, + "end_byte": 2269 + }, + { + "name": "Start", + "code": "protected override void Start() => _processorThread.Start();", + "start_line": 40, + "end_line": 40, + "start_byte": 1093, + "end_byte": 1153 + }, + { + "name": "InitializeAndGetPort", + "code": "public override int InitializeAndGetPort()\n {\n _processorThread = new Thread(Processing);\n return 0;\n }", + "start_line": 34, + "end_line": 38, + "start_byte": 964, + "end_byte": 1087 + }, + { + "name": "Stop", + "code": "protected override void Stop()\n {\n _cancel = true;\n _processorThread.Join();\n _processorThread = null;\n Finished(true);\n }", + "start_line": 26, + "end_line": 32, + "start_byte": 802, + "end_byte": 958 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Listeners/SimpleListener.cs": [ + { + "name": "Dispose", + "code": "public virtual void Dispose()\n {\n Cancel();\n GC.SuppressFinalize(this);\n }", + "start_line": 144, + "end_line": 148, + "start_byte": 3942, + "end_byte": 4036 + }, + { + "name": "Cancel", + "code": "public void Cancel()\n {\n lock (_connected)\n {\n if (!_connected.TrySetCanceled())\n {\n return;\n }\n }\n\n try\n {\n // Wait a second just in case more data arrives\n if (!_stopped.Task.Wait(TimeSpan.FromSeconds(1)))\n {\n Stop();\n }\n }\n catch (Exception e)\n {\n // We might have stopped already, so just ignore any exceptions.\n Log.WriteLine($\"An exception occurred in processing thread: {e.Message}\");\n }\n }", + "start_line": 119, + "end_line": 142, + "start_byte": 3341, + "end_byte": 3936 + }, + { + "name": "WaitForCompletion", + "code": "public bool WaitForCompletion(TimeSpan ts) => _stopped.Task.Wait(ts);", + "start_line": 115, + "end_line": 115, + "start_byte": 3210, + "end_byte": 3279 + }, + { + "name": "StopAsync", + "code": "public Task StopAsync()\n {\n var t = new Thread(() =>\n {\n try\n {\n Stop();\n }\n catch (Exception e)\n {\n Log.WriteLine($\"{GetType().Name}: an exception occurred in processing thread: {e}\");\n }\n })\n {\n IsBackground = true,\n };\n t.Start();\n return _stopped.Task;\n }", + "start_line": 95, + "end_line": 113, + "start_byte": 2783, + "end_byte": 3204 + }, + { + "name": "StartAsync", + "code": "public void StartAsync()\n {\n var t = new Thread(() =>\n {\n try\n {\n Start();\n }\n catch (Exception e)\n {\n Log.WriteLine($\"{GetType().Name}: an exception occurred in processing thread: {e}\");\n }\n })\n {\n IsBackground = true,\n };\n t.Start();\n }", + "start_line": 76, + "end_line": 93, + "start_byte": 2384, + "end_byte": 2777 + }, + { + "name": "Finished", + "code": "protected void Finished(bool early_termination = false)\n {\n if (_stopped.TrySetResult(early_termination))\n {\n if (early_termination)\n {\n Log.WriteLine(\"Tests were terminated before completion\");\n }\n else\n {\n Log.WriteLine(\"Tests have finished executing\");\n }\n }\n }", + "start_line": 61, + "end_line": 74, + "start_byte": 1991, + "end_byte": 2378 + }, + { + "name": "Connected", + "code": "protected void Connected(string remote)\n {\n // When app is in some crashing state, it might start connecting and disconnecting in a loop until we end up with an infinite log\n // So logging only when the endpoint would change (which it shouldn't but we want to know)\n if (_remoteAddress != remote)\n {\n _remoteAddress = remote;\n Log.WriteLine(\"Connection from {0} saving logs to {1}\", remote, TestLog.FullPath);\n }\n\n _connected.TrySetResult(true);\n }", + "start_line": 48, + "end_line": 59, + "start_byte": 1467, + "end_byte": 1985 + }, + { + "name": "InitializeAndGetPort", + "code": "public abstract int InitializeAndGetPort();", + "start_line": 40, + "end_line": 40, + "start_byte": 1196, + "end_byte": 1239 + }, + { + "name": "Stop", + "code": "protected abstract void Stop();", + "start_line": 37, + "end_line": 37, + "start_byte": 1103, + "end_byte": 1134 + }, + { + "name": "Start", + "code": "protected abstract void Start();", + "start_line": 36, + "end_line": 36, + "start_byte": 1066, + "end_byte": 1098 + }, + { + "name": "StopAsync", + "code": "Task StopAsync();", + "start_line": 23, + "end_line": 23, + "start_byte": 659, + "end_byte": 676 + }, + { + "name": "StartAsync", + "code": "void StartAsync();", + "start_line": 22, + "end_line": 22, + "start_byte": 636, + "end_byte": 654 + }, + { + "name": "InitializeAndGetPort", + "code": "int InitializeAndGetPort();", + "start_line": 21, + "end_line": 21, + "start_byte": 604, + "end_byte": 631 + }, + { + "name": "Cancel", + "code": "void Cancel();", + "start_line": 20, + "end_line": 20, + "start_byte": 585, + "end_byte": 599 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Listeners/TcpTunnel.cs": [ + { + "name": "DisposeAsync", + "code": "public async ValueTask DisposeAsync()\n {\n await Close();\n GC.SuppressFinalize(this);\n }", + "start_line": 112, + "end_line": 116, + "start_byte": 4627, + "end_byte": 4734 + }, + { + "name": "Close", + "code": "public async Task Close()\n {\n if (_cancellationToken == null)\n {\n throw new InvalidOperationException(\"Cannot close tunnel that was not opened.\");\n }\n // cancel process and wait for it to terminate, else we might want to start a second tunnel to the same device\n // which is going to give problems.\n _cancellationToken.Cancel();\n await _tcpTunnelExecutionTask;\n }", + "start_line": 100, + "end_line": 110, + "start_byte": 4192, + "end_byte": 4621 + }, + { + "name": "Open", + "code": "public void Open(string device, ITunnelListener simpleListener, TimeSpan timeout, ILog mainLog)\n {\n if (device == null)\n {\n throw new ArgumentNullException(nameof(device));\n }\n\n if (simpleListener == null)\n {\n throw new ArgumentNullException(nameof(simpleListener));\n }\n\n if (mainLog == null)\n {\n throw new ArgumentNullException(nameof(mainLog));\n }\n\n lock (_processExecutionLock)\n {\n // launch app, but do not await for the result, since we need to create the tunnel\n var tcpArgs = new MlaunchArguments\n {\n new TcpTunnelArgument(simpleListener.Port),\n new DeviceNameArgument(device),\n };\n\n // use a cancelation token, later will be used to kill the tcp tunnel process\n _cancellationToken = new CancellationTokenSource();\n mainLog.WriteLine($\"Starting TCP tunnel between mac port: {simpleListener.Port} and device port {simpleListener.Port}\");\n Port = simpleListener.Port;\n var tunnelbackLog = new CallbackLog((line) =>\n {\n mainLog.WriteLine($\"[TCP tunnel] {line}\");\n if (line.Contains(\"Tcp tunnel started on device\"))\n {\n mainLog.Write($\"TCP tunnel created on port {simpleListener.Port}\");\n startedCompletionSource.TrySetResult(true);\n simpleListener.TunnelHoleThrough.TrySetResult(true);\n }\n });\n // do not await since we are going to be running the process in parallel\n _tcpTunnelExecutionTask = _processManager.ExecuteCommandAsync(tcpArgs, tunnelbackLog, timeout, cancellationToken: _cancellationToken.Token);\n _tcpTunnelExecutionTask.ContinueWith(delegate (Task task)\n {\n // if the task completes, means that we had issues with the creation of the tunnel and the process\n // exited, if that is the case, we do not want to make the app wait, therefore, set the hole to false\n // which will throw an exception from the listener.\n simpleListener.TunnelHoleThrough.TrySetResult(task.Result.Succeeded);\n });\n }\n }", + "start_line": 48, + "end_line": 98, + "start_byte": 1827, + "end_byte": 4186 + }, + { + "name": "Close", + "code": "public Task Close();", + "start_line": 26, + "end_line": 26, + "start_byte": 925, + "end_byte": 945 + }, + { + "name": "Open", + "code": "public void Open(string device, ITunnelListener simpleListener, TimeSpan timeout, ILog mainLog);", + "start_line": 25, + "end_line": 25, + "start_byte": 824, + "end_byte": 920 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Listeners/SimpleListenerFactory.cs": [ + { + "name": "Create", + "code": "public (ListenerTransport transport, ISimpleListener listener, string listenerTempFile) Create(\n RunMode mode,\n ILog log,\n IFileBackedLog testLog,\n bool isSimulator,\n bool autoExit,\n bool xmlOutput)\n {\n string listenerTempFile = null;\n ISimpleListener listener;\n ListenerTransport transport;\n\n if (mode == RunMode.WatchOS)\n {\n transport = isSimulator ? ListenerTransport.File : ListenerTransport.Http;\n }\n else\n {\n transport = ListenerTransport.Tcp;\n }\n\n switch (transport)\n {\n case ListenerTransport.File:\n listenerTempFile = testLog.FullPath + \".tmp\";\n listener = new SimpleFileListener(listenerTempFile, log, testLog, xmlOutput);\n break;\n case ListenerTransport.Http:\n listener = new SimpleHttpListener(log, testLog, autoExit);\n break;\n case ListenerTransport.Tcp:\n listener = new SimpleTcpListener(log, testLog, autoExit, UseTunnel);\n break;\n default:\n throw new NotImplementedException(\"Unknown type of listener\");\n }\n\n return (transport, listener, listenerTempFile);\n }", + "start_line": 41, + "end_line": 79, + "start_byte": 1074, + "end_byte": 2374 + }, + { + "name": "Create", + "code": "(ListenerTransport transport, ISimpleListener listener, string listenerTempFile) Create(\n RunMode mode,\n ILog log,\n IFileBackedLog testLog,\n bool isSimulator,\n bool autoExit,\n bool xmlOutput);", + "start_line": 19, + "end_line": 25, + "start_byte": 439, + "end_byte": 673 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Listeners/SimpleHttpListener.cs": [ + { + "name": "Processing", + "code": "private bool Processing(HttpListenerContext context)\n {\n var finished = false;\n\n var request = context.Request;\n var response = \"OK\";\n\n var stream = request.InputStream;\n var data = string.Empty;\n using (var reader = new StreamReader(stream))\n {\n data = reader.ReadToEnd();\n }\n\n stream.Close();\n\n switch (request.RawUrl)\n {\n case \"/Start\":\n if (!_connected_once)\n {\n _connected_once = true;\n Connected(request.RemoteEndPoint.ToString());\n }\n break;\n case \"/Finish\":\n if (!finished)\n {\n TestLog.Write(data);\n TestLog.Flush();\n finished = true;\n }\n break;\n default:\n Log.WriteLine(\"Unknown upload url: {0}\", request.RawUrl);\n response = \"Unknown upload url\";\n context.Response.StatusCode = (int)HttpStatusCode.NotFound;\n break;\n }\n\n var buf = System.Text.Encoding.UTF8.GetBytes(response);\n context.Response.ContentLength64 = buf.Length;\n context.Response.OutputStream.Write(buf, 0, buf.Length);\n context.Response.OutputStream.Close();\n context.Response.Close();\n\n return finished;\n }", + "start_line": 93, + "end_line": 140, + "start_byte": 2470, + "end_byte": 3902 + }, + { + "name": "Start", + "code": "protected override void Start()\n {\n bool processed;\n\n try\n {\n Log.WriteLine(\"Test log server listening on: {0}:{1}\", Address, Port);\n do\n {\n var context = _server.GetContext();\n processed = Processing(context);\n } while (!_autoExit || !processed);\n }\n catch (Exception e)\n {\n if (e is not SocketException se || se.SocketErrorCode != SocketError.Interrupted)\n {\n Console.WriteLine(\"[{0}] : {1}\", DateTime.Now, e);\n }\n }\n finally\n {\n try\n {\n _server.Stop();\n }\n finally\n {\n Finished();\n }\n }\n }", + "start_line": 60, + "end_line": 91, + "start_byte": 1678, + "end_byte": 2464 + }, + { + "name": "Stop", + "code": "protected override void Stop() => _server.Stop();", + "start_line": 58, + "end_line": 58, + "start_byte": 1623, + "end_byte": 1672 + }, + { + "name": "InitializeAndGetPort", + "code": "public override int InitializeAndGetPort()\n {\n _server = new HttpListener();\n\n if (Port != 0)\n {\n throw new NotImplementedException();\n }\n\n // Try and find an unused port\n int attemptsLeft = 50;\n var r = new Random((int)DateTime.Now.Ticks);\n while (attemptsLeft-- > 0)\n {\n var newPort = r.Next(49152, 65535); // The suggested range for dynamic ports is 49152-65535 (IANA)\n _server.Prefixes.Clear();\n _server.Prefixes.Add(\"http://*:\" + newPort + \"/\");\n try\n {\n _server.Start();\n Port = newPort;\n break;\n }\n catch (Exception ex)\n {\n Log.WriteLine(\"Failed to listen on port {0}: {1}\", newPort, ex.Message);\n }\n }\n\n return Port;\n }", + "start_line": 26, + "end_line": 56, + "start_byte": 737, + "end_byte": 1617 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Logging/AppInstallMonitorLog.cs": [ + { + "name": "Write", + "code": "public override void Write(byte[] buffer, int offset, int count) => _copyTo.Write(buffer, offset, count);", + "start_line": 122, + "end_line": 122, + "start_byte": 3978, + "end_byte": 4083 + }, + { + "name": "WriteImpl", + "code": "protected override void WriteImpl(string value)\n {\n var v = value.Trim();\n if (v.StartsWith(\"Installing application bundle\", StringComparison.Ordinal))\n {\n if (!CopyingApp)\n {\n CopyingApp = true;\n AppCopyStart.Start();\n }\n else if (!CopyingWatchApp)\n {\n CopyingApp = false;\n CopyingWatchApp = true;\n AppCopyStart.Stop();\n WatchAppCopyStart.Start();\n }\n }\n else if (v.StartsWith(\"PercentComplete: \", StringComparison.Ordinal) && int.TryParse(v.Substring(\"PercentComplete: \".Length).Trim(), out var percent))\n {\n if (CopyingApp)\n {\n AppPercentComplete = percent;\n }\n else if (CopyingWatchApp)\n {\n WatchAppPercentComplete = percent;\n }\n }\n else if (v.StartsWith(\"NumBytes: \", StringComparison.Ordinal) && int.TryParse(v.Substring(\"NumBytes: \".Length).Trim(), out var num_bytes))\n {\n if (CopyingApp)\n {\n AppBytes = num_bytes;\n AppCopyDuration = AppCopyStart.Elapsed;\n }\n else if (CopyingWatchApp)\n {\n WatchAppBytes = num_bytes;\n WatchAppCopyDuration = WatchAppCopyStart.Elapsed;\n }\n }\n else if (v.StartsWith(\"TotalBytes: \", StringComparison.Ordinal) && int.TryParse(v.Substring(\"TotalBytes: \".Length).Trim(), out var total_bytes))\n {\n if (CopyingApp)\n {\n AppTotalBytes = total_bytes;\n }\n else if (CopyingWatchApp)\n {\n WatchAppTotalBytes = total_bytes;\n }\n }\n\n ResetTimer();\n\n _copyTo.WriteLine(value);\n }", + "start_line": 63, + "end_line": 120, + "start_byte": 2087, + "end_byte": 3972 + }, + { + "name": "ResetTimer", + "code": "private void ResetTimer() => _cancellationSource.CancelAfter(TimeSpan.FromMinutes(1));", + "start_line": 61, + "end_line": 61, + "start_byte": 1995, + "end_byte": 2081 + }, + { + "name": "Dispose", + "code": "public override void Dispose()\n {\n _copyTo.Dispose();\n _cancellationSource.Dispose();\n GC.SuppressFinalize(this);\n }", + "start_line": 54, + "end_line": 59, + "start_byte": 1846, + "end_byte": 1989 + }, + { + "name": "GetReader", + "code": "public override StreamReader GetReader() => _copyTo.GetReader();", + "start_line": 52, + "end_line": 52, + "start_byte": 1776, + "end_byte": 1840 + }, + { + "name": "Flush", + "code": "public override void Flush() => _copyTo.Flush();", + "start_line": 50, + "end_line": 50, + "start_byte": 1722, + "end_byte": 1770 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Logging/IEventLogger.cs": [ + { + "name": "LogEvent", + "code": "public void LogEvent(ILog log, string text, params object[] args);", + "start_line": 11, + "end_line": 11, + "start_byte": 349, + "end_byte": 415 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Logging/WrenchLog.cs": [ + { + "name": "WriteLine", + "code": "public static void WriteLine(string message)\n {\n // disabled, might be deleted later.\n }", + "start_line": 12, + "end_line": 15, + "start_byte": 417, + "end_byte": 518 + }, + { + "name": "WriteLine", + "code": "public static void WriteLine(string message, params object[] args) => WriteLine(string.Format(message, args));", + "start_line": 10, + "end_line": 10, + "start_byte": 301, + "end_byte": 411 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Logging/LogType.cs": [], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Logging/CaptureLog.cs": [ + { + "name": "Dispose", + "code": "public override void Dispose()\n {\n StopCapture();\n GC.SuppressFinalize(this);\n }", + "start_line": 221, + "end_line": 225, + "start_byte": 6789, + "end_byte": 6889 + }, + { + "name": "WriteImpl", + "code": "protected override void WriteImpl(string value) => throw new InvalidOperationException();", + "start_line": 219, + "end_line": 219, + "start_byte": 6694, + "end_byte": 6783 + }, + { + "name": "Flush", + "code": "public override void Flush() => Capture();", + "start_line": 217, + "end_line": 217, + "start_byte": 6646, + "end_byte": 6688 + }, + { + "name": "GetReader", + "code": "public override StreamReader GetReader()\n {\n lock (CapturePath)\n {\n // If we copied the original file over, use it as the source for reading\n // (original file might not exist anymore)\n if (_stopped)\n {\n return new StreamReader(new FileStream(FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));\n }\n }\n\n // If we want to capture something in the future that doesn't exist yet\n if (!File.Exists(CapturePath))\n {\n return null;\n }\n\n var stream = new FileStream(CapturePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n\n // Find the spot where we started capturing\n stream.Seek(_startPosition, SeekOrigin.Begin);\n\n return new StreamReader(stream);\n }", + "start_line": 191, + "end_line": 215, + "start_byte": 5808, + "end_byte": 6640 + }, + { + "name": "Capture", + "code": "private void Capture()\n {\n if (_entireFile)\n {\n return;\n }\n\n if (!File.Exists(CapturePath))\n {\n File.AppendAllText(FullPath, $\"{Environment.NewLine}Could not capture the file '{CapturePath}' because it does not exist.\");\n return;\n }\n\n var sourceLength = new FileInfo(CapturePath).Length;\n\n var endPosition = _endPosition;\n if (endPosition == 0)\n {\n endPosition = sourceLength;\n }\n\n // The file shrank? lets copy the entire file in this case, which is better than nothing\n if (endPosition < _startPosition)\n {\n File.Copy(CapturePath, FullPath, true);\n return;\n }\n\n var destFile = new FileInfo(FullPath);\n var alreadyCapturedLength = destFile.Exists ? destFile.Length : 0L;\n if (alreadyCapturedLength + _startPosition >= sourceLength)\n {\n // We've captured before, and nothing new as added since last time.\n return;\n }\n\n var readPosition = _startPosition + alreadyCapturedLength;\n\n using var reader = new FileStream(CapturePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n using var writer = new FileStream(FullPath, FileMode.Create, FileAccess.Write, FileShare.Read);\n\n var buffer = new byte[4096];\n reader.Seek(readPosition, SeekOrigin.Begin);\n\n while (readPosition < endPosition)\n {\n int bytesRead = reader.Read(buffer, 0, (int)Math.Min(buffer.Length, endPosition - readPosition));\n if (bytesRead > 0)\n {\n writer.Write(buffer, 0, bytesRead);\n readPosition += bytesRead;\n }\n else\n {\n // There's nothing more to read.\n // I can't see how we get here, since we calculate the amount to read based on what's available, but it does happen randomly.\n break;\n }\n }\n }", + "start_line": 130, + "end_line": 189, + "start_byte": 3789, + "end_byte": 5802 + }, + { + "name": "StopCapture", + "code": "public void StopCapture(TimeSpan? waitIfEmpty = null)\n {\n if (_stopped)\n {\n return;\n }\n\n lock (CapturePath)\n {\n if (_stopped)\n {\n return;\n }\n\n try\n {\n if (!_started && !_entireFile)\n {\n throw new InvalidOperationException(\"StartCapture() must be called before StopCature() on when the entire file is being captured.\");\n }\n\n if (!File.Exists(CapturePath))\n {\n File.WriteAllText(FullPath, $\"Could not capture the file '{CapturePath}' because it doesn't exist.\");\n return;\n }\n\n _endPosition = new FileInfo(CapturePath).Length;\n\n if ((_endPosition == 0 || (_startPosition == _endPosition && !_entireFile)) && waitIfEmpty.HasValue)\n {\n Thread.Sleep((int)waitIfEmpty.Value.TotalMilliseconds);\n _endPosition = new FileInfo(CapturePath).Length;\n }\n\n if (_entireFile)\n {\n File.Copy(CapturePath, FullPath, true);\n return;\n }\n\n Capture();\n }\n finally\n {\n _stopped = true;\n }\n }\n }", + "start_line": 80, + "end_line": 128, + "start_byte": 2383, + "end_byte": 3783 + }, + { + "name": "StartCapture", + "code": "public void StartCapture()\n {\n if (_entireFile)\n {\n return;\n }\n\n if (File.Exists(CapturePath))\n {\n _startPosition = new FileInfo(CapturePath).Length;\n }\n\n _started = true;\n }", + "start_line": 65, + "end_line": 78, + "start_byte": 2126, + "end_byte": 2377 + }, + { + "name": "StopCapture", + "code": "void StopCapture(TimeSpan? waitIfEmpty = null);", + "start_line": 33, + "end_line": 33, + "start_byte": 1138, + "end_byte": 1185 + }, + { + "name": "StartCapture", + "code": "void StartCapture();", + "start_line": 32, + "end_line": 32, + "start_byte": 1113, + "end_byte": 1133 + }, + { + "name": "Create", + "code": "public ICaptureLog Create(string path, string systemLogPath, bool entireFile, LogType logType)\n => Create(path, systemLogPath, entireFile, logType.ToString());", + "start_line": 26, + "end_line": 27, + "start_byte": 891, + "end_byte": 1057 + }, + { + "name": "Create", + "code": "public ICaptureLog Create(string path, string systemLogPath, bool entireFile, string description = null) =>\n new CaptureLog(path, systemLogPath, entireFile)\n {\n Description = description\n };", + "start_line": 20, + "end_line": 24, + "start_byte": 663, + "end_byte": 885 + }, + { + "name": "Create", + "code": "ICaptureLog Create(string path, string systemLogPath, bool entireFile, LogType logType);", + "start_line": 15, + "end_line": 15, + "start_byte": 513, + "end_byte": 601 + }, + { + "name": "Create", + "code": "ICaptureLog Create(string path, string systemLogPath, bool entireFile, string description = null);", + "start_line": 14, + "end_line": 14, + "start_byte": 410, + "end_byte": 508 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Logging/ILogs.cs": [ + { + "name": "CreateFile", + "code": "string CreateFile(string path, LogType type);", + "start_line": 30, + "end_line": 30, + "start_byte": 1194, + "end_byte": 1239 + }, + { + "name": "CreateFile", + "code": "string CreateFile(string path, string description);", + "start_line": 29, + "end_line": 29, + "start_byte": 1138, + "end_byte": 1189 + }, + { + "name": "AddFile", + "code": "IFileBackedLog AddFile(string path, string name);", + "start_line": 26, + "end_line": 26, + "start_byte": 997, + "end_byte": 1046 + }, + { + "name": "AddFile", + "code": "IFileBackedLog AddFile(string path);", + "start_line": 21, + "end_line": 21, + "start_byte": 775, + "end_byte": 811 + }, + { + "name": "Create", + "code": "IFileBackedLog Create(string filename, string description, bool? timestamp = null);", + "start_line": 16, + "end_line": 16, + "start_byte": 506, + "end_byte": 589 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Logging/DeviceLogCapturer.cs": [ + { + "name": "Dispose", + "code": "public void Dispose() => StopCapture();", + "start_line": 101, + "end_line": 101, + "start_byte": 3105, + "end_byte": 3144 + }, + { + "name": "StopCapture", + "code": "public void StopCapture()\n {\n if (_process.HasExited)\n {\n return;\n }\n\n _process.StandardInput.WriteLine();\n if (_process.WaitForExit((int)TimeSpan.FromSeconds(5).TotalMilliseconds))\n {\n return;\n }\n\n _processManager.KillTreeAsync(_process, _mainLog, diagnostics: false).Wait();\n _process.Dispose();\n }", + "start_line": 84, + "end_line": 99, + "start_byte": 2708, + "end_byte": 3099 + }, + { + "name": "StartCapture", + "code": "public void StartCapture()\n {\n var args = new MlaunchArguments\n {\n new SdkRootArgument(_processManager.XcodeRoot),\n new LogDevArgument(),\n new DeviceNameArgument(_deviceName),\n };\n\n _process = new Process();\n _process.StartInfo.FileName = _processManager.MlaunchPath;\n _process.StartInfo.Arguments = args.AsCommandLine();\n _process.StartInfo.UseShellExecute = false;\n _process.StartInfo.RedirectStandardOutput = true;\n _process.StartInfo.RedirectStandardError = true;\n _process.StartInfo.RedirectStandardInput = true;\n _process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>\n {\n if (e.Data != null)\n {\n return;\n }\n\n lock (_deviceLog)\n {\n _deviceLog.WriteLine(e.Data);\n }\n };\n\n _process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>\n {\n if (e.Data == null)\n {\n return;\n }\n\n lock (_deviceLog)\n {\n _deviceLog.WriteLine(e.Data);\n }\n };\n\n _deviceLog.WriteLine(\"{0} {1}\", _process.StartInfo.FileName, _process.StartInfo.Arguments);\n\n _process.Start();\n _process.BeginOutputReadLine();\n _process.BeginErrorReadLine();\n }", + "start_line": 35, + "end_line": 82, + "start_byte": 1260, + "end_byte": 2702 + }, + { + "name": "StopCapture", + "code": "void StopCapture();", + "start_line": 15, + "end_line": 15, + "start_byte": 485, + "end_byte": 504 + }, + { + "name": "StartCapture", + "code": "void StartCapture();", + "start_line": 14, + "end_line": 14, + "start_byte": 460, + "end_byte": 480 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Logging/LogFile.cs": [ + { + "name": "Dispose", + "code": "public override void Dispose()\n {\n lock (_lockObj)\n {\n if (!_disposed)\n {\n _writer?.Flush();\n _writer?.Dispose();\n _writer = null;\n }\n }\n\n _disposed = true;\n GC.SuppressFinalize(this);\n }", + "start_line": 76, + "end_line": 90, + "start_byte": 2234, + "end_byte": 2540 + }, + { + "name": "GetReader", + "code": "public override StreamReader GetReader() => new(new FileStream(FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));", + "start_line": 74, + "end_line": 74, + "start_byte": 2101, + "end_byte": 2228 + }, + { + "name": "WriteImpl", + "code": "protected override void WriteImpl(string value)\n {\n var bytes = Encoding.GetBytes(value);\n Write(bytes, 0, bytes.Length);\n }", + "start_line": 68, + "end_line": 72, + "start_byte": 1951, + "end_byte": 2095 + }, + { + "name": "Flush", + "code": "public override void Flush()\n {\n if (!_disposed)\n {\n _writer?.Flush();\n }\n }", + "start_line": 60, + "end_line": 66, + "start_byte": 1831, + "end_byte": 1945 + }, + { + "name": "Write", + "code": "public override void Write(byte[] buffer, int offset, int count)\n {\n try\n {\n // We don't want to open the file every time someone writes to the log, so we keep it as an instance\n // variable until we're disposed. Due to the async nature of how we run tests, writes may still\n // happen after we're disposed, in which case we create a temporary stream we close after writing\n lock (_lockObj)\n {\n var fs = _writer ?? new FileStream(FullPath, FileMode.Append, FileAccess.Write, FileShare.Read);\n\n fs.Write(buffer, offset, count);\n\n if (_disposed)\n {\n fs.Dispose();\n }\n else\n {\n _writer = fs;\n }\n }\n }\n catch (Exception e)\n {\n Console.Error.WriteLine($\"Failed to write to the file {FullPath}: {e}.\");\n return;\n }\n }", + "start_line": 30, + "end_line": 58, + "start_byte": 820, + "end_byte": 1825 + } + ], + "src/Microsoft.DotNet.XHarness.iOS.Shared/Logging/Logs.cs": [ + { + "name": "Dispose", + "code": "public void Dispose()\n {\n foreach (var log in this)\n {\n log.Dispose();\n }\n GC.SuppressFinalize(this);\n }", + "start_line": 81, + "end_line": 88, + "start_byte": 2653, + "end_byte": 2802 + }, + { + "name": "CreateFile", + "code": "public string CreateFile(string path, LogType type) => CreateFile(path, type.ToString());", + "start_line": 79, + "end_line": 79, + "start_byte": 2558, + "end_byte": 2647 + }, + { + "name": "CreateFile", + "code": "public string CreateFile(string path, string description)\n {\n if (path == null)\n {\n throw new ArgumentNullException(nameof(path));\n }\n\n using (var rv = new LogFile(description, Path.Combine(Directory, path), false))\n {\n Add(rv);\n return rv.FullPath;\n }\n }", + "start_line": 65, + "end_line": 77, + "start_byte": 2216, + "end_byte": 2552 + }, + { + "name": "AddFile", + "code": "public IFileBackedLog AddFile(string path, string name)\n {\n if (path == null)\n {\n throw new ArgumentNullException(nameof(path));\n }\n\n if (!path.StartsWith(Directory, StringComparison.Ordinal))\n {\n var newPath = Path.Combine(Directory, Path.GetFileNameWithoutExtension(path) + \"-\" + _helpers.Timestamp + Path.GetExtension(path));\n File.Copy(path, newPath, true);\n path = newPath;\n }\n\n var log = new LogFile(name, path, true);\n Add(log);\n return log;\n }", + "start_line": 45, + "end_line": 62, + "start_byte": 1560, + "end_byte": 2124 + }, + { + "name": "AddFile", + "code": "public IFileBackedLog AddFile(string path) => AddFile(path, Path.GetFileName(path));", + "start_line": 40, + "end_line": 40, + "start_byte": 1290, + "end_byte": 1374 + }, + { + "name": "Create", + "code": "public IFileBackedLog Create(string filename, string description, bool? timestamp = null)\n {\n System.IO.Directory.CreateDirectory(Directory);\n var rv = new LogFile(description, Path.GetFullPath(Path.Combine(Directory, filename)));\n if (timestamp.HasValue)\n {\n rv.Timestamp = timestamp.Value;\n }\n\n Add(rv);\n return rv;\n }", + "start_line": 24, + "end_line": 35, + "start_byte": 718, + "end_byte": 1104 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/AppOperations/AppTester.cs": [ + { + "name": "GetDeviceArguments", + "code": "private MlaunchArguments GetDeviceArguments(\n AppBundleInformation appInformation,\n IDevice device,\n bool isWatchTarget,\n XmlResultJargon xmlResultJargon,\n string[]? skippedMethods,\n string[]? skippedTestClasses,\n ListenerTransport deviceListenerTransport,\n int deviceListenerPort,\n string deviceListenerTmpFile,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables,\n string? appEndTag)\n {\n var args = GetCommonArguments(\n xmlResultJargon,\n skippedMethods,\n skippedTestClasses,\n deviceListenerTransport,\n deviceListenerPort,\n deviceListenerTmpFile,\n extraAppArguments,\n extraEnvVariables,\n appEndTag);\n\n var ips = string.Join(\",\", _helpers.GetLocalIpAddresses().Select(ip => ip.ToString()));\n\n args.Add(new SetEnvVariableArgument(EnviromentVariables.HostName, ips));\n args.Add(new DisableMemoryLimitsArgument());\n args.Add(new DeviceNameArgument(device));\n\n if (_listenerFactory.UseTunnel)\n {\n args.Add(new SetEnvVariableArgument(EnviromentVariables.UseTcpTunnel, true));\n }\n\n if (appInformation.Extension.HasValue)\n {\n switch (appInformation.Extension)\n {\n case Extension.TodayExtension:\n args.Add(new LaunchDeviceExtensionArgument(appInformation.LaunchAppPath, appInformation.BundleIdentifier));\n break;\n case Extension.WatchKit2:\n default:\n throw new NotImplementedException();\n }\n }\n else\n {\n args.Add(new LaunchDeviceBundleIdArgument(appInformation));\n }\n\n if (isWatchTarget)\n {\n args.Add(new AttachNativeDebuggerArgument()); // this prevents the watch from backgrounding the app.\n }\n else\n {\n args.Add(new WaitForExitArgument());\n }\n\n return args;\n }", + "start_line": 672, + "end_line": 735, + "start_byte": 26433, + "end_byte": 28540 + }, + { + "name": "GetSimulatorArguments", + "code": "private MlaunchArguments GetSimulatorArguments(\n AppBundleInformation appInformation,\n IDevice simulator,\n XmlResultJargon xmlResultJargon,\n string[]? skippedMethods,\n string[]? skippedTestClasses,\n ListenerTransport deviceListenerTransport,\n int deviceListenerPort,\n string deviceListenerTmpFile,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables)\n {\n var args = GetCommonArguments(\n xmlResultJargon,\n skippedMethods,\n skippedTestClasses,\n deviceListenerTransport,\n deviceListenerPort,\n deviceListenerTmpFile,\n extraAppArguments,\n extraEnvVariables,\n appEndTag: null);\n\n args.Add(new SetEnvVariableArgument(EnviromentVariables.HostName, \"127.0.0.1\"));\n args.Add(new SimulatorUDIDArgument(simulator));\n\n if (appInformation.Extension.HasValue)\n {\n switch (appInformation.Extension)\n {\n case Extension.TodayExtension:\n args.Add(new LaunchSimulatorExtensionArgument(appInformation.LaunchAppPath, appInformation.BundleIdentifier));\n break;\n case Extension.WatchKit2:\n default:\n throw new NotImplementedException();\n }\n }\n else\n {\n args.Add(new LaunchSimulatorBundleArgument(appInformation));\n }\n\n return args;\n }", + "start_line": 626, + "end_line": 670, + "start_byte": 24889, + "end_byte": 26427 + }, + { + "name": "GetCommonArguments", + "code": "private MlaunchArguments GetCommonArguments(\n XmlResultJargon xmlResultJargon,\n string[]? skippedMethods,\n string[]? skippedTestClasses,\n ListenerTransport listenerTransport,\n int listenerPort,\n string listenerTmpFile,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables,\n string? appEndTag)\n {\n var args = new MlaunchArguments();\n\n // Environment variables\n var envVariables = GetEnvVariables(\n xmlResultJargon,\n skippedMethods,\n skippedTestClasses,\n listenerTransport,\n listenerPort,\n listenerTmpFile,\n extraEnvVariables,\n appEndTag);\n\n // Variables passed through --set-env\n args.AddRange(envVariables.Select(pair => new SetEnvVariableArgument(pair.Key, pair.Value)));\n\n // Arguments passed to the iOS app bundle\n args.AddRange(extraAppArguments.Select(arg => new SetAppArgumentArgument(arg)));\n\n return args;\n }", + "start_line": 593, + "end_line": 624, + "start_byte": 23818, + "end_byte": 24883 + }, + { + "name": "GetEnvVariables", + "code": "private Dictionary GetEnvVariables(\n XmlResultJargon xmlResultJargon,\n string[]? skippedMethods,\n string[]? skippedTestClasses,\n ListenerTransport listenerTransport,\n int listenerPort,\n string listenerTmpFile,\n IEnumerable<(string, string)> extraEnvVariables,\n string? appEndTag)\n {\n var variables = new Dictionary\n {\n { EnviromentVariables.AutoExit, \"true\" },\n { EnviromentVariables.HostPort, listenerPort.ToString() },\n\n // Let the runner know that we want to get an XML output and not plain text\n { EnviromentVariables.EnableXmlOutput, \"true\" },\n { EnviromentVariables.XmlVersion, xmlResultJargon.ToString() },\n };\n\n if (skippedMethods?.Any() ?? skippedTestClasses?.Any() ?? false)\n {\n // Do not run all the tests, we are using filters\n variables.Add(EnviromentVariables.RunAllTestsByDefault, \"false\");\n\n // Add the skipped test classes and methods\n if (skippedMethods != null && skippedMethods.Length > 0)\n {\n var skippedMethodsValue = string.Join(',', skippedMethods);\n variables.Add(EnviromentVariables.SkippedMethods, skippedMethodsValue);\n }\n\n if (skippedTestClasses != null && skippedTestClasses!.Length > 0)\n {\n var skippedClassesValue = string.Join(',', skippedTestClasses);\n variables.Add(EnviromentVariables.SkippedClasses, skippedClassesValue);\n }\n }\n\n if (listenerTransport == ListenerTransport.File)\n {\n variables.Add(EnviromentVariables.LogFilePath, listenerTmpFile);\n }\n\n if (appEndTag != null)\n {\n variables.Add(EnviromentVariables.AppEndTag, appEndTag);\n }\n\n AddExtraEnvVars(variables, extraEnvVariables);\n\n return variables;\n }", + "start_line": 539, + "end_line": 591, + "start_byte": 21806, + "end_byte": 23812 + }, + { + "name": "RunMacCatalystTests", + "code": "private async Task<(TestExecutingResult Result, string ResultMessage)> RunMacCatalystTests(\n ListenerTransport deviceListenerTransport,\n ISimpleListener deviceListener,\n string deviceListenerTmpFile,\n AppBundleInformation appInformation,\n ILog appOutputLog,\n TimeSpan timeout,\n TimeSpan testLaunchTimeout,\n XmlResultJargon xmlResultJargon,\n string[]? skippedMethods,\n string[]? skippedTestClasses,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables,\n string? appEndTag,\n CancellationToken cancellationToken)\n {\n var deviceListenerPort = deviceListener.InitializeAndGetPort();\n deviceListener.StartAsync();\n\n using var crashLogs = new Logs(_logs.Directory);\n\n ICrashSnapshotReporter crashReporter = _snapshotReporterFactory.Create(_mainLog, crashLogs, isDevice: false, null);\n using ITestReporter testReporter = _testReporterFactory.Create(\n _mainLog,\n _mainLog,\n _logs,\n crashReporter,\n deviceListener,\n _resultParser,\n appInformation,\n RunMode.MacOS,\n xmlResultJargon,\n null,\n timeout,\n null,\n (level, message) => _mainLog.WriteLine(message));\n\n deviceListener.ConnectedTask\n .TimeoutAfter(testLaunchTimeout)\n .ContinueWith(async (Task task) =>\n {\n testReporter.LaunchCallback(task);\n\n // Stop listening so that TCP doesn't get connected before here and when we evaluate why we failed\n // If no TCP happens, app didn't start in time => APP_LAUNCH_TIMEOUT\n // If TCP connects during this method or right after - a very narrow race condition - we would categorize it as TIMED_OUT\n // because we would consider the app run started and actually timing out.\n if (!deviceListener.ConnectedTask.IsCompleted)\n {\n await deviceListener.StopAsync();\n }\n else if (task.IsCompleted && task.Result)\n {\n ListenerConnected = true;\n }\n }, cancellationToken)\n .DoNotAwait();\n\n _mainLog.WriteLine($\"*** Executing '{appInformation.AppName}' on MacCatalyst ***\");\n\n try\n {\n using var combinedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(testReporter.CancellationToken, cancellationToken);\n\n var envVariables = GetEnvVariables(\n xmlResultJargon,\n skippedMethods,\n skippedTestClasses,\n deviceListenerTransport,\n deviceListenerPort,\n deviceListenerTmpFile,\n extraEnvVariables,\n appEndTag);\n\n envVariables[EnviromentVariables.HostName] = \"127.0.0.1\";\n\n AddExtraEnvVars(envVariables, extraEnvVariables);\n\n await crashReporter.StartCaptureAsync();\n\n var result = await RunMacCatalystApp(appInformation, appOutputLog, timeout, waitForExit: true, extraAppArguments, envVariables, combinedCancellationToken.Token);\n await testReporter.CollectSimulatorResult(result);\n }\n finally\n {\n deviceListener.Cancel();\n }\n\n return await testReporter.ParseResult();\n }", + "start_line": 448, + "end_line": 537, + "start_byte": 18295, + "end_byte": 21800 + }, + { + "name": "RunDeviceTests", + "code": "private async Task RunDeviceTests(\n AppBundleInformation appInformation,\n MlaunchArguments mlaunchArguments,\n ICrashSnapshotReporter crashReporter,\n ITestReporter testReporter,\n IResultFileHandler resultFileHandler,\n ISimpleListener deviceListener,\n IDevice device,\n ILog appOutputLog,\n TimeSpan timeout,\n IEnumerable<(string, string)> extraEnvVariables,\n CancellationToken cancellationToken,\n RunMode runMode)\n {\n var deviceSystemLog = _logs.Create($\"device-{device.Name}-{_helpers.Timestamp}.log\", LogType.SystemLog.ToString());\n deviceSystemLog.Timestamp = false;\n\n var deviceLogCapturer = _deviceLogCapturerFactory.Create(_mainLog, deviceSystemLog, device.Name);\n deviceLogCapturer.StartCapture();\n\n try\n {\n await crashReporter.StartCaptureAsync();\n\n // create a tunnel to communicate with the device\n if (_listenerFactory.UseTunnel && deviceListener is SimpleTcpListener tcpListener)\n {\n // create a new tunnel using the listener\n var tunnel = _listenerFactory.TunnelBore.Create(device.UDID, _mainLog);\n tunnel.Open(device.UDID, tcpListener, timeout, _mainLog);\n // wait until we started the tunnel\n await tunnel.Started;\n }\n\n _mainLog.WriteLine(\"Starting the application\");\n\n var envVars = new Dictionary();\n AddExtraEnvVars(envVars, extraEnvVariables);\n\n // We need to check for MT1111 (which means that mlaunch won't wait for the app to exit)\n IFileBackedLog aggregatedLog = Log.CreateReadableAggregatedLog(_mainLog, testReporter.CallbackLog);\n\n\n var result = await RunAndWatchForAppSignal(() => _processManager.ExecuteCommandAsync(\n mlaunchArguments,\n aggregatedLog,\n appOutputLog,\n appOutputLog,\n timeout,\n envVars,\n cancellationToken: cancellationToken));\n\n await testReporter.CollectDeviceResult(result);\n }\n finally\n {\n deviceLogCapturer.StopCapture();\n deviceSystemLog.Dispose();\n\n // close a tunnel if it was created\n if (_listenerFactory.UseTunnel)\n {\n await _listenerFactory.TunnelBore.Close(device.UDID);\n }\n }\n\n // Upload the system log\n if (File.Exists(deviceSystemLog.FullPath))\n {\n _mainLog.WriteLine(\"Device log captured in {0}\", deviceSystemLog.FullPath);\n }\n\n // On iOS 18 and later, transferring results over a TCP tunnel isn\u2019t supported.\n // Instead, copy the results file from the device to the host machine.\n if (deviceListener.TestLog != null &&\n !await resultFileHandler.CopyResultsAsync(\n runMode,\n false,\n device.OSVersion,\n device.UDID,\n appInformation.BundleIdentifier,\n deviceListener.TestLog.FullPath,\n cancellationToken))\n {\n throw new InvalidOperationException(\"Failed to copy test results from device to host.\");\n }\n }", + "start_line": 357, + "end_line": 443, + "start_byte": 14819, + "end_byte": 18149 + }, + { + "name": "RunSimulatorTests", + "code": "private async Task RunSimulatorTests(\n AppBundleInformation appInformation,\n MlaunchArguments mlaunchArguments,\n ICrashSnapshotReporter crashReporter,\n ITestReporter testReporter,\n IResultFileHandler resultFileHandler,\n ISimpleListener deviceListener,\n ISimulatorDevice simulator,\n ISimulatorDevice? companionSimulator,\n TimeSpan timeout,\n CancellationToken cancellationToken,\n RunMode runMode)\n {\n var result = await RunSimulatorApp(\n appInformation,\n mlaunchArguments,\n crashReporter,\n simulator,\n companionSimulator,\n timeout,\n waitForExit: true,\n cancellationToken);\n\n await testReporter.CollectSimulatorResult(result);\n\n // On iOS 18 and later, transferring results over a TCP tunnel isn\u2019t supported.\n // Instead, copy the results file from the device to the host machine.\n if (deviceListener.TestLog != null &&\n !await resultFileHandler.CopyResultsAsync(\n runMode,\n true,\n simulator.OSVersion,\n simulator.UDID,\n appInformation.BundleIdentifier,\n deviceListener.TestLog.FullPath,\n cancellationToken))\n {\n throw new InvalidOperationException(\"Failed to copy test results from simulator to host.\");\n }\n }", + "start_line": 316, + "end_line": 355, + "start_byte": 13357, + "end_byte": 14813 + }, + { + "name": "TestApp", + "code": "public async Task<(TestExecutingResult Result, string ResultMessage)> TestApp(\n AppBundleInformation appInformation,\n TestTargetOs target,\n IDevice device,\n IDevice? companionDevice,\n TimeSpan timeout,\n TimeSpan testLaunchTimeout,\n bool signalAppEnd,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables,\n XmlResultJargon xmlResultJargon = XmlResultJargon.xUnit,\n string[]? skippedMethods = null,\n string[]? skippedTestClasses = null,\n CancellationToken cancellationToken = default)\n {\n var runMode = target.Platform.ToRunMode();\n var isSimulator = target.Platform.IsSimulator();\n\n var testLog = _logs.Create($\"test-{target.AsString()}-{_helpers.Timestamp}.log\", LogType.TestLog.ToString(), timestamp: false);\n\n ListenerConnected = false;\n var (deviceListenerTransport, deviceListener, deviceListenerTmpFile) = _listenerFactory.Create(\n runMode,\n log: _mainLog,\n testLog: testLog,\n isSimulator: isSimulator,\n autoExit: true,\n xmlOutput: true); // cli always uses xml\n\n using (testLog)\n using (deviceListener)\n {\n var deviceListenerPort = deviceListener.InitializeAndGetPort();\n deviceListener.StartAsync();\n\n using var crashLogs = new Logs(_logs.Directory);\n\n ICrashSnapshotReporter crashReporter = _snapshotReporterFactory.Create(_mainLog, crashLogs, isDevice: !isSimulator, device.Name);\n using ITestReporter testReporter = _testReporterFactory.Create(\n _mainLog,\n _mainLog,\n _logs,\n crashReporter,\n deviceListener,\n _resultParser,\n appInformation,\n runMode,\n xmlResultJargon,\n device.Name,\n timeout,\n null,\n (level, message) => _mainLog.WriteLine(message));\n IResultFileHandler resultFileHandler = new ResultFileHandler(_processManager, _mainLog);\n\n // For iOS 18+ devices/simulators, result files are copied directly from the app container\n // rather than transmitted over TCP. In these cases, we skip the TCP launch timeout logic\n // to prevent test termination when no TCP connection is established.\n if (deviceListener.TestLog != null && !resultFileHandler.IsVersionSupported(device.OSVersion, isSimulator))\n {\n deviceListener.ConnectedTask\n .TimeoutAfter(testLaunchTimeout)\n .ContinueWith(async (Task task) =>\n {\n testReporter.LaunchCallback(task);\n\n // Stop listening so that TCP doesn't get connected before here and when we evaluate why we failed\n // If no TCP happens, app didn't start in time => APP_LAUNCH_TIMEOUT\n // If TCP connects during this method or right after - a very narrow race condition - we would categorize it as TIMED_OUT\n // because we would consider the app run started and actually timing out.\n if (!deviceListener.ConnectedTask.IsCompleted)\n {\n await deviceListener.StopAsync();\n }\n else if (task.IsCompleted && task.Result)\n {\n ListenerConnected = true;\n }\n }, cancellationToken)\n .DoNotAwait();\n }\n\n _mainLog.WriteLine($\"*** Executing '{appInformation.AppName}' on {target.AsString()} '{device.Name}' ***\");\n\n using var combinedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(\n testReporter.CancellationToken,\n cancellationToken);\n cancellationToken = combinedCancellationToken.Token;\n\n if (isSimulator)\n {\n var mlaunchArguments = GetSimulatorArguments(\n appInformation,\n device,\n xmlResultJargon,\n skippedMethods,\n skippedTestClasses,\n deviceListenerTransport,\n deviceListenerPort,\n deviceListenerTmpFile,\n extraAppArguments,\n extraEnvVariables);\n\n await RunSimulatorTests(\n appInformation,\n mlaunchArguments,\n crashReporter,\n testReporter,\n resultFileHandler,\n deviceListener,\n (ISimulatorDevice)device,\n companionDevice as ISimulatorDevice,\n timeout,\n cancellationToken,\n runMode);\n }\n else\n {\n var appOutputLog = _logs.Create(appInformation.BundleIdentifier + \".log\", LogType.ApplicationLog.ToString(), timestamp: true);\n string? appEndTag = null;\n if (signalAppEnd)\n {\n WatchForAppEndTag(out appEndTag, ref appOutputLog, ref cancellationToken);\n }\n\n using (appOutputLog)\n {\n var mlaunchArguments = GetDeviceArguments(\n appInformation,\n device,\n target.Platform.IsWatchOSTarget(),\n xmlResultJargon,\n skippedMethods,\n skippedTestClasses,\n deviceListenerTransport,\n deviceListenerPort,\n deviceListenerTmpFile,\n extraAppArguments,\n extraEnvVariables,\n appEndTag);\n\n await RunDeviceTests(\n appInformation,\n mlaunchArguments,\n crashReporter,\n testReporter,\n resultFileHandler,\n deviceListener,\n device,\n appOutputLog,\n timeout,\n extraEnvVariables,\n cancellationToken,\n runMode);\n }\n }\n\n // Check the final status, copy all the required data\n return await testReporter.ParseResult();\n }\n }", + "start_line": 155, + "end_line": 314, + "start_byte": 6588, + "end_byte": 13351 + }, + { + "name": "TestMacCatalystApp", + "code": "public async Task<(TestExecutingResult Result, string ResultMessage)> TestMacCatalystApp(\n AppBundleInformation appInformation,\n TimeSpan timeout,\n TimeSpan testLaunchTimeout,\n bool signalAppEnd,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables,\n XmlResultJargon xmlResultJargon = XmlResultJargon.xUnit,\n string[]? skippedMethods = null,\n string[]? skippedTestClasses = null,\n CancellationToken cancellationToken = default)\n {\n var testLog = _logs.Create($\"test-{TestTarget.MacCatalyst.AsString()}-{_helpers.Timestamp}.log\", LogType.TestLog.ToString(), timestamp: false);\n var appOutputLog = _logs.Create(appInformation.BundleIdentifier + \".log\", LogType.ApplicationLog.ToString(), timestamp: true);\n\n ListenerConnected = false;\n var (deviceListenerTransport, deviceListener, deviceListenerTmpFile) = _listenerFactory.Create(\n RunMode.MacOS,\n log: _mainLog,\n testLog: testLog,\n isSimulator: true,\n autoExit: true,\n xmlOutput: true);\n\n string? appEndTag = null;\n if (signalAppEnd)\n {\n WatchForAppEndTag(out appEndTag, ref appOutputLog, ref cancellationToken);\n }\n\n using (testLog)\n using (deviceListener)\n {\n var (catalystTestResult, catalystResultMessage) = await RunMacCatalystTests(\n deviceListenerTransport,\n deviceListener,\n deviceListenerTmpFile,\n appInformation,\n appOutputLog,\n timeout,\n testLaunchTimeout,\n xmlResultJargon,\n skippedMethods,\n skippedTestClasses,\n extraAppArguments,\n extraEnvVariables,\n appEndTag,\n cancellationToken);\n\n return (catalystTestResult, catalystResultMessage);\n }\n }", + "start_line": 102, + "end_line": 153, + "start_byte": 4571, + "end_byte": 6582 + }, + { + "name": "TestMacCatalystApp", + "code": "Task<(TestExecutingResult Result, string ResultMessage)> TestMacCatalystApp(\n AppBundleInformation appInformation,\n TimeSpan timeout,\n TimeSpan testLaunchTimeout,\n bool signalAppEnd,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables,\n XmlResultJargon xmlResultJargon = XmlResultJargon.xUnit,\n string[]? skippedMethods = null,\n string[]? skippedTestClasses = null,\n CancellationToken cancellationToken = default);", + "start_line": 42, + "end_line": 52, + "start_byte": 1510, + "end_byte": 2031 + }, + { + "name": "TestApp", + "code": "Task<(TestExecutingResult Result, string ResultMessage)> TestApp(\n AppBundleInformation appInformation,\n TestTargetOs target,\n IDevice device,\n IDevice? companionDevice,\n TimeSpan timeout,\n TimeSpan testLaunchTimeout,\n bool signalAppEnd,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables,\n XmlResultJargon xmlResultJargon = XmlResultJargon.xUnit,\n string[]? skippedMethods = null,\n string[]? skippedTestClasses = null,\n CancellationToken cancellationToken = default);", + "start_line": 27, + "end_line": 40, + "start_byte": 907, + "end_byte": 1504 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/AppOperations/AppRunner.cs": [ + { + "name": "GetDeviceArguments", + "code": "private MlaunchArguments GetDeviceArguments(\n AppBundleInformation appInformation,\n IDevice device,\n bool waitForExit,\n bool isWatchTarget,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables,\n string? appEndTag)\n {\n var args = GetCommonArguments(extraAppArguments, extraEnvVariables, appEndTag);\n\n args.Add(new DisableMemoryLimitsArgument());\n args.Add(new DeviceNameArgument(device));\n\n if (appInformation.Extension.HasValue)\n {\n switch (appInformation.Extension)\n {\n case Extension.TodayExtension:\n args.Add(new LaunchDeviceExtensionArgument(appInformation.LaunchAppPath, appInformation.BundleIdentifier));\n break;\n case Extension.WatchKit2:\n default:\n throw new NotImplementedException();\n }\n }\n else\n {\n args.Add(new LaunchDeviceBundleIdArgument(appInformation));\n }\n\n if (isWatchTarget)\n {\n args.Add(new AttachNativeDebuggerArgument()); // this prevents the watch from backgrounding the app.\n }\n else if (waitForExit)\n {\n args.Add(new WaitForExitArgument());\n }\n\n return args;\n }", + "start_line": 278, + "end_line": 319, + "start_byte": 10084, + "end_byte": 11441 + }, + { + "name": "GetSimulatorArguments", + "code": "private MlaunchArguments GetSimulatorArguments(\n AppBundleInformation appInformation,\n ISimulatorDevice simulator,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables)\n {\n var args = GetCommonArguments(extraAppArguments, extraEnvVariables, appEndTag: null);\n\n args.Add(new SimulatorUDIDArgument(simulator.UDID));\n\n if (appInformation.Extension.HasValue)\n {\n switch (appInformation.Extension)\n {\n case Extension.TodayExtension:\n args.Add(new LaunchSimulatorExtensionArgument(appInformation.LaunchAppPath, appInformation.BundleIdentifier));\n break;\n case Extension.WatchKit2:\n default:\n throw new NotImplementedException();\n }\n }\n else\n {\n args.Add(new LaunchSimulatorBundleArgument(appInformation));\n }\n\n return args;\n }", + "start_line": 248, + "end_line": 276, + "start_byte": 9079, + "end_byte": 10078 + }, + { + "name": "GetCommonArguments", + "code": "private static MlaunchArguments GetCommonArguments(\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables,\n string? appEndTag)\n {\n var args = new MlaunchArguments();\n\n // Arguments passed to the iOS app bundle\n args.AddRange(extraAppArguments.Select(arg => new SetAppArgumentArgument(arg)));\n args.AddRange(extraEnvVariables.Select(v => new SetEnvVariableArgument(v.Item1, v.Item2)));\n\n if (appEndTag != null)\n {\n args.Add(new SetEnvVariableArgument(EnviromentVariables.AppEndTag, appEndTag));\n }\n\n return args;\n }", + "start_line": 229, + "end_line": 246, + "start_byte": 8430, + "end_byte": 9073 + }, + { + "name": "RunDeviceApp", + "code": "private async Task RunDeviceApp(\n MlaunchArguments mlaunchArguments,\n ICrashSnapshotReporter crashReporter,\n IDevice device,\n ILog appOutputLog,\n IEnumerable<(string, string)> extraEnvVariables,\n TimeSpan timeout,\n CancellationToken cancellationToken)\n {\n using var deviceSystemLog = _logs.Create($\"device-{device.Name}-{_helpers.Timestamp}.log\", LogType.SystemLog.ToString());\n using var deviceLogCapturer = _deviceLogCapturerFactory.Create(_mainLog, deviceSystemLog, device.Name);\n deviceLogCapturer.StartCapture();\n\n await crashReporter.StartCaptureAsync();\n\n _mainLog.WriteLine(\"Starting the app\");\n\n var envVars = new Dictionary();\n AddExtraEnvVars(envVars, extraEnvVariables);\n\n return await RunAndWatchForAppSignal(() => _processManager.ExecuteCommandAsync(\n mlaunchArguments,\n _mainLog,\n appOutputLog,\n appOutputLog,\n timeout,\n envVars,\n cancellationToken: cancellationToken));\n }", + "start_line": 199, + "end_line": 227, + "start_byte": 7308, + "end_byte": 8424 + }, + { + "name": "RunApp", + "code": "public async Task RunApp(\n AppBundleInformation appInformation,\n TestTargetOs target,\n IDevice device,\n IDevice? companionDevice,\n TimeSpan timeout,\n bool signalAppEnd,\n bool waitForExit,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables,\n CancellationToken cancellationToken = default)\n {\n ProcessExecutionResult result;\n ISimulatorDevice? simulator;\n ISimulatorDevice? companionSimulator;\n\n var isSimulator = target.Platform.IsSimulator();\n using var crashLogs = new Logs(_logs.Directory);\n\n ICrashSnapshotReporter crashReporter = _snapshotReporterFactory.Create(\n _mainLog,\n crashLogs,\n isDevice: !isSimulator,\n device.Name);\n\n _mainLog.WriteLine($\"*** Executing '{appInformation.AppName}' on {target.AsString()} '{device.Name}' ***\");\n\n\n if (isSimulator)\n {\n simulator = device as ISimulatorDevice;\n companionSimulator = companionDevice as ISimulatorDevice;\n\n if (simulator == null)\n {\n _mainLog.WriteLine(\"Didn't find any suitable simulator\");\n throw new NoDeviceFoundException();\n }\n\n var mlaunchArguments = GetSimulatorArguments(\n appInformation,\n simulator,\n extraAppArguments,\n extraEnvVariables);\n\n result = await RunSimulatorApp(\n appInformation,\n mlaunchArguments,\n crashReporter,\n simulator,\n companionSimulator,\n timeout,\n waitForExit,\n cancellationToken);\n }\n else\n {\n var appOutputLog = _logs.Create(appInformation.BundleIdentifier + \".log\", LogType.ApplicationLog.ToString(), timestamp: true);\n string? appEndTag = null;\n if (signalAppEnd)\n {\n WatchForAppEndTag(out appEndTag, ref appOutputLog, ref cancellationToken);\n }\n\n using (appOutputLog)\n {\n var mlaunchArguments = GetDeviceArguments(\n appInformation,\n device,\n waitForExit: waitForExit,\n isWatchTarget: target.Platform.IsWatchOSTarget(),\n extraAppArguments,\n extraEnvVariables,\n appEndTag);\n\n result = await RunDeviceApp(\n mlaunchArguments,\n crashReporter,\n device,\n appOutputLog,\n extraEnvVariables,\n timeout,\n cancellationToken);\n }\n }\n\n return result;\n }", + "start_line": 110, + "end_line": 197, + "start_byte": 4403, + "end_byte": 7302 + }, + { + "name": "RunMacCatalystApp", + "code": "public async Task RunMacCatalystApp(\n AppBundleInformation appInformation,\n TimeSpan timeout,\n bool signalAppEnd,\n bool waitForExit,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables,\n CancellationToken cancellationToken = default)\n {\n _mainLog.WriteLine($\"*** Executing '{appInformation.AppName}' on MacCatalyst ***\");\n var appOutputLog = _logs.Create(appInformation.BundleIdentifier + \".log\", LogType.ApplicationLog.ToString(), timestamp: true);\n\n var envVariables = new Dictionary();\n AddExtraEnvVars(envVariables, extraEnvVariables);\n\n if (signalAppEnd)\n {\n WatchForAppEndTag(out var appEndTag, ref appOutputLog, ref cancellationToken);\n envVariables.Add(EnviromentVariables.AppEndTag, appEndTag);\n }\n\n using (appOutputLog)\n {\n return await RunAndWatchForAppSignal(() => RunMacCatalystApp(\n appInformation,\n appOutputLog,\n timeout,\n waitForExit,\n extraAppArguments ?? Enumerable.Empty(),\n envVariables,\n cancellationToken));\n }\n }", + "start_line": 76, + "end_line": 108, + "start_byte": 3113, + "end_byte": 4397 + }, + { + "name": "RunMacCatalystApp", + "code": "Task RunMacCatalystApp(\n AppBundleInformation appInformation,\n TimeSpan timeout,\n bool signalAppEnd,\n bool waitForExit,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables,\n CancellationToken cancellationToken = default);", + "start_line": 35, + "end_line": 42, + "start_byte": 1216, + "end_byte": 1547 + }, + { + "name": "RunApp", + "code": "Task RunApp(\n AppBundleInformation appInformation,\n TestTargetOs target,\n IDevice device,\n IDevice? companionDevice,\n TimeSpan timeout,\n bool signalAppEnd,\n bool waitForExit,\n IEnumerable extraAppArguments,\n IEnumerable<(string, string)> extraEnvVariables,\n CancellationToken cancellationToken = default);", + "start_line": 23, + "end_line": 33, + "start_byte": 803, + "end_byte": 1210 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/AppOperations/AppInstaller.cs": [ + { + "name": "InstallApp", + "code": "public async Task InstallApp(\n AppBundleInformation appBundleInformation,\n TestTargetOs target,\n IDevice device,\n CancellationToken cancellationToken = default)\n {\n if (!Directory.Exists(appBundleInformation.LaunchAppPath))\n {\n throw new DirectoryNotFoundException(\"Failed to find the app bundle directory\");\n }\n\n var args = new MlaunchArguments();\n\n if (target.Platform.IsSimulator())\n {\n args.Add(new SimulatorUDIDArgument(device));\n args.Add(new InstallAppOnSimulatorArgument(appBundleInformation.LaunchAppPath));\n }\n else\n {\n args.Add(new DeviceNameArgument(device));\n args.Add(new InstallAppOnDeviceArgument(appBundleInformation.LaunchAppPath));\n\n if (target.Platform.IsWatchOSTarget())\n {\n args.Add(new DeviceArgument(\"ios,watchos\"));\n }\n }\n\n var totalSize = Directory.GetFiles(appBundleInformation.LaunchAppPath, \"*\", SearchOption.AllDirectories).Select((v) => new FileInfo(v).Length).Sum();\n _mainLog.WriteLine($\"Installing '{appBundleInformation.LaunchAppPath}' to '{device.Name}' ({totalSize / 1024.0 / 1024.0:N2} MB)\");\n\n return await _processManager.ExecuteCommandAsync(args, _mainLog, TimeSpan.FromMinutes(15), verbosity: 2, cancellationToken: cancellationToken);\n }", + "start_line": 38, + "end_line": 71, + "start_byte": 1263, + "end_byte": 2694 + }, + { + "name": "InstallApp", + "code": "Task InstallApp(\n AppBundleInformation appBundleInformation,\n TestTargetOs target,\n IDevice device,\n CancellationToken cancellationToken = default);", + "start_line": 20, + "end_line": 24, + "start_byte": 642, + "end_byte": 842 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/AppOperations/AppRunnerBase.cs": [ + { + "name": "CaptureLogStream", + "code": "private CancellationTokenSource CaptureLogStream(string appName, bool useSimctl, IEnumerable args, CancellationToken cancellationToken)\n {\n var logReadTokenSource = new CancellationTokenSource();\n var log = _logs.Create($\"{appName}.log\", LogType.SystemLog.ToString(), timestamp: false);\n var logArgs = args.Concat(new[]\n {\n \"stream\",\n \"--level=debug\",\n \"--color=none\",\n \"--style=compact\",\n \"--predicate\",\n $\"senderImagePath contains '{appName}'\"\n }).ToArray();\n\n _mainLog.WriteLine($\"Scanning log stream for {appName} into '{log.FullPath}'..\");\n\n var streamCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, logReadTokenSource.Token).Token;\n\n if (useSimctl)\n {\n _processManager\n .ExecuteXcodeCommandAsync(\"simctl\", logArgs, _mainLog, log, log, TimeSpan.FromDays(1), cancellationToken: streamCancellation)\n .DoNotAwait();\n }\n else\n {\n _processManager\n .ExecuteCommandAsync(\"log\", logArgs, _mainLog, log, log, TimeSpan.FromDays(1), cancellationToken: streamCancellation)\n .DoNotAwait();\n }\n\n logReadTokenSource.Token.Register(log.Dispose);\n\n return logReadTokenSource;\n }", + "start_line": 304, + "end_line": 338, + "start_byte": 12340, + "end_byte": 13707 + }, + { + "name": "CaptureSimulatorLog", + "code": "protected async Task CaptureSimulatorLog(\n ISimulatorDevice simulator,\n AppBundleInformation appInformation,\n CancellationToken cancellationToken)\n {\n if (!await simulator.Boot(_mainLog, cancellationToken))\n {\n _mainLog.WriteLine($\"Failed to boot simulator {simulator.Name} in time! Exit code detection might fail\");\n }\n\n var appName = appInformation.BundleExecutable ?? appInformation.AppName;\n\n return CaptureLogStream(appName, true, new[] { \"spawn\", simulator.UDID, \"log\" }, cancellationToken);\n }", + "start_line": 289, + "end_line": 302, + "start_byte": 11736, + "end_byte": 12334 + }, + { + "name": "CaptureMacCatalystLog", + "code": "protected CancellationTokenSource CaptureMacCatalystLog(AppBundleInformation appInformation, CancellationToken cancellationToken) =>\n CaptureLogStream(appInformation.BundleExecutable ?? appInformation.AppName, false, Array.Empty(), cancellationToken);", + "start_line": 282, + "end_line": 283, + "start_byte": 11172, + "end_byte": 11438 + }, + { + "name": "RunAndWatchForAppSignal", + "code": "protected async Task RunAndWatchForAppSignal(Func> action)\n {\n var result = await action();\n\n // When signal is detected, we cancel the call above via the cancellation token so we need to fix the result\n if (_appEndSignalDetected)\n {\n result.TimedOut = false;\n result.ExitCode = 0;\n }\n\n return result;\n }", + "start_line": 264, + "end_line": 276, + "start_byte": 10447, + "end_byte": 10874 + }, + { + "name": "WatchForAppEndTag", + "code": "protected string WatchForAppEndTag(\n out string tag,\n ref IFileBackedLog appLog,\n ref CancellationToken cancellationToken)\n {\n tag = _helpers.GenerateGuid().ToString();\n var appEndDetected = new CancellationTokenSource();\n var appEndScanner = new ScanLog(tag, () =>\n {\n _mainLog.WriteLine(\"Detected test end tag in application's output\");\n _appEndSignalDetected = true;\n appEndDetected.Cancel();\n });\n\n // We need to check for test end tag since iOS 14+ doesn't send the pidDiedCallback event to mlaunch\n appLog = Log.CreateReadableAggregatedLog(appLog, appEndScanner);\n cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, appEndDetected.Token).Token;\n\n return tag;\n }", + "start_line": 243, + "end_line": 262, + "start_byte": 9615, + "end_byte": 10441 + }, + { + "name": "AddExtraEnvVars", + "code": "protected void AddExtraEnvVars(Dictionary envVariables, IEnumerable<(string, string)> variables)\n {\n using (var enumerator = variables.GetEnumerator())\n {\n while (enumerator.MoveNext())\n {\n var (name, value) = enumerator.Current;\n if (envVariables.ContainsKey(name))\n {\n _mainLog.WriteLine($\"Environmental variable {name} is already passed to the application to drive test run, skipping..\");\n continue;\n }\n\n envVariables[name] = value;\n }\n }\n }", + "start_line": 225, + "end_line": 241, + "start_byte": 8976, + "end_byte": 9609 + }, + { + "name": "RunSimulatorApp", + "code": "protected async Task RunSimulatorApp(\n AppBundleInformation appInformation,\n MlaunchArguments mlaunchArguments,\n ICrashSnapshotReporter crashReporter,\n ISimulatorDevice simulator,\n ISimulatorDevice? companionSimulator,\n TimeSpan timeout,\n bool waitForExit,\n CancellationToken cancellationToken)\n {\n _mainLog.WriteLine(\"System log for the '{1}' simulator is: {0}\", simulator.SystemLog, simulator.Name);\n\n var simulatorLog = _captureLogFactory.Create(\n path: Path.Combine(_logs.Directory, simulator.Name + \".log\"),\n systemLogPath: simulator.SystemLog,\n entireFile: false,\n LogType.SystemLog);\n\n simulatorLog.StartCapture();\n _logs.Add(simulatorLog);\n\n var simulatorScanToken = await CaptureSimulatorLog(simulator, appInformation, cancellationToken);\n\n using var systemLogs = new DisposableList\n {\n simulatorLog\n };\n\n if (companionSimulator != null)\n {\n _mainLog.WriteLine(\"System log for the '{1}' companion simulator is: {0}\", companionSimulator.SystemLog, companionSimulator.Name);\n\n var companionLog = _captureLogFactory.Create(\n path: Path.Combine(_logs.Directory, companionSimulator.Name + \".log\"),\n systemLogPath: companionSimulator.SystemLog,\n entireFile: false,\n LogType.CompanionSystemLog);\n\n companionLog.StartCapture();\n _logs.Add(companionLog);\n systemLogs.Add(companionLog);\n\n var companionScanToken = await CaptureSimulatorLog(companionSimulator, appInformation, cancellationToken);\n if (companionScanToken != null)\n {\n simulatorScanToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, companionScanToken.Token);\n }\n }\n\n await crashReporter.StartCaptureAsync();\n\n _mainLog.WriteLine(\"Launching the app\");\n\n if (waitForExit)\n {\n var result = await _processManager.ExecuteCommandAsync(mlaunchArguments, _mainLog, timeout, cancellationToken: cancellationToken);\n simulatorScanToken?.Cancel();\n return result;\n }\n\n TaskCompletionSource appLaunched = new();\n var scanLog = new ScanLog($\"Launched {appInformation.BundleIdentifier} with pid\", () =>\n {\n _mainLog.WriteLine(\"App launch detected\");\n appLaunched.SetResult();\n });\n\n _mainLog.WriteLine(\"Waiting for the app to launch..\");\n\n var runTask = _processManager.ExecuteCommandAsync(mlaunchArguments, Log.CreateAggregatedLog(_mainLog, scanLog), timeout, cancellationToken: cancellationToken);\n await Task.WhenAny(runTask, appLaunched.Task);\n\n if (!appLaunched.Task.IsCompleted)\n {\n // In case the other task completes first, it is because one of these scenarios happened:\n // - The app crashed and never launched\n // - We missed the launch signal somehow and the app timed out\n // - The app launched and quit immediately and race condition noticed that before the scan log did its job\n // In all cases, we should return the result of the run task, it will be most likely 137 + Timeout (killed by us)\n // If not, it will be a success because the app ran for a super short amount of time\n _mainLog.WriteLine(\"App launch was not detected in time\");\n return runTask.Result;\n }\n\n _mainLog.WriteLine(\"Not waiting for the app to exit\");\n\n return new ProcessExecutionResult\n {\n ExitCode = 0\n };\n }", + "start_line": 128, + "end_line": 218, + "start_byte": 4917, + "end_byte": 8678 + }, + { + "name": "RunMacCatalystApp", + "code": "protected async Task RunMacCatalystApp(\n AppBundleInformation appInformation,\n ILog appOutputLog,\n TimeSpan timeout,\n bool waitForExit,\n IEnumerable extraArguments,\n Dictionary environmentVariables,\n CancellationToken cancellationToken)\n {\n using var systemLog = _captureLogFactory.Create(\n path: _logs.CreateFile(\"MacCatalyst.system.log\", LogType.SystemLog),\n systemLogPath: SystemLogPath,\n entireFile: false,\n LogType.SystemLog);\n\n // We need to make the binary executable\n var binaryPath = Path.Combine(appInformation.AppPath, \"Contents\", \"MacOS\", appInformation.BundleExecutable ?? appInformation.AppName);\n if (File.Exists(binaryPath))\n {\n await _processManager.ExecuteCommandAsync(\"chmod\", new[] { \"+x\", binaryPath }, _mainLog, TimeSpan.FromSeconds(10), cancellationToken: cancellationToken);\n }\n\n // On Big Sur it seems like the launch services database is not updated fast enough after we do some I/O with the app bundle.\n // Force registration for the app by running\n // /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f /path/to/app.app\n var lsRegisterPath = @\"/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister\";\n await _processManager.ExecuteCommandAsync(lsRegisterPath, new[] { \"-f\", appInformation.LaunchAppPath }, _mainLog, TimeSpan.FromSeconds(10), cancellationToken: cancellationToken);\n\n var arguments = new List\n {\n \"-n\" // Open a new instance of the application(s) even if one is already running.\n };\n\n if (waitForExit)\n {\n // Wait until the applications exit (even if they were already open)\n arguments.Add(\"-W\");\n }\n\n arguments.Add(appInformation.LaunchAppPath);\n arguments.AddRange(extraArguments);\n\n systemLog.StartCapture();\n\n var logStreamScanToken = CaptureMacCatalystLog(appInformation, cancellationToken);\n\n try\n {\n return await _processManager.ExecuteCommandAsync(\n \"open\",\n arguments,\n _mainLog,\n appOutputLog,\n appOutputLog,\n timeout,\n environmentVariables,\n cancellationToken);\n }\n finally\n {\n if (waitForExit)\n {\n systemLog.StopCapture(waitIfEmpty: TimeSpan.FromSeconds(10));\n }\n\n // Stop scanning the logs\n logStreamScanToken.Cancel();\n }\n }", + "start_line": 58, + "end_line": 126, + "start_byte": 2134, + "end_byte": 4911 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/AppOperations/AppTesterFactory.cs": [ + { + "name": "Create", + "code": "public IAppTester Create(\n CommunicationChannel communicationChannel,\n bool isSimulator,\n IFileBackedLog log,\n ILogs logs,\n Action? logCallback,\n Version? osVersion)\n {\n // On iOS 18 and later, transferring results over a TCP tunnel isn\u2019t supported.\n var tunnelBore = (communicationChannel == CommunicationChannel.UsbTunnel && !isSimulator && osVersion !=null && osVersion.Major < 18)\n ? new TunnelBore(_processManager)\n : null;\n\n return new AppTester(\n _processManager,\n new SimpleListenerFactory(tunnelBore),\n _snapshotReporterFactory,\n _captureLogFactory,\n _deviceLogCapturerFactory,\n _reporterFactory,\n _resultParser,\n log,\n logs,\n _helpers,\n logCallback);\n }", + "start_line": 48, + "end_line": 73, + "start_byte": 2371, + "end_byte": 3256 + }, + { + "name": "Create", + "code": "IAppTester Create(CommunicationChannel communicationChannel, bool isSimulator, IFileBackedLog log, ILogs logs, Action? logCallback, Version? osVersion);", + "start_line": 17, + "end_line": 17, + "start_byte": 613, + "end_byte": 773 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/AppOperations/AppRunnerFactory.cs": [ + { + "name": "Create", + "code": "public IAppRunner Create(IFileBackedLog log, ILogs logs, Action? logCallback) =>\n new AppRunner(_processManager, _snapshotReporterFactory, _captureLogFactory, _deviceLogCapturerFactory, log, logs, _helpers, logCallback);", + "start_line": 40, + "end_line": 41, + "start_byte": 1801, + "end_byte": 2036 + }, + { + "name": "Create", + "code": "IAppRunner Create(IFileBackedLog log, ILogs logs, Action? logCallback);", + "start_line": 15, + "end_line": 15, + "start_byte": 515, + "end_byte": 594 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/AppOperations/AppUninstaller.cs": [ + { + "name": "UninstallDeviceApp", + "code": "public Task UninstallDeviceApp(IHardwareDevice device, string appBundleId, CancellationToken cancellationToken = default)\n {\n var args = new MlaunchArguments\n {\n new UninstallAppFromDeviceArgument(appBundleId),\n new DeviceNameArgument(device)\n };\n\n return _processManager.ExecuteCommandAsync(args, _mainLog, TimeSpan.FromMinutes(3), cancellationToken: cancellationToken);\n }", + "start_line": 40, + "end_line": 49, + "start_byte": 1688, + "end_byte": 2158 + }, + { + "name": "UninstallSimulatorApp", + "code": "public Task UninstallSimulatorApp(ISimulatorDevice simulator, string appBundleId, CancellationToken cancellationToken = default)\n => _processManager.ExecuteXcodeCommandAsync(\n \"simctl\",\n new[] { \"uninstall\", simulator.UDID, appBundleId },\n _mainLog,\n TimeSpan.FromMinutes(3),\n cancellationToken: cancellationToken);", + "start_line": 32, + "end_line": 38, + "start_byte": 1281, + "end_byte": 1682 + }, + { + "name": "UninstallDeviceApp", + "code": "Task UninstallDeviceApp(IHardwareDevice device, string appBundleId, CancellationToken cancellationToken = default);", + "start_line": 18, + "end_line": 18, + "start_byte": 715, + "end_byte": 854 + }, + { + "name": "UninstallSimulatorApp", + "code": "Task UninstallSimulatorApp(ISimulatorDevice simulator, string appBundleId, CancellationToken cancellationToken = default);", + "start_line": 17, + "end_line": 17, + "start_byte": 564, + "end_byte": 710 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/Orchestration/JustRunOrchestrator.cs": [ + { + "name": "UninstallApp", + "code": "protected override Task UninstallApp(TestTarget target, string bundleIdentifier, IDevice device, bool isPreparation, CancellationToken cancellationToken)\n => Task.FromResult(ExitCode.SUCCESS);", + "start_line": 98, + "end_line": 99, + "start_byte": 3970, + "end_byte": 4179 + }, + { + "name": "InstallApp", + "code": "protected override Task InstallApp(AppBundleInformation appBundleInfo, IDevice device, TestTargetOs target, CancellationToken cancellationToken)\n => Task.FromResult(ExitCode.SUCCESS);", + "start_line": 95, + "end_line": 96, + "start_byte": 3725, + "end_byte": 3925 + }, + { + "name": "CleanUpSimulators", + "code": "protected override Task CleanUpSimulators(IDevice device, IDevice? companionDevice)\n => Task.CompletedTask;", + "start_line": 92, + "end_line": 93, + "start_byte": 3521, + "end_byte": 3635 + }, + { + "name": "OrchestrateRun", + "code": "Task IJustRunOrchestrator.OrchestrateRun(\n string bundleIdentifier,\n TestTargetOs target,\n string? deviceName,\n TimeSpan timeout,\n TimeSpan launchTimeout,\n int expectedExitCode,\n bool includeWirelessDevices,\n bool enableLldb,\n bool signalAppEnd,\n bool waitForExit,\n IReadOnlyCollection<(string, string)> environmentalVariables,\n IEnumerable passthroughArguments,\n CancellationToken cancellationToken)\n => OrchestrateRun(\n (target, device, cancellationToken) => GetAppBundleFromId(target, device, bundleIdentifier, cancellationToken),\n target,\n deviceName,\n timeout: timeout,\n launchTimeout: launchTimeout,\n expectedExitCode,\n includeWirelessDevices: includeWirelessDevices,\n resetSimulator: false, // No simulator reset for just- commands\n enableLldb: enableLldb,\n signalAppEnd: signalAppEnd,\n waitForExit: waitForExit,\n environmentalVariables,\n passthroughArguments,\n cancellationToken);", + "start_line": 62, + "end_line": 90, + "start_byte": 2357, + "end_byte": 3515 + }, + { + "name": "OrchestrateRun", + "code": "Task OrchestrateRun(\n string bundleIdentifier,\n TestTargetOs target,\n string? deviceName,\n TimeSpan timeout,\n TimeSpan launchTimeout,\n int expectedExitCode,\n bool includeWirelessDevices,\n bool enableLldb,\n bool signalAppEnd,\n bool waitForExit,\n IReadOnlyCollection<(string, string)> environmentalVariables,\n IEnumerable passthroughArguments,\n CancellationToken cancellationToken);", + "start_line": 21, + "end_line": 34, + "start_byte": 733, + "end_byte": 1222 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/Orchestration/SimulatorResetOrchestrator.cs": [ + { + "name": "ParseFromProject", + "code": "public Task ParseFromProject(string projectFilePath, TestTarget target, string buildConfiguration)\n => Task.FromResult(new AppBundleInformation(string.Empty, string.Empty, string.Empty, string.Empty, false));", + "start_line": 94, + "end_line": 95, + "start_byte": 4198, + "end_byte": 4439 + }, + { + "name": "ParseFromAppBundle", + "code": "public Task ParseFromAppBundle(string appPackagePath, TestTarget target, ILog log, CancellationToken cancellationToken = default)\n => Task.FromResult(new AppBundleInformation(string.Empty, string.Empty, string.Empty, string.Empty, false));", + "start_line": 91, + "end_line": 92, + "start_byte": 3916, + "end_byte": 4188 + }, + { + "name": "CleanUpSimulators", + "code": "protected override Task CleanUpSimulators(IDevice device, IDevice? companionDevice)\n => Task.CompletedTask;", + "start_line": 85, + "end_line": 86, + "start_byte": 3502, + "end_byte": 3616 + }, + { + "name": "UninstallApp", + "code": "protected override Task UninstallApp(TestTarget target, string bundleIdentifier, IDevice device, bool isPreparation, CancellationToken cancellationToken)\n => Task.FromResult(ExitCode.SUCCESS);", + "start_line": 82, + "end_line": 83, + "start_byte": 3240, + "end_byte": 3449 + }, + { + "name": "InstallApp", + "code": "protected override Task InstallApp(AppBundleInformation appBundleInfo, IDevice device, TestTargetOs target, CancellationToken cancellationToken)\n => Task.FromResult(ExitCode.SUCCESS);", + "start_line": 79, + "end_line": 80, + "start_byte": 2987, + "end_byte": 3187 + }, + { + "name": "OrchestrateSimulatorReset", + "code": "public Task OrchestrateSimulatorReset(\n TestTargetOs target,\n string? deviceName,\n TimeSpan timeout,\n CancellationToken cancellationToken)\n {\n if (!target.Platform.IsSimulator() || target.Platform.ToRunMode() == RunMode.MacOS)\n {\n _consoleLogger.LogError($\"The simulator reset action requires a simulator target while {target.AsString()} specified\");\n return Task.FromResult(ExitCode.INVALID_ARGUMENTS);\n }\n\n static Task ExecuteMacCatalystApp(AppBundleInformation appBundleInfo)\n => throw new InvalidOperationException(\"reset-simulator command not available on maccatalyst\");\n\n static Task ExecuteApp(AppBundleInformation appBundleInfo, IDevice device, IDevice? companionDevice)\n => Task.FromResult(ExitCode.SUCCESS); // no-op\n\n return OrchestrateOperation(\n target,\n deviceName,\n includeWirelessDevices: false,\n resetSimulator: true,\n enableLldb: false,\n (_, __, ___) => Task.FromResult(AppBundleInformation.FromBundleId(string.Empty)), // This is not really needed for this command\n ExecuteMacCatalystApp,\n ExecuteApp,\n cancellationToken);\n }", + "start_line": 49, + "end_line": 77, + "start_byte": 1688, + "end_byte": 2981 + }, + { + "name": "OrchestrateSimulatorReset", + "code": "Task OrchestrateSimulatorReset(\n TestTargetOs target,\n string? deviceName,\n TimeSpan timeout,\n CancellationToken cancellationToken);", + "start_line": 20, + "end_line": 24, + "start_byte": 706, + "end_byte": 876 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/Orchestration/UninstallOrchestrator.cs": [ + { + "name": "UninstallApp", + "code": "protected override Task UninstallApp(TestTarget target, string bundleIdentifier, IDevice device, bool isPreparation, CancellationToken cancellationToken)\n {\n // For the uninstallation, we don't want to uninstall twice so we skip the preparation one\n if (isPreparation)\n {\n return Task.FromResult(ExitCode.SUCCESS);\n }\n\n return base.UninstallApp(target, bundleIdentifier, device, isPreparation, cancellationToken);\n }", + "start_line": 82, + "end_line": 91, + "start_byte": 3079, + "end_byte": 3557 + }, + { + "name": "InstallApp", + "code": "protected override Task InstallApp(AppBundleInformation appBundleInfo, IDevice device, TestTargetOs target, CancellationToken cancellationToken)\n => Task.FromResult(ExitCode.SUCCESS);", + "start_line": 79, + "end_line": 80, + "start_byte": 2828, + "end_byte": 3028 + }, + { + "name": "OrchestrateAppUninstall", + "code": "public Task OrchestrateAppUninstall(\n string bundleIdentifier,\n TestTargetOs target,\n string? deviceName,\n TimeSpan timeout,\n bool includeWirelessDevices,\n bool resetSimulator,\n bool enableLldb,\n CancellationToken cancellationToken)\n {\n static Task ExecuteMacCatalystApp(AppBundleInformation appBundleInfo)\n => throw new InvalidOperationException(\"uninstall command not available on maccatalyst\");\n\n static Task ExecuteApp(AppBundleInformation appBundleInfo, IDevice device, IDevice? companionDevice)\n => Task.FromResult(ExitCode.SUCCESS); // no-op\n\n return OrchestrateOperation(\n target,\n deviceName,\n includeWirelessDevices,\n resetSimulator,\n enableLldb,\n (target, device, cancellationToken) => GetAppBundleFromId(target, device, bundleIdentifier, cancellationToken),\n ExecuteMacCatalystApp,\n ExecuteApp,\n cancellationToken);\n }", + "start_line": 51, + "end_line": 77, + "start_byte": 1758, + "end_byte": 2822 + }, + { + "name": "OrchestrateAppUninstall", + "code": "Task OrchestrateAppUninstall(\n string bundleIdentifier,\n TestTargetOs target,\n string? deviceName,\n TimeSpan timeout,\n bool includeWirelessDevices,\n bool resetSimulator,\n bool enableLldb,\n CancellationToken cancellationToken);", + "start_line": 20, + "end_line": 28, + "start_byte": 701, + "end_byte": 993 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/Orchestration/JustTestOrchestrator.cs": [ + { + "name": "UninstallApp", + "code": "protected override Task UninstallApp(TestTarget target, string bundleIdentifier, IDevice device, bool isPreparation, CancellationToken cancellationToken)\n => Task.FromResult(ExitCode.SUCCESS);", + "start_line": 105, + "end_line": 106, + "start_byte": 4210, + "end_byte": 4419 + }, + { + "name": "InstallApp", + "code": "protected override Task InstallApp(AppBundleInformation appBundleInfo, IDevice device, TestTargetOs target, CancellationToken cancellationToken)\n => Task.FromResult(ExitCode.SUCCESS);", + "start_line": 102, + "end_line": 103, + "start_byte": 3965, + "end_byte": 4165 + }, + { + "name": "CleanUpSimulators", + "code": "protected override Task CleanUpSimulators(IDevice device, IDevice? companionDevice)\n => Task.CompletedTask;", + "start_line": 99, + "end_line": 100, + "start_byte": 3761, + "end_byte": 3875 + }, + { + "name": "OrchestrateTest", + "code": "Task IJustTestOrchestrator.OrchestrateTest(\n string bundleIdentifier,\n TestTargetOs target,\n string? deviceName,\n TimeSpan timeout,\n TimeSpan launchTimeout,\n CommunicationChannel communicationChannel,\n XmlResultJargon xmlResultJargon,\n IEnumerable singleMethodFilters,\n IEnumerable classMethodFilters,\n bool includeWirelessDevices,\n bool enableLldb,\n bool signalAppEnd,\n IReadOnlyCollection<(string, string)> environmentalVariables,\n IEnumerable passthroughArguments,\n CancellationToken cancellationToken)\n => OrchestrateTest(\n (target, device, ct) => GetAppBundleFromId(target, device, bundleIdentifier, ct),\n target,\n deviceName,\n timeout,\n launchTimeout,\n communicationChannel,\n xmlResultJargon,\n singleMethodFilters,\n classMethodFilters,\n includeWirelessDevices,\n resetSimulator: false, // No simulator reset for just- commands\n enableLldb,\n signalAppEnd,\n environmentalVariables,\n passthroughArguments,\n cancellationToken);", + "start_line": 65, + "end_line": 97, + "start_byte": 2505, + "end_byte": 3755 + }, + { + "name": "OrchestrateTest", + "code": "Task OrchestrateTest(\n string bundleIdentifier,\n TestTargetOs target,\n string? deviceName,\n TimeSpan timeout,\n TimeSpan launchTimeout,\n CommunicationChannel communicationChannel,\n XmlResultJargon xmlResultJargon,\n IEnumerable singleMethodFilters,\n IEnumerable classMethodFilters,\n bool includeWirelessDevices,\n bool enableLldb,\n bool signalAppEnd,\n IReadOnlyCollection<(string, string)> environmentalVariables,\n IEnumerable passthroughArguments,\n CancellationToken cancellationToken);", + "start_line": 21, + "end_line": 36, + "start_byte": 734, + "end_byte": 1357 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/Orchestration/TestOrchestrator.cs": [ + { + "name": "CopyLogsToMainLog", + "code": "private void CopyLogsToMainLog()\r\n {\r\n var logs = _logs.Where(log => log.Description == LogType.SystemLog.ToString() || log.Description == LogType.ApplicationLog.ToString()).ToList();\r\n\r\n foreach (var log in logs)\r\n {\r\n _mainLog.WriteLine($\"==================== {log.Description} ====================\");\r\n _mainLog.WriteLine($\"Log file: {log.FullPath}\");\r\n\r\n try\r\n {\r\n // Read and append log content to the main log\r\n using var reader = log.GetReader();\r\n while (!reader.EndOfStream)\r\n {\r\n var logContent = reader.ReadLine();\r\n if (logContent is null)\r\n continue;\r\n _mainLog.WriteLine(logContent);\r\n }\r\n }\r\n catch (Exception ex)\r\n {\r\n _mainLog.WriteLine($\"Failed to read {log.Description}: {ex.Message}\");\r\n }\r\n\r\n _mainLog.WriteLine($\"==================== End of {log.Description} ====================\");\r\n _mainLog.WriteLine(string.Empty);\r\n }\r\n }", + "start_line": 385, + "end_line": 414, + "start_byte": 16455, + "end_byte": 17617 + }, + { + "name": "ParseResult", + "code": "private ExitCode ParseResult(TestExecutingResult testResult, string resultMessage, bool listenerConnected)\r\n {\r\n string newLine = Environment.NewLine;\r\n const string checkLogsMessage = \"Check logs for more information\";\r\n bool tcpErrorFound = false;\r\n\r\n ExitCode LogProblem(string message, ExitCode defaultExitCode)\r\n {\r\n foreach (var log in _logs)\r\n {\r\n if (_errorKnowledgeBase.IsKnownTestIssue(log, out var issue))\r\n {\r\n if (!listenerConnected && issue.SuggestedExitCode.HasValue && (ExitCode)issue.SuggestedExitCode.Value == ExitCode.TCP_CONNECTION_FAILED)\r\n {\r\n tcpErrorFound = true;\r\n }\r\n else\r\n {\r\n _logger.LogError(message + newLine + issue.HumanMessage);\r\n return issue.SuggestedExitCode.HasValue ? (ExitCode)issue.SuggestedExitCode.Value : defaultExitCode;\r\n }\r\n }\r\n }\r\n\r\n if (resultMessage != null)\r\n {\r\n _logger.LogError(message + newLine + resultMessage + newLine + newLine + checkLogsMessage);\r\n }\r\n else\r\n {\r\n _logger.LogError(message + newLine + checkLogsMessage);\r\n }\r\n\r\n // TCP errors are encounter all the time but they are not always the cause of the failure\r\n // If the app crashed, TCP_CONNECTION_FAILED and there was not other exit code we will return TCP_CONNECTION_FAILED\r\n if (defaultExitCode == ExitCode.APP_CRASH && tcpErrorFound)\r\n {\r\n return ExitCode.TCP_CONNECTION_FAILED;\r\n }\r\n\r\n return defaultExitCode;\r\n }\r\n\r\n switch (testResult)\r\n {\r\n case TestExecutingResult.Succeeded:\r\n _logger.LogInformation($\"Application finished the test run successfully\");\r\n _logger.LogInformation(resultMessage);\r\n return ExitCode.SUCCESS;\r\n\r\n case TestExecutingResult.Failed:\r\n _logger.LogInformation($\"Application finished the test run successfully with some failed tests\");\r\n _logger.LogInformation(resultMessage);\r\n return ExitCode.TESTS_FAILED;\r\n\r\n case TestExecutingResult.LaunchFailure:\r\n return LogProblem(\"Failed to launch the application\", ExitCode.APP_LAUNCH_FAILURE);\r\n\r\n case TestExecutingResult.Crashed:\r\n return LogProblem(\"Application test run crashed\", ExitCode.APP_CRASH);\r\n\r\n case TestExecutingResult.LaunchTimedOut:\r\n _logger.LogError(\"Application launch timed out before the test execution has started\");\r\n return ExitCode.APP_LAUNCH_TIMEOUT;\r\n\r\n case TestExecutingResult.TimedOut:\r\n _logger.LogWarning($\"Application test run timed out\");\r\n return ExitCode.TIMED_OUT;\r\n\r\n default:\r\n _logger.LogError($\"Application test run ended in an unexpected way: '{testResult}'\" +\r\n newLine + (resultMessage != null ? resultMessage + newLine + newLine : null) + checkLogsMessage);\r\n return ExitCode.GENERAL_FAILURE;\r\n }\r\n }", + "start_line": 306, + "end_line": 380, + "start_byte": 12961, + "end_byte": 16316 + }, + { + "name": "GetAppTester", + "code": "private IAppTester GetAppTester(CommunicationChannel communicationChannel, bool isSimulator, Version? osVersion)\r\n {\r\n // Only add the extra callback if we do know that the feature was indeed enabled\r\n Action? logCallback = IsLldbEnabled() ? (l) => NotifyUserLldbCommand(_logger, l) : null;\r\n\r\n return _appTesterFactory.Create(communicationChannel, isSimulator, _mainLog, _logs, logCallback, osVersion);\r\n }", + "start_line": 298, + "end_line": 304, + "start_byte": 12511, + "end_byte": 12953 + }, + { + "name": "ExecuteMacCatalystApp", + "code": "private async Task ExecuteMacCatalystApp(\r\n AppBundleInformation appBundleInfo,\r\n TimeSpan timeout,\r\n TimeSpan launchTimeout,\r\n CommunicationChannel communicationChannel,\r\n XmlResultJargon xmlResultJargon,\r\n IEnumerable singleMethodFilters,\r\n IEnumerable classMethodFilters,\r\n IReadOnlyCollection<(string, string)> environmentalVariables,\r\n IEnumerable passthroughArguments,\r\n bool signalAppEnd,\r\n CancellationToken cancellationToken)\r\n {\r\n var appTester = GetAppTester(communicationChannel, TestTarget.MacCatalyst.IsSimulator(), null);\r\n\r\n (TestExecutingResult testResult, string resultMessage) = await appTester.TestMacCatalystApp(\r\n appBundleInfo,\r\n timeout,\r\n launchTimeout,\r\n signalAppEnd,\r\n passthroughArguments,\r\n environmentalVariables,\r\n xmlResultJargon,\r\n skippedMethods: singleMethodFilters?.ToArray(),\r\n skippedTestClasses: classMethodFilters?.ToArray(),\r\n cancellationToken: cancellationToken);\r\n\r\n ExitCode exitCode = ParseResult(testResult, resultMessage, appTester.ListenerConnected);\r\n\r\n // Copy system and application logs to the main log for better failure investigation.\r\n CopyLogsToMainLog();\r\n\r\n return exitCode;\r\n }", + "start_line": 263, + "end_line": 296, + "start_byte": 11096, + "end_byte": 12503 + }, + { + "name": "ExecuteApp", + "code": "private async Task ExecuteApp(\r\n AppBundleInformation appBundleInfo,\r\n TestTargetOs target,\r\n IDevice device,\r\n IDevice? companionDevice,\r\n TimeSpan timeout,\r\n TimeSpan launchTimeout,\r\n CommunicationChannel communicationChannel,\r\n XmlResultJargon xmlResultJargon,\r\n IEnumerable singleMethodFilters,\r\n IEnumerable classMethodFilters,\r\n IReadOnlyCollection<(string, string)> environmentalVariables,\r\n IEnumerable passthroughArguments,\r\n bool signalAppEnd,\r\n CancellationToken cancellationToken)\r\n {\r\n bool versionParsed = Version.TryParse(device.OSVersion, out var version);\r\n // iOS 14+ devices do not allow local network access and won't work unless the user confirms a dialog on the screen\r\n // https://developer.apple.com/forums/thread/663858\r\n if (versionParsed && version!.Major >= 14 && target.Platform.ToRunMode() == RunMode.iOS && communicationChannel == CommunicationChannel.Network)\r\n {\r\n _logger.LogWarning(\r\n \"Applications need user permission for communication over local network on iOS 14 and newer.\" + Environment.NewLine +\r\n \"Either confirm a dialog on the device after the application launches or use the USB tunnel communication channel.\" + Environment.NewLine +\r\n \"Test run might fail if permission is not granted. Permission is valid until app is uninstalled.\");\r\n }\r\n\r\n if (signalAppEnd && target.Platform.IsSimulator())\r\n {\r\n _logger.LogWarning(\"The --signal-app-end option is used for device tests and has no effect on simulators\");\r\n }\r\n\r\n _logger.LogInformation(\"Starting test run for \" + appBundleInfo.BundleIdentifier + \"..\");\r\n\r\n var appTester = GetAppTester(communicationChannel, target.Platform.IsSimulator(), version);\r\n\r\n (TestExecutingResult testResult, string resultMessage) = await appTester.TestApp(\r\n appBundleInfo,\r\n target,\r\n device,\r\n companionDevice,\r\n timeout,\r\n launchTimeout,\r\n signalAppEnd,\r\n passthroughArguments,\r\n environmentalVariables,\r\n xmlResultJargon,\r\n skippedMethods: singleMethodFilters?.ToArray(),\r\n skippedTestClasses: classMethodFilters?.ToArray(),\r\n cancellationToken: cancellationToken);\r\n\r\n ExitCode exitCode = ParseResult(testResult, resultMessage, appTester.ListenerConnected);\r\n\r\n if (!target.Platform.IsSimulator()) // Simulator app logs are already included in the main log\r\n {\r\n // Copy system and application logs to the main log for better failure investigation.\r\n CopyLogsToMainLog();\r\n }\r\n\r\n return exitCode;\r\n }", + "start_line": 201, + "end_line": 261, + "start_byte": 8216, + "end_byte": 11088 + }, + { + "name": "OrchestrateTest", + "code": "public virtual async Task OrchestrateTest(\r\n GetAppBundleInfoFunc getAppBundlePath,\r\n TestTargetOs target,\r\n string? deviceName,\r\n TimeSpan timeout,\r\n TimeSpan launchTimeout,\r\n CommunicationChannel communicationChannel,\r\n XmlResultJargon xmlResultJargon,\r\n IEnumerable singleMethodFilters,\r\n IEnumerable classMethodFilters,\r\n bool includeWirelessDevices,\r\n bool resetSimulator,\r\n bool enableLldb,\r\n bool signalAppEnd,\r\n IReadOnlyCollection<(string, string)> environmentalVariables,\r\n IEnumerable passthroughArguments,\r\n CancellationToken cancellationToken)\r\n {\r\n // The --launch-timeout option must start counting now and not complete before we start running tests to succeed.\r\n // After then, this timeout must not interfere.\r\n // Tests start running inside of ExecuteApp() which means we have to time-constrain all operations happening inside\r\n // OrchestrateRun() that happen before we start the app execution.\r\n // We will achieve this by sending a special cancellation token to OrchestrateRun() and only cancel if it in case\r\n // we didn't manage to start the app run until then.\r\n using var launchTimeoutCancellation = new CancellationTokenSource();\r\n var appRunStarted = false;\r\n var shorterTimeout = launchTimeout < timeout ? launchTimeout : timeout;\r\n var task = Task.Delay(shorterTimeout, cancellationToken).ContinueWith(t =>\r\n {\r\n if (!appRunStarted)\r\n {\r\n _logger.LogError($\"Cancelling the run after {Math.Ceiling(shorterTimeout.TotalSeconds)} seconds as application failed to launch in time\");\r\n launchTimeoutCancellation.Cancel();\r\n }\r\n }, cancellationToken);\r\n\r\n // We also want to shrink the launch timeout by whatever elapsed before we get to ExecuteApp\r\n Stopwatch watch = Stopwatch.StartNew();\r\n\r\n using var launchTimeoutCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(\r\n launchTimeoutCancellation.Token,\r\n cancellationToken);\r\n\r\n Task ExecuteMacCatalystApp(AppBundleInformation appBundleInfo)\r\n {\r\n appRunStarted = true;\r\n return this.ExecuteMacCatalystApp(\r\n appBundleInfo,\r\n timeout,\r\n launchTimeout - watch.Elapsed,\r\n communicationChannel,\r\n xmlResultJargon,\r\n singleMethodFilters,\r\n classMethodFilters,\r\n environmentalVariables,\r\n passthroughArguments,\r\n signalAppEnd,\r\n cancellationToken); // This cancellation token doesn't include the launch-timeout one\r\n }\r\n\r\n Task ExecuteApp(AppBundleInformation appBundleInfo, IDevice device, IDevice? companionDevice)\r\n {\r\n appRunStarted = true;\r\n return this.ExecuteApp(\r\n appBundleInfo,\r\n target,\r\n device,\r\n companionDevice,\r\n timeout,\r\n launchTimeout - watch.Elapsed,\r\n communicationChannel,\r\n xmlResultJargon,\r\n singleMethodFilters,\r\n classMethodFilters,\r\n environmentalVariables,\r\n passthroughArguments,\r\n signalAppEnd,\r\n cancellationToken); // This cancellation token doesn't include the launch-timeout one\r\n }\r\n\r\n return await OrchestrateOperation(\r\n target,\r\n deviceName,\r\n includeWirelessDevices,\r\n resetSimulator,\r\n enableLldb,\r\n getAppBundlePath,\r\n ExecuteMacCatalystApp,\r\n ExecuteApp,\r\n launchTimeoutCancellationToken.Token);\r\n }", + "start_line": 109, + "end_line": 199, + "start_byte": 4252, + "end_byte": 8208 + }, + { + "name": "OrchestrateTest", + "code": "public Task OrchestrateTest(\r\n string appBundlePath,\r\n TestTargetOs target,\r\n string? deviceName,\r\n TimeSpan timeout,\r\n TimeSpan launchTimeout,\r\n CommunicationChannel communicationChannel,\r\n XmlResultJargon xmlResultJargon,\r\n IEnumerable singleMethodFilters,\r\n IEnumerable classMethodFilters,\r\n bool includeWirelessDevices,\r\n bool resetSimulator,\r\n bool enableLldb,\r\n bool signalAppEnd,\r\n IReadOnlyCollection<(string, string)> environmentalVariables,\r\n IEnumerable passthroughArguments,\r\n CancellationToken cancellationToken)\r\n => OrchestrateTest(\r\n (target, device, ct) => GetAppBundleFromPath(target, appBundlePath, ct),\r\n target,\r\n deviceName,\r\n timeout,\r\n launchTimeout,\r\n communicationChannel,\r\n xmlResultJargon,\r\n singleMethodFilters,\r\n classMethodFilters,\r\n includeWirelessDevices,\r\n resetSimulator: resetSimulator,\r\n enableLldb,\r\n signalAppEnd,\r\n environmentalVariables,\r\n passthroughArguments,\r\n cancellationToken);", + "start_line": 74, + "end_line": 107, + "start_byte": 2991, + "end_byte": 4244 + }, + { + "name": "OrchestrateTest", + "code": "Task OrchestrateTest(\r\n string appBundlePath,\r\n TestTargetOs target,\r\n string? deviceName,\r\n TimeSpan timeout,\r\n TimeSpan launchTimeout,\r\n CommunicationChannel communicationChannel,\r\n XmlResultJargon xmlResultJargon,\r\n IEnumerable singleMethodFilters,\r\n IEnumerable classMethodFilters,\r\n bool includeWirelessDevices,\r\n bool resetSimulator,\r\n bool enableLldb,\r\n bool signalAppEnd,\r\n IReadOnlyCollection<(string, string)> environmentalVariables,\r\n IEnumerable passthroughArguments,\r\n CancellationToken cancellationToken);", + "start_line": 23, + "end_line": 39, + "start_byte": 797, + "end_byte": 1462 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/Orchestration/RunOrchestrator.cs": [ + { + "name": "ParseResult", + "code": "private ExitCode ParseResult(\r\n IExitCodeDetector exitCodeDetector,\r\n int expectedExitCode,\r\n AppBundleInformation appBundleInfo,\r\n ProcessExecutionResult result)\r\n {\r\n if (result.TimedOut)\r\n {\r\n _logger.LogError($\"App run has timed out\");\r\n return ExitCode.TIMED_OUT;\r\n }\r\n\r\n // On iOS 18 and later, mlaunch returns exit code 1 with the following error message:\r\n // \"Failed to execute 'devicectl': returned the exit code .\"\r\n if (!result.Succeeded && result.ExitCode != expectedExitCode)\r\n {\r\n _logger.LogError($\"App run has failed. mlaunch exited with {result.ExitCode}\");\r\n return ExitCode.APP_LAUNCH_FAILURE;\r\n }\r\n\r\n var logs = _logs.Where(log => log.Description == LogType.SystemLog.ToString() || log.Description == LogType.ApplicationLog.ToString()).ToList();\r\n if (!logs.Any())\r\n {\r\n _logger.LogError(\"Application has finished but no system log found. Failed to determine the exit code!\");\r\n return ExitCode.RETURN_CODE_NOT_SET;\r\n }\r\n\r\n int? exitCode = null;\r\n foreach (var log in logs)\r\n {\r\n try\r\n {\r\n exitCode = exitCodeDetector.DetectExitCode(appBundleInfo, log);\r\n\r\n if (exitCode.HasValue)\r\n {\r\n _logger.LogDebug($\"Detected exit code {exitCode.Value} from {log.FullPath}\");\r\n break;\r\n }\r\n\r\n if (result.ExitCode != 0)\r\n {\r\n exitCode = result.ExitCode;\r\n }\r\n\r\n _logger.LogDebug($\"Failed to determine the exit code from {log.FullPath}\");\r\n }\r\n catch (Exception e)\r\n {\r\n _logger.LogDebug($\"Failed to determine the exit code from {log.FullPath}:{Environment.NewLine}{e.Message}\");\r\n }\r\n }\r\n\r\n if (exitCode is null)\r\n {\r\n if (expectedExitCode != 0)\r\n {\r\n _logger.LogError(\"Application has finished but XHarness failed to determine its exit code!\");\r\n return ExitCode.RETURN_CODE_NOT_SET;\r\n }\r\n\r\n _logger.LogInformation(\"App run ended, no abnormal exit code detected (0 assumed)\");\r\n exitCode = 0;\r\n }\r\n else\r\n {\r\n _logger.LogInformation($\"App run ended with {exitCode}\");\r\n }\r\n\r\n if (expectedExitCode != exitCode)\r\n {\r\n _logger.LogError($\"Application has finished with exit code {exitCode} but {expectedExitCode} was expected\");\r\n var cliExitCode = ExitCode.GENERAL_FAILURE;\r\n\r\n foreach (var log in _logs)\r\n {\r\n if (_errorKnowledgeBase.IsKnownTestIssue(log, out var failure))\r\n {\r\n _logger.LogError(failure.HumanMessage);\r\n\r\n if (failure.SuggestedExitCode.HasValue)\r\n {\r\n cliExitCode = (ExitCode)failure.SuggestedExitCode.Value;\r\n }\r\n\r\n break;\r\n }\r\n }\r\n\r\n return cliExitCode;\r\n }\r\n\r\n _logger.LogInformation(\"Application has finished with exit code: \" + exitCode +\r\n (expectedExitCode != 0 ? \" (as expected)\" : null));\r\n\r\n return ExitCode.SUCCESS;\r\n }", + "start_line": 304, + "end_line": 400, + "start_byte": 12013, + "end_byte": 15463 + }, + { + "name": "ExecuteMacCatalystApp", + "code": "private async Task ExecuteMacCatalystApp(\r\n AppBundleInformation appBundleInfo,\r\n TimeSpan timeout,\r\n int expectedExitCode,\r\n bool signalAppEnd,\r\n bool waitForExit,\r\n IReadOnlyCollection<(string, string)> environmentalVariables,\r\n IEnumerable passthroughArguments,\r\n CancellationToken cancellationToken)\r\n {\r\n _logger.LogInformation($\"Starting '{appBundleInfo.AppName}' on MacCatalyst\");\r\n\r\n ProcessExecutionResult result = await _appRunner.RunMacCatalystApp(\r\n appBundleInfo,\r\n timeout,\r\n signalAppEnd: signalAppEnd,\r\n waitForExit: waitForExit,\r\n passthroughArguments,\r\n environmentalVariables,\r\n cancellationToken: cancellationToken);\r\n\r\n if (!waitForExit)\r\n {\r\n _logger.LogInformation(\"Not waiting for app to exit\");\r\n return ExitCode.SUCCESS;\r\n }\r\n\r\n return ParseResult(_macCatalystExitCodeDetector, expectedExitCode, appBundleInfo, result);\r\n }", + "start_line": 274, + "end_line": 302, + "start_byte": 10935, + "end_byte": 12005 + }, + { + "name": "ExecuteApp", + "code": "private async Task ExecuteApp(\r\n AppBundleInformation appBundleInfo,\r\n TestTargetOs target,\r\n IDevice device,\r\n IDevice? companionDevice,\r\n TimeSpan timeout,\r\n int expectedExitCode,\r\n bool signalAppEnd,\r\n bool waitForExit,\r\n IReadOnlyCollection<(string, string)> environmentalVariables,\r\n IEnumerable passthroughArguments,\r\n CancellationToken cancellationToken)\r\n {\r\n if (signalAppEnd && target.Platform.IsSimulator())\r\n {\r\n _logger.LogWarning(\"The --signal-app-end option is used for device tests and has no effect on simulators\");\r\n }\r\n\r\n _logger.LogInformation($\"Starting '{appBundleInfo.AppName}' on '{device.Name}'\");\r\n\r\n ProcessExecutionResult result = await _appRunner.RunApp(\r\n appBundleInfo,\r\n target,\r\n device,\r\n companionDevice,\r\n timeout,\r\n signalAppEnd: signalAppEnd,\r\n waitForExit: waitForExit,\r\n passthroughArguments,\r\n environmentalVariables,\r\n cancellationToken);\r\n\r\n if (!waitForExit)\r\n {\r\n _logger.LogInformation(\"Not waiting for app to exit\");\r\n return ExitCode.SUCCESS;\r\n }\r\n\r\n return ParseResult(_iOSExitCodeDetector, expectedExitCode, appBundleInfo, result);\r\n }", + "start_line": 233, + "end_line": 272, + "start_byte": 9535, + "end_byte": 10927 + }, + { + "name": "OrchestrateRun", + "code": "protected async Task OrchestrateRun(\r\n GetAppBundleInfoFunc getAppBundleInfo,\r\n TestTargetOs target,\r\n string? deviceName,\r\n TimeSpan timeout,\r\n TimeSpan launchTimeout,\r\n int expectedExitCode,\r\n bool includeWirelessDevices,\r\n bool resetSimulator,\r\n bool enableLldb,\r\n bool signalAppEnd,\r\n bool waitForExit,\r\n IReadOnlyCollection<(string, string)> environmentalVariables,\r\n IEnumerable passthroughArguments,\r\n CancellationToken cancellationToken)\r\n {\r\n if (signalAppEnd && !waitForExit)\r\n {\r\n throw new InvalidOperationException(\"Cannot receive app end signal without waiting for it to exit\");\r\n }\r\n\r\n _waitForExit = waitForExit;\r\n\r\n // The --launch-timeout option must start counting now and not complete before we start running tests to succeed.\r\n // After then, this timeout must not interfere.\r\n // Tests start running inside of ExecuteApp() which means we have to time-constrain all operations happening inside\r\n // OrchestrateRun() that happen before we start the app execution.\r\n // We will achieve this by sending a special cancellation token to OrchestrateRun() and only cancel if it in case\r\n // we didn't manage to start the app run until then.\r\n using var launchTimeoutCancellation = new CancellationTokenSource();\r\n var appRunStarted = false;\r\n var task = Task.Delay(launchTimeout < timeout ? launchTimeout : timeout, cancellationToken).ContinueWith(t =>\r\n {\r\n if (!appRunStarted)\r\n {\r\n _logger.LogError(\"Cancelling the run as application failed to launch in time\");\r\n launchTimeoutCancellation.Cancel();\r\n }\r\n }, cancellationToken);\r\n\r\n using var launchTimeoutCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(\r\n launchTimeoutCancellation.Token,\r\n cancellationToken);\r\n\r\n Task ExecuteMacCatalystApp(AppBundleInformation appBundleInfo)\r\n {\r\n appRunStarted = true;\r\n return this.ExecuteMacCatalystApp(\r\n appBundleInfo,\r\n timeout,\r\n expectedExitCode,\r\n signalAppEnd,\r\n waitForExit,\r\n environmentalVariables,\r\n passthroughArguments,\r\n cancellationToken);\r\n }\r\n\r\n Task ExecuteApp(AppBundleInformation appBundleInfo, IDevice device, IDevice? companionDevice)\r\n {\r\n // Exit code detection is broken on the newest iOS\r\n // More details here: https://github.com/dotnet/xharness/issues/819\r\n if (expectedExitCode != 0)\r\n {\r\n var os = target.Platform.IsSimulator() ? device.OSVersion.Split(' ', 2).Last() : device.OSVersion;\r\n if (Version.TryParse(os, out var version) && version.Major > 14)\r\n {\r\n _logger.LogWarning(\r\n \"Exit code detection is not working on iOS/tvOS 15+ so the run will fail to match it with the expected value\");\r\n }\r\n }\r\n\r\n appRunStarted = true;\r\n return this.ExecuteApp(\r\n appBundleInfo,\r\n target,\r\n device,\r\n companionDevice,\r\n timeout,\r\n expectedExitCode,\r\n signalAppEnd: signalAppEnd,\r\n waitForExit: waitForExit,\r\n environmentalVariables,\r\n passthroughArguments,\r\n cancellationToken);\r\n }\r\n\r\n return await OrchestrateOperation(\r\n target,\r\n deviceName,\r\n includeWirelessDevices: includeWirelessDevices,\r\n resetSimulator: resetSimulator,\r\n enableLldb: enableLldb,\r\n getAppBundleInfo,\r\n ExecuteMacCatalystApp,\r\n ExecuteApp,\r\n launchTimeoutCancellationToken.Token);\r\n }", + "start_line": 134, + "end_line": 231, + "start_byte": 5434, + "end_byte": 9527 + }, + { + "name": "CleanUpSimulators", + "code": "protected override Task CleanUpSimulators(IDevice device, IDevice? companionDevice)\r\n {\r\n if (!_waitForExit)\r\n {\r\n return Task.FromResult(ExitCode.SUCCESS);\r\n }\r\n\r\n return base.CleanUpSimulators(device, companionDevice);\r\n }", + "start_line": 124, + "end_line": 132, + "start_byte": 5157, + "end_byte": 5426 + }, + { + "name": "UninstallApp", + "code": "protected override Task UninstallApp(TestTarget target, string bundleIdentifier, IDevice device, bool isPreparation, CancellationToken cancellationToken)\r\n {\r\n if (!_waitForExit && !isPreparation)\r\n {\r\n return Task.FromResult(ExitCode.SUCCESS);\r\n }\r\n\r\n return base.UninstallApp(target, bundleIdentifier, device, isPreparation, cancellationToken);\r\n }", + "start_line": 114, + "end_line": 122, + "start_byte": 4744, + "end_byte": 5149 + }, + { + "name": "OrchestrateRun", + "code": "public Task OrchestrateRun(\r\n string appBundlePath,\r\n TestTargetOs target,\r\n string? deviceName,\r\n TimeSpan timeout,\r\n TimeSpan launchTimeout,\r\n int expectedExitCode,\r\n bool includeWirelessDevices,\r\n bool resetSimulator,\r\n bool enableLldb,\r\n bool signalAppEnd,\r\n bool waitForExit,\r\n IReadOnlyCollection<(string, string)> environmentalVariables,\r\n IEnumerable passthroughArguments,\r\n CancellationToken cancellationToken)\r\n => OrchestrateRun(\r\n (target, device, ct) => GetAppBundleFromPath(target, appBundlePath, ct),\r\n target,\r\n deviceName,\r\n timeout: timeout,\r\n launchTimeout: launchTimeout,\r\n expectedExitCode,\r\n includeWirelessDevices: includeWirelessDevices,\r\n resetSimulator: resetSimulator,\r\n enableLldb: enableLldb,\r\n signalAppEnd: signalAppEnd,\r\n waitForExit: waitForExit,\r\n environmentalVariables,\r\n passthroughArguments,\r\n cancellationToken);", + "start_line": 83, + "end_line": 112, + "start_byte": 3608, + "end_byte": 4736 + }, + { + "name": "OrchestrateRun", + "code": "Task OrchestrateRun(\r\n string appBundlePath,\r\n TestTargetOs target,\r\n string? deviceName,\r\n TimeSpan timeout,\r\n TimeSpan launchTimeout,\r\n int expectedExitCode,\r\n bool includeWirelessDevices,\r\n bool resetSimulator,\r\n bool enableLldb,\r\n bool signalAppEnd,\r\n bool waitForExit,\r\n IReadOnlyCollection<(string, string)> environmentalVariables,\r\n IEnumerable passthroughArguments,\r\n CancellationToken cancellationToken);", + "start_line": 23, + "end_line": 37, + "start_byte": 820, + "end_byte": 1349 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/Orchestration/BaseOrchestrator.cs": [ + { + "name": "NotifyUserLldbCommand", + "code": "protected static void NotifyUserLldbCommand(ILogger logger, string line)\r\n {\r\n if (!line.Contains(\"mtouch-lldb-prep-cmds\"))\r\n {\r\n return;\r\n }\r\n\r\n // let the user know the command to execute. Might change in mlaunch so trust the log\r\n var sb = new StringBuilder();\r\n sb.AppendLine(\"LLDB debugging is enabled.\");\r\n sb.AppendLine(\"You must now execute:\");\r\n sb.AppendLine(line.Substring(line.IndexOf(\"lldb\", StringComparison.Ordinal)));\r\n\r\n logger.LogInformation(sb.ToString());\r\n }", + "start_line": 524, + "end_line": 538, + "start_byte": 21255, + "end_byte": 21814 + }, + { + "name": "IsLldbEnabled", + "code": "protected static bool IsLldbEnabled() => File.Exists(s_mlaunchLldbConfigFile);", + "start_line": 522, + "end_line": 522, + "start_byte": 21169, + "end_byte": 21247 + }, + { + "name": "GetAppBundleFromPath", + "code": "protected Task GetAppBundleFromPath(TestTargetOs target, string appBundlePath, CancellationToken cancellationToken)\r\n {\r\n appBundlePath = Path.GetFullPath(appBundlePath);\r\n _logger.LogInformation($\"Getting app bundle information from '{appBundlePath}'..\");\r\n return _appBundleInformationParser.ParseFromAppBundle(appBundlePath, target.Platform, _mainLog, cancellationToken);\r\n }", + "start_line": 515, + "end_line": 520, + "start_byte": 20734, + "end_byte": 21161 + }, + { + "name": "GetAppBundleFromId", + "code": "protected async Task GetAppBundleFromId(TestTargetOs target, IDevice device, string bundleIdentifier, CancellationToken cancellationToken)\r\n {\r\n // We can exchange bundle ID for path where the bundle is on the simulator and get that\r\n if (device is ISimulatorDevice simulator)\r\n {\r\n _logger.LogInformation($\"Querying simulator for app bundle information..\");\r\n await simulator.Boot(_mainLog, cancellationToken);\r\n var appBundlePath = await simulator.GetAppBundlePath(_mainLog, bundleIdentifier, cancellationToken);\r\n return await GetAppBundleFromPath(target, appBundlePath, cancellationToken);\r\n }\r\n\r\n // We're unable to do this for real devices / or MacCatalyst\r\n // It is not ideal but doesn't matter much at the moment as we don't need the full list of properties there\r\n _logger.LogDebug(\"Supplemented full app bundle information with bundle identifier\");\r\n return AppBundleInformation.FromBundleId(bundleIdentifier);\r\n }", + "start_line": 498, + "end_line": 513, + "start_byte": 19673, + "end_byte": 20726 + }, + { + "name": "CleanUpSimulators", + "code": "protected virtual async Task CleanUpSimulators(IDevice device, IDevice? companionDevice)\r\n {\r\n try\r\n {\r\n var simulator = (ISimulatorDevice)device;\r\n\r\n _logger.LogInformation($\"Cleaning up simulator '{device.Name}'\");\r\n await simulator.KillEverything(_mainLog);\r\n\r\n if (companionDevice != null)\r\n {\r\n _logger.LogInformation($\"Cleaning up companion simulator '{companionDevice.Name}'\");\r\n var companionSimulator = (ISimulatorDevice)companionDevice;\r\n await companionSimulator.KillEverything(_mainLog);\r\n }\r\n }\r\n finally\r\n {\r\n _logger.LogInformation(\"Simulators cleaned up\");\r\n }\r\n }", + "start_line": 476, + "end_line": 496, + "start_byte": 18915, + "end_byte": 19665 + }, + { + "name": "UninstallApp", + "code": "protected virtual async Task UninstallApp(TestTarget target, string bundleIdentifier, IDevice device, bool isPreparation, CancellationToken cancellationToken)\r\n {\r\n if (isPreparation)\r\n {\r\n _logger.LogInformation($\"Uninstalling any previous instance of '{bundleIdentifier}' from '{device.Name}'\");\r\n }\r\n else\r\n {\r\n _logger.LogInformation($\"Uninstalling the application '{bundleIdentifier}' from '{device.Name}'\");\r\n }\r\n\r\n ProcessExecutionResult uninstallResult = target.IsSimulator()\r\n ? await _appUninstaller.UninstallSimulatorApp((ISimulatorDevice)device, bundleIdentifier, cancellationToken)\r\n : await _appUninstaller.UninstallDeviceApp((IHardwareDevice)device, bundleIdentifier, cancellationToken);\r\n\r\n if (uninstallResult.Succeeded)\r\n {\r\n _logger.LogInformation($\"Application '{bundleIdentifier}' was uninstalled successfully\");\r\n return ExitCode.SUCCESS;\r\n }\r\n\r\n // We try to uninstall app before each run to clear it from the device\r\n // For those cases, we don't care about the result\r\n if (isPreparation)\r\n {\r\n _logger.LogDebug($\"Preemptive uninstallation of application {(uninstallResult.TimedOut ? \"timed out\" : \"failed\")}\");\r\n }\r\n else\r\n {\r\n if (target.IsSimulator() && uninstallResult.ExitCode == 165)\r\n {\r\n // When uninstallation returns 165, the simulator is in a weird state where it cannot be booted and running an app later will fail\r\n _logger.LogCritical($\"Failed to uninstall the application - bad simulator state detected!\");\r\n return ExitCode.SIMULATOR_FAILURE;\r\n }\r\n else\r\n {\r\n _logger.LogError($\"Failed to uninstall the app bundle! Check logs for more details!\");\r\n }\r\n }\r\n\r\n return ExitCode.GENERAL_FAILURE;\r\n }", + "start_line": 432, + "end_line": 474, + "start_byte": 16919, + "end_byte": 18907 + }, + { + "name": "InstallApp", + "code": "protected virtual async Task InstallApp(\r\n AppBundleInformation appBundleInfo,\r\n IDevice device,\r\n TestTargetOs target,\r\n CancellationToken cancellationToken)\r\n {\r\n _logger.LogInformation($\"Installing application '{appBundleInfo.AppName}' on '{device.Name}'\");\r\n\r\n ProcessExecutionResult result;\r\n\r\n try\r\n {\r\n result = await _appInstaller.InstallApp(appBundleInfo, target, device, cancellationToken);\r\n }\r\n catch (Exception e)\r\n {\r\n _logger.LogError($\"Failed to install the app bundle:{Environment.NewLine}{e}\");\r\n return ExitCode.PACKAGE_INSTALLATION_FAILURE;\r\n }\r\n\r\n if (!result.Succeeded)\r\n {\r\n cancellationToken.ThrowIfCancellationRequested();\r\n\r\n var exitCode = ExitCode.PACKAGE_INSTALLATION_FAILURE;\r\n\r\n // use the knowledge base class to decide if the error is known, if it is, let the user know\r\n // the failure reason\r\n if (_errorKnowledgeBase.IsKnownInstallIssue(_mainLog, out var failure))\r\n {\r\n var error = new StringBuilder()\r\n .AppendLine(\"Failed to install the application\")\r\n .AppendLine(failure.HumanMessage);\r\n\r\n if (failure.IssueLink != null)\r\n {\r\n error\r\n .AppendLine()\r\n .AppendLine($\" Find more information at {failure.IssueLink}\");\r\n }\r\n\r\n if (failure.SuggestedExitCode.HasValue)\r\n {\r\n exitCode = (ExitCode)failure.SuggestedExitCode.Value;\r\n }\r\n\r\n _logger.LogError(error.ToString());\r\n }\r\n else\r\n {\r\n _logger.LogError($\"Failed to install the application\");\r\n }\r\n\r\n return exitCode;\r\n }\r\n\r\n _logger.LogInformation($\"Application '{appBundleInfo.AppName}' was installed successfully on '{device.Name}'\");\r\n\r\n return ExitCode.SUCCESS;\r\n }", + "start_line": 371, + "end_line": 430, + "start_byte": 14808, + "end_byte": 16911 + }, + { + "name": "Dispose", + "code": "public void Dispose()\r\n {\r\n _mainLog.Dispose();\r\n\r\n if (_lldbFileCreated)\r\n {\r\n File.Delete(s_mlaunchLldbConfigFile);\r\n }\r\n\r\n GC.SuppressFinalize(this);\r\n }", + "start_line": 359, + "end_line": 369, + "start_byte": 14592, + "end_byte": 14800 + }, + { + "name": "OrchestrateOperationInternal", + "code": "private async Task OrchestrateOperationInternal(\r\n TestTargetOs target,\r\n string? deviceName,\r\n bool includeWirelessDevices,\r\n bool resetSimulator,\r\n bool enableLldb,\r\n GetAppBundleInfoFunc getAppBundle,\r\n ExecuteMacCatalystAppFunc executeMacCatalystApp,\r\n ExecuteAppFunc executeApp,\r\n CancellationToken cancellationToken)\r\n {\r\n _lldbFileCreated = false;\r\n var isLldbEnabled = IsLldbEnabled();\r\n if (isLldbEnabled && !enableLldb)\r\n {\r\n // the file is present, but the user did not set it, warn him about it\r\n _logger.LogWarning(\"Lldb will be used since '~/.mtouch-launch-with-lldb' was found in the system but it was not created by xharness.\");\r\n }\r\n else if (enableLldb)\r\n {\r\n if (!File.Exists(s_mlaunchLldbConfigFile))\r\n {\r\n // create empty file\r\n File.WriteAllText(s_mlaunchLldbConfigFile, string.Empty);\r\n _lldbFileCreated = true;\r\n }\r\n }\r\n\r\n if (includeWirelessDevices && target.Platform.IsSimulator())\r\n {\r\n _logger.LogWarning(\"Including wireless devices while targeting a simulator has no effect\");\r\n }\r\n\r\n if (resetSimulator && !target.Platform.IsSimulator())\r\n {\r\n _logger.LogWarning(\"Targeting device but requesting simulator reset has no effect\");\r\n resetSimulator = false;\r\n }\r\n\r\n ExitCode exitCode;\r\n IDevice device;\r\n IDevice? companionDevice;\r\n AppBundleInformation appBundleInfo;\r\n\r\n if (target.Platform == TestTarget.MacCatalyst)\r\n {\r\n try\r\n {\r\n appBundleInfo = await getAppBundle(target, null!, cancellationToken);\r\n }\r\n catch (Exception e)\r\n {\r\n cancellationToken.ThrowIfCancellationRequested();\r\n _logger.LogError(e.Message);\r\n return ExitCode.PACKAGE_NOT_FOUND;\r\n }\r\n\r\n try\r\n {\r\n return await executeMacCatalystApp(appBundleInfo);\r\n }\r\n catch (Exception e)\r\n {\r\n var message = new StringBuilder().AppendLine(\"Application run failed:\");\r\n exitCode = ExitCode.APP_LAUNCH_FAILURE;\r\n\r\n if (_errorKnowledgeBase.IsKnownTestIssue(_mainLog, out var failure))\r\n {\r\n message.Append(failure.HumanMessage);\r\n if (failure.IssueLink != null)\r\n {\r\n message.AppendLine($\" Find more information at {failure.IssueLink}\");\r\n }\r\n\r\n if (failure.SuggestedExitCode.HasValue)\r\n {\r\n exitCode = (ExitCode)failure.SuggestedExitCode.Value;\r\n }\r\n }\r\n else\r\n {\r\n message.AppendLine(e.ToString());\r\n }\r\n\r\n _logger.LogError(message.ToString());\r\n\r\n return exitCode;\r\n }\r\n }\r\n\r\n try\r\n {\r\n _logger.LogInformation($\"Looking for available {target.AsString()} {(target.Platform.IsSimulator() ? \"simulators\" : \"devices\")}..\");\r\n\r\n var finderLogName = $\"list-{target.AsString()}-{_helpers.Timestamp}.log\";\r\n using var finderLog = _logs.Create(finderLogName, \"DeviceList\", true);\r\n\r\n _mainLog.WriteLine(\r\n $\"Looking for available {target.AsString()} {(target.Platform.IsSimulator() ? \"simulators\" : \"devices\")}. \" +\r\n $\"Storing logs into {finderLogName}\");\r\n\r\n (device, companionDevice) = await _deviceFinder.FindDevice(\r\n target,\r\n deviceName,\r\n finderLog,\r\n includeWirelessDevices,\r\n pairedDevicesOnly: true,\r\n cancellationToken);\r\n\r\n _logger.LogInformation($\"Found {(target.Platform.IsSimulator() ? \"simulator\" : \"physical\")} device '{device.Name}'\");\r\n\r\n if (companionDevice != null)\r\n {\r\n _logger.LogInformation($\"Found companion {(target.Platform.IsSimulator() ? \"simulator\" : \"physical\")} device '{companionDevice.Name}'\");\r\n }\r\n }\r\n catch (NoDeviceFoundException e)\r\n {\r\n _logger.LogError(e.Message);\r\n return ExitCode.DEVICE_NOT_FOUND;\r\n }\r\n\r\n cancellationToken.ThrowIfCancellationRequested();\r\n\r\n try\r\n {\r\n appBundleInfo = await getAppBundle(target, device, cancellationToken);\r\n }\r\n catch (Exception e)\r\n {\r\n cancellationToken.ThrowIfCancellationRequested();\r\n _logger.LogError(e.Message);\r\n return ExitCode.PACKAGE_NOT_FOUND;\r\n }\r\n\r\n cancellationToken.ThrowIfCancellationRequested();\r\n\r\n if (target.Platform.IsSimulator() && resetSimulator)\r\n {\r\n try\r\n {\r\n var simulator = (ISimulatorDevice)device;\r\n var bundleIds = appBundleInfo.BundleIdentifier == string.Empty ? Array.Empty() : new[] { appBundleInfo.BundleIdentifier };\r\n\r\n _logger.LogInformation($\"Reseting simulator '{device.Name}'\");\r\n await simulator.PrepareSimulator(_mainLog, bundleIds);\r\n\r\n if (companionDevice != null)\r\n {\r\n _logger.LogInformation($\"Reseting companion simulator '{companionDevice.Name}'\");\r\n var companionSimulator = (ISimulatorDevice)companionDevice;\r\n await companionSimulator.PrepareSimulator(_mainLog, bundleIds);\r\n }\r\n\r\n _logger.LogInformation(\"Simulator reset finished\");\r\n }\r\n catch (Exception e)\r\n {\r\n _logger.LogError($\"Failed to reset simulator: \" + Environment.NewLine + e);\r\n return ExitCode.SIMULATOR_FAILURE;\r\n }\r\n }\r\n\r\n cancellationToken.ThrowIfCancellationRequested();\r\n\r\n // Note down the actual test target\r\n // For simulators (e.g. \"iOS 13.4\"), we strip the iOS part and keep the version only, for devices there's no OS\r\n _diagnosticsData.TargetOS = target.Platform.IsSimulator() ? device.OSVersion.Split(' ', 2).Last() : device.OSVersion;\r\n _diagnosticsData.Device = device.Name ?? device.UDID;\r\n\r\n // Uninstall the app first to get a clean state\r\n if (!resetSimulator)\r\n {\r\n await UninstallApp(target.Platform, appBundleInfo.BundleIdentifier, device, isPreparation: true, cancellationToken);\r\n cancellationToken.ThrowIfCancellationRequested();\r\n }\r\n\r\n exitCode = await InstallApp(appBundleInfo, device, target, cancellationToken);\r\n\r\n if (exitCode != ExitCode.SUCCESS)\r\n {\r\n _logger.LogInformation($\"Cleaning up the failed installation from '{device.Name}'\");\r\n\r\n var uninstallResult = await UninstallApp(target.Platform, appBundleInfo.BundleIdentifier, device, isPreparation: false, new CancellationToken());\r\n if (uninstallResult == ExitCode.SIMULATOR_FAILURE)\r\n {\r\n // Sometimes the simulator gets in a bad shape and we won't be able to install the app, we can tell here\r\n return ExitCode.SIMULATOR_FAILURE;\r\n }\r\n\r\n return exitCode;\r\n }\r\n\r\n try\r\n {\r\n exitCode = await executeApp(appBundleInfo, device, companionDevice);\r\n }\r\n catch (Exception e)\r\n {\r\n exitCode = ExitCode.GENERAL_FAILURE;\r\n\r\n var message = new StringBuilder().AppendLine(\"Application run failed:\");\r\n\r\n if (_errorKnowledgeBase.IsKnownTestIssue(_mainLog, out var failure))\r\n {\r\n message.Append(failure.HumanMessage);\r\n if (failure.IssueLink != null)\r\n {\r\n message.AppendLine($\" Find more information at {failure.IssueLink}\");\r\n }\r\n\r\n if (failure.SuggestedExitCode.HasValue)\r\n {\r\n exitCode = (ExitCode)failure.SuggestedExitCode.Value;\r\n }\r\n }\r\n else\r\n {\r\n message.AppendLine(e.ToString());\r\n }\r\n\r\n _logger.LogError(message.ToString());\r\n }\r\n finally\r\n {\r\n if (target.Platform.IsSimulator() && resetSimulator)\r\n {\r\n await CleanUpSimulators(device, companionDevice);\r\n }\r\n else if (device != null) // Do not uninstall if device was cleaned up\r\n {\r\n var uninstallResult = await UninstallApp(target.Platform, appBundleInfo.BundleIdentifier, device, false, new CancellationToken());\r\n\r\n // We are able to detect a case when simulator is in a bad shape\r\n // If it also failed the test/run, we should present that as the failure\r\n if (uninstallResult == ExitCode.SIMULATOR_FAILURE && exitCode != ExitCode.SUCCESS && exitCode != ExitCode.TESTS_FAILED)\r\n {\r\n exitCode = ExitCode.SIMULATOR_FAILURE;\r\n }\r\n }\r\n }\r\n\r\n return exitCode;\r\n }", + "start_line": 114, + "end_line": 357, + "start_byte": 5147, + "end_byte": 14584 + }, + { + "name": "OrchestrateOperation", + "code": "protected async Task OrchestrateOperation(\r\n TestTargetOs target,\r\n string? deviceName,\r\n bool includeWirelessDevices,\r\n bool resetSimulator,\r\n bool enableLldb,\r\n GetAppBundleInfoFunc getAppBundle,\r\n ExecuteMacCatalystAppFunc executeMacCatalystApp,\r\n ExecuteAppFunc executeApp,\r\n CancellationToken cancellationToken)\r\n {\r\n try\r\n {\r\n return await OrchestrateOperationInternal(\r\n target,\r\n deviceName,\r\n includeWirelessDevices,\r\n resetSimulator,\r\n enableLldb,\r\n getAppBundle,\r\n executeMacCatalystApp,\r\n executeApp,\r\n cancellationToken);\r\n }\r\n catch (OperationCanceledException e)\r\n {\r\n _logger.LogDebug(e.ToString());\r\n return ExitCode.APP_LAUNCH_TIMEOUT;\r\n }\r\n }", + "start_line": 83, + "end_line": 112, + "start_byte": 4189, + "end_byte": 5139 + } + ], + "src/Microsoft.DotNet.XHarness.Apple/Orchestration/InstallOrchestrator.cs": [ + { + "name": "UninstallApp", + "code": "protected override Task UninstallApp(TestTarget target, string bundleIdentifier, IDevice device, bool isPreparation, CancellationToken cancellationToken)\r\n {\r\n // For the installation, we want to uninstall during preparation only\r\n if (isPreparation)\r\n {\r\n return base.UninstallApp(target, bundleIdentifier, device, isPreparation, cancellationToken);\r\n }\r\n\r\n return Task.FromResult(ExitCode.SUCCESS);\r\n }", + "start_line": 91, + "end_line": 100, + "start_byte": 3325, + "end_byte": 3791 + }, + { + "name": "CleanUpSimulators", + "code": "protected override Task CleanUpSimulators(IDevice device, IDevice? companionDevice)\r\n => Task.CompletedTask;", + "start_line": 88, + "end_line": 89, + "start_byte": 3118, + "end_byte": 3233 + }, + { + "name": "OrchestrateInstall", + "code": "public async Task OrchestrateInstall(\r\n TestTargetOs target,\r\n string? deviceName,\r\n string appPackagePath,\r\n TimeSpan timeout,\r\n bool includeWirelessDevices,\r\n bool resetSimulator,\r\n bool enableLldb,\r\n CancellationToken cancellationToken)\r\n {\r\n Task GetAppBundleInfo(TestTargetOs target, IDevice device, CancellationToken ct) => GetAppBundleFromPath(target, appPackagePath, ct);\r\n\r\n static Task ExecuteMacCatalystApp(AppBundleInformation appBundleInfo)\r\n => throw new InvalidOperationException(\"install command not available on maccatalyst\");\r\n\r\n static Task ExecuteApp(AppBundleInformation appBundleInfo, IDevice device, IDevice? companionDevice)\r\n => Task.FromResult(ExitCode.SUCCESS); // no-op\r\n\r\n var result = await OrchestrateOperation(\r\n target,\r\n deviceName,\r\n includeWirelessDevices,\r\n resetSimulator,\r\n enableLldb,\r\n GetAppBundleInfo,\r\n ExecuteMacCatalystApp,\r\n ExecuteApp,\r\n cancellationToken);\r\n\r\n if (cancellationToken.IsCancellationRequested)\r\n {\r\n return ExitCode.PACKAGE_INSTALLATION_TIMEOUT;\r\n }\r\n\r\n return result;\r\n }", + "start_line": 51, + "end_line": 86, + "start_byte": 1773, + "end_byte": 3110 + }, + { + "name": "OrchestrateInstall", + "code": "Task OrchestrateInstall(\r\n TestTargetOs target,\r\n string? deviceName,\r\n string appPackagePath,\r\n TimeSpan timeout,\r\n bool includeWirelessDevices,\r\n bool resetSimulator,\r\n bool enableLldb,\r\n CancellationToken cancellationToken);", + "start_line": 20, + "end_line": 28, + "start_byte": 703, + "end_byte": 996 + } + ], + "src/Microsoft.DotNet.XHarness.TestRunners.Xunit/Properties/AssemblyInfo.cs": [], + "src/Microsoft.DotNet.XHarness.TestRunners.NUnit/Properties/AssemblyInfo.cs": [], + "tests/Microsoft.DotNet.XHarness.Android.Tests/AdbRunnerTests.cs": [ + { + "name": "VerifyAdbCall", + "code": "private void VerifyAdbCall(Times occurence, params string[] arguments)\n {\n _processManager.Verify(\n x => x.Run(s_adbPath, It.Is>(args => Enumerable.SequenceEqual(arguments, args)), It.IsAny()),\n occurence);\n }", + "start_line": 430, + "end_line": 435, + "start_byte": 16598, + "end_byte": 16872 + }, + { + "name": "VerifyAdbCall", + "code": "private void VerifyAdbCall(params string[] arguments) => VerifyAdbCall(Times.Once(), arguments);", + "start_line": 428, + "end_line": 428, + "start_byte": 16496, + "end_byte": 16592 + }, + { + "name": "CallFakeProcessManager", + "code": "private ProcessExecutionResults CallFakeProcessManager(string process, string[] arguments, TimeSpan timeout)\n {\n if (Debugger.IsAttached)\n {\n Debug.WriteLine($\"Fake ADB Process Manager invoked with args: '{process} {StringUtils.FormatArguments(arguments)}' (timeout = {timeout.TotalSeconds})\");\n }\n\n bool timedOut = false;\n int exitCode = 0;\n string stdOut = \"\";\n string stdErr = \"\";\n int argStart = 0;\n\n if (arguments[0] == \"-s\")\n {\n s_currentDeviceSerial = arguments[1];\n argStart = 2;\n }\n\n switch (arguments[argStart].ToLowerInvariant())\n {\n case \"get-state\":\n stdOut = \"device\";\n exitCode = 0;\n break;\n\n case \"devices\":\n var s = new StringBuilder();\n int transportId = 1;\n s.AppendLine(\"List of devices attached\");\n\n foreach (var device in _fakeDeviceList)\n {\n string state = device == _fakeDeviceList.Last() ? \"offline\" : \"online\";\n s.AppendLine($\"{device.DeviceSerial} {state} transportid:{transportId++}\");\n }\n\n stdOut = s.ToString();\n break;\n\n case \"shell\":\n if ($\"{arguments[argStart + 1]} {arguments[argStart + 2]}\".Equals(\"getprop ro.product.cpu.abilist\"))\n {\n stdOut = string.Join(\",\", _fakeDeviceList.Single(d => d.DeviceSerial == s_currentDeviceSerial).SupportedArchitectures);\n }\n\n if ($\"{arguments[argStart + 1]} {arguments[argStart + 2]}\".Equals(\"getprop ro.product.cpu.abi\"))\n {\n stdOut = _fakeDeviceList.Single(d => d.DeviceSerial == s_currentDeviceSerial).Architecture;\n }\n\n if ($\"{arguments[argStart + 1]} {arguments[argStart + 2]}\".Equals(\"getprop ro.build.version.sdk\"))\n {\n stdOut = _fakeDeviceList.Single(d => d.DeviceSerial == s_currentDeviceSerial).ApiVersion + Environment.NewLine;\n }\n\n if ($\"{arguments[argStart + 1]} {arguments[argStart + 2]}\".Equals(\"getprop sys.boot_completed\"))\n {\n // Newline is strange, but this is actually what it looks like\n if (s_bootCompleteCheckTimes > 0)\n {\n // Tell it we've booted.\n stdOut = $\"1{Environment.NewLine}\";\n }\n else\n {\n stdOut = Environment.NewLine;\n }\n s_bootCompleteCheckTimes++;\n }\n\n if (string.Join(\" \", arguments.Skip(argStart).Take(5)).Equals(\"shell pm list packages -3\"))\n {\n stdOut = \"package:\" + string.Join(\"\\npackage:\", _fakeDeviceList.Single(d => d.DeviceSerial == s_currentDeviceSerial).InstalledApplications);\n }\n\n exitCode = 0;\n break;\n\n case \"logcat\":\n if (arguments[argStart + 1].Equals(\"-d\"))\n {\n stdOut = \"Sample LogCat Output\";\n }\n\n break;\n\n case \"bugreport\":\n var outputPath = arguments[argStart + 1];\n File.WriteAllText(outputPath, \"Sample BugReport Output\");\n break;\n\n case \"install\":\n case \"reboot\":\n case \"uninstall\":\n case \"wait-for-device\":\n case \"start-server\":\n case \"kill-server\":\n break;\n\n default:\n throw new InvalidOperationException($\"Fake ADB doesn't know how to handle argument: {string.Join(\" \", arguments)}\");\n }\n\n return new ProcessExecutionResults\n {\n TimedOut = timedOut,\n ExitCode = exitCode,\n StandardError = stdErr,\n StandardOutput = stdOut\n };\n }", + "start_line": 315, + "end_line": 426, + "start_byte": 12374, + "end_byte": 16490 + }, + { + "name": "InitializeFakeDeviceList", + "code": "private static List InitializeFakeDeviceList()\n {\n var r = new Random();\n return new List\n {\n new AndroidDevice($\"somedevice-{r.Next(9999)}\")\n {\n ApiVersion = 29,\n Architecture = \"x86_64\",\n SupportedArchitectures = new[] { \"x86_64\", \"x86\" },\n InstalledApplications = new[] { \"net.dot.A\", \"net.dot.B\" }\n },\n\n new AndroidDevice($\"somedevice-{r.Next(9999)}\")\n {\n ApiVersion = 30,\n Architecture = \"x86\",\n SupportedArchitectures = new[] { \"x86\" },\n InstalledApplications = new[] { \"net.dot.C\", \"net.dot.D\" }\n },\n\n new AndroidDevice($\"emulator-{r.Next(9999)}\")\n {\n ApiVersion = 31,\n Architecture = \"arm64-v8a\",\n SupportedArchitectures = new[] { \"arm64-v8a\", \"x86_64\", \"x86\" },\n InstalledApplications = new[] { \"net.dot.E\", \"net.dot.F\" }\n },\n\n new AndroidDevice($\"emulator-{r.Next(9999)}\")\n {\n ApiVersion = 32,\n Architecture = \"armeabi-v7a\",\n SupportedArchitectures = new[] { \"armeabi-v7a\", \"x86_64\", \"x86\" },\n InstalledApplications = new[] { \"net.dot.G\", \"net.dot.H\" }\n },\n };\n }", + "start_line": 276, + "end_line": 313, + "start_byte": 10959, + "end_byte": 12368 + }, + { + "name": "RunInstrumentation", + "code": "[Theory]\n [InlineData(null)]\n [InlineData(\"\")]\n [InlineData(\"FakeInstrumentationName\")]\n public void RunInstrumentation(string instrumentationName)\n {\n string fakeApkName = Path.GetRandomFileName();\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n\n ProcessExecutionResults result;\n var fakeArgs = new Dictionary()\n {\n { \"arg1\", \"value1\" },\n { \"arg2\", \"value2\" }\n };\n\n result = runner.RunApkInstrumentation(fakeApkName, instrumentationName, fakeArgs, TimeSpan.FromSeconds(123));\n Assert.Equal(0, result.ExitCode);\n\n result = runner.RunApkInstrumentation(fakeApkName, instrumentationName, new Dictionary(), TimeSpan.FromSeconds(456));\n Assert.Equal(0, result.ExitCode);\n\n if (string.IsNullOrEmpty(instrumentationName))\n {\n VerifyAdbCall(\"shell\", \"am\", \"instrument\", \"-e\", \"arg1\", \"value1\", \"-e\", \"arg2\", \"value2\", \"-w\", fakeApkName);\n VerifyAdbCall(\"shell\", \"am\", \"instrument\", \"-w\", fakeApkName);\n }\n else\n {\n VerifyAdbCall(\"shell\", \"am\", \"instrument\", \"-e\", \"arg1\", \"value1\", \"-e\", \"arg2\", \"value2\", \"-w\", $\"{fakeApkName}/{instrumentationName}\");\n VerifyAdbCall(\"shell\", \"am\", \"instrument\", \"-w\", $\"{fakeApkName}/{instrumentationName}\");\n }\n }", + "start_line": 236, + "end_line": 268, + "start_byte": 9254, + "end_byte": 10674 + }, + { + "name": "RebootAndroidDevice", + "code": "[Fact]\n public void RebootAndroidDevice()\n {\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n runner.RebootAndroidDevice();\n VerifyAdbCall(\"reboot\");\n }", + "start_line": 228, + "end_line": 234, + "start_byte": 9033, + "end_byte": 9248 + }, + { + "name": "GetDeviceWithAppAndApiVersion", + "code": "[Fact]\n public void GetDeviceWithAppAndApiVersion()\n {\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n var device = _fakeDeviceList.Single(d => d.ApiVersion == 31 && d.InstalledApplications.Contains(\"net.dot.E\"));\n var result = runner.GetDevice(requiredInstalledApp: \"net.dot.E\", requiredApiVersion: 31);\n VerifyAdbCall(\"devices\", \"-l\");\n Assert.Equal(device.DeviceSerial, result.DeviceSerial);\n Assert.Equal(device.ApiVersion, result.ApiVersion);\n }", + "start_line": 217, + "end_line": 226, + "start_byte": 8492, + "end_byte": 9027 + }, + { + "name": "GetDeviceWithApiVersion", + "code": "[Fact]\n public void GetDeviceWithApiVersion()\n {\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n var device = _fakeDeviceList.Single(d => d.ApiVersion == 30);\n var result = runner.GetDevice(loadArchitecture: true, requiredApiVersion: 30);\n VerifyAdbCall(\"devices\", \"-l\");\n Assert.Equal(device.DeviceSerial, result.DeviceSerial);\n Assert.Equal(device.ApiVersion, result.ApiVersion);\n Assert.Equal(device.Architecture, result.Architecture);\n }", + "start_line": 205, + "end_line": 215, + "start_byte": 7953, + "end_byte": 8486 + }, + { + "name": "GetDeviceWithArchitecture", + "code": "[Fact]\n public void GetDeviceWithArchitecture()\n {\n var requiredArchitecture = \"x86\";\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n var result = runner.GetDevice(loadArchitecture: true, requiredArchitectures: new[] { requiredArchitecture });\n VerifyAdbCall(\"devices\", \"-l\");\n VerifyAdbCall(\"-s\", result.DeviceSerial, \"shell\", \"getprop\", \"ro.product.cpu.abi\");\n Assert.Contains(_fakeDeviceList, d => d.DeviceSerial == result.DeviceSerial && d.Architecture == result.Architecture);\n }", + "start_line": 194, + "end_line": 203, + "start_byte": 7378, + "end_byte": 7947 + }, + { + "name": "GetDevice", + "code": "[Fact]\n public void GetDevice()\n {\n var requiredArchitecture = \"x86_64\";\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n var result = runner.GetDevice(requiredArchitectures: new[] { requiredArchitecture });\n VerifyAdbCall(\"devices\", \"-l\");\n Assert.Contains(_fakeDeviceList, d => d.DeviceSerial == result.DeviceSerial);\n }", + "start_line": 184, + "end_line": 192, + "start_byte": 6973, + "end_byte": 7372 + }, + { + "name": "KillApk", + "code": "[Fact]\n public void KillApk()\n {\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n string fakeApkName = $\"{Path.GetRandomFileName()}\";\n int exitCode = runner.KillApk(fakeApkName);\n VerifyAdbCall(\"shell\", \"am\", \"kill\", \"--user\", \"all\", fakeApkName);\n Assert.Equal(0, exitCode);\n }", + "start_line": 174, + "end_line": 182, + "start_byte": 6612, + "end_byte": 6967 + }, + { + "name": "UninstallApk", + "code": "[Fact]\n public void UninstallApk()\n {\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n string fakeApkName = $\"{Path.GetRandomFileName()}\";\n int exitCode = runner.UninstallApk(fakeApkName);\n VerifyAdbCall(\"uninstall\", fakeApkName);\n Assert.Equal(0, exitCode);\n }", + "start_line": 164, + "end_line": 172, + "start_byte": 6268, + "end_byte": 6606 + }, + { + "name": "InstallApk", + "code": "[Fact]\n public void InstallApk()\n {\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n string fakeApkPath = Path.Join(s_scratchAndOutputPath, $\"{Path.GetRandomFileName()}.apk\");\n File.Create(fakeApkPath).Close();\n int exitCode = runner.InstallApk(fakeApkPath);\n VerifyAdbCall(\"install\", fakeApkPath);\n Assert.Equal(0, exitCode);\n }", + "start_line": 153, + "end_line": 162, + "start_byte": 5849, + "end_byte": 6262 + }, + { + "name": "KillAdbServer", + "code": "[Fact]\n public void KillAdbServer()\n {\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n runner.KillAdbServer();\n VerifyAdbCall(\"kill-server\");\n }", + "start_line": 145, + "end_line": 151, + "start_byte": 5635, + "end_byte": 5843 + }, + { + "name": "StartAdbServer", + "code": "[Fact]\n public void StartAdbServer()\n {\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n runner.StartAdbServer();\n VerifyAdbCall(\"start-server\");\n }", + "start_line": 137, + "end_line": 143, + "start_byte": 5418, + "end_byte": 5629 + }, + { + "name": "ListDevicesAndArchitectures", + "code": "[Fact]\n public void ListDevicesAndArchitectures()\n {\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n var result = runner.GetDevices();\n VerifyAdbCall(\"devices\", \"-l\");\n\n // Ensure it called, parsed the four random device names and found all four architectures\n foreach (var fakeDevice in _fakeDeviceList)\n {\n VerifyAdbCall(\"-s\", fakeDevice.DeviceSerial, \"shell\", \"getprop\", \"ro.product.cpu.abilist\");\n Assert.Equal(fakeDevice.SupportedArchitectures, result.Single(d => d.DeviceSerial == fakeDevice.DeviceSerial).SupportedArchitectures);\n\n VerifyAdbCall(\"-s\", fakeDevice.DeviceSerial, \"shell\", \"getprop\", \"ro.build.version.sdk\");\n Assert.Equal(fakeDevice.ApiVersion, result.Single(d => d.ApiVersion == fakeDevice.ApiVersion).ApiVersion);\n\n VerifyAdbCall(\"-s\", fakeDevice.DeviceSerial, \"shell\", \"getprop\", \"ro.product.cpu.abi\");\n Assert.Equal(fakeDevice.Architecture, result.Single(d => d.DeviceSerial == fakeDevice.DeviceSerial).Architecture);\n }\n\n Assert.Equal(4, result.Count);\n }", + "start_line": 114, + "end_line": 135, + "start_byte": 4266, + "end_byte": 5412 + }, + { + "name": "WaitForDevice", + "code": "[Fact]\n public void WaitForDevice()\n {\n s_bootCompleteCheckTimes = 0; // Force simulating device is offline\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n string fakeDeviceName = $\"emulator-{new Random().Next(9999)}\";\n runner.SetActiveDevice(new AndroidDevice(fakeDeviceName));\n runner.WaitForDevice();\n\n s_bootCompleteCheckTimes = 0; // Force simulating device is offline\n runner.SetActiveDevice(null);\n runner.WaitForDevice();\n VerifyAdbCall(Times.Exactly(2), \"wait-for-device\");\n VerifyAdbCall(Times.Exactly(2), \"-s\", fakeDeviceName, \"shell\", \"getprop\", \"sys.boot_completed\");\n VerifyAdbCall(Times.Exactly(2), \"shell\", \"getprop\", \"sys.boot_completed\");\n }", + "start_line": 97, + "end_line": 112, + "start_byte": 3481, + "end_byte": 4260 + }, + { + "name": "DumpBugReport", + "code": "[Fact]\n public void DumpBugReport()\n {\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n string pathToDumpBugReport = Path.Join(s_scratchAndOutputPath, Path.GetRandomFileName());\n runner.GetDevice(requiredDeviceId: _fakeDeviceList.First().DeviceSerial);\n runner.DumpBugReport(pathToDumpBugReport);\n VerifyAdbCall(\"bugreport\", $\"{pathToDumpBugReport}.zip\");\n\n Assert.Equal(\"Sample BugReport Output\", File.ReadAllText($\"{pathToDumpBugReport}.zip\"));\n }", + "start_line": 85, + "end_line": 95, + "start_byte": 2942, + "end_byte": 3475 + }, + { + "name": "DumpAdbLog", + "code": "[Fact]\n public void DumpAdbLog()\n {\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n string pathToDumpLogTo = Path.Join(s_scratchAndOutputPath, $\"{Path.GetRandomFileName()}.log\");\n runner.TryDumpAdbLog(pathToDumpLogTo);\n VerifyAdbCall(\"logcat\", \"-d\", \"\");\n\n Assert.Equal(\"Sample LogCat Output\", File.ReadAllText(pathToDumpLogTo));\n }", + "start_line": 74, + "end_line": 83, + "start_byte": 2526, + "end_byte": 2936 + }, + { + "name": "ClearAdbLog", + "code": "[Fact]\n public void ClearAdbLog()\n {\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n runner.ClearAdbLog();\n VerifyAdbCall(\"logcat\", \"-b\", \"all\", \"-c\");\n }", + "start_line": 67, + "end_line": 73, + "start_byte": 2303, + "end_byte": 2521 + }, + { + "name": "GetAdbState", + "code": "[Fact]\n public void GetAdbState()\n {\n var runner = new AdbRunner(_mainLog.Object, _processManager.Object, s_adbPath);\n string result = runner.GetAdbState();\n VerifyAdbCall(\"get-state\");\n Assert.Equal(\"device\", result);\n }", + "start_line": 58, + "end_line": 65, + "start_byte": 2039, + "end_byte": 2297 + }, + { + "name": "Dispose", + "code": "public void Dispose()\n {\n Directory.Delete(s_scratchAndOutputPath, true);\n GC.SuppressFinalize(this);\n }", + "start_line": 50, + "end_line": 54, + "start_byte": 1890, + "end_byte": 2014 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/TestReporterTests.cs": [ + { + "name": "ParseResultLaunchTimedOutTest", + "code": "[Fact]\n public async Task ParseResultLaunchTimedOutTest()\n {\n // set the listener to return a task that we are not going to complete\n var cancellationTokenSource = new CancellationTokenSource();\n var tcs = new TaskCompletionSource();\n _listener.Setup(l => l.ConnectedTask).Returns(tcs.Task); // will never be set to be completed\n var listenerLog = Mock.Of(l => l.FullPath == \"/this/path/does/not/exist\");\n _listener.Setup(l => l.TestLog).Returns(listenerLog);\n\n var failurePath = Path.Combine(_logsDirectory, \"my-failure.xml\");\n var failureLog = new Mock();\n failureLog.Setup(l => l.FullPath).Returns(failurePath);\n _logs.Setup(l => l.Create(It.IsAny(), It.IsAny(), null)).Returns(failureLog.Object);\n\n // create some data for the stderr\n var stderr = Path.GetTempFileName();\n using (var stream = File.Create(stderr))\n using (var writer = new StreamWriter(stream))\n {\n await writer.WriteAsync(\"Some data to be added to stderr of the failure\");\n }\n _mainLog.Setup(l => l.FullPath).Returns(stderr);\n\n var testReporter = BuildTestReporter();\n\n // this is called when launch timeout expires\n // false means we never received a connection which would flip it to true\n testReporter.LaunchCallback(Task.FromResult(false));\n\n var (result, resultMessage) = await testReporter.ParseResult();\n Assert.Equal(TestExecutingResult.LaunchTimedOut, result);\n\n // verify that we do not try to kill a process that never got started\n _processManager.Verify(p => p.KillTreeAsync(It.IsAny(), It.IsAny(), true), Times.Never);\n _crashReporter.Verify(c => c.EndCaptureAsync(TimeSpan.FromSeconds(5)), Times.Once);\n }", + "start_line": 393, + "end_line": 429, + "start_byte": 16428, + "end_byte": 18285 + }, + { + "name": "ParseResultTimeoutTestsTest", + "code": "[Fact]\n public async Task ParseResultTimeoutTestsTest()\n {\n // more complicated test, we need to fake a process timeout, then ensure that the result is the expected one\n var tcs = new TaskCompletionSource();\n _listener.Setup(l => l.CompletionTask).Returns(tcs.Task); // will never be set to be completed\n\n var listenerLog = new Mock();\n _listener.Setup(l => l.TestLog).Returns(listenerLog.Object);\n listenerLog.Setup(l => l.FullPath).Returns(\"/my/missing/path\");\n\n // ensure that we do provide the required runlog information so that we know if it was a launch failure or not, we are\n // not dealing with the launch faliure\n _runLog.Setup(l => l.GetReader()).Returns(new StreamReader(GetRunLogSample()));\n\n var failurePath = Path.Combine(_logsDirectory, \"my-failure.xml\");\n var failureLog = new Mock();\n failureLog.Setup(l => l.FullPath).Returns(failurePath);\n _logs.Setup(l => l.Create(It.IsAny(), It.IsAny(), null)).Returns(failureLog.Object);\n\n // create some data for the stderr\n var stderr = Path.GetTempFileName();\n using (var stream = File.Create(stderr))\n using (var writer = new StreamWriter(stream))\n {\n await writer.WriteAsync(\"Some data to be added to stderr of the failure\");\n }\n _mainLog.Setup(l => l.FullPath).Returns(stderr);\n\n var testReporter = BuildTestReporter();\n var processResult = new ProcessExecutionResult() { TimedOut = true, ExitCode = 0 };\n await testReporter.CollectDeviceResult(processResult);\n // we should have timeout, since the task completion source was never set\n var (result, failure) = await testReporter.ParseResult();\n Assert.False(testReporter.Success, \"success\");\n\n // verify that we state that there was a timeout\n _mainLog.Verify(l => l.WriteLine(It.Is(s => s.Equals(\"Test run never launched\"))), Times.Once);\n // assert that the timeout failure was created.\n Assert.True(File.Exists(failurePath), \"failure path\");\n var isTimeoutFailure = false;\n using (var reader = new StreamReader(failurePath))\n {\n string line = null;\n while ((line = await reader.ReadLineAsync()) != null)\n {\n if (line.Contains(\"App Timeout\"))\n {\n isTimeoutFailure = true;\n break;\n }\n }\n }\n Assert.True(isTimeoutFailure, \"correct xml\");\n File.Delete(failurePath);\n }", + "start_line": 335, + "end_line": 390, + "start_byte": 13663, + "end_byte": 16306 + }, + { + "name": "ParseResultSuccessTestsTest", + "code": "[Fact]\n public async Task ParseResultSuccessTestsTest()\n {\n // get a file with a success result so that we can return it as part of the listener log\n var sample = CreateSampleFile(\"NUnitV3SampleSuccess.xml\");\n var listenerLog = Mock.Of(l => l.FullPath == sample);\n _listener.Setup(l => l.TestLog).Returns(listenerLog);\n\n var testReporter = BuildTestReporter();\n var (result, resultMessage) = await testReporter.ParseResult();\n Assert.Equal(TestExecutingResult.Succeeded, result);\n Assert.Equal(\"Tests run: 5 Passed: 4 Inconclusive: 0 Failed: 0 Ignored: 1\", resultMessage);\n\n // ensure that we do call the crash reporter end capture but with 0, since it was a success\n _crashReporter.Verify(c => c.EndCaptureAsync(It.Is(t => t.TotalSeconds == 0)), Times.Once);\n }", + "start_line": 318, + "end_line": 333, + "start_byte": 12789, + "end_byte": 13657 + }, + { + "name": "ParseResultFailingTestsTest", + "code": "[Fact]\n public async Task ParseResultFailingTestsTest()\n {\n var sample = CreateSampleFile(\"NUnitV3SampleFailure.xml\");\n var listenerLog = Mock.Of(l => l.FullPath == sample);\n _listener.Setup(l => l.TestLog).Returns(listenerLog);\n\n var testReporter = BuildTestReporter();\n var (result, resultMessage) = await testReporter.ParseResult();\n Assert.Equal(TestExecutingResult.Failed, result);\n Assert.Equal(\"Tests run: 5 Passed: 3 Inconclusive: 1 Failed: 2 Ignored: 4\", resultMessage);\n\n // ensure that we do call the crash reporter end capture but with 0, since it was a success\n _crashReporter.Verify(c => c.EndCaptureAsync(TimeSpan.FromSeconds(5)), Times.Once);\n }", + "start_line": 302, + "end_line": 316, + "start_byte": 12033, + "end_byte": 12783 + }, + { + "name": "CreateSampleFile", + "code": "private string CreateSampleFile(string resourceName)\n {\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(resourceName, StringComparison.Ordinal)).FirstOrDefault();\n var tempPath = Path.GetTempFileName();\n using var outputStream = new StreamWriter(tempPath);\n using var sampleStream = new StreamReader(GetType().Assembly.GetManifestResourceStream(name));\n string line;\n while ((line = sampleStream.ReadLine()) != null)\n {\n outputStream.WriteLine(line);\n }\n\n return tempPath;\n }", + "start_line": 287, + "end_line": 300, + "start_byte": 11440, + "end_byte": 12027 + }, + { + "name": "LaunchCallbackLaunchTimedOutTest", + "code": "[Fact]\n public void LaunchCallbackLaunchTimedOutTest()\n {\n var tcs = new TaskCompletionSource();\n _listener.Setup(l => l.ConnectedTask).Returns(Task.FromResult(false));\n var testReporter = BuildTestReporter();\n var t = Task.FromResult(false);\n testReporter.LaunchCallback(t);\n _mainLog.Verify(l => l.WriteLine(It.Is(s => s.Contains(\"Test failed to start\"))), Times.Once);\n }", + "start_line": 275, + "end_line": 284, + "start_byte": 10947, + "end_byte": 11386 + }, + { + "name": "LaunchCallbackTimedOutTest", + "code": "[Fact]\n public void LaunchCallbackTimedOutTest()\n {\n var tcs = new TaskCompletionSource();\n _listener.Setup(l => l.ConnectedTask).Returns(Task.FromResult(true));\n var testReporter = BuildTestReporter();\n var t = Task.FromResult(false);\n testReporter.LaunchCallback(t);\n _mainLog.Verify(l => l.WriteLine(It.Is(s => s.Contains(\"Test execution timed out\"))), Times.Once);\n }", + "start_line": 264, + "end_line": 273, + "start_byte": 10505, + "end_byte": 10941 + }, + { + "name": "LaunchCallbackSuccessTest", + "code": "[Fact]\n public void LaunchCallbackSuccessTest()\n {\n var testReporter = BuildTestReporter();\n var t = Task.FromResult(true);\n testReporter.LaunchCallback(t);\n _mainLog.Verify(l => l.WriteLine(It.Is(s => s.Equals(\"Test execution started\"))), Times.Once);\n }", + "start_line": 255, + "end_line": 262, + "start_byte": 10199, + "end_byte": 10499 + }, + { + "name": "LaunchCallbackCanceledTest", + "code": "[Fact]\n public void LaunchCallbackCanceledTest()\n {\n var testReporter = BuildTestReporter();\n var tcs = new TaskCompletionSource();\n tcs.TrySetCanceled();\n testReporter.LaunchCallback(tcs.Task);\n // verify we notify that the execution was canceled\n _mainLog.Verify(l => l.WriteLine(It.Is(s => s.Equals(\"Test execution was cancelled\"))), Times.Once);\n }", + "start_line": 244, + "end_line": 253, + "start_byte": 9776, + "end_byte": 10193 + }, + { + "name": "LaunchCallbackFaultedTest", + "code": "[Fact]\n public void LaunchCallbackFaultedTest()\n {\n var testReporter = BuildTestReporter();\n var t = Task.FromException(new Exception(\"test\"));\n testReporter.LaunchCallback(t);\n // verify that we did report the launch proble\n _mainLog.Verify(l => l.WriteLine(\n It.Is(s => s.StartsWith($\"Test execution failed:\"))), Times.Once);\n }", + "start_line": 233, + "end_line": 242, + "start_byte": 9372, + "end_byte": 9770 + }, + { + "name": "CollectDeviceResultSuccessTest", + "code": "[Theory]\n [InlineData(0)]\n [InlineData(1)]\n public async Task CollectDeviceResultSuccessTest(int processExitCode)\n {\n // fake the best case scenario, we got the process to exit correctly\n var processResult = new ProcessExecutionResult() { TimedOut = false, ExitCode = processExitCode };\n\n // ensure we do not consider it to be a launch failure\n _runLog.Setup(l => l.GetReader()).Returns(new StreamReader(GetRunLogSample()));\n\n var testReporter = BuildTestReporter();\n await testReporter.CollectDeviceResult(processResult);\n\n // we should have timeout, since the task completion source was never set\n if (processExitCode != 0)\n {\n Assert.False(testReporter.Success, \"success\");\n }\n else\n {\n Assert.True(testReporter.Success, \"success\");\n }\n }", + "start_line": 208, + "end_line": 231, + "start_byte": 8497, + "end_byte": 9366 + }, + { + "name": "CollectDeviceResultTimeoutTest", + "code": "[Fact]\n public async Task CollectDeviceResultTimeoutTest()\n {\n // set the listener to return a task that we are not going to complete\n var tcs = new TaskCompletionSource();\n _listener.Setup(l => l.CompletionTask).Returns(tcs.Task); // will never be set to be completed\n\n // ensure that we do provide the required runlog information so that we know if it was a launch failure or not, we are\n // not dealing with the launch faliure\n _runLog.Setup(l => l.GetReader()).Returns(new StreamReader(GetRunLogSample()));\n\n var testReporter = BuildTestReporter();\n var processResult = new ProcessExecutionResult() { TimedOut = true, ExitCode = 0 };\n await testReporter.CollectDeviceResult(processResult);\n // we should have timeout, since the task completion source was never set\n Assert.False(testReporter.Success, \"success\");\n }", + "start_line": 190, + "end_line": 206, + "start_byte": 7580, + "end_byte": 8491 + }, + { + "name": "CollectSimulatorResultsSuccessLaunchTest", + "code": "[Theory]\n [InlineData(0)]\n [InlineData(1)]\n public async Task CollectSimulatorResultsSuccessLaunchTest(int processExitCode)\n {\n // fake the best case scenario, we got the process to exit correctly\n var cancellationTokenSource = new CancellationTokenSource();\n var tcs = new TaskCompletionSource();\n var processResult = new ProcessExecutionResult() { TimedOut = false, ExitCode = processExitCode };\n\n // ensure we do not consider it to be a launch failure\n _runLog.Setup(l => l.GetReader()).Returns(new StreamReader(GetRunLogSample()));\n\n var testReporter = BuildTestReporter();\n await testReporter.CollectSimulatorResult(processResult);\n\n // we should have timeout, since the task completion source was never set\n if (processExitCode != 0)\n {\n Assert.False(testReporter.Success, \"success\");\n }\n else\n {\n Assert.True(testReporter.Success, \"success\");\n }\n\n if (processExitCode != 0)\n {\n _processManager.Verify(p => p.KillTreeAsync(It.IsAny(), It.IsAny(), true), Times.Once);\n }\n else\n {\n // verify that we do not try to kill a process that never got started\n _processManager.Verify(p => p.KillTreeAsync(It.IsAny(), It.IsAny(), true), Times.Never);\n }\n }", + "start_line": 153, + "end_line": 188, + "start_byte": 6176, + "end_byte": 7574 + }, + { + "name": "CollectSimulatorResultsLaunchFailureTest", + "code": "[Theory]\n [InlineData(\"Some Data\")]\n [InlineData(null)]\n public async Task CollectSimulatorResultsLaunchFailureTest(string runLogData)\n {\n // similar to the above test, but in this case we ware going to fake a launch issue, that is, the runlog\n // does not contain a PID that we can parse and later try to kill.\n\n // set the listener to return a task that we are not going to complete\n var cancellationTokenSource = new CancellationTokenSource();\n var tcs = new TaskCompletionSource();\n _listener.Setup(l => l.CompletionTask).Returns(tcs.Task); // will never be set to be completed\n\n // empty test file to be returned as the runlog stream\n var tmpFile = Path.GetTempFileName();\n if (!string.IsNullOrEmpty(runLogData))\n {\n using (var writer = new StreamWriter(tmpFile))\n {\n writer.Write(runLogData);\n }\n }\n\n // ensure that we do provide the required runlog information so that we know if it was a launch failure or not, we are\n // not dealing with the launch faliure\n _runLog.Setup(l => l.GetReader()).Returns(new StreamReader(File.Create(tmpFile)));\n\n var testReporter = BuildTestReporter();\n var processResult = new ProcessExecutionResult() { TimedOut = true, ExitCode = 0 };\n await testReporter.CollectSimulatorResult(processResult);\n // we should have timeout, since the task completion source was never set\n Assert.False(testReporter.Success, \"success\");\n\n // verify that we do not try to kill a process that never got started\n _processManager.Verify(p => p.KillTreeAsync(It.IsAny(), It.IsAny(), true), Times.Never);\n File.Delete(tmpFile);\n }", + "start_line": 115, + "end_line": 151, + "start_byte": 4390, + "end_byte": 6170 + }, + { + "name": "CollectSimulatorResultsSucess", + "code": "[Fact]\n public async Task CollectSimulatorResultsSucess()\n {\n // set the listener to return a task that we are not going to complete\n var cancellationTokenSource = new CancellationTokenSource();\n var tcs = new TaskCompletionSource();\n _listener.Setup(l => l.CompletionTask).Returns(tcs.Task); // will never be set to be completed\n\n // ensure that we do provide the required runlog information so that we know if it was a launch failure or not, we are\n // not dealing with the launch faliure\n _runLog.Setup(l => l.GetReader()).Returns(new StreamReader(GetRunLogSample()));\n\n var testReporter = BuildTestReporter();\n var processResult = new ProcessExecutionResult() { TimedOut = false, ExitCode = 0 };\n await testReporter.CollectSimulatorResult(processResult);\n // we should have timeout, since the task completion source was never set\n Assert.True(testReporter.Success, \"success\");\n\n _processManager.Verify(p => p.KillTreeAsync(It.IsAny(), It.IsAny(), true), Times.Never);\n }", + "start_line": 92, + "end_line": 111, + "start_byte": 3131, + "end_byte": 4222 + }, + { + "name": "BuildTestReporter", + "code": "private TestReporter BuildTestReporter()\n {\n _logs.Setup(l => l.Directory).Returns(_logsDirectory);\n\n return new TestReporter(_processManager.Object,\n _mainLog.Object,\n _runLog.Object,\n _logs.Object,\n _crashReporter.Object,\n _listener.Object,\n _parser,\n _appInformation,\n RunMode.iOS,\n XmlResultJargon.NUnitV3,\n _deviceName,\n TimeSpan.FromSeconds(2));\n }", + "start_line": 74, + "end_line": 90, + "start_byte": 2630, + "end_byte": 3125 + }, + { + "name": "GetRunLogSample", + "code": "private Stream GetRunLogSample()\n {\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(\"run-log.txt\", StringComparison.Ordinal)).FirstOrDefault();\n return GetType().Assembly.GetManifestResourceStream(name);\n }", + "start_line": 68, + "end_line": 72, + "start_byte": 2366, + "end_byte": 2624 + }, + { + "name": "Dispose", + "code": "public void Dispose()\n {\n if (Directory.Exists(_logsDirectory))\n {\n Directory.Delete(_logsDirectory, true);\n }\n GC.SuppressFinalize(this);\n }", + "start_line": 59, + "end_line": 66, + "start_byte": 2174, + "end_byte": 2360 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/AppBundleInformationParserTests.cs": [ + { + "name": "ParseFromProjectWithLocatorTest", + "code": "[Fact]\n public async Task ParseFromProjectWithLocatorTest()\n {\n var locator = new Mock();\n locator\n .Setup(x => x.LocateAppBundle(It.IsAny(), s_projectFilePath, TestTarget.Simulator_iOS64, \"Debug\"))\n .ReturnsAsync(\"bin2\")\n .Verifiable();\n\n var parser = new AppBundleInformationParser(Mock.Of(), locator.Object);\n\n var info = await parser.ParseFromProject(s_projectFilePath, TestTarget.Simulator_iOS64, \"Debug\");\n\n Assert.Equal(AppName, info.AppName);\n Assert.Equal(s_appPath2, info.AppPath);\n Assert.Equal(s_appPath2, info.LaunchAppPath);\n Assert.Equal(AppName, info.BundleIdentifier);\n\n locator.VerifyAll();\n }", + "start_line": 66, + "end_line": 85, + "start_byte": 2539, + "end_byte": 3311 + }, + { + "name": "ParseFromMacCatalystProjectTest", + "code": "[Fact]\n public async Task ParseFromMacCatalystProjectTest()\n {\n var parser = new AppBundleInformationParser(Mock.Of());\n\n var info = await parser.ParseFromProject(s_projectFilePath, TestTarget.MacCatalyst, \"Debug\");\n\n Assert.Equal(AppName, info.AppName);\n Assert.Equal(s_appPath, info.AppPath);\n Assert.Equal(s_appPath, info.LaunchAppPath);\n Assert.Equal(AppName, info.BundleIdentifier);\n Assert.Equal(Executable, info.BundleExecutable);\n }", + "start_line": 52, + "end_line": 64, + "start_byte": 2011, + "end_byte": 2533 + }, + { + "name": "ParseFromProjectTest", + "code": "[Fact]\n public async Task ParseFromProjectTest()\n {\n var parser = new AppBundleInformationParser(Mock.Of());\n\n var info = await parser.ParseFromProject(s_projectFilePath, TestTarget.Simulator_iOS64, \"Debug\");\n\n Assert.Equal(AppName, info.AppName);\n Assert.Equal(s_appPath, info.AppPath);\n Assert.Equal(s_appPath, info.LaunchAppPath);\n Assert.Equal(AppName, info.BundleIdentifier);\n }", + "start_line": 39, + "end_line": 50, + "start_byte": 1547, + "end_byte": 2005 + }, + { + "name": "Dispose", + "code": "public void Dispose()\n {\n Directory.Delete(s_appPath, true);\n Directory.Delete(s_appPath2, true);\n GC.SuppressFinalize(this);\n }", + "start_line": 32, + "end_line": 37, + "start_byte": 1386, + "end_byte": 1541 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/CrashSnapshotReporterTests.cs": [ + { + "name": "DeviceCaptureTest", + "code": "[Fact]\n public async Task DeviceCaptureTest()\n {\n var tempFilePath = Path.GetTempFileName();\n\n const string deviceName = \"Sample-iPhone\";\n const string crashLogPath = \"/path/to/crash.log\";\n const string symbolicateLogPath = \"/path/to/\" + deviceName + \".symbolicated.log\";\n\n var crashReport = Mock.Of(x => x.FullPath == crashLogPath);\n var symbolicateReport = Mock.Of(x => x.FullPath == symbolicateLogPath);\n\n // Crash report is added\n _logs.Setup(x => x.Create(deviceName, \"Crash report: \" + deviceName, It.IsAny()))\n .Returns(crashReport);\n\n // Symbolicate report is added\n _logs.Setup(x => x.Create(\"crash.symbolicated.log\", \"Symbolicated crash report: crash.log\", It.IsAny()))\n .Returns(symbolicateReport);\n\n _processManager.SetReturnsDefault(Task.FromResult(new ProcessExecutionResult() { ExitCode = 0 }));\n\n // Act\n var snapshotReport = new CrashSnapshotReporter(_processManager.Object,\n _log.Object,\n _logs.Object,\n true,\n deviceName,\n () => tempFilePath);\n\n File.WriteAllLines(tempFilePath, new[] { \"crash 1\", \"crash 2\" });\n\n await snapshotReport.StartCaptureAsync();\n\n File.WriteAllLines(tempFilePath, new[] { \"Sample-iPhone\" });\n\n await snapshotReport.EndCaptureAsync(TimeSpan.FromSeconds(10));\n\n // Verify\n _logs.VerifyAll();\n\n // List of crash reports is retrieved\n _processManager.Verify(\n x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() ==\n StringUtils.FormatArguments(\n $\"--list-crash-reports={tempFilePath}\") + \" \" +\n $\"--devname {StringUtils.FormatArguments(deviceName)}\"),\n _log.Object,\n TimeSpan.FromMinutes(1),\n null,\n It.IsAny(),\n null),\n Times.Exactly(2));\n\n // Device crash log is downloaded\n _processManager.Verify(\n x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() ==\n StringUtils.FormatArguments(\n $\"--download-crash-report={deviceName}\") + \" \" +\n StringUtils.FormatArguments($\"--download-crash-report-to={crashLogPath}\") + \" \" +\n $\"--devname {StringUtils.FormatArguments(deviceName)}\"),\n _log.Object,\n TimeSpan.FromMinutes(1),\n null,\n It.IsAny(),\n null),\n Times.Once);\n\n // Symbolicate is ran\n _processManager.Verify(\n x => x.ExecuteCommandAsync(\n Path.Combine(_symbolicatePath, \"symbolicatecrash\"),\n It.Is>(args => args.First() == crashLogPath),\n symbolicateReport,\n TimeSpan.FromMinutes(1),\n It.IsAny>(),\n null),\n Times.Once);\n }", + "start_line": 54, + "end_line": 134, + "start_byte": 1922, + "end_byte": 5088 + }, + { + "name": "Dispose", + "code": "public void Dispose()\n {\n Directory.Delete(_tempXcodeRoot, true);\n GC.SuppressFinalize(this);\n }", + "start_line": 48, + "end_line": 52, + "start_byte": 1800, + "end_byte": 1916 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/TestExecutingResultTests.cs": [ + { + "name": "ResultHasFlag", + "code": "[Theory]\n [InlineData(\n TestExecutingResult.LaunchTimedOut,\n new[]\n {\n TestExecutingResult.TimedOut,\n TestExecutingResult.LaunchFailure,\n TestExecutingResult.Failed,\n }\n )]\n public void ResultHasFlag(TestExecutingResult result, TestExecutingResult[] flags)\n {\n foreach (var flag in flags)\n {\n Assert.True(result.HasFlag(flag), $\"{result} should have {flag}\");\n }\n }", + "start_line": 65, + "end_line": 81, + "start_byte": 1905, + "end_byte": 2378 + }, + { + "name": "FlagIsPresentWhereItShouldBe", + "code": "[Theory]\n [InlineData(\n new[]\n {\n TestExecutingResult.Crashed,\n TestExecutingResult.TimedOut,\n TestExecutingResult.HarnessException,\n TestExecutingResult.LaunchFailure,\n TestExecutingResult.BuildFailure,\n TestExecutingResult.LaunchTimedOut,\n TestExecutingResult.Failed,\n },\n TestExecutingResult.Failed\n )]\n [InlineData(\n new[]\n {\n TestExecutingResult.Building,\n TestExecutingResult.BuildQueued,\n TestExecutingResult.Built,\n TestExecutingResult.Running,\n TestExecutingResult.RunQueued,\n TestExecutingResult.InProgress,\n TestExecutingResult.StateMask,\n },\n TestExecutingResult.InProgress\n )]\n [InlineData(\n new[]\n {\n TestExecutingResult.Succeeded,\n TestExecutingResult.BuildSucceeded,\n },\n TestExecutingResult.Succeeded\n )]\n public void FlagIsPresentWhereItShouldBe(TestExecutingResult[] withFlag, TestExecutingResult flag)\n {\n var withoutFlag = Enum.GetValues(typeof(TestExecutingResult))\n .Cast()\n .Except(withFlag);\n\n foreach (var result in withoutFlag)\n {\n Assert.False(result.HasFlag(flag), $\"{result} should not have {flag}\");\n }\n\n foreach (var result in withFlag)\n {\n Assert.True(result.HasFlag(flag), $\"{result} should have {flag}\");\n }\n }", + "start_line": 13, + "end_line": 63, + "start_byte": 353, + "end_byte": 1899 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/ResultFileHandlerTests.cs": [ + { + "name": "DeviceOsVersion18FileMissingReturnsFalse", + "code": "[Fact]\n public async Task DeviceOsVersion18FileMissingReturnsFalse()\n {\n Mock pm = new Mock();\n Mock log = new Mock();\n ResultFileHandler handler = CreateHandler(pm, log);\n\n if (File.Exists(_tempFile))\n File.Delete(_tempFile);\n\n bool result = await handler.CopyResultsAsync(\n RunMode.iOS, false, \"18.0\", \"udid\", \"bundle\", _tempFile, CancellationToken.None);\n\n Assert.False(result);\n log.Verify(l => l.WriteLine($\"Failed to copy results file from device. Expected at: {_tempFile}\"), Times.Once);\n }", + "start_line": 156, + "end_line": 171, + "start_byte": 5581, + "end_byte": 6238 + }, + { + "name": "DeviceOsVersion18FileExistsReturnsTrue", + "code": "[Fact]\n public async Task DeviceOsVersion18FileExistsReturnsTrue()\n {\n Mock pm = new Mock();\n Mock log = new Mock();\n ResultFileHandler handler = CreateHandler(pm, log);\n\n File.WriteAllText(_tempFile, \"dummy\");\n\n bool result = await handler.CopyResultsAsync(\n RunMode.iOS, false, \"18.0\", \"udid\", \"bundle\", _tempFile, CancellationToken.None);\n\n Assert.True(result);\n }", + "start_line": 141, + "end_line": 154, + "start_byte": 5066, + "end_byte": 5575 + }, + { + "name": "DeviceOsVersionLessThan18ReturnsTrue", + "code": "[Fact]\n public async Task DeviceOsVersionLessThan18ReturnsTrue()\n {\n Mock pm = new Mock();\n Mock log = new Mock();\n ResultFileHandler handler = CreateHandler(pm, log);\n\n bool result = await handler.CopyResultsAsync(\n RunMode.iOS, false, \"17.4\", \"udid\", \"bundle\", _tempFile, CancellationToken.None);\n\n Assert.True(result);\n }", + "start_line": 128, + "end_line": 139, + "start_byte": 4601, + "end_byte": 5060 + }, + { + "name": "DeviceBadOsVersionFormatThrowsException", + "code": "[Fact]\n public async Task DeviceBadOsVersionFormatThrowsException()\n {\n Mock pm = new Mock();\n Mock log = new Mock();\n ResultFileHandler handler = CreateHandler(pm, log);\n\n var exception = await Assert.ThrowsAsync(async () =>\n await handler.CopyResultsAsync(\n RunMode.iOS, false, \"notanumber\", \"udid\", \"bundle\", _tempFile, CancellationToken.None));\n\n Assert.Equal(\"Device OS version is not in the expected format.\", exception.Message);\n }", + "start_line": 114, + "end_line": 126, + "start_byte": 3990, + "end_byte": 4595 + }, + { + "name": "SimulatorOsVersion18FileMissingReturnsFalse", + "code": "[Fact]\n public async Task SimulatorOsVersion18FileMissingReturnsFalse()\n {\n Mock pm = new Mock();\n Mock log = new Mock();\n ResultFileHandler handler = CreateHandler(pm, log);\n\n if (File.Exists(_tempFile))\n File.Delete(_tempFile);\n\n bool result = await handler.CopyResultsAsync(\n RunMode.iOS, true, \"Simulator 18.0\", \"udid\", \"bundle\", _tempFile, CancellationToken.None);\n\n Assert.False(result);\n log.Verify(l => l.WriteLine($\"Failed to copy results file from simulator. Expected at: {_tempFile}\"), Times.Once);\n }", + "start_line": 97, + "end_line": 112, + "start_byte": 3312, + "end_byte": 3984 + }, + { + "name": "SimulatorOsVersion18FileExistsReturnsTrue", + "code": "[Fact]\n public async Task SimulatorOsVersion18FileExistsReturnsTrue()\n {\n Mock pm = new Mock();\n Mock log = new Mock();\n ResultFileHandler handler = CreateHandler(pm, log);\n\n File.WriteAllText(_tempFile, \"dummy\");\n\n bool result = await handler.CopyResultsAsync(\n RunMode.iOS, true, \"Simulator 18.0\", \"udid\", \"bundle\", _tempFile, CancellationToken.None);\n\n Assert.True(result);\n }", + "start_line": 82, + "end_line": 95, + "start_byte": 2785, + "end_byte": 3306 + }, + { + "name": "SimulatorOsVersionLessThan18ReturnsFalse", + "code": "[Fact]\n public async Task SimulatorOsVersionLessThan18ReturnsFalse()\n {\n Mock pm = new Mock();\n Mock log = new Mock();\n ResultFileHandler handler = CreateHandler(pm, log);\n\n bool result = await handler.CopyResultsAsync(\n RunMode.iOS, true, \"Simulator 17.4\", \"udid\", \"bundle\", _tempFile, CancellationToken.None);\n\n Assert.True(result);\n }", + "start_line": 69, + "end_line": 80, + "start_byte": 2307, + "end_byte": 2779 + }, + { + "name": "SimulatorBadOsVersionNumberThrowsException", + "code": "[Fact]\n public async Task SimulatorBadOsVersionNumberThrowsException()\n {\n Mock pm = new Mock();\n Mock log = new Mock();\n ResultFileHandler handler = CreateHandler(pm, log);\n\n var exception = await Assert.ThrowsAsync(async () =>\n await handler.CopyResultsAsync(\n RunMode.iOS, true, \"Simulator notanumber\", \"udid\", \"bundle\", _tempFile, CancellationToken.None));\n\n Assert.Equal(\"Simulator OS version is not in the expected format.\", exception.Message);\n }", + "start_line": 55, + "end_line": 67, + "start_byte": 1681, + "end_byte": 2301 + }, + { + "name": "SimulatorBadOsVersionFormatThrowsException", + "code": "[Fact]\n public async Task SimulatorBadOsVersionFormatThrowsException()\n {\n Mock pm = new Mock();\n Mock log = new Mock();\n ResultFileHandler handler = CreateHandler(pm, log);\n\n var exception = await Assert.ThrowsAsync(async () =>\n await handler.CopyResultsAsync(\n RunMode.iOS, true, \"Simulator\", \"udid\", \"bundle\", _tempFile, CancellationToken.None));\n\n Assert.Equal(\"Simulator OS version is not in the expected format.\", exception.Message);\n }", + "start_line": 41, + "end_line": 53, + "start_byte": 1066, + "end_byte": 1675 + }, + { + "name": "CreateHandler", + "code": "private static ResultFileHandler CreateHandler(\n Mock processManagerMock,\n Mock logMock)\n {\n return new ResultFileHandler(processManagerMock.Object, logMock.Object);\n }", + "start_line": 34, + "end_line": 39, + "start_byte": 825, + "end_byte": 1060 + }, + { + "name": "Dispose", + "code": "public void Dispose()\n {\n if (File.Exists(_tempFile))\n {\n File.Delete(_tempFile);\n }\n }", + "start_line": 26, + "end_line": 32, + "start_byte": 694, + "end_byte": 819 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/XmlResultParserTests.cs": [ + { + "name": "NUnitV3MultipleTestFailures", + "code": "[Fact]\n public void NUnitV3MultipleTestFailures()\n {\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(\"NUnitV3SampleFailures.xml\", StringComparison.Ordinal)).FirstOrDefault();\n using var writer = new StringWriter();\n using var stream = GetType().Assembly.GetManifestResourceStream(name);\n using var reader = new StreamReader(stream);\n _resultParser.GenerateTestReport(writer, reader, XmlResultJargon.NUnitV3);\n\n var expectedOutput =\n@\"
\n
    \n
  • \nBug17793: Not signalled twice in 5s
    \n Expected: True
    \n But was: False
    \n
    \n
  • \n
  • \nBug2443: Not signalled twice in 5s
    \n Expected: True
    \n But was: False
    \n
    \n
  • \n
  • \nCreateTimer_NewSignature: WaitOne
    \n Expected: True
    \n But was: False
    \n
    \n
  • \n
\n
\n\";\n Assert.Equal(writer.ToString().Replace(\"\\r\", \"\"), expectedOutput.Replace(\"\\r\", \"\"));\n }", + "start_line": 535, + "end_line": 569, + "start_byte": 24401, + "end_byte": 25383 + }, + { + "name": "NUnitV2GenerateTestReportWithInlineDataFailures", + "code": "[Fact]\n public void NUnitV2GenerateTestReportWithInlineDataFailures()\n {\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(\"TestCaseFailures.xml\", StringComparison.Ordinal)).FirstOrDefault();\n using var writer = new StringWriter();\n using var stream = GetType().Assembly.GetManifestResourceStream(name);\n using var reader = new StreamReader(stream);\n _resultParser.GenerateTestReport(writer, reader, XmlResultJargon.NUnitV2);\n\n var expectedOutput =\n@\"
\n
    \n
  • \nXamarin.MTouch.FastDev_LinkAll(iOS): message
  • \n
  • \nXamarin.MTouch.RebuildWhenReferenceSymbolsInCode: message
  • \n
\n
\n\";\n Assert.Equal(writer.ToString(), expectedOutput);\n }", + "start_line": 513, + "end_line": 533, + "start_byte": 23626, + "end_byte": 24395 + }, + { + "name": "NUnitV2GenerateTestReport", + "code": "[Fact]\n public void NUnitV2GenerateTestReport()\n {\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(\"NUnitV2SampleFailure.xml\", StringComparison.Ordinal)).FirstOrDefault();\n using var writer = new StringWriter();\n using var stream = GetType().Assembly.GetManifestResourceStream(name);\n using var reader = new StreamReader(stream);\n _resultParser.GenerateTestReport(writer, reader, XmlResultJargon.NUnitV2);\n var expectedOutput =\n@\"
\n
    \n
  • \nErrorTest1:
    \n\" + \"Multiline
    \\nerror
    \\nmessage
    \" + @\"\n
  • \n
  • \nNUnit.Tests.Assemblies.MockTestFixture.FailingTest: Intentional failure
  • \n
  • \nNUnit.Tests.Assemblies.MockTestFixture.TestWithException: System.ApplicationException : Intentional Exception
  • \n
\n
\n\";\n Assert.Equal(expectedOutput, writer.ToString());\n }", + "start_line": 488, + "end_line": 511, + "start_byte": 22681, + "end_byte": 23620 + }, + { + "name": "HumanReadableResultsTest", + "code": "[Theory]\n [InlineData(\"Issue8214.xml\", true, \"Tests run: 2376 Passed: 2301 Inconclusive: 13 Failed: 1 Ignored: 74\")] // https://github.com/xamarin/xamarin-macios/issues/8214\n [InlineData(\"NUnitV2Sample.xml\", true, \"Tests run: 21 Passed: 4 Inconclusive: 1 Failed: 2 Ignored: 7\")]\n [InlineData(\"NUnitV2SampleFailure.xml\", true, \"Tests run: 21 Passed: 4 Inconclusive: 1 Failed: 2 Ignored: 7\")]\n [InlineData(\"NUnitV3Sample.xml\", true, \"Tests run: 25 Passed: 12 Inconclusive: 1 Failed: 2 Ignored: 4\")]\n [InlineData(\"NUnitV3SampleFailure.xml\", true, \"Tests run: 5 Passed: 3 Inconclusive: 1 Failed: 2 Ignored: 4\")]\n [InlineData(\"TestCaseFailures.xml\", true, \"Tests run: 440 Passed: 405 Inconclusive: 0 Failed: 23 Ignored: 6\")]\n [InlineData(\"TouchUnitSample.xml\", false, \"Tests run: 2354 Passed: 2223 Inconclusive: 13 Failed: 0 Ignored: 59\", new string[] { \"Tests run: 2286 Passed: 2282 Inconclusive: 4 Failed: 0 Ignored: 47\" })] // The counting is a bit off here, seems like that's in Touch.Unit\n [InlineData(\"xUnitSample.xml\", false, \"Tests run: 53821 Passed: 53801 Inconclusive: 0 Failed: 0 Ignored: 20\")]\n [InlineData(\"NUnitV3SampleParameterizedFailure.xml\", true, \"Tests run: 2086 Passed: 2041 Inconclusive: 7 Failed: 2 Ignored: 43\", new string[] { \"\t[FAIL] GHIssue8342(OK,\\\"mandel\\\",\\\"12345678\\\",\\\"mandel\\\",\\\"12345678\\\") : Status not ok\" })]\n public void HumanReadableResultsTest(string xmlFile, bool expectedFailure, string expectedResultLine, string[] additionalLines = null)\n {\n // get the sample xml to parse\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(xmlFile, StringComparison.Ordinal)).FirstOrDefault();\n using var validXmlSource = new StreamReader(GetType().Assembly.GetManifestResourceStream(name));\n using var source = new StreamReader(GetType().Assembly.GetManifestResourceStream(name));\n using var memoryStream = new MemoryStream();\n using var destination = new StreamWriter(memoryStream);\n\n var tempPath = Path.GetTempFileName();\n using (var outputStream = new StreamWriter(tempPath))\n using (var sampleStream = new StreamReader(GetType().Assembly.GetManifestResourceStream(name)))\n {\n string line;\n while ((line = sampleStream.ReadLine()) != null)\n {\n outputStream.WriteLine(line);\n }\n }\n\n // Get the xml type\n Assert.True(_resultParser.IsValidXml(validXmlSource, out var type));\n\n // generate the results\n var (resultLine, failed) = _resultParser.ParseResults(tempPath, type, destination);\n destination.Flush();\n memoryStream.Position = 0;\n using var reader = new StreamReader(memoryStream);\n var output = reader.ReadToEnd();\n\n Assert.Equal(expectedFailure, failed);\n Assert.Equal(expectedResultLine, resultLine);\n\n if (additionalLines != null)\n {\n var lines = output.Split('\\n');\n foreach (var line in additionalLines)\n {\n Assert.Contains(line, lines);\n }\n }\n\n if (expectedFailure)\n {\n Assert.Contains(\"[FAIL]\", output);\n }\n else\n {\n Assert.DoesNotContain(\"[FAIL]\", output);\n }\n }", + "start_line": 426, + "end_line": 486, + "start_byte": 19357, + "end_byte": 22675 + }, + { + "name": "Issue91Test", + "code": "[Fact]\n public void Issue91Test() // make sure that the skipped value is correct according to the provided xml in the issue.\n {\n string expectedResultLine = \"Tests run: 3 Passed: 1 Inconclusive: 0 Failed: 1 Ignored: 1\";\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(\"Issue95.xml\", StringComparison.Ordinal)).FirstOrDefault();\n var tempPath = Path.GetTempFileName();\n using (var outputStream = new StreamWriter(tempPath))\n using (var sampleStream = new StreamReader(GetType().Assembly.GetManifestResourceStream(name)))\n {\n string line;\n while ((line = sampleStream.ReadLine()) != null)\n {\n outputStream.WriteLine(line);\n }\n }\n\n var (resultLine, failed) = _resultParser.ParseResults(tempPath, XmlResultJargon.NUnitV2, (StreamWriter)null);\n\n Assert.True(failed, \"failed\");\n Assert.Equal(expectedResultLine, resultLine);\n }", + "start_line": 404, + "end_line": 424, + "start_byte": 18360, + "end_byte": 19351 + }, + { + "name": "DoNotGenerateHtmlReport", + "code": "[Theory]\n [InlineData(\"Issue8214.xml\", true, \"Tests run: 2376 Passed: 2301 Inconclusive: 13 Failed: 1 Ignored: 74\")] // https://github.com/xamarin/xamarin-macios/issues/8214\n [InlineData(\"NUnitV2Sample.xml\", true, \"Tests run: 21 Passed: 4 Inconclusive: 1 Failed: 2 Ignored: 7\")]\n [InlineData(\"NUnitV2SampleFailure.xml\", true, \"Tests run: 21 Passed: 4 Inconclusive: 1 Failed: 2 Ignored: 7\")]\n [InlineData(\"NUnitV3Sample.xml\", true, \"Tests run: 25 Passed: 12 Inconclusive: 1 Failed: 2 Ignored: 4\")]\n [InlineData(\"NUnitV3SampleFailure.xml\", true, \"Tests run: 5 Passed: 3 Inconclusive: 1 Failed: 2 Ignored: 4\")]\n [InlineData(\"TestCaseFailures.xml\", true, \"Tests run: 440 Passed: 405 Inconclusive: 0 Failed: 23 Ignored: 6\")]\n [InlineData(\"TouchUnitSample.xml\", false, \"Tests run: 2354 Passed: 2223 Inconclusive: 13 Failed: 0 Ignored: 59\")] // The counting is a bit off here, seems like that's in Touch.Unit\n [InlineData(\"xUnitSample.xml\", false, \"Tests run: 53821 Passed: 53801 Inconclusive: 0 Failed: 0 Ignored: 20\")]\n [InlineData(\"NUnitV3SampleParameterizedFailure.xml\", true, \"Tests run: 2086 Passed: 2041 Inconclusive: 7 Failed: 2 Ignored: 43\")]\n public void DoNotGenerateHtmlReport(string xmlFile, bool expectedFailure, string expectedResultLine)\n {\n // get the sample xml to parse\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(xmlFile, StringComparison.Ordinal)).FirstOrDefault();\n using var validXmlSource = new StreamReader(GetType().Assembly.GetManifestResourceStream(name));\n using var source = new StreamReader(GetType().Assembly.GetManifestResourceStream(name));\n\n var tempPath = Path.GetTempFileName();\n using (var outputStream = new StreamWriter(tempPath))\n using (var sampleStream = new StreamReader(GetType().Assembly.GetManifestResourceStream(name)))\n {\n string line;\n while ((line = sampleStream.ReadLine()) != null)\n {\n outputStream.WriteLine(line);\n }\n }\n\n // Get the xml type\n Assert.True(_resultParser.IsValidXml(validXmlSource, out var type));\n\n // generate the results\n var (resultLine, failed) = _resultParser.ParseResults(tempPath, type, humanReadableReportDestination: (StreamWriter)null);\n\n Assert.Equal(expectedFailure, failed);\n Assert.Equal(expectedResultLine, resultLine);\n }", + "start_line": 366, + "end_line": 402, + "start_byte": 15918, + "end_byte": 18354 + }, + { + "name": "Issue8214Test", + "code": "[Fact]\n public void Issue8214Test()\n {\n string expectedResultLine = \"Tests run: 2376 Passed: 2301 Inconclusive: 13 Failed: 1 Ignored: 74\";\n // get the sample that was added to the issue to validate that we do parse the resuls correctly and copy it to a local\n // path to be parsed\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(\"Issue8214.xml\", StringComparison.Ordinal)).FirstOrDefault();\n var tempPath = Path.GetTempFileName();\n var destinationFile = Path.GetTempFileName();\n using (var outputStream = new StreamWriter(tempPath))\n using (var sampleStream = new StreamReader(GetType().Assembly.GetManifestResourceStream(name)))\n {\n string line;\n while ((line = sampleStream.ReadLine()) != null)\n {\n outputStream.WriteLine(line);\n }\n }\n var (resultLine, failed) = _resultParser.ParseResults(tempPath, XmlResultJargon.NUnitV3, destinationFile);\n Assert.True(failed, \"failed\");\n Assert.Equal(expectedResultLine, resultLine);\n // verify that the destination does contain the result line\n string resultLineInDestinationFile = null;\n using (var resultReader = new StreamReader(destinationFile))\n {\n string line;\n while ((line = resultReader.ReadLine()) != null)\n {\n if (line.Contains(\"Tests run:\"))\n {\n resultLineInDestinationFile = line;\n break;\n }\n }\n }\n Assert.NotNull(resultLineInDestinationFile);\n Assert.Equal(expectedResultLine, resultLineInDestinationFile);\n }", + "start_line": 327, + "end_line": 364, + "start_byte": 14181, + "end_byte": 15912 + }, + { + "name": "GenerateFailureTest", + "code": "[Theory]\n [InlineData(XmlResultJargon.NUnitV2)]\n [InlineData(XmlResultJargon.NUnitV3)]\n [InlineData(XmlResultJargon.xUnit)]\n public void GenerateFailureTest(XmlResultJargon jargon)\n {\n var src = \"test-case\";\n var appName = \"MyUnitTest\";\n var variation = \"Debug\";\n var title = \"Testing\";\n var message = \"This is a test\";\n var stderrMessage = \"Something went very wrong\";\n\n var stderrPath = Path.GetTempFileName();\n\n // write the message in the stderrParh that should be read\n using (var writer = new StreamWriter(stderrPath))\n {\n writer.WriteLine(stderrMessage);\n }\n\n // create a path with data in it\n var logs = new Mock();\n var tmpLogMock = new Mock();\n var xmlLogMock = new Mock();\n\n var tmpPath = Path.GetTempFileName();\n var finalPath = Path.GetTempFileName();\n\n // create a number of fake logs to be added to the failure\n var logsDir = Path.GetTempFileName();\n File.Delete(logsDir);\n Directory.CreateDirectory(logsDir);\n var failureLogs = new[] { \"first.txt\", \"second.txt\", \"last.txt\" };\n\n foreach (var file in failureLogs)\n {\n var path = Path.Combine(logsDir, file);\n File.WriteAllText(path, \"\");\n }\n\n // expect the creation of the two diff xml file logs\n _ = logs.Setup(l => l.Create(It.IsAny(), \"Failure Log tmp\", null)).Returns(tmpLogMock.Object);\n _ = logs.Setup(l => l.Create(It.IsAny(), LogType.XmlLog.ToString(), null)).Returns(xmlLogMock.Object);\n if (jargon == XmlResultJargon.NUnitV3)\n {\n _ = logs.Setup(l => l.Directory).Returns(logsDir);\n _ = tmpLogMock.Setup(tmpLog => tmpLog.FullPath).Returns(tmpPath);\n\n }\n\n // return the two temp files so that we can later validate that everything is present\n _ = xmlLogMock.Setup(xmlLog => xmlLog.FullPath).Returns(finalPath);\n\n _resultParser.GenerateFailure(logs.Object, src, appName, variation, title, message, stderrPath, jargon);\n\n // actual assertions do happen in the validation functions\n s_validationMap[jargon](src, appName, variation, title, message, stderrMessage, finalPath, failureLogs.Length);\n\n // verify that we are correctly adding the logs\n logs.Verify(l => l.Create(It.IsAny(), It.IsAny(), null), jargon == XmlResultJargon.NUnitV3 ? Times.AtMost(2) : Times.AtMostOnce());\n if (jargon == XmlResultJargon.NUnitV3)\n {\n logs.Verify(l => l.Directory, Times.Once);\n tmpLogMock.Verify(l => l.FullPath, Times.AtLeastOnce);\n\n }\n\n xmlLogMock.Verify(l => l.FullPath, Times.AtLeastOnce);\n\n // clean files\n File.Delete(stderrPath);\n File.Delete(tmpPath);\n File.Delete(finalPath);\n Directory.Delete(logsDir, true);\n }", + "start_line": 247, + "end_line": 322, + "start_byte": 11102, + "end_byte": 14076 + }, + { + "name": "ValidatexUnitFailure", + "code": "private static void ValidatexUnitFailure(string src, string appName, string variation, string title, string message, string stderrMessage, string xmlPath, int _)\n {\n var doc = XDocument.Load(xmlPath);\n // get the assemlby and validate its attrs\n var assemblies = doc.Descendants().Where(e => e.Name == \"assembly\");\n Assert.Single(assemblies);\n var assemblyNode = assemblies.FirstOrDefault();\n Assert.Equal(title, assemblyNode.Attribute(\"name\").Value);\n Assert.Equal(\"1\", assemblyNode.Attribute(\"total\").Value);\n Assert.Equal(\"1\", assemblyNode.Attribute(\"failed\").Value);\n Assert.Equal(\"0\", assemblyNode.Attribute(\"passed\").Value);\n var collections = assemblyNode.Descendants().Where(e => e.Name == \"collection\");\n Assert.Single(collections);\n var collectionNode = collections.FirstOrDefault();\n // assert the collection attrs\n Assert.Equal(\"1\", collectionNode.Attribute(\"failed\").Value);\n Assert.Equal(\"0\", collectionNode.Attribute(\"passed\").Value);\n }", + "start_line": 228, + "end_line": 245, + "start_byte": 10033, + "end_byte": 11096 + }, + { + "name": "ValidateNUnitV3Failure", + "code": "private static void ValidateNUnitV3Failure(string src, string appName, string variation, string title, string message, string stderrMessage, string xmlPath, int attachemntsCount)\n {\n var doc = XDocument.Load(xmlPath);\n // get test-run and verify attrs\n var testResultNodes = doc.Descendants().Where(e => e.Name == \"test-run\");\n Assert.Single(testResultNodes);\n var testResultNode = testResultNodes.FirstOrDefault();\n Assert.Equal(title, testResultNode.Attribute(\"name\").Value);\n Assert.Equal(\"1\", testResultNode.Attribute(\"testcasecount\").Value);\n Assert.Equal(\"Failed\", testResultNode.Attribute(\"result\").Value);\n Assert.Equal(\"1\", testResultNode.Attribute(\"total\").Value);\n Assert.Equal(\"0\", testResultNode.Attribute(\"passed\").Value);\n Assert.Equal(\"1\", testResultNode.Attribute(\"failed\").Value);\n Assert.Equal(\"1\", testResultNode.Attribute(\"asserts\").Value);\n // important attrs for the import, if they miss, we wont be able to add the files to vsts\n Assert.NotNull(testResultNode.Attribute(\"run-date\").Value);\n Assert.NotNull(testResultNode.Attribute(\"start-time\").Value);\n // get the test-suite and verify the name and fullname are correct\n var testSuite = testResultNode.Descendants().Where(e => e.Name == \"test-suite\" && e.Attribute(\"type\").Value == \"TestFixture\").FirstOrDefault();\n Assert.NotNull(testSuite);\n Assert.Equal(title, testSuite.Attribute(\"name\").Value);\n Assert.Equal(title, testSuite.Attribute(\"fullname\").Value);\n // verify the test case\n var testCase = testSuite.Descendants().Where(e => e.Name == \"test-case\").FirstOrDefault();\n Assert.NotNull(testCase);\n Assert.Equal(\"Failed\", testCase.Attribute(\"result\").Value);\n // validate that we do have attachments\n var attachmentsNode = testCase.Descendants().Where(e => e.Name == \"attachments\").FirstOrDefault();\n Assert.NotNull(attachmentsNode);\n var attachments = attachmentsNode.Descendants().Where(e => e.Name == \"attachment\");\n Assert.Equal(attachemntsCount, attachments.Count());\n }", + "start_line": 195, + "end_line": 226, + "start_byte": 7861, + "end_byte": 10027 + }, + { + "name": "ValidateNUnitV2Failure", + "code": "private static void ValidateNUnitV2Failure(string src, string appName, string variation, string title, string message, string stderrMessage, string xmlPath, int _)\n {\n // load the doc and ensure that all the data is correct setup\n var doc = XDocument.Load(xmlPath);\n var testResultsNodes = doc.Descendants().Where(e => e.Name == \"test-results\");\n Assert.Single(testResultsNodes);\n var rootNode = testResultsNodes.FirstOrDefault();\n Assert.Equal(title, rootNode.Attribute(\"name\").Value);\n Assert.Equal(\"1\", rootNode.Attribute(\"total\").Value);\n Assert.Equal(\"0\", rootNode.Attribute(\"errors\").Value);\n Assert.Equal(\"1\", rootNode.Attribute(\"failures\").Value);\n // ensure we do have a test result with the failure data\n var testResult = doc.Descendants().Where(e => e.Name == \"test-suite\" && e.Attribute(\"type\").Value == \"TestFixture\");\n Assert.Single(testResult);\n }", + "start_line": 179, + "end_line": 193, + "start_byte": 6903, + "end_byte": 7855 + }, + { + "name": "GetVSTSFileNameTest", + "code": "[Fact]\n public void GetVSTSFileNameTest()\n {\n var path = Path.GetTempFileName();\n var newPath = XmlResultParser.GetVSTSFilename(path);\n Assert.StartsWith(\"vsts-\", Path.GetFileName(newPath));\n File.Delete(path);\n }", + "start_line": 170, + "end_line": 177, + "start_byte": 6647, + "end_byte": 6897 + }, + { + "name": "UpdateMissingDataTest", + "code": "[Fact]\n public void UpdateMissingDataTest() // only works with NUnitV3\n {\n string appName = \"TestApp\";\n var path = CreateResultSample(XmlResultJargon.NUnitV3);\n var cleanPath = path + \"_clean\";\n _resultParser.CleanXml(path, cleanPath);\n var updatedXml = path + \"_updated\";\n var logs = new[] { \"/first/path\", \"/second/path\", \"/last/path\" };\n _resultParser.UpdateMissingData(cleanPath, updatedXml, appName, logs);\n // assert that the required info was updated\n Assert.True(File.Exists(updatedXml), \"file exists\");\n var doc = XDocument.Load(updatedXml);\n var testSuiteElements = doc.Descendants().Where(e => e.Name == \"test-suite\" && e.Attribute(\"type\")?.Value == \"Assembly\");\n // assert root node contains the attachments\n var rootNode = testSuiteElements.FirstOrDefault();\n Assert.NotNull(rootNode);\n var attachments = rootNode.Descendants().Where(e => e.Name == \"attachment\");\n var failureCount = rootNode.Descendants().Where(e => e.Name == \"test-case\" && e.Attribute(\"result\").Value == \"Failed\").Count();\n Assert.Equal(logs.Length * (failureCount + 1), attachments.Count());\n\n // assert that name and full name are present and are the app name\n foreach (var node in testSuiteElements)\n {\n Assert.Equal(appName, node.Attribute(\"name\").Value);\n Assert.Equal(appName, node.Attribute(\"fullname\").Value);\n }\n File.Delete(path);\n File.Delete(cleanPath);\n File.Delete(updatedXml);\n }", + "start_line": 138, + "end_line": 168, + "start_byte": 5065, + "end_byte": 6641 + }, + { + "name": "CleanXmlTouchUnitTest", + "code": "[Fact]\n public void CleanXmlTouchUnitTest()\n {\n // similar to CleanXmlPingTest but using TouchUnit, so we do not want to see the extra nodes\n var path = CreateResultSample(XmlResultJargon.TouchUnit, includePing: true);\n var cleanPath = path + \"_clean\";\n _resultParser.CleanXml(path, cleanPath);\n Assert.True(_resultParser.IsValidXml(cleanPath, out var resultJargon), \"is valid\");\n Assert.Equal(XmlResultJargon.NUnitV2, resultJargon);\n // load the xml, ensure we do not have the nodes we removed\n var doc = XDocument.Load(cleanPath);\n Assert.False(doc.Descendants().Where(e => e.Name == \"TouchUnitTestRun\").Any(), \"TouchUnitTestRun\");\n Assert.False(doc.Descendants().Where(e => e.Name == \"NUnitOutput\").Any(), \"NUnitOutput\");\n File.Delete(path);\n File.Delete(cleanPath);\n }", + "start_line": 121, + "end_line": 136, + "start_byte": 4194, + "end_byte": 5059 + }, + { + "name": "CleanXmlPingTest", + "code": "[Theory]\n [InlineData(XmlResultJargon.NUnitV3)]\n [InlineData(XmlResultJargon.NUnitV2)]\n [InlineData(XmlResultJargon.xUnit)]\n public void CleanXmlPingTest(XmlResultJargon jargon)\n {\n var path = CreateResultSample(jargon, includePing: true);\n var cleanPath = path + \"_clean\";\n _resultParser.CleanXml(path, cleanPath);\n Assert.True(_resultParser.IsValidXml(cleanPath, out var resultJargon), \"is valid\");\n Assert.Equal(jargon, resultJargon);\n File.Delete(path);\n File.Delete(cleanPath);\n }", + "start_line": 106, + "end_line": 119, + "start_byte": 3636, + "end_byte": 4188 + }, + { + "name": "GetXmlFilePathTest", + "code": "[Theory]\n [InlineData(\"nunit-\", XmlResultJargon.NUnitV2)]\n [InlineData(\"nunit-\", XmlResultJargon.TouchUnit)]\n [InlineData(\"xunit-\", XmlResultJargon.xUnit)]\n public void GetXmlFilePathTest(string prefix, XmlResultJargon jargon)\n {\n var orignialPath = \"/path/to/a/xml/result.xml\";\n var xmlPath = _resultParser.GetXmlFilePath(orignialPath, jargon);\n var fileName = Path.GetFileName(xmlPath);\n Assert.StartsWith(prefix, fileName);\n }", + "start_line": 94, + "end_line": 104, + "start_byte": 3155, + "end_byte": 3630 + }, + { + "name": "IsValidXmlTest", + "code": "[Theory]\n [InlineData(XmlResultJargon.NUnitV2)]\n [InlineData(XmlResultJargon.NUnitV3)]\n [InlineData(XmlResultJargon.TouchUnit)]\n [InlineData(XmlResultJargon.xUnit)]\n public void IsValidXmlTest(XmlResultJargon jargon)\n {\n var path = CreateResultSample(jargon);\n Assert.True(_resultParser.IsValidXml(path, out var resultJargon), \"is valid\");\n Assert.Equal(jargon, resultJargon);\n File.Delete(path);\n }", + "start_line": 80, + "end_line": 91, + "start_byte": 2700, + "end_byte": 3148 + }, + { + "name": "IsValidXmlMissingFileTest", + "code": "[Fact]\n public void IsValidXmlMissingFileTest()\n {\n var path = Path.GetTempFileName();\n File.Delete(path);\n Assert.False(_resultParser.IsValidXml(path, out _), \"missing file\");\n }", + "start_line": 72, + "end_line": 78, + "start_byte": 2485, + "end_byte": 2694 + }, + { + "name": "CreateResultSample", + "code": "private string CreateResultSample(XmlResultJargon jargon, bool includePing = false)\n {\n string sampleFileName = null;\n switch (jargon)\n {\n case XmlResultJargon.NUnitV2:\n sampleFileName = \"NUnitV2Sample.xml\";\n break;\n case XmlResultJargon.NUnitV3:\n sampleFileName = \"NUnitV3Sample.xml\";\n break;\n case XmlResultJargon.TouchUnit:\n sampleFileName = \"TouchUnitSample.xml\";\n break;\n case XmlResultJargon.xUnit:\n sampleFileName = \"xUnitSample.xml\";\n break;\n }\n Assert.NotNull(sampleFileName);\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(sampleFileName, StringComparison.Ordinal)).FirstOrDefault();\n var tempPath = Path.GetTempFileName();\n using (var outputStream = new StreamWriter(tempPath))\n using (var sampleStream = new StreamReader(GetType().Assembly.GetManifestResourceStream(name)))\n {\n if (includePing)\n {\n outputStream.WriteLine(\"ping\");\n }\n string line;\n while ((line = sampleStream.ReadLine()) != null)\n {\n outputStream.WriteLine(line);\n }\n }\n return tempPath;\n }", + "start_line": 35, + "end_line": 70, + "start_byte": 1115, + "end_byte": 2479 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/MockLogs.cs": [ + { + "name": "Dispose", + "code": "public void Dispose() { }", + "start_line": 33, + "end_line": 33, + "start_byte": 1047, + "end_byte": 1072 + }, + { + "name": "CreateFile", + "code": "public string CreateFile(string path, LogType type) => CreateFile(path, type.ToString());", + "start_line": 31, + "end_line": 31, + "start_byte": 952, + "end_byte": 1041 + }, + { + "name": "Create", + "code": "public IFileBackedLog Create(string filename, string name, bool? timestamp = null) => AddFile(filename, name);", + "start_line": 29, + "end_line": 29, + "start_byte": 836, + "end_byte": 946 + }, + { + "name": "CreateFile", + "code": "public string CreateFile(string path, string description)\n {\n var log = Mock.Of(x => x.FullPath == path && x.Description == description);\n Add(log);\n return Directory + path;\n }", + "start_line": 22, + "end_line": 27, + "start_byte": 610, + "end_byte": 830 + }, + { + "name": "AddFile", + "code": "public IFileBackedLog AddFile(string path, string name)\n {\n var log = Mock.Of(x => x.FullPath == path && x.Description == name);\n Add(log);\n return log;\n }", + "start_line": 15, + "end_line": 20, + "start_byte": 406, + "end_byte": 604 + }, + { + "name": "AddFile", + "code": "public IFileBackedLog AddFile(string path) => AddFile(path, path);", + "start_line": 13, + "end_line": 13, + "start_byte": 334, + "end_byte": 400 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/DeviceFinderTests.cs": [ + { + "name": "CreateDevice", + "code": "private static IHardwareDevice CreateDevice(DeviceClass deviceClass, string udid, bool isPaired = true) =>\n new Device(\n buildVersion: \"17A577\",\n deviceClass: deviceClass,\n deviceIdentifier: udid,\n interfaceType: \"USB\",\n isUsableForDebugging: true,\n name: \"Test iPhone\",\n productType: \"iPhone12,1\",\n productVersion: \"12.1\",\n isPaired: isPaired);", + "start_line": 89, + "end_line": 99, + "start_byte": 4326, + "end_byte": 4777 + }, + { + "name": "OnlyPairedDevicesAreFoundTest", + "code": "[Fact]\n public async Task OnlyPairedDevicesAreFoundTest()\n {\n _hardwareDevices.Add(CreateDevice(DeviceClass.iPhone, \"8A450AA31EA94191AD6B02455F377CC1\", false));\n _hardwareDevices.Add(CreateDevice(DeviceClass.iPhone, \"30C0630E03EB40A19F9A40D61E66796B\"));\n\n var device = await _deviceFinder.FindDevice(new TestTargetOs(TestTarget.Device_iOS, null), null, new MemoryLog(), false);\n Assert.Equal(\"30C0630E03EB40A19F9A40D61E66796B\", device.Device.UDID);\n\n _hardwareDevices.Clear();\n _hardwareDevices.Add(CreateDevice(DeviceClass.iPhone, \"8A450AA31EA94191AD6B02455F377CC1\", false));\n _hardwareDevices.Add(CreateDevice(DeviceClass.iPhone, \"30C0630E03EB40A19F9A40D61E66796B\", false));\n\n await Assert.ThrowsAsync(async () => await _deviceFinder.FindDevice(new TestTargetOs(TestTarget.Device_iOS, null), null, new MemoryLog(), false));\n }", + "start_line": 73, + "end_line": 87, + "start_byte": 3403, + "end_byte": 4320 + }, + { + "name": "DeviceIsFoundByNameTest", + "code": "[Fact]\n public async Task DeviceIsFoundByNameTest()\n {\n _hardwareDevices.Add(CreateDevice(DeviceClass.iPhone, \"8A450AA31EA94191AD6B02455F377CC1\"));\n _hardwareDevices.Add(CreateDevice(DeviceClass.iPhone, \"30C0630E03EB40A19F9A40D61E66796B\"));\n\n var device = await _deviceFinder.FindDevice(new TestTargetOs(TestTarget.Device_iOS, null), \"30C0630E03EB40A19F9A40D61E66796B\", new MemoryLog(), false);\n Assert.Equal(\"30C0630E03EB40A19F9A40D61E66796B\", device.Device.UDID);\n await Assert.ThrowsAsync(async () => await _deviceFinder.FindDevice(new TestTargetOs(TestTarget.Device_iOS, null), \"unknown\", new MemoryLog(), false));\n }", + "start_line": 62, + "end_line": 71, + "start_byte": 2708, + "end_byte": 3397 + }, + { + "name": "CorrectTypeOfDeviceIsFoundTest", + "code": "[Fact]\n public async Task CorrectTypeOfDeviceIsFoundTest()\n {\n _hardwareDevices.Add(CreateDevice(DeviceClass.iPhone, \"8A450AA31EA94191AD6B02455F377CC1\"));\n _hardwareDevices.Add(CreateDevice(DeviceClass.AppleTV, \"30C0630E03EB40A19F9A40D61E66796B\"));\n\n var device = await _deviceFinder.FindDevice(new TestTargetOs(TestTarget.Device_tvOS, null), null, new MemoryLog(), false);\n Assert.Equal(\"30C0630E03EB40A19F9A40D61E66796B\", device.Device.UDID);\n\n _hardwareDevices.Clear();\n _hardwareDevices.Add(CreateDevice(DeviceClass.iPhone, \"8A450AA31EA94191AD6B02455F377CC1\"));\n _hardwareDevices.Add(CreateDevice(DeviceClass.iPhone, \"30C0630E03EB40A19F9A40D61E66796B\"));\n\n await Assert.ThrowsAsync(async () => await _deviceFinder.FindDevice(new TestTargetOs(TestTarget.Device_tvOS, null), null, new MemoryLog(), false));\n }", + "start_line": 46, + "end_line": 60, + "start_byte": 1802, + "end_byte": 2702 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/ErrorKnowledgeBaseTests.cs": [ + { + "name": "DeviceUpdateNotFinishedTest", + "code": "[Fact]\n public void DeviceUpdateNotFinishedTest()\n {\n var expectedFailureMessage = \"Cannot launch the application because the device's update hasn't been finished. The setup assistant is still running. Please finish the device OS update on the device\";\n using (var log = new LogFile(\"test\", _logPath))\n {\n log.WriteLine(\"[08:44:10.0123870] Xamarin.Hosting: Mounted developer image on 'DNCENGTVOS-090'\");\n log.WriteLine(\"[08:44:10.7259750] warning MT1043: Failed to launch the application using the instruments service. Will try launching the app using gdb service.\");\n log.WriteLine(\"[08:44:10.7260060] \");\n log.WriteLine(\"[08:44:10.7260580] --- inner exception\");\n log.WriteLine(\"[08:44:10.7265060] error HE0003: Failed to launch the application 'net.dot.System.Buffers.Tests' on 'DNCENGTVOS-090: 1 (Request to launch net.dot.System.Buffers.Tests failed.)\");\n log.WriteLine(\"[08:44:10.7265220] \");\n log.WriteLine(\"[08:44:10.7265280] ---\");\n log.WriteLine(\"[08:44:10.7278170] Launching 'net.dot.System.Buffers.Tests' on the device 'DNCENGTVOS-090'\");\n log.WriteLine(\"[08:44:11.3152170] Launching /private/var/containers/Bundle/Application/27FA8535-C645-413A-ABE9-2ABD0BC6086B/System.Buffers.Tests.app\");\n log.WriteLine(\"[08:44:11.3156130] Xamarin.Hosting: Sending command: $A208,0,2f707269766174652f7661722f636f6e7461696e6572732f42756e646c652f4170706c69636174696f6e2f32374641383533352d433634352d343133412d414245392d3241424430424336303836422f53797374656d2e427566666572732e54657374732e617070#43\");\n log.WriteLine(\"[08:44:11.3174180] Xamarin.Hosting: Received command: OK\");\n log.WriteLine(\"[08:44:11.3174360] Xamarin.Hosting: Sending command: $qLaunchSuccess#a5\");\n log.WriteLine(\"[08:44:11.3864920] Xamarin.Hosting: Received command: EThe operation couldnt be completed. [PBD] Denying open-application request for reason: Disabled (Cannot launch app 'net.dot.System.Buffers.Tests' while Setup Assistant is running)\");\n log.WriteLine(\"[08:44:11.3886900] error MT1007: Failed to launch the application 'net.dot.System.Buffers.Tests' on the device 'DNCENGTVOS-090': Failed to launch the application 'net.dot.System.Buffers.Tests' on the device 'DNCENGTVOS-090': Application failed to launch: EThe operation couldnt be completed. [PBD] Denying open-application request for reason: Disabled (Cannot launch app 'net.dot.System.Buffers.Tests' while Setup Assistant is running)\");\n log.WriteLine(\"[08:44:11.3887100] \");\n log.WriteLine(\"[08:44:11.3887170] . You can still launch the application manually by tapping on it.\");\n log.WriteLine(\"[08:44:11.3887220] \");\n log.WriteLine(\"[08:44:11.3887260] --- inner exception\");\n log.WriteLine(\"[08:44:11.3887310] error MT1020: Failed to launch the application 'net.dot.System.Buffers.Tests' on the device 'DNCENGTVOS-090': Application failed to launch: EThe operation couldnt be completed. [PBD] Denying open-application request for reason: Disabled (Cannot launch app 'net.dot.System.Buffers.Tests' while Setup Assistant is running)\");\n log.WriteLine(\"[08:44:11.3887360] \");\n log.WriteLine(\"[08:44:11.3887400] \");\n log.WriteLine(\"[08:44:11.3887450] ---\");\n log.WriteLine(\"[08:44:11.3887490] --- inner exception\");\n log.WriteLine(\"[08:44:11.3887570] error HE1107: Application failed to launch: EThe operation couldnt be completed. [PBD] Denying open-application request for reason: Disabled (Cannot launch app 'net.dot.System.Buffers.Tests' while Setup Assistant is running)\");\n log.WriteLine(\"[08:44:11.3887790] \");\n log.WriteLine(\"[08:44:11.3887840] ---\");\n log.WriteLine(\"[08:44:11.3917790] at Xamarin.Launcher.DevController.LaunchDeviceBundleIdAsync (System.String bundle_id, Xamarin.Hosting.DeviceLaunchConfig config) [0x001cc] in /Users/builder/azdo/_work/1/s/maccore/tools/mlaunch/Xamarin.Hosting/Xamarin.Launcher/controller-device.cs:208 \");\n log.WriteLine(\"[08:44:11.3917960] at Xamarin.Utils.NSRunLoopExtensions.RunUntilTaskCompletion[T] (Foundation.NSRunLoop this, System.Threading.Tasks.Task`1[TResult] task) [0x00082] in /Users/builder/azdo/_work/1/s/maccore/tools/mlaunch/Xamarin.Hosting/Xamarin.Utils/Extensions.cs:35 \");\n log.WriteLine(\"[08:44:11.3918040] at Xamarin.Launcher.Driver.Main2 (System.String[] args) [0x00b43] in /Users/builder/azdo/_work/1/s/maccore/tools/mlaunch/Xamarin.Hosting/Xamarin.Launcher/Main.cs:459 \");\n log.WriteLine(\"[08:44:11.3918090] at Xamarin.Launcher.Driver.Main (System.String[] args) [0x0006d] in /Users/builder/azdo/_work/1/s/maccore/tools/mlaunch/Xamarin.Hosting/Xamarin.Launcher/Main.cs:151 \");\n log.Flush();\n\n Assert.True(_errorKnowledgeBase.IsKnownTestIssue(log, out var failure));\n Assert.Equal(expectedFailureMessage, failure?.HumanMessage);\n }\n }", + "start_line": 132, + "end_line": 173, + "start_byte": 6579, + "end_byte": 11691 + }, + { + "name": "DeviceLockedTest", + "code": "[Fact]\n public void DeviceLockedTest()\n {\n var expectedFailureMessage = \"Cannot launch the application because the device is locked. Please unlock the device and try again\";\n using (var log = new LogFile(\"test\", _logPath))\n {\n log.WriteLine(\"05:55:56.7712200 05:55:56.7712030 Xamarin.Hosting: Mounting developer image on 'iPremek'\");\n log.WriteLine(\"05:55:56.7716040 05:55:56.7715960 Xamarin.Hosting: Mounted developer image on 'iPremek'\");\n log.WriteLine(\"05:55:56.8494160 05:55:56.8494020 error MT1031: Could not launch the app 'net.dot.HelloiOS' on the device 'iPremek' because the device is locked. Please unlock the device and try again.\");\n log.WriteLine(\"05:55:56.8537390 05:55:56.8537300 at Xamarin.Launcher.DevController+<>c__DisplayClass14_0.b__0 () [0x0059d] in /Users/rolf/work/maccore/xcode12/maccore/tools/mlaunch/Xamarin.Hosting/Xamarin.Launcher/controller-device.cs:372\");\n log.WriteLine(\"05:55:56.8537720 05:55:56.8537700 at Xamarin.Launcher.DevController.LaunchDeviceBundleAsync (System.String app_path, Xamarin.Hosting.DeviceLaunchConfig config) [0x00111] in /Users/rolf/work/maccore/xcode12/maccore/tools/mlaunch/Xamarin.Hosting/Xamarin.Launcher/controller-device.cs:176\");\n log.WriteLine(\"05:55:56.8537800 05:55:56.8537790 at Xamarin.Utils.NSRunLoopExtensions.RunUntilTaskCompletion[T] (Foundation.NSRunLoop this, System.Threading.Tasks.Task`1[TResult] task) [0x00082] in /Users/rolf/work/maccore/xcode12/maccore/tools/mlaunch/Xamarin.Hosting/Xamarin.Utils/Extensions.cs:35\");\n log.WriteLine(\"05:55:56.8537870 05:55:56.8537860 at Xamarin.Launcher.Driver.Main2 (System.String[] args) [0x00b43] in /Users/rolf/work/maccore/xcode12/maccore/tools/mlaunch/Xamarin.Hosting/Xamarin.Launcher/Main.cs:458\");\n log.WriteLine(\"05:55:56.8538290 05:55:56.8538250 at Xamarin.Launcher.Driver.Main (System.String[] args) [0x0006d] in /Users/rolf/work/maccore/xcode12/maccore/tools/mlaunch/Xamarin.Hosting/Xamarin.Launcher/Main.cs:150\");\n log.WriteLine(\"05:55:56.8618920 05:55:56.8618780 Process mlaunch exited with 1\");\n log.WriteLine(\"05:56:01.8765370 05:56:01.8765240 Killing process tree of 2797...\");\n log.WriteLine(\"05:56:01.8938830 05:56:01.8938670 Pids to kill: 2797\");\n log.Flush();\n\n Assert.True(_errorKnowledgeBase.IsKnownTestIssue(log, out var failure));\n Assert.Equal(expectedFailureMessage, failure?.HumanMessage);\n }\n }", + "start_line": 108, + "end_line": 130, + "start_byte": 4013, + "end_byte": 6573 + }, + { + "name": "UsbIssuesMissingTest", + "code": "[Fact]\n public void UsbIssuesMissingTest()\n {\n using (var log = new LogFile(\"test\", _logPath))\n {\n // initial lines are not interesting\n log.WriteLine(\"InstallingEmbeddedProfile: 65%\");\n log.WriteLine(\"PercentComplete: 30\");\n log.WriteLine(\"Status: InstallingEmbeddedProfile\");\n log.WriteLine(\"VerifyingApplication: 70%\");\n log.WriteLine(\"PercentComplete: 40\");\n log.Flush();\n\n Assert.False(_errorKnowledgeBase.IsKnownTestIssue(log, out var failure));\n Assert.Null(failure);\n }\n }", + "start_line": 90, + "end_line": 106, + "start_byte": 3398, + "end_byte": 4007 + }, + { + "name": "UsbIssuesPresentTest", + "code": "[Fact]\n public void UsbIssuesPresentTest()\n {\n var expectedFailureMessage =\n \"Failed to communicate with the device. Please ensure the cable is properly connected, and try rebooting the device\";\n using (var log = new LogFile(\"test\", _logPath))\n {\n // initial lines are not interesting\n log.WriteLine(\"InstallingEmbeddedProfile: 65%\");\n log.WriteLine(\"PercentComplete: 30\");\n log.WriteLine(\"Status: InstallingEmbeddedProfile\");\n log.WriteLine(\"VerifyingApplication: 70%\");\n log.WriteLine(\"PercentComplete: 40\");\n log.WriteLine(\"Xamarin.Hosting.MobileDeviceException: Failed to communicate with the device. Please ensure the cable is properly connected, and try rebooting the device (error: 0xe8000065 kAMDMuxConnectError)\");\n log.Flush();\n\n Assert.True(_errorKnowledgeBase.IsKnownTestIssue(log, out var failure));\n Assert.Equal(expectedFailureMessage, failure?.HumanMessage);\n }\n }", + "start_line": 69, + "end_line": 88, + "start_byte": 2354, + "end_byte": 3392 + }, + { + "name": "WrongArchNotPresentTest", + "code": "[Fact]\n public void WrongArchNotPresentTest()\n {\n using (var log = new LogFile(\"test\", _logPath))\n {\n // write some data in it\n log.WriteLine(\"InstallingEmbeddedProfile: 65%\");\n log.WriteLine(\"PercentComplete: 30\");\n log.WriteLine(\"Status: InstallingEmbeddedProfile\");\n log.WriteLine(\"VerifyingApplication: 70%\");\n log.WriteLine(\"PercentComplete: 40\");\n log.WriteLine(\"Status: VerifyingApplication\");\n log.Flush();\n\n Assert.False(_errorKnowledgeBase.IsKnownInstallIssue(log, out var failure));\n Assert.Null(failure);\n }\n }", + "start_line": 50, + "end_line": 67, + "start_byte": 1686, + "end_byte": 2348 + }, + { + "name": "WrongArchPresentTest", + "code": "[Fact]\n public void WrongArchPresentTest()\n {\n var expectedFailureMessage =\n \"IncorrectArchitecture: Failed to find matching device arch for the application\";\n using (var log = new LogFile(\"test\", _logPath))\n {\n // write some data in it\n log.WriteLine(\"InstallingEmbeddedProfile: 65%\");\n log.WriteLine(\"PercentComplete: 30\");\n log.WriteLine(\"Status: InstallingEmbeddedProfile\");\n log.WriteLine(\"VerifyingApplication: 70%\");\n log.WriteLine(\"PercentComplete: 40\");\n log.WriteLine(\"Status: VerifyingApplication\");\n log.WriteLine(\n \"IncorrectArchitecture: Failed to find matching arch for 64-bit Mach-O input file /private/var/installd/Library/Caches/com.apple.mobile.installd.staging/temp.Ic8Ank/extracted/monotouchtest.app/monotouchtest\");\n log.Flush();\n\n Assert.True(_errorKnowledgeBase.IsKnownInstallIssue(log, out var failure));\n Assert.Equal(expectedFailureMessage, failure?.HumanMessage);\n }\n }", + "start_line": 27, + "end_line": 48, + "start_byte": 599, + "end_byte": 1680 + }, + { + "name": "Dispose", + "code": "public void Dispose()\n {\n if (File.Exists(_logPath))\n {\n File.Delete(_logPath);\n }\n GC.SuppressFinalize(this);\n }", + "start_line": 18, + "end_line": 25, + "start_byte": 435, + "end_byte": 593 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/ExitCodeDetectorTests.cs": [ + { + "name": "GetLogMock", + "code": "private static IFileBackedLog GetLogMock(string[] loglines)\n {\n byte[] byteArray = Encoding.ASCII.GetBytes(string.Join(Environment.NewLine, loglines));\n var stream = new MemoryStream(byteArray);\n var reader = new StreamReader(stream);\n\n var mock = new Mock();\n\n mock.Setup(x => x.GetReader()).Returns(reader);\n\n return mock.Object;\n }", + "start_line": 194, + "end_line": 205, + "start_byte": 21740, + "end_byte": 22138 + }, + { + "name": "Dispose", + "code": "public void Dispose()\n {\n if (_tempFilename != null)\n {\n File.Delete(_tempFilename);\n }\n GC.SuppressFinalize(this);\n }", + "start_line": 185, + "end_line": 192, + "start_byte": 21571, + "end_byte": 21734 + }, + { + "name": "ExitCodeFromPreviousRunIsIgnored", + "code": "[Fact]\n public void ExitCodeFromPreviousRunIsIgnored()\n {\n var previousLog =\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class MockAKSRefKeyObject is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b738) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x103259970). One of the two will be used. Which one is undefined.\" + Environment.NewLine +\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class MockAKSOptionalParameters is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b788) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x1032599c0). One of the two will be used. Which one is undefined.\" + Environment.NewLine +\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class SecXPCHelper is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b918) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x103259a60). One of the two will be used. Which one is undefined.\" + Environment.NewLine +\n \"Nov 18 04:31:44 dci-mac-build-053 ML-MacVM com.apple.CoreSimulator.SimDevice.2E1EE736-5672-4220-89B5-B7C77DB6AF18[55655] (UIKitApplication:net.dot.HelloiOS[9a0b][rb-legacy][57331]): Some other error message\" + Environment.NewLine +\n \"Nov 18 04:31:44 dci-mac-build-053 ML-MacVM com.apple.CoreSimulator.SimDevice.2E1EE736-5672-4220-89B5-B7C77DB6AF18[55655] (UIKitApplication:net.dot.HelloiOS[9a0b][rb-legacy][57331]): Service exited with abnormal code: 55\" + Environment.NewLine +\n \"Nov 18 04:31:44 dci-mac-build-053 com.apple.CoreSimulator.SimDevice.F67392D9-A327-4217-B924-5DA0918415E5[811] (com.apple.security.cloudkeychainproxy3): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.\" + Environment.NewLine;\n\n var currentRunLog =\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class MockAKSRefKeyObject is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b738) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x103259970). One of the two will be used. Which one is undefined.\" + Environment.NewLine +\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class MockAKSOptionalParameters is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b788) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x1032599c0). One of the two will be used. Which one is undefined.\" + Environment.NewLine +\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class SecXPCHelper is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b918) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x103259a60). One of the two will be used. Which one is undefined.\" + Environment.NewLine +\n \"Nov 18 04:31:44 dci-mac-build-053 ML-MacVM com.apple.CoreSimulator.SimDevice.2E1EE736-5672-4220-89B5-B7C77DB6AF18[55655] (UIKitApplication:net.dot.HelloiOS[9a0b][rb-legacy][57331]): Some other error message\" + Environment.NewLine +\n \"Nov 18 04:31:44 dci-mac-build-053 ML-MacVM com.apple.CoreSimulator.SimDevice.2E1EE736-5672-4220-89B5-B7C77DB6AF18[55655] (UIKitApplication:net.dot.HelloiOS[9a0b][rb-legacy][57331]): Service exited with abnormal code: 72\" + Environment.NewLine +\n \"Nov 18 04:31:44 dci-mac-build-053 com.apple.CoreSimulator.SimDevice.F67392D9-A327-4217-B924-5DA0918415E5[811] (com.apple.security.cloudkeychainproxy3): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.\" + Environment.NewLine;\n\n var tempFilename = Path.GetTempFileName();\n File.WriteAllText(tempFilename, previousLog);\n\n var capturedFilename = Path.GetTempFileName();\n\n using var captureLog = new CaptureLog(capturedFilename, tempFilename, false);\n captureLog.StartCapture();\n File.AppendAllText(tempFilename, currentRunLog);\n captureLog.StopCapture();\n\n var appBundleInformation = new AppBundleInformation(\"net.dot.HelloiOS\", \"net.dot.HelloiOS\", \"some/path\", \"some/path\", false, null);\n var exitCode = new iOSExitCodeDetector().DetectExitCode(appBundleInformation, captureLog);\n\n Assert.Equal(72, exitCode);\n }", + "start_line": 150, + "end_line": 183, + "start_byte": 14887, + "end_byte": 21565 + }, + { + "name": "ExitCodeIsNotDetectedTest", + "code": "[Fact]\n public void ExitCodeIsNotDetectedTest()\n {\n var appBundleInformation = new AppBundleInformation(\"HelloiOS\", \"net.dot.HelloiOS\", \"some/path\", \"some/path\", false, null);\n\n var detector = new iOSExitCodeDetector();\n\n var log = new[]\n {\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class MockAKSRefKeyObject is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b738) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x103259970). One of the two will be used. Which one is undefined.\",\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class MockAKSOptionalParameters is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b788) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x1032599c0). One of the two will be used. Which one is undefined.\",\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class SecXPCHelper is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b918) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x103259a60). One of the two will be used. Which one is undefined.\",\n \"Nov 18 04:31:44 ML-MacVM com.apple.CoreSimulator.SimDevice.2E1EE736-5672-4220-89B5-B7C77DB6AF18[55655] (UIKitApplication:net.dot.HelloiOS[9a0b][rb-legacy][57331]): Some other error message\",\n \"Nov 18 04:31:44 dci-mac-build-053 com.apple.CoreSimulator.SimDevice.F67392D9-A327-4217-B924-5DA0918415E5[811] (com.apple.security.cloudkeychainproxy3[67121]): Service exited with abnormal code: 1\",\n \"Nov 18 04:31:44 dci-mac-build-053 com.apple.CoreSimulator.SimDevice.F67392D9-A327-4217-B924-5DA0918415E5[811] (com.apple.security.cloudkeychainproxy3): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.\",\n };\n\n var exitCode = detector.DetectExitCode(appBundleInformation, GetLogMock(log));\n\n Assert.Null(exitCode);\n }", + "start_line": 128, + "end_line": 148, + "start_byte": 11698, + "end_byte": 14881 + }, + { + "name": "iOSDeviceCodeIsDetectedTest", + "code": "[Fact]\n public void iOSDeviceCodeIsDetectedTest()\n {\n var appBundleInformation = new AppBundleInformation(\"iOS.Simulator.PInvoke.Test\", \"net.dot.iOS.Simulator.PInvoke.Test\", \"some/path\", \"some/path\", false, null);\n\n var detector = new iOSExitCodeDetector();\n\n var log = new[]\n {\n \"[07:02:15.9749990] Xamarin.Hosting: Mounting developer image on 'DNCENGOSX-003'\",\n \"[07:02:15.9752160] Xamarin.Hosting: Mounted developer image on 'DNCENGOSX-003'\",\n \"[07:02:16.5177370] Xamarin.Hosting: Launched net.dot.Some.Other.App with PID: 13942\",\n \"[07:02:16.5181560] Launched application 'net.dot.Some.Other.App' on 'DNCENGOSX-003' with pid 13942\",\n \"[07:02:16.6150270] 2022-03-30 07:02:16.601 Some.Other.App[13942:136284382] Done!\",\n \"[07:02:21.6632630] Xamarin.Hosting: Process '13942' exited with exit code 143 or crashing signal .\",\n \"[07:02:21.6637600] Application 'net.dot.Some.Other.App' terminated (with exit code '143' and/or crashing signal ').\",\n\n // We care about this run\n \"[07:02:15.9749990] Xamarin.Hosting: Mounting developer image on 'DNCENGOSX-003'\",\n \"[07:02:15.9752160] Xamarin.Hosting: Mounted developer image on 'DNCENGOSX-003'\",\n \"[07:02:16.5177370] Xamarin.Hosting: Launched net.dot.iOS.Simulator.PInvoke.Test with PID: 83937\",\n \"[07:02:16.5181560] Launched application 'net.dot.iOS.Simulator.PInvoke.Test' on 'DNCENGOSX-003' with pid 83937\",\n \"[07:02:16.6150270] 2022-03-30 07:02:16.601 iOS.Simulator.PInvoke.Test[83937:136284382] Done!\",\n \"[07:02:21.6632630] Xamarin.Hosting: Process '83937' exited with exit code 42 or crashing signal .\",\n \"[07:02:21.6637600] Application 'net.dot.iOS.Simulator.PInvoke.Test' terminated (with exit code '42' and/or crashing signal ').\",\n };\n\n var exitCode = detector.DetectExitCode(appBundleInformation, GetLogMock(log));\n\n Assert.Equal(42, exitCode);\n }", + "start_line": 96, + "end_line": 126, + "start_byte": 9667, + "end_byte": 11692 + }, + { + "name": "NegativeExitCodeIsDetectedTest", + "code": "[Fact]\n public void NegativeExitCodeIsDetectedTest()\n {\n var appBundleInformation = new AppBundleInformation(\"HelloiOS\", \"net.dot.HelloiOS\", \"some/path\", \"some/path\", false, null);\n\n var detector = new iOSExitCodeDetector();\n\n var log = new[]\n {\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class MockAKSRefKeyObject is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b738) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x103259970). One of the two will be used. Which one is undefined.\",\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class MockAKSOptionalParameters is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b788) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x1032599c0). One of the two will be used. Which one is undefined.\",\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class SecXPCHelper is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b918) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x103259a60). One of the two will be used. Which one is undefined.\",\n \"Nov 18 04:31:44 ML-MacVM com.apple.CoreSimulator.SimDevice.2E1EE736-5672-4220-89B5-B7C77DB6AF18[55655] (UIKitApplication:net.dot.HelloiOS[9a0b][rb-legacy][57331]): Service exited with abnormal code: -2\",\n \"Nov 18 04:31:44 dci-mac-build-053 com.apple.CoreSimulator.SimDevice.F67392D9-A327-4217-B924-5DA0918415E5[811] (com.apple.security.cloudkeychainproxy3[67121]): Service exited with abnormal code: 1\",\n \"Nov 18 04:31:44 dci-mac-build-053 com.apple.CoreSimulator.SimDevice.F67392D9-A327-4217-B924-5DA0918415E5[811] (com.apple.security.cloudkeychainproxy3): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.\",\n };\n\n var exitCode = detector.DetectExitCode(appBundleInformation, GetLogMock(log));\n\n Assert.Equal(-2, exitCode);\n }", + "start_line": 74, + "end_line": 94, + "start_byte": 6455, + "end_byte": 9661 + }, + { + "name": "ExitCodeIsDetectedOnMacCatalystTest", + "code": "[Fact]\n public void ExitCodeIsDetectedOnMacCatalystTest()\n {\n var appBundleInformation = new AppBundleInformation(\"System.Buffers.Tests\", \"net.dot.System.Buffers.Tests\", \"some/path\", \"some/path\", false, null);\n\n var detector = new MacCatalystExitCodeDetector();\n\n var log = new[]\n {\n \"Feb 18 06:40:16 Admins-Mac-Mini System.Buffers.Tests[59229]: CDN - client insert callback function client = 0 type = 17 function = 0x7fff3b262246 local_olny = false\",\n \"Feb 18 06:40:16 Admins-Mac-Mini System.Buffers.Tests[59229]: CDN - client setup_remote_port\",\n \"Feb 18 06:40:16 Admins-Mac-Mini System.Buffers.Tests[59229]: CDN - Bootstrap Port: 1799\",\n \"Feb 18 06:40:16 Admins-Mac-Mini System.Buffers.Tests[59229]: CDN - Remote Port: 56835 (com.apple.CoreDisplay.Notification)\",\n \"Feb 18 06:40:16 Admins-Mac-Mini System.Buffers.Tests[59229]: CDN - client setup_local_port\",\n \"Feb 18 06:40:16 Admins-Mac-Mini System.Buffers.Tests[59229]: CDN - Local Port: 78339\",\n \"Feb 18 06:40:16 Admins-Mac-Mini com.apple.xpc.launchd[1] (net.dot.System.Buffers.Tests.15140[59229]): Service exited with abnormal code: 74\",\n \"Feb 18 06:40:49 Admins-Mac-Mini com.apple.xpc.launchd[1] (com.apple.mdworker.shared.09000000-0600-0000-0000-000000000000[59231]): Service exited due to SIGKILL | sent by mds[88]\",\n \"Feb 18 06:40:58 Admins-Mac-Mini com.apple.xpc.launchd[1] (com.apple.mdworker.shared.02000000-0100-0000-0000-000000000000[59232]): Service exited due to SIGKILL | sent by mds[88]\",\n \"Feb 18 06:41:01 Admins-Mac-Mini com.apple.xpc.launchd[1] (com.apple.mdworker.shared.0D000000-0000-0000-0000-000000000000[59237]): Service exited due to SIGKILL | sent by mds[88]\",\n \"Feb 18 06:41:23 Admins-Mac-Mini System.Buffers.Tests[59248]: CDN - client insert callback function client = 0 type = 17 function = 0x7fff3b262246 local_olny = false\",\n \"Feb 18 06:41:23 Admins-Mac-Mini System.Buffers.Tests[59248]: CDN - client setup_remote_port\",\n \"Feb 18 06:41:23 Admins-Mac-Mini System.Buffers.Tests[59248]: CDN - Bootstrap Port: 1799\",\n \"Feb 18 06:41:23 Admins-Mac-Mini System.Buffers.Tests[59248]: CDN - Remote Port: 75271 (com.apple.CoreDisplay.Notification)\",\n \"Feb 18 06:41:23 Admins-Mac-Mini System.Buffers.Tests[59248]: CDN - client setup_local_port\",\n \"Feb 18 06:41:23 Admins-Mac-Mini System.Buffers.Tests[59248]: CDN - Local Port: 52995\",\n };\n\n var exitCode = detector.DetectExitCode(appBundleInformation, GetLogMock(log));\n\n Assert.Equal(74, exitCode);\n }", + "start_line": 42, + "end_line": 72, + "start_byte": 3789, + "end_byte": 6449 + }, + { + "name": "ExitCodeIsDetectedTest", + "code": "[Fact]\n public void ExitCodeIsDetectedTest()\n {\n var appBundleInformation = new AppBundleInformation(\"HelloiOS\", \"net.dot.HelloiOS\", \"some/path\", \"some/path\", false, null);\n\n var detector = new iOSExitCodeDetector();\n\n var log = new[]\n {\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class MockAKSRefKeyObject is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b738) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x103259970). One of the two will be used. Which one is undefined.\",\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class MockAKSOptionalParameters is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b788) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x1032599c0). One of the two will be used. Which one is undefined.\",\n \"Nov 18 04:31:44 dci-mac-build-053 CloudKeychainProxy[67121]: objc[67121]: Class SecXPCHelper is implemented in both /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/Security (0x10350b918) and /Applications/Xcode115.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Security.framework/CloudKeychainProxy.bundle/CloudKeychainProxy (0x103259a60). One of the two will be used. Which one is undefined.\",\n \"Nov 18 04:31:44 ML-MacVM com.apple.CoreSimulator.SimDevice.2E1EE736-5672-4220-89B5-B7C77DB6AF18[55655] (UIKitApplication:net.dot.HelloiOS[9a0b][rb-legacy][57331]): Service exited with abnormal code: 200\",\n \"Nov 18 04:31:44 dci-mac-build-053 com.apple.CoreSimulator.SimDevice.F67392D9-A327-4217-B924-5DA0918415E5[811] (com.apple.security.cloudkeychainproxy3[67121]): Service exited with abnormal code: 1\",\n \"Nov 18 04:31:44 dci-mac-build-053 com.apple.CoreSimulator.SimDevice.F67392D9-A327-4217-B924-5DA0918415E5[811] (com.apple.security.cloudkeychainproxy3): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.\",\n };\n\n var exitCode = detector.DetectExitCode(appBundleInformation, GetLogMock(log));\n\n Assert.Equal(200, exitCode);\n }", + "start_line": 20, + "end_line": 40, + "start_byte": 583, + "end_byte": 3783 + } + ], + "tests/Microsoft.DotNet.XHarness.CLI.Tests/UnitTestArguments.cs": [ + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new[] { Argument };", + "start_line": 19, + "end_line": 19, + "start_byte": 579, + "end_byte": 657 + } + ], + "tests/Microsoft.DotNet.XHarness.CLI.Tests/UnitTestCommand.cs": [ + { + "name": "InvokeInternal", + "code": "protected override Task InvokeInternal(ILogger logger)\n {\n CommandRun = true;\n return Task.FromResult(ExitCode.SUCCESS);\n }", + "start_line": 45, + "end_line": 49, + "start_byte": 1625, + "end_byte": 1778 + }, + { + "name": "FromArgument", + "code": "public static UnitTestCommand> FromArgument(TArgument arg) where TArgument : Argument\n {\n return new UnitTestCommand>(new UnitTestArguments(arg));\n }", + "start_line": 18, + "end_line": 21, + "start_byte": 625, + "end_byte": 867 + } + ], + "tests/Microsoft.DotNet.XHarness.CLI.Tests/CommandArguments/ArgumentTests.cs": [ + { + "name": "ArgumentsAreInterpolatedWell", + "code": "[Fact]\n public void ArgumentsAreInterpolatedWell()\n {\n var timespanArg = new SampleTimeSpanArgument(TimeSpan.FromSeconds(5));\n var switchArg = new SampleSwitchArgument(true);\n var stringArg = new SampleStringArgument();\n stringArg.Action(\"string-value\");\n\n Assert.Equal(\"time is 00:00:05\", $\"time is {timespanArg}\");\n Assert.Equal(\"switch is true\", $\"switch is {switchArg}\");\n Assert.Equal(\"string is string-value\", $\"string is {stringArg}\");\n }", + "start_line": 186, + "end_line": 197, + "start_byte": 4710, + "end_byte": 5213 + }, + { + "name": "TimeSpanArgumentIsSet", + "code": "[Fact]\n public void TimeSpanArgumentIsSet()\n {\n var arg = new SampleTimeSpanArgument(TimeSpan.FromMinutes(3));\n var command = UnitTestCommand.FromArgument(arg);\n\n var exitCode = command.Invoke(new[]\n {\n \"-t\",\n \"00:02:30\",\n });\n\n Assert.Equal(0, exitCode);\n Assert.True(command.CommandRun);\n Assert.Equal(TimeSpan.FromSeconds(150), arg.Value);\n }", + "start_line": 169, + "end_line": 184, + "start_byte": 4272, + "end_byte": 4704 + }, + { + "name": "TimeSpanArgumentHasDefault", + "code": "[Fact]\n public void TimeSpanArgumentHasDefault()\n {\n var arg = new SampleTimeSpanArgument(TimeSpan.FromMinutes(3));\n var command = UnitTestCommand.FromArgument(arg);\n\n var exitCode = command.Invoke(Array.Empty());\n\n Assert.Equal(0, exitCode);\n Assert.True(command.CommandRun);\n Assert.Equal(TimeSpan.FromMinutes(3), arg.Value);\n }", + "start_line": 156, + "end_line": 167, + "start_byte": 3877, + "end_byte": 4266 + }, + { + "name": "RequiredStringArgumentIsValidated", + "code": "[Fact]\n public void RequiredStringArgumentIsValidated()\n {\n var arg = new SampleStringArgument();\n var command = UnitTestCommand.FromArgument(arg);\n\n var exitCode = command.Invoke(Array.Empty());\n\n Assert.Equal((int)ExitCode.INVALID_ARGUMENTS, exitCode);\n }", + "start_line": 137, + "end_line": 146, + "start_byte": 3362, + "end_byte": 3664 + }, + { + "name": "RequiredStringArgumentIsSet", + "code": "[Fact]\n public void RequiredStringArgumentIsSet()\n {\n var arg = new SampleStringArgument();\n var command = UnitTestCommand.FromArgument(arg);\n\n var exitCode = command.Invoke(new[]\n {\n \"-c\",\n \"xyz\",\n });\n\n Assert.Equal(0, exitCode);\n Assert.True(command.CommandRun);\n Assert.Equal(\"xyz\", arg.Value);\n }", + "start_line": 120, + "end_line": 135, + "start_byte": 2968, + "end_byte": 3356 + }, + { + "name": "SwitchArgumentArgumentWithDefaultValueIsFalse", + "code": "[Fact]\n public void SwitchArgumentArgumentWithDefaultValueIsFalse()\n {\n var arg = new SampleSwitchArgument(true);\n var command = UnitTestCommand.FromArgument(arg);\n\n var exitCode = command.Invoke(new[]\n {\n \"-b=off\",\n });\n\n Assert.Equal(0, exitCode);\n Assert.True(command.CommandRun);\n Assert.False(arg.Value);\n }", + "start_line": 96, + "end_line": 110, + "start_byte": 2400, + "end_byte": 2788 + }, + { + "name": "SwitchArgumentArgumentWithValueIsFalse", + "code": "[Fact]\n public void SwitchArgumentArgumentWithValueIsFalse()\n {\n var arg = new SampleSwitchArgument(false);\n var command = UnitTestCommand.FromArgument(arg);\n\n var exitCode = command.Invoke(new[]\n {\n \"-b=false\",\n });\n\n Assert.Equal(0, exitCode);\n Assert.True(command.CommandRun);\n Assert.False(arg.Value);\n }", + "start_line": 80, + "end_line": 94, + "start_byte": 2010, + "end_byte": 2394 + }, + { + "name": "SwitchArgumentArgumentWithTrueDefaultIsFalse", + "code": "[Fact]\n public void SwitchArgumentArgumentWithTrueDefaultIsFalse()\n {\n var arg = new SampleSwitchArgument(true);\n var command = UnitTestCommand.FromArgument(arg);\n\n var exitCode = command.Invoke(new[]\n {\n \"-b\",\n });\n\n Assert.Equal(0, exitCode);\n Assert.True(command.CommandRun);\n Assert.False(arg.Value);\n }", + "start_line": 64, + "end_line": 78, + "start_byte": 1621, + "end_byte": 2004 + }, + { + "name": "SwitchArgumentArgumentWithoutValueIsTrue", + "code": "[Fact]\n public void SwitchArgumentArgumentWithoutValueIsTrue()\n {\n var arg = new SampleSwitchArgument(false);\n var command = UnitTestCommand.FromArgument(arg);\n\n var exitCode = command.Invoke(new[]\n {\n \"-b\",\n });\n\n Assert.Equal(0, exitCode);\n Assert.True(command.CommandRun);\n Assert.True(arg.Value);\n }", + "start_line": 48, + "end_line": 62, + "start_byte": 1236, + "end_byte": 1615 + }, + { + "name": "RepetableArgumentsAreParsed", + "code": "[Fact]\n public void RepetableArgumentsAreParsed()\n {\n var arg = new SampleRepeatableArgument();\n var command = UnitTestCommand.FromArgument(arg);\n\n var exitCode = command.Invoke(new[]\n {\n \"-a\",\n \"foo\",\n \"-a=bar\",\n });\n\n Assert.Equal(0, exitCode);\n Assert.True(command.CommandRun);\n Assert.Equal(new[] { \"foo\", \"bar\" }, arg.Value);\n }", + "start_line": 22, + "end_line": 38, + "start_byte": 602, + "end_byte": 1033 + } + ], + "tests/Microsoft.DotNet.XHarness.CLI.Tests/Commands/XHarnessCommandTests.cs": [ + { + "name": "Action", + "code": "public override void Action(string argumentValue) => Value = ParseArgument(\"enum\", argumentValue, SampleEnum.ForbiddenValue);", + "start_line": 329, + "end_line": 329, + "start_byte": 9347, + "end_byte": 9472 + }, + { + "name": "Validate", + "code": "public override void Validate()\r\n {\r\n base.Validate();\r\n\r\n if (Value > 100)\r\n {\r\n throw new ArgumentOutOfRangeException();\r\n }\r\n }", + "start_line": 311, + "end_line": 319, + "start_byte": 8928, + "end_byte": 9131 + }, + { + "name": "GetArguments", + "code": "protected override IEnumerable GetArguments() => new Argument[]\r\n {\n Number,\n Enum,\n String,\r\n };", + "start_line": 289, + "end_line": 294, + "start_byte": 8437, + "end_byte": 8603 + }, + { + "name": "ArgumentPrototypesAreNotClashing", + "code": "[Theory]\r\n [InlineData(\"apple test -h\")]\r\n [InlineData(\"apple run -h\")]\r\n [InlineData(\"apple just-test -h\")]\r\n [InlineData(\"apple just-run -h\")]\r\n [InlineData(\"apple install -h\")]\r\n [InlineData(\"apple uninstall -h\")]\r\n [InlineData(\"apple state -h\")]\r\n\r\n [InlineData(\"android test -h\")]\r\n [InlineData(\"android run -h\")]\r\n [InlineData(\"android install -h\")]\r\n [InlineData(\"android uninstall -h\")]\r\n [InlineData(\"android state -h\")]\r\n\r\n [InlineData(\"wasm test -h\")]\r\n [InlineData(\"wasm test-browser -h\")]\r\n public void ArgumentPrototypesAreNotClashing(string command)\r\n {\r\n // This test tries to run all of the commands which will fail because of some missing argument\r\n // If we for example add a new option and that would clash with some already existing argument,\r\n // this will fail to add the duplicate option prototype.\r\n // (it already happened that we added -d to all commands and the WASM command failed because it already had -d)\r\n var commandSet = new CommandSet(\"test\")\r\n {\r\n new AppleCommandSet(),\r\n new AndroidCommandSet(),\r\n new WasmCommandSet(),\r\n new XHarnessHelpCommand(),\r\n new XHarnessVersionCommand()\r\n };\r\n\r\n Assert.Equal((int)ExitCode.HELP_SHOWN, commandSet.Run(command.Split(\" \")));\r\n }", + "start_line": 248, + "end_line": 281, + "start_byte": 6767, + "end_byte": 8164 + }, + { + "name": "ExtraneousArgumentsDetectedInPassThroughMode", + "code": "[Fact]\r\n public void ExtraneousArgumentsDetectedInPassThroughMode()\r\n {\r\n var exitCode = _command.Invoke(new[]\r\n {\n \"v8\",\n \"--foo\",\n \"runtime.js\",\n Program.VerbatimArgumentPlaceholder,\n \"-n\",\n \"50\",\n \"--enum\",\n \"--invalid-arg=foo\",\n });\r\n\r\n Assert.Equal((int)ExitCode.INVALID_ARGUMENTS, exitCode);\r\n Assert.False(_command.CommandRun);\r\n }", + "start_line": 229, + "end_line": 246, + "start_byte": 6289, + "end_byte": 6759 + }, + { + "name": "PassThroughArgumentsAreParsedInCommandSet", + "code": "[Fact]\r\n public void PassThroughArgumentsAreParsedInCommandSet()\r\n {\r\n var arguments = new SampleUnitTestArguments();\r\n var command = new UnitTestCommand(arguments, false);\r\n var commandSet = new CommandSet(\"set\")\n {\n command\n };\r\n\r\n var exitCode = commandSet.Run(new[]\r\n {\n \"unit-test\",\n \"-n\",\n \"50\",\n \"--enum\",\n \"Value2\",\n Program.VerbatimArgumentPlaceholder,\n \"v8\",\n \"--foo\",\n \"runtime.js\",\n });\r\n\r\n Assert.Equal(0, exitCode);\r\n Assert.True(command.CommandRun);\r\n Assert.Equal(50, arguments.Number);\r\n Assert.Equal(SampleEnum.Value2, arguments.Enum);\r\n Assert.Equal(new[] { \"v8\", \"--foo\", \"runtime.js\" }, command.PassThroughArgs.ToArray());\r\n }", + "start_line": 199, + "end_line": 227, + "start_byte": 5387, + "end_byte": 6281 + }, + { + "name": "PassThroughArgumentsAreParsed", + "code": "[Fact]\r\n public void PassThroughArgumentsAreParsed()\r\n {\r\n var exitCode = _command.Invoke(new[]\r\n {\n \"-n\",\n \"50\",\n \"--enum\",\n \"Value2\",\n Program.VerbatimArgumentPlaceholder,\n \"v8\",\n \"--foo\",\n \"runtime.js\",\n });\r\n\r\n Assert.Equal(0, exitCode);\r\n Assert.True(_command.CommandRun);\r\n Assert.Equal(50, _arguments.Number);\r\n Assert.Equal(SampleEnum.Value2, _arguments.Enum);\r\n Assert.Equal(new[] { \"v8\", \"--foo\", \"runtime.js\" }, _command.PassThroughArgs.ToArray());\r\n }", + "start_line": 177, + "end_line": 197, + "start_byte": 4763, + "end_byte": 5379 + }, + { + "name": "ForbiddenEnumValuesAreValidated", + "code": "[Fact]\r\n public void ForbiddenEnumValuesAreValidated()\r\n {\r\n var exitCode = _command.Invoke(new[]\r\n {\n \"--enum\",\n \"ForbiddenValue\",\n });\r\n\r\n Assert.Equal((int)ExitCode.INVALID_ARGUMENTS, exitCode);\r\n Assert.False(_command.CommandRun);\r\n }", + "start_line": 164, + "end_line": 175, + "start_byte": 4451, + "end_byte": 4755 + }, + { + "name": "EnumsAreValidated", + "code": "[Fact]\r\n public void EnumsAreValidated()\r\n {\r\n var exitCode = _command.Invoke(new[]\r\n {\n \"--enum\",\n \"Foo\",\n });\r\n\r\n Assert.Equal((int)ExitCode.INVALID_ARGUMENTS, exitCode);\r\n Assert.False(_command.CommandRun);\r\n }", + "start_line": 151, + "end_line": 162, + "start_byte": 4164, + "end_byte": 4443 + }, + { + "name": "ExtraneousArgumentsAreDetected", + "code": "[Fact]\r\n public void ExtraneousArgumentsAreDetected()\r\n {\r\n var arguments = new SampleUnitTestArguments();\r\n var command = new UnitTestCommand(arguments, true);\r\n var exitCode = command.Invoke(new[]\r\n {\n \"-n\",\n \"50\",\n \"--enum\",\n \"Value2\",\n \"some\",\n \"other=1\",\n \"args\",\n });\r\n\r\n Assert.Equal(0, exitCode);\r\n Assert.True(command.CommandRun);\r\n Assert.Equal(50, arguments.Number);\r\n Assert.Equal(SampleEnum.Value2, arguments.Enum);\r\n Assert.Equal(new[] { \"some\", \"other=1\", \"args\" }, command.ExtraArgs);\r\n }", + "start_line": 128, + "end_line": 149, + "start_byte": 3471, + "end_byte": 4156 + }, + { + "name": "ExtraneousArgumentsAreRejected", + "code": "[Fact]\r\n public void ExtraneousArgumentsAreRejected()\r\n {\r\n var exitCode = _command.Invoke(new[]\r\n {\n \"-n\",\n \"50\",\n \"--enum\",\n \"Value2\",\n \"--invalid-arg=foo\",\n });\r\n\r\n Assert.Equal((int)ExitCode.INVALID_ARGUMENTS, exitCode);\r\n Assert.False(_command.CommandRun);\r\n }", + "start_line": 112, + "end_line": 126, + "start_byte": 3099, + "end_byte": 3463 + }, + { + "name": "HelpArgumentIsDetected", + "code": "[Fact]\r\n public void HelpArgumentIsDetected()\r\n {\r\n var exitCode = _command.Invoke(new[]\r\n {\n \"--help\",\n });\r\n\r\n Assert.Equal((int)ExitCode.HELP_SHOWN, exitCode);\r\n Assert.False(_command.CommandRun);\r\n Assert.True(_arguments.ShowHelp);\r\n }", + "start_line": 99, + "end_line": 110, + "start_byte": 2790, + "end_byte": 3091 + }, + { + "name": "VerbosityArgumentIsDetected", + "code": "[Fact]\r\n public void VerbosityArgumentIsDetected()\r\n {\r\n var exitCode = _command.Invoke(new[]\r\n {\n \"-n\",\n \"50\",\n \"--verbosity=Warning\",\n });\r\n\r\n Assert.Equal(0, exitCode);\r\n Assert.True(_command.CommandRun);\r\n Assert.Equal(50, _arguments.Number);\r\n Assert.Equal(LogLevel.Warning, _arguments.Verbosity);\r\n }", + "start_line": 83, + "end_line": 97, + "start_byte": 2385, + "end_byte": 2782 + }, + { + "name": "ArgumentsAreValidated", + "code": "[Fact]\r\n public void ArgumentsAreValidated()\r\n {\r\n var exitCode = _command.Invoke(new[]\r\n {\n \"-n\",\n \"200\",\n \"--enum\",\n \"Value2\",\n });\r\n\r\n Assert.Equal((int)ExitCode.INVALID_ARGUMENTS, exitCode);\r\n Assert.False(_command.CommandRun);\r\n }", + "start_line": 68, + "end_line": 81, + "start_byte": 2054, + "end_byte": 2377 + }, + { + "name": "ArgumentsWithSpacesAreParsed", + "code": "[Fact]\r\n public void ArgumentsWithSpacesAreParsed()\r\n {\r\n var exitCode = _command.Invoke(new[]\r\n {\n \"--number\",\n \"50\",\n \"--enum\",\n \"Value2\",\n \"-s\",\n \"foobar\",\n });\r\n\r\n Assert.Equal(0, exitCode);\r\n Assert.True(_command.CommandRun);\r\n Assert.Equal(50, _arguments.Number);\r\n Assert.Equal(SampleEnum.Value2, _arguments.Enum);\r\n Assert.Equal(\"foobar\", _arguments.String);\r\n }", + "start_line": 48, + "end_line": 66, + "start_byte": 1545, + "end_byte": 2046 + }, + { + "name": "ArgumentsWithEqualSignsAreParsed", + "code": "[Fact]\r\n public void ArgumentsWithEqualSignsAreParsed()\r\n {\r\n var exitCode = _command.Invoke(new[]\r\n {\n \"--number=50\",\n \"--enum=Value2\",\n \"--string=foobar\",\n });\r\n\r\n Assert.Equal(0, exitCode);\r\n Assert.True(_command.CommandRun);\r\n Assert.Equal(50, _arguments.Number);\r\n Assert.Equal(SampleEnum.Value2, _arguments.Enum);\r\n Assert.Equal(\"foobar\", _arguments.String);\r\n }", + "start_line": 31, + "end_line": 46, + "start_byte": 1071, + "end_byte": 1537 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/AppOperations/AppInstallerTests.cs": [ + { + "name": "InstallOnDeviceTest", + "code": "[Fact]\n public async Task InstallOnDeviceTest()\n {\n // Act\n var appInstaller = new AppInstaller(_processManager.Object, _mainLog.Object);\n\n var result = await appInstaller.InstallApp(_appBundleInformation, new TestTargetOs(TestTarget.Device_iOS, null), s_mockDevice);\n\n // Verify\n Assert.Equal(0, result.ExitCode);\n\n var expectedArgs = $\"--devname {s_mockDevice.UDID} --installdev {StringUtils.FormatArguments(s_appPath)}\";\n\n _processManager.Verify(x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs),\n _mainLog.Object,\n It.IsAny(),\n null,\n It.IsAny(),\n It.IsAny()));\n }", + "start_line": 78, + "end_line": 98, + "start_byte": 2803, + "end_byte": 3572 + }, + { + "name": "InstallOnSimulatorTest", + "code": "[Fact]\n public async Task InstallOnSimulatorTest()\n {\n // Act\n var appInstaller = new AppInstaller(_processManager.Object, _mainLog.Object);\n\n var result = await appInstaller.InstallApp(_appBundleInformation, new TestTargetOs(TestTarget.Simulator_iOS64, null), s_mockDevice);\n\n // Verify\n Assert.Equal(0, result.ExitCode);\n\n var expectedArgs = $\"--device=:v2:udid={s_mockDevice.UDID} --installsim {StringUtils.FormatArguments(s_appPath)}\";\n\n _processManager.Verify(x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs),\n _mainLog.Object,\n It.IsAny(),\n null,\n It.IsAny(),\n It.IsAny()));\n }", + "start_line": 56, + "end_line": 76, + "start_byte": 2012, + "end_byte": 2797 + }, + { + "name": "Dispose", + "code": "public void Dispose()\n {\n Directory.Delete(s_appPath, true);\n GC.SuppressFinalize(this);\n }", + "start_line": 50, + "end_line": 54, + "start_byte": 1895, + "end_byte": 2006 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/AppOperations/AppRunnerTests.cs": [ + { + "name": "SetupLogList", + "code": "private void SetupLogList(IEnumerable logs)\n {\n _logs\n .Setup(x => x.GetEnumerator())\n .Returns(() => logs.GetEnumerator());\n\n _logs\n .Setup(m => m.Count)\n .Returns(() => logs.Count());\n\n _logs\n .Setup(m => m[It.IsAny()])\n .Returns(i => logs.ElementAt(i));\n }", + "start_line": 686, + "end_line": 699, + "start_byte": 25538, + "end_byte": 25916 + }, + { + "name": "GetExpectedSimulatorMlaunchArgs", + "code": "private string GetExpectedSimulatorMlaunchArgs() =>\n \"-argument=--foo=bar \" +\n \"-argument=--xyz \" +\n \"-setenv=appArg1=value1 \" +\n $\"--device=:v2:udid={_mockSimulator.UDID} \" +\n $\"--launchsimbundleid={AppBundleIdentifier}\";", + "start_line": 679, + "end_line": 684, + "start_byte": 25275, + "end_byte": 25532 + }, + { + "name": "GetExpectedDeviceMlaunchArgs", + "code": "private static string GetExpectedDeviceMlaunchArgs() =>\n \"-argument=--foo=bar \" +\n \"-argument=--xyz \" +\n \"-setenv=appArg1=value1 \" +\n \"--disable-memory-limits \" +\n $\"--devname {s_mockDevice.DeviceIdentifier} \" +\n $\"--launchdevbundleid {AppBundleIdentifier} \" +\n \"--wait-for-exit\";", + "start_line": 670, + "end_line": 677, + "start_byte": 24940, + "end_byte": 25269 + }, + { + "name": "RunOnMacCatalystNoWaitTest", + "code": "[Fact]\n public async Task RunOnMacCatalystNoWaitTest()\n {\n var captureLog = new Mock();\n captureLog.SetupGet(x => x.FullPath).Returns(_simulatorLogPath);\n captureLog.SetupGet(x => x.Description).Returns(LogType.SystemLog.ToString());\n\n var captureLogFactory = new Mock();\n captureLogFactory\n .Setup(x => x.Create(\n It.IsAny(),\n It.IsAny(),\n false,\n LogType.SystemLog))\n .Returns(captureLog.Object);\n\n SetupLogList(new[] { captureLog.Object });\n\n // Act\n var appRunner = new AppRunner(\n _processManager.Object,\n _snapshotReporterFactory,\n captureLogFactory.Object,\n Mock.Of(),\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var result = await appRunner.RunMacCatalystApp(\n _appBundleInfo,\n timeout: TimeSpan.FromSeconds(30),\n signalAppEnd: false,\n waitForExit: false,\n extraAppArguments: Array.Empty(),\n extraEnvVariables: Array.Empty<(string, string)>());\n\n // Verify\n Assert.True(result.Succeeded);\n\n var expectedArgs = GetExpectedSimulatorMlaunchArgs();\n\n _processManager\n .Verify(\n x => x.ExecuteCommandAsync(\n \"open\",\n It.Is>(args => args.Count == 2 && args[0] == \"-n\" && args[1] == s_appPath),\n _mainLog.Object,\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny>(),\n It.IsAny()),\n Times.Once);\n\n captureLog.Verify(x => x.StartCapture(), Times.AtLeastOnce);\n }", + "start_line": 613, + "end_line": 668, + "start_byte": 22985, + "end_byte": 24934 + }, + { + "name": "RunOnSimulatorNoWaitNoLaunchSignalTest", + "code": "[Fact]\n public async Task RunOnSimulatorNoWaitNoLaunchSignalTest()\n {\n var captureLog = new Mock();\n captureLog.SetupGet(x => x.FullPath).Returns(_simulatorLogPath);\n captureLog.SetupGet(x => x.Description).Returns(LogType.SystemLog.ToString());\n\n var captureLogFactory = new Mock();\n captureLogFactory\n .Setup(x => x.Create(\n Path.Combine(_logs.Object.Directory, _mockSimulator.Name + \".log\"),\n _mockSimulator.SystemLog,\n false,\n LogType.SystemLog))\n .Returns(captureLog.Object);\n\n SetupLogList(new[] { captureLog.Object });\n\n var expectedArgs = GetExpectedSimulatorMlaunchArgs();\n\n var appLaunchedTask = new TaskCompletionSource();\n var appRunTask = new TaskCompletionSource();\n\n _processManager\n .Setup(\n x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs),\n It.IsAny(),\n It.IsAny(),\n It.IsAny>(),\n It.IsAny(),\n It.IsAny()))\n .Callback((MlaunchArguments args, ILog log, TimeSpan timeout, Dictionary env, int verbosity, CancellationToken? ct) =>\n {\n appLaunchedTask.SetResult();\n })\n .Returns(appRunTask.Task); // This task will complete and the ScanLog task won't (we won't log the \"app launched\" message)\n\n // Act\n var appRunner = new AppRunner(\n _processManager.Object,\n _snapshotReporterFactory,\n captureLogFactory.Object,\n Mock.Of(),\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var runTask = appRunner.RunApp(\n _appBundleInfo,\n new TestTargetOs(TestTarget.Simulator_tvOS, null),\n _mockSimulator,\n null,\n timeout: TimeSpan.FromSeconds(30),\n signalAppEnd: false,\n waitForExit: false,\n extraAppArguments: new[] { \"--foo=bar\", \"--xyz\" },\n extraEnvVariables: new[] { (\"appArg1\", \"value1\") });\n\n // No we wait for the code to start launching the app\n await appLaunchedTask.Task;\n\n Assert.False(runTask.IsCompleted);\n\n // In this phase, the code waits for both ScanLog or the app run task\n // We will simulate a case when the app never reports back (never launches)\n appRunTask.SetResult(new ProcessExecutionResult\n {\n ExitCode = 137, // This is what we get when app run times out and is killed by our timeout\n TimedOut = true,\n });\n\n var result = await runTask;\n\n // Verify\n Assert.False(result.Succeeded);\n Assert.True(result.TimedOut);\n\n _processManager\n .Verify(\n x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs),\n It.IsAny(),\n It.IsAny(),\n It.IsAny>(),\n It.IsAny(),\n It.IsAny()),\n Times.Once);\n\n _processManager\n .Verify(\n x => x.ExecuteXcodeCommandAsync(\n \"simctl\",\n It.Is>(args => args.Contains(\"log\") && args.Contains(_mockSimulator.UDID) && args.Contains(\"stream\") && args.Any(a => a.Contains(BundleExecutable))),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()),\n Times.Once);\n\n captureLog.Verify(x => x.StartCapture(), Times.AtLeastOnce);\n }", + "start_line": 509, + "end_line": 611, + "start_byte": 18919, + "end_byte": 22979 + }, + { + "name": "RunOnSimulatorNoWaitTest", + "code": "[Fact]\n public async Task RunOnSimulatorNoWaitTest()\n {\n var captureLog = new Mock();\n captureLog.SetupGet(x => x.FullPath).Returns(_simulatorLogPath);\n captureLog.SetupGet(x => x.Description).Returns(LogType.SystemLog.ToString());\n\n var captureLogFactory = new Mock();\n captureLogFactory\n .Setup(x => x.Create(\n Path.Combine(_logs.Object.Directory, _mockSimulator.Name + \".log\"),\n _mockSimulator.SystemLog,\n false,\n LogType.SystemLog))\n .Returns(captureLog.Object);\n\n SetupLogList(new[] { captureLog.Object });\n\n var expectedArgs = GetExpectedSimulatorMlaunchArgs();\n\n var appLaunchedTask = new TaskCompletionSource();\n ILog? appLog = null;\n\n _processManager\n .Setup(\n x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs),\n It.IsAny(),\n It.IsAny(),\n It.IsAny>(),\n It.IsAny(),\n It.IsAny()))\n .Callback((MlaunchArguments args, ILog log, TimeSpan timeout, Dictionary env, int verbosity, CancellationToken? ct) =>\n {\n appLog = log;\n appLaunchedTask.SetResult();\n })\n .Returns(new TaskCompletionSource().Task); // This task must never complete (it represents running app)\n\n // Act\n var appRunner = new AppRunner(\n _processManager.Object,\n _snapshotReporterFactory,\n captureLogFactory.Object,\n Mock.Of(),\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var runTask = appRunner.RunApp(\n _appBundleInfo,\n new TestTargetOs(TestTarget.Simulator_tvOS, null),\n _mockSimulator,\n null,\n timeout: TimeSpan.FromSeconds(30),\n signalAppEnd: false,\n waitForExit: false,\n extraAppArguments: new[] { \"--foo=bar\", \"--xyz\" },\n extraEnvVariables: new[] { (\"appArg1\", \"value1\") });\n\n // No we wait for the launch of the app (which will then hang and the ScanLog will start waiting for the launch signal)\n await appLaunchedTask.Task;\n\n Assert.False(runTask.IsCompleted);\n\n // Now we send the signal that the app has launched\n Assert.NotNull(appLog);\n appLog!.WriteLine($\"Some message\");\n appLog!.WriteLine($\"Xamarin.Hosting: Launched {AppBundleIdentifier} with pid 39402\");\n appLog!.WriteLine($\"Some other message\");\n\n // We should now be able to return from here since the ScanLog will finish\n var result = await runTask;\n\n // Verify\n Assert.True(result.Succeeded);\n\n _processManager\n .Verify(\n x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs),\n It.IsAny(),\n It.IsAny(),\n It.IsAny>(),\n It.IsAny(),\n It.IsAny()),\n Times.Once);\n\n _processManager\n .Verify(\n x => x.ExecuteXcodeCommandAsync(\n \"simctl\",\n It.Is>(args => args.Contains(\"log\") && args.Contains(_mockSimulator.UDID) && args.Contains(\"stream\") && args.Any(a => a.Contains(BundleExecutable))),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()),\n Times.Once);\n\n captureLog.Verify(x => x.StartCapture(), Times.AtLeastOnce);\n }", + "start_line": 406, + "end_line": 507, + "start_byte": 14862, + "end_byte": 18913 + }, + { + "name": "RunOnDeviceNoWaitTest", + "code": "[Fact]\n public async Task RunOnDeviceNoWaitTest()\n {\n var deviceSystemLog = new Mock();\n deviceSystemLog.SetupGet(x => x.FullPath).Returns(AppBundleIdentifier + \"system.log\");\n deviceSystemLog.SetupGet(x => x.Description).Returns(LogType.SystemLog.ToString());\n\n SetupLogList(new[] { deviceSystemLog.Object });\n\n _logs\n .Setup(x => x.Create(\"device-\" + DeviceName + \"-mocked_timestamp.log\", LogType.SystemLog.ToString(), It.IsAny()))\n .Returns(deviceSystemLog.Object);\n\n var deviceLogCapturer = new Mock();\n\n var deviceLogCapturerFactory = new Mock();\n deviceLogCapturerFactory\n .Setup(x => x.Create(_mainLog.Object, deviceSystemLog.Object, DeviceName))\n .Returns(deviceLogCapturer.Object);\n\n var x = _logs.Object.First();\n\n // Act\n var appRunner = new AppRunner(\n _processManager.Object,\n _snapshotReporterFactory,\n Mock.Of(),\n deviceLogCapturerFactory.Object,\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var result = await appRunner.RunApp(\n _appBundleInfo,\n new TestTargetOs(TestTarget.Device_iOS, null),\n s_mockDevice,\n null,\n timeout: TimeSpan.FromSeconds(30),\n signalAppEnd: false,\n waitForExit: false,\n extraAppArguments: new[] { \"--foo=bar\", \"--xyz\" },\n extraEnvVariables: new[] { (\"appArg1\", \"value1\") });\n\n // Verify\n Assert.True(result.Succeeded);\n\n var expectedArgs = GetExpectedDeviceMlaunchArgs();\n\n _processManager\n .Verify(\n x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs.Replace(\" --wait-for-exit\", null)),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny>(),\n It.IsAny(),\n It.IsAny()),\n Times.Once);\n\n _snapshotReporter.Verify(x => x.StartCaptureAsync(), Times.AtLeastOnce);\n\n deviceSystemLog.Verify(x => x.Dispose(), Times.AtLeastOnce);\n }", + "start_line": 340, + "end_line": 404, + "start_byte": 12415, + "end_byte": 14856 + }, + { + "name": "RunOnMacCatalystTest", + "code": "[Fact]\n public async Task RunOnMacCatalystTest()\n {\n var captureLog = new Mock();\n captureLog.SetupGet(x => x.FullPath).Returns(_simulatorLogPath);\n captureLog.SetupGet(x => x.Description).Returns(LogType.SystemLog.ToString());\n\n var captureLogFactory = new Mock();\n captureLogFactory\n .Setup(x => x.Create(\n It.IsAny(),\n It.IsAny(),\n false,\n LogType.SystemLog))\n .Returns(captureLog.Object);\n\n SetupLogList(new[] { captureLog.Object });\n\n // Act\n var appRunner = new AppRunner(\n _processManager.Object,\n _snapshotReporterFactory,\n captureLogFactory.Object,\n Mock.Of(),\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var result = await appRunner.RunMacCatalystApp(\n _appBundleInfo,\n timeout: TimeSpan.FromSeconds(30),\n signalAppEnd: false,\n waitForExit: true,\n extraAppArguments: new[] { \"--foo=bar\", \"--xyz\" },\n extraEnvVariables: new[] { (\"appArg1\", \"value1\") });\n\n // Verify\n Assert.True(result.Succeeded);\n\n var expectedArgs = GetExpectedSimulatorMlaunchArgs();\n\n _processManager\n .Verify(\n x => x.ExecuteCommandAsync(\n \"open\",\n It.Is>(args => args[0] == \"-n\" && args[1] == \"-W\" && args[2] == s_appPath),\n _mainLog.Object,\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny>(),\n It.IsAny()),\n Times.Once);\n\n _processManager\n .Verify(\n x => x.ExecuteCommandAsync(\n \"log\",\n It.Is>(args => args.Contains(\"stream\") && args.Any(a => a.Contains(BundleExecutable))),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny?>(),\n It.IsAny()),\n Times.Once);\n\n captureLog.Verify(x => x.StartCapture(), Times.AtLeastOnce);\n }", + "start_line": 270, + "end_line": 338, + "start_byte": 9929, + "end_byte": 12409 + }, + { + "name": "RunOnDeviceWithAppEndSignalTest", + "code": "[Fact]\n public async Task RunOnDeviceWithAppEndSignalTest()\n {\n var deviceSystemLog = new Mock();\n deviceSystemLog.SetupGet(x => x.FullPath).Returns(AppBundleIdentifier + \"system.log\");\n deviceSystemLog.SetupGet(x => x.Description).Returns(LogType.SystemLog.ToString());\n\n SetupLogList(new[] { deviceSystemLog.Object });\n\n _logs\n .Setup(x => x.Create(\"device-\" + DeviceName + \"-mocked_timestamp.log\", LogType.SystemLog.ToString(), It.IsAny()))\n .Returns(deviceSystemLog.Object);\n\n var deviceLogCapturer = new Mock();\n\n var deviceLogCapturerFactory = new Mock();\n deviceLogCapturerFactory\n .Setup(x => x.Create(_mainLog.Object, deviceSystemLog.Object, DeviceName))\n .Returns(deviceLogCapturer.Object);\n\n var testEndSignal = Guid.NewGuid();\n _helpers\n .Setup(x => x.GenerateGuid())\n .Returns(testEndSignal);\n\n List mlaunchArguments = new();\n List appOutputLogs = new();\n List cancellationTokens = new();\n\n // Endlessly running mlaunch until it gets cancelled by the signal\n var mlaunchCompleted = new TaskCompletionSource();\n var appStarted = new TaskCompletionSource();\n\n _processManager\n .Setup(x => x.ExecuteCommandAsync(\n Capture.In(mlaunchArguments),\n It.IsAny(),\n Capture.In(appOutputLogs),\n Capture.In(appOutputLogs),\n It.IsAny(),\n It.IsAny?>(),\n It.IsAny(),\n Capture.In(cancellationTokens)))\n .Callback(() =>\n {\n // Signal we have started mlaunch\n appStarted.SetResult();\n\n // When mlaunch gets signalled to shut down, shut down even our fake mlaunch\n cancellationTokens.Last().Register(() => mlaunchCompleted.SetResult(new ProcessExecutionResult\n {\n TimedOut = true,\n }));\n })\n .Returns(mlaunchCompleted.Task);\n\n // Act\n var appRunner = new AppRunner(\n _processManager.Object,\n _snapshotReporterFactory,\n Mock.Of(),\n deviceLogCapturerFactory.Object,\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var runTask = appRunner.RunApp(\n _appBundleInfo,\n new TestTargetOs(TestTarget.Device_iOS, null),\n s_mockDevice,\n null,\n timeout: TimeSpan.FromSeconds(30),\n signalAppEnd: true,\n waitForExit: true,\n Array.Empty(),\n Array.Empty<(string, string)>());\n\n // Everything should hang now since we mimicked mlaunch not being able to tell the app quits\n // We will wait for XHarness to kick off the mlaunch (the app)\n Assert.False(runTask.IsCompleted);\n await Task.WhenAny(appStarted.Task, Task.Delay(1000));\n\n // XHarness should still be running\n Assert.False(runTask.IsCompleted);\n\n // mlaunch should be started\n Assert.True(appStarted.Task.IsCompleted);\n\n // We will mimick the app writing the end signal\n var appLog = appOutputLogs.First();\n appLog.WriteLine(testEndSignal.ToString());\n\n // AppTester should now complete fine\n var result = await runTask;\n\n // Verify\n Assert.True(result.Succeeded);\n\n var expectedArgs = $\"-setenv=RUN_END_TAG={testEndSignal} \" +\n \"--disable-memory-limits \" +\n $\"--devname {s_mockDevice.DeviceIdentifier} \" +\n $\"--launchdevbundleid {AppBundleIdentifier} \" +\n \"--wait-for-exit\";\n\n Assert.Equal(mlaunchArguments.Last().AsCommandLine(), expectedArgs);\n\n _snapshotReporter.Verify(x => x.StartCaptureAsync(), Times.AtLeastOnce);\n\n deviceSystemLog.Verify(x => x.Dispose(), Times.AtLeastOnce);\n }", + "start_line": 159, + "end_line": 268, + "start_byte": 5699, + "end_byte": 9923 + }, + { + "name": "RunOnDeviceTest", + "code": "[Fact]\n public async Task RunOnDeviceTest()\n {\n var deviceSystemLog = new Mock();\n deviceSystemLog.SetupGet(x => x.FullPath).Returns(AppBundleIdentifier + \"system.log\");\n deviceSystemLog.SetupGet(x => x.Description).Returns(LogType.SystemLog.ToString());\n\n SetupLogList(new[] { deviceSystemLog.Object });\n\n _logs\n .Setup(x => x.Create(\"device-\" + DeviceName + \"-mocked_timestamp.log\", LogType.SystemLog.ToString(), It.IsAny()))\n .Returns(deviceSystemLog.Object);\n\n var deviceLogCapturer = new Mock();\n\n var deviceLogCapturerFactory = new Mock();\n deviceLogCapturerFactory\n .Setup(x => x.Create(_mainLog.Object, deviceSystemLog.Object, DeviceName))\n .Returns(deviceLogCapturer.Object);\n\n var x = _logs.Object.First();\n\n // Act\n var appRunner = new AppRunner(\n _processManager.Object,\n _snapshotReporterFactory,\n Mock.Of(),\n deviceLogCapturerFactory.Object,\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var result = await appRunner.RunApp(\n _appBundleInfo,\n new TestTargetOs(TestTarget.Device_iOS, null),\n s_mockDevice,\n null,\n timeout: TimeSpan.FromSeconds(30),\n signalAppEnd: false,\n waitForExit: true,\n extraAppArguments: new[] { \"--foo=bar\", \"--xyz\" },\n extraEnvVariables: new[] { (\"appArg1\", \"value1\") });\n\n // Verify\n Assert.True(result.Succeeded);\n\n var expectedArgs = GetExpectedDeviceMlaunchArgs();\n\n _processManager\n .Verify(\n x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny>(),\n It.IsAny(),\n It.IsAny()),\n Times.Once);\n\n _snapshotReporter.Verify(x => x.StartCaptureAsync(), Times.AtLeastOnce);\n\n deviceSystemLog.Verify(x => x.Dispose(), Times.AtLeastOnce);\n }", + "start_line": 93, + "end_line": 157, + "start_byte": 3293, + "end_byte": 5693 + }, + { + "name": "RunOnSimulatorTest", + "code": "[Fact]\n public async Task RunOnSimulatorTest()\n {\n var captureLog = new Mock();\n captureLog.SetupGet(x => x.FullPath).Returns(_simulatorLogPath);\n captureLog.SetupGet(x => x.Description).Returns(LogType.SystemLog.ToString());\n\n var captureLogFactory = new Mock();\n captureLogFactory\n .Setup(x => x.Create(\n Path.Combine(_logs.Object.Directory, _mockSimulator.Name + \".log\"),\n _mockSimulator.SystemLog,\n false,\n LogType.SystemLog))\n .Returns(captureLog.Object);\n\n SetupLogList(new[] { captureLog.Object });\n\n // Act\n var appRunner = new AppRunner(\n _processManager.Object,\n _snapshotReporterFactory,\n captureLogFactory.Object,\n Mock.Of(),\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var result = await appRunner.RunApp(\n _appBundleInfo,\n new TestTargetOs(TestTarget.Simulator_tvOS, null),\n _mockSimulator,\n null,\n timeout: TimeSpan.FromSeconds(30),\n signalAppEnd: false,\n waitForExit: true,\n extraAppArguments: new[] { \"--foo=bar\", \"--xyz\" },\n extraEnvVariables: new[] { (\"appArg1\", \"value1\") });\n\n // Verify\n Assert.True(result.Succeeded);\n\n var expectedArgs = GetExpectedSimulatorMlaunchArgs();\n\n _processManager\n .Verify(\n x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs),\n It.IsAny(),\n It.IsAny(),\n It.IsAny>(),\n It.IsAny(),\n It.IsAny()),\n Times.Once);\n\n _processManager\n .Verify(\n x => x.ExecuteXcodeCommandAsync(\n \"simctl\",\n It.Is>(args => args.Contains(\"log\") && args.Contains(_mockSimulator.UDID) && args.Contains(\"stream\") && args.Any(a => a.Contains(BundleExecutable))),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()),\n Times.Once);\n\n captureLog.Verify(x => x.StartCapture(), Times.AtLeastOnce);\n }", + "start_line": 23, + "end_line": 91, + "start_byte": 730, + "end_byte": 3287 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/AppOperations/AppTesterTests.cs": [ + { + "name": "GetExpectedSimulatorMlaunchArgs", + "code": "private string GetExpectedSimulatorMlaunchArgs() =>\n \"-setenv=NUNIT_AUTOEXIT=true \" +\n $\"-setenv=NUNIT_HOSTPORT={Port} \" +\n \"-setenv=NUNIT_ENABLE_XML_OUTPUT=true \" +\n \"-setenv=NUNIT_XML_VERSION=xUnit \" +\n \"-setenv=appArg1=value1 \" +\n \"-argument=--foo=bar \" +\n \"-argument=--xyz \" +\n \"-setenv=NUNIT_HOSTNAME=127.0.0.1 \" +\n $\"--device=:v2:udid={_mockSimulator.UDID} \" +\n $\"--launchsimbundleid={AppBundleIdentifier}\";", + "start_line": 637, + "end_line": 647, + "start_byte": 25878, + "end_byte": 26361 + }, + { + "name": "GetExpectedDeviceMlaunchArgs", + "code": "private string GetExpectedDeviceMlaunchArgs(string? skippedTests = null, bool useTunnel = false, string? extraArgs = null) =>\n \"-setenv=NUNIT_AUTOEXIT=true \" +\n $\"-setenv=NUNIT_HOSTPORT={Port} \" +\n \"-setenv=NUNIT_ENABLE_XML_OUTPUT=true \" +\n \"-setenv=NUNIT_XML_VERSION=xUnit \" +\n skippedTests +\n extraArgs +\n \"-setenv=NUNIT_HOSTNAME=127.0.0.1,::1 \" +\n \"--disable-memory-limits \" +\n $\"--devname {s_mockDevice.DeviceIdentifier} \" +\n (useTunnel ? \"-setenv=USE_TCP_TUNNEL=true \" : null) +\n $\"--launchdevbundleid {AppBundleIdentifier} \" +\n \"--wait-for-exit\";", + "start_line": 623, + "end_line": 635, + "start_byte": 25236, + "end_byte": 25872 + }, + { + "name": "TestOnDeviceWithAppEndSignalTest", + "code": "[Fact]\n public async Task TestOnDeviceWithAppEndSignalTest()\n {\n var deviceSystemLog = new Mock();\n deviceSystemLog.SetupGet(x => x.FullPath).Returns(Path.GetTempFileName());\n\n var deviceLogCapturer = new Mock();\n\n var deviceLogCapturerFactory = new Mock();\n deviceLogCapturerFactory\n .Setup(x => x.Create(_mainLog.Object, deviceSystemLog.Object, DeviceName))\n .Returns(deviceLogCapturer.Object);\n\n var testResultFilePath = Path.GetTempFileName();\n var listenerLogFile = Mock.Of(x => x.FullPath == testResultFilePath);\n File.WriteAllLines(testResultFilePath, new[] { \"Some result here\", \"Tests run: 124\", \"Some result there\" });\n\n _logs\n .Setup(x => x.Create(\"test-ios-device-mocked_timestamp.log\", \"TestLog\", It.IsAny()))\n .Returns(listenerLogFile);\n\n _logs\n .Setup(x => x.Create($\"device-{DeviceName}-mocked_timestamp.log\", LogType.SystemLog.ToString(), It.IsAny()))\n .Returns(deviceSystemLog.Object);\n\n _tunnelBore.Setup(t => t.Create(DeviceName, It.IsAny()));\n _listenerFactory\n .Setup(f => f.UseTunnel)\n .Returns(true);\n\n var testEndSignal = Guid.NewGuid();\n _helpers\n .Setup(x => x.GenerateGuid())\n .Returns(testEndSignal);\n\n List mlaunchArguments = new();\n List appOutputLogs = new();\n List cancellationTokens = new();\n\n // Endlessly running mlaunch until it gets cancelled by the signal\n var mlaunchCompleted = new TaskCompletionSource();\n var appStarted = new TaskCompletionSource();\n\n _processManager\n .Setup(x => x.ExecuteCommandAsync(\n Capture.In(mlaunchArguments),\n It.IsAny(),\n Capture.In(appOutputLogs),\n Capture.In(appOutputLogs),\n It.IsAny(),\n It.IsAny?>(),\n It.IsAny(),\n Capture.In(cancellationTokens)))\n .Callback(() =>\n {\n // Signal we have started mlaunch\n appStarted.SetResult();\n\n // When mlaunch gets signalled to shut down, shut down even our fake mlaunch\n cancellationTokens.Last().Register(() => mlaunchCompleted.SetResult(new ProcessExecutionResult\n {\n TimedOut = true,\n }));\n })\n .Returns(mlaunchCompleted.Task);\n\n // Act\n var appTester = new AppTester(\n _processManager.Object,\n _listenerFactory.Object,\n _snapshotReporterFactory,\n Mock.Of(),\n deviceLogCapturerFactory.Object,\n _testReporterFactory,\n new XmlResultParser(),\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var testTask = appTester.TestApp(\n _appBundleInfo,\n new TestTargetOs(TestTarget.Device_iOS, null),\n s_mockDevice,\n null,\n timeout: TimeSpan.FromMinutes(30),\n testLaunchTimeout: TimeSpan.FromMinutes(30),\n signalAppEnd: true,\n Array.Empty(),\n Array.Empty<(string, string)>());\n\n // Everything should hang now since we mimicked mlaunch not being able to tell the app quits\n // We will wait for XHarness to kick off the mlaunch (the app)\n Assert.False(testTask.IsCompleted);\n await Task.WhenAny(appStarted.Task, Task.Delay(1000));\n\n // XHarness should still be running\n Assert.False(testTask.IsCompleted);\n\n // mlaunch should be started\n Assert.True(appStarted.Task.IsCompleted);\n\n // We will mimick the app writing the end signal\n var appLog = appOutputLogs.First();\n appLog.WriteLine(testEndSignal.ToString());\n\n // AppTester should now complete fine but we safe guard it to be sure\n await Task.WhenAny(testTask, Task.Delay(10000));\n\n Assert.True(testTask.IsCompleted, \"Test tag wasn't detected\");\n\n var (result, resultMessage) = await testTask;\n\n // Verify\n Assert.Equal(TestExecutingResult.Succeeded, result);\n Assert.Equal(\"Tests run: 1194 Passed: 1191 Inconclusive: 0 Failed: 0 Ignored: 0\", resultMessage);\n\n var expectedArgs = GetExpectedDeviceMlaunchArgs(\n useTunnel: true,\n extraArgs: $\"-setenv=RUN_END_TAG={testEndSignal} \");\n\n Assert.Equal(mlaunchArguments.Last().AsCommandLine(), expectedArgs);\n\n _listener.Verify(x => x.InitializeAndGetPort(), Times.AtLeastOnce);\n _listener.Verify(x => x.StartAsync(), Times.AtLeastOnce);\n _listener.Verify(x => x.Dispose(), Times.AtLeastOnce);\n\n // verify that we do close the tunnel when it was used\n // we dont want to leak a process\n _tunnelBore.Verify(t => t.Close(s_mockDevice.DeviceIdentifier));\n\n _snapshotReporter.Verify(x => x.StartCaptureAsync(), Times.AtLeastOnce);\n\n deviceSystemLog.Verify(x => x.Dispose(), Times.AtLeastOnce);\n }", + "start_line": 488, + "end_line": 621, + "start_byte": 19862, + "end_byte": 25230 + }, + { + "name": "TestOnMacCatalystTest", + "code": "[Fact]\n public async Task TestOnMacCatalystTest()\n {\n var testResultFilePath = Path.GetTempFileName();\n var listenerLogFile = Mock.Of(x => x.FullPath == testResultFilePath);\n File.WriteAllLines(testResultFilePath, new[] { \"Some result here\", \"Tests run: 124\", \"Some result there\" });\n\n _logs\n .Setup(x => x.Create(\"test-maccatalyst-mocked_timestamp.log\", \"TestLog\", It.IsAny()))\n .Returns(listenerLogFile);\n\n var captureLog = new Mock();\n captureLog.SetupGet(x => x.FullPath).Returns(_simulatorLogPath);\n\n var captureLogFactory = new Mock();\n captureLogFactory\n .Setup(x => x.Create(\n It.IsAny(),\n \"/var/log/system.log\",\n false,\n It.IsAny()))\n .Returns(captureLog.Object);\n\n // Act\n var appTester = new AppTester(\n _processManager.Object,\n _listenerFactory.Object,\n _snapshotReporterFactory,\n captureLogFactory.Object,\n Mock.Of(),\n _testReporterFactory,\n new XmlResultParser(),\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var (result, resultMessage) = await appTester.TestMacCatalystApp(\n _appBundleInfo,\n timeout: TimeSpan.FromSeconds(30),\n testLaunchTimeout: TimeSpan.FromSeconds(30),\n signalAppEnd: false,\n extraAppArguments: new[] { \"--foo=bar\", \"--xyz\" },\n extraEnvVariables: new[] { (\"appArg1\", \"value1\") });\n\n // Verify\n Assert.Equal(TestExecutingResult.Succeeded, result);\n Assert.Equal(\"Tests run: 1194 Passed: 1191 Inconclusive: 0 Failed: 0 Ignored: 0\", resultMessage);\n\n _processManager\n .Verify(\n x => x.ExecuteCommandAsync(\n \"open\",\n It.Is>(args => args.Contains(s_appPath) && args.Contains(\"--foo=bar\") && args.Contains(\"--foo=bar\")),\n _mainLog.Object,\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.Is>(envVars =>\n envVars[\"NUNIT_HOSTNAME\"] == \"127.0.0.1\" &&\n envVars[\"NUNIT_HOSTPORT\"] == Port.ToString() &&\n envVars[\"NUNIT_AUTOEXIT\"] == \"true\" &&\n envVars[\"NUNIT_XML_VERSION\"] == \"xUnit\" &&\n envVars[\"NUNIT_ENABLE_XML_OUTPUT\"] == \"true\"),\n It.IsAny()),\n Times.Once);\n\n _listener.Verify(x => x.InitializeAndGetPort(), Times.AtLeastOnce);\n _listener.Verify(x => x.StartAsync(), Times.AtLeastOnce);\n _listener.Verify(x => x.Dispose(), Times.AtLeastOnce);\n }", + "start_line": 417, + "end_line": 486, + "start_byte": 16887, + "end_byte": 19856 + }, + { + "name": "TestOnDeviceWithSkippedClassesTestTest", + "code": "[Theory]\n [InlineData(\"MyClass\")]\n [InlineData(\"MyClass\", \"MySecondClass\")]\n public async Task TestOnDeviceWithSkippedClassesTestTest(params string[] skippedClasses)\n {\n var deviceSystemLog = new Mock();\n deviceSystemLog.SetupGet(x => x.FullPath).Returns(Path.GetTempFileName());\n\n var deviceLogCapturer = new Mock();\n\n var deviceLogCapturerFactory = new Mock();\n deviceLogCapturerFactory\n .Setup(x => x.Create(_mainLog.Object, deviceSystemLog.Object, DeviceName))\n .Returns(deviceLogCapturer.Object);\n\n var testResultFilePath = Path.GetTempFileName();\n var listenerLogFile = Mock.Of(x => x.FullPath == testResultFilePath);\n File.WriteAllLines(testResultFilePath, new[] { \"Some result here\", \"Tests run: 124\", \"Some result there\" });\n\n _logs\n .Setup(x => x.Create(\"test-ios-device-mocked_timestamp.log\", \"TestLog\", It.IsAny()))\n .Returns(listenerLogFile);\n\n _logs\n .Setup(x => x.Create($\"device-{DeviceName}-mocked_timestamp.log\", LogType.SystemLog.ToString(), It.IsAny()))\n .Returns(deviceSystemLog.Object);\n\n // Act\n var appTester = new AppTester(_processManager.Object,\n _listenerFactory.Object,\n _snapshotReporterFactory,\n Mock.Of(),\n deviceLogCapturerFactory.Object,\n _testReporterFactory,\n new XmlResultParser(),\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var (result, resultMessage) = await appTester.TestApp(\n _appBundleInfo,\n new TestTargetOs(TestTarget.Device_iOS, null),\n s_mockDevice,\n null,\n extraAppArguments: new[] { \"--foo=bar\", \"--xyz\" },\n extraEnvVariables: new[] { (\"appArg1\", \"value1\") },\n timeout: TimeSpan.FromSeconds(30),\n testLaunchTimeout: TimeSpan.FromSeconds(30),\n signalAppEnd: false,\n skippedTestClasses: skippedClasses);\n\n // Verify\n Assert.Equal(TestExecutingResult.Succeeded, result);\n Assert.Equal(\"Tests run: 1194 Passed: 1191 Inconclusive: 0 Failed: 0 Ignored: 0\", resultMessage);\n\n var skippedTestsArg = $\"-setenv=NUNIT_RUN_ALL=false -setenv=NUNIT_SKIPPED_CLASSES={string.Join(',', skippedClasses)} \";\n var expectedArgs = GetExpectedDeviceMlaunchArgs(skippedTestsArg, extraArgs: \"-setenv=appArg1=value1 -argument=--foo=bar -argument=--xyz \");\n\n _processManager\n .Verify(\n x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny>(),\n It.IsAny(),\n It.IsAny()),\n Times.Once);\n\n _listener.Verify(x => x.InitializeAndGetPort(), Times.AtLeastOnce);\n _listener.Verify(x => x.StartAsync(), Times.AtLeastOnce);\n _listener.Verify(x => x.Dispose(), Times.AtLeastOnce);\n\n _snapshotReporter.Verify(x => x.StartCaptureAsync(), Times.AtLeastOnce);\n\n deviceSystemLog.Verify(x => x.Dispose(), Times.AtLeastOnce);\n }", + "start_line": 337, + "end_line": 415, + "start_byte": 13395, + "end_byte": 16881 + }, + { + "name": "TestOnDeviceWithSkippedTestsTest", + "code": "[Theory]\n [InlineData(\"MyClass.MyMethod\")]\n [InlineData(\"MyClass.MyMethod\", \"MyClass.MySecondMethod\")]\n public async Task TestOnDeviceWithSkippedTestsTest(params string[] skippedTests)\n {\n var deviceSystemLog = new Mock();\n deviceSystemLog.SetupGet(x => x.FullPath).Returns(Path.GetTempFileName());\n\n var deviceLogCapturer = new Mock();\n\n var deviceLogCapturerFactory = new Mock();\n deviceLogCapturerFactory\n .Setup(x => x.Create(_mainLog.Object, deviceSystemLog.Object, DeviceName))\n .Returns(deviceLogCapturer.Object);\n\n var testResultFilePath = Path.GetTempFileName();\n var listenerLogFile = Mock.Of(x => x.FullPath == testResultFilePath);\n File.WriteAllLines(testResultFilePath, new[] { \"Some result here\", \"Tests run: 124\", \"Some result there\" });\n\n _logs\n .Setup(x => x.Create(\"test-ios-device-mocked_timestamp.log\", \"TestLog\", It.IsAny()))\n .Returns(listenerLogFile);\n\n _logs\n .Setup(x => x.Create($\"device-{DeviceName}-mocked_timestamp.log\", LogType.SystemLog.ToString(), It.IsAny()))\n .Returns(deviceSystemLog.Object);\n\n // Act\n var appTester = new AppTester(\n _processManager.Object,\n _listenerFactory.Object,\n _snapshotReporterFactory,\n Mock.Of(),\n deviceLogCapturerFactory.Object,\n _testReporterFactory,\n new XmlResultParser(),\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var (result, resultMessage) = await appTester.TestApp(\n _appBundleInfo,\n new TestTargetOs(TestTarget.Device_iOS, null),\n s_mockDevice,\n null,\n timeout: TimeSpan.FromSeconds(30),\n testLaunchTimeout: TimeSpan.FromSeconds(30),\n signalAppEnd: false,\n extraAppArguments: new[] { \"--foo=bar\", \"--xyz\" },\n extraEnvVariables: new[] { (\"appArg1\", \"value1\") },\n skippedMethods: skippedTests);\n\n // Verify\n Assert.Equal(TestExecutingResult.Succeeded, result);\n Assert.Equal(\"Tests run: 1194 Passed: 1191 Inconclusive: 0 Failed: 0 Ignored: 0\", resultMessage);\n\n var skippedTestsArg = $\"-setenv=NUNIT_RUN_ALL=false -setenv=NUNIT_SKIPPED_METHODS={string.Join(',', skippedTests)} \";\n\n var expectedArgs = GetExpectedDeviceMlaunchArgs(skippedTestsArg, extraArgs: \"-setenv=appArg1=value1 -argument=--foo=bar -argument=--xyz \");\n\n _processManager\n .Verify(\n x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny>(),\n It.IsAny(),\n It.IsAny()),\n Times.Once);\n\n _listener.Verify(x => x.InitializeAndGetPort(), Times.AtLeastOnce);\n _listener.Verify(x => x.StartAsync(), Times.AtLeastOnce);\n _listener.Verify(x => x.Dispose(), Times.AtLeastOnce);\n\n _snapshotReporter.Verify(x => x.StartCaptureAsync(), Times.AtLeastOnce);\n\n deviceSystemLog.Verify(x => x.Dispose(), Times.AtLeastOnce);\n }", + "start_line": 255, + "end_line": 335, + "start_byte": 9878, + "end_byte": 13389 + }, + { + "name": "TestOnDeviceTest", + "code": "[Theory]\n [InlineData(false)]\n [InlineData(true)]\n public async Task TestOnDeviceTest(bool useTunnel)\n {\n var deviceSystemLog = new Mock();\n deviceSystemLog.SetupGet(x => x.FullPath).Returns(Path.GetTempFileName());\n\n var deviceLogCapturer = new Mock();\n\n var deviceLogCapturerFactory = new Mock();\n deviceLogCapturerFactory\n .Setup(x => x.Create(_mainLog.Object, deviceSystemLog.Object, DeviceName))\n .Returns(deviceLogCapturer.Object);\n\n var testResultFilePath = Path.GetTempFileName();\n var listenerLogFile = Mock.Of(x => x.FullPath == testResultFilePath);\n File.WriteAllLines(testResultFilePath, new[] { \"Some result here\", \"Tests run: 124\", \"Some result there\" });\n\n _logs\n .Setup(x => x.Create(\"test-ios-device-mocked_timestamp.log\", \"TestLog\", It.IsAny()))\n .Returns(listenerLogFile);\n\n _logs\n .Setup(x => x.Create($\"device-{DeviceName}-mocked_timestamp.log\", LogType.SystemLog.ToString(), It.IsAny()))\n .Returns(deviceSystemLog.Object);\n\n // set tunnel bore expectation\n if (useTunnel)\n {\n _tunnelBore.Setup(t => t.Create(DeviceName, It.IsAny()));\n }\n\n _listenerFactory\n .Setup(f => f.UseTunnel)\n .Returns(useTunnel);\n\n // Act\n var appTester = new AppTester(\n _processManager.Object,\n _listenerFactory.Object,\n _snapshotReporterFactory,\n Mock.Of(),\n deviceLogCapturerFactory.Object,\n _testReporterFactory,\n new XmlResultParser(),\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var (result, resultMessage) = await appTester.TestApp(\n _appBundleInfo,\n new TestTargetOs(TestTarget.Device_iOS, null),\n s_mockDevice,\n null,\n timeout: TimeSpan.FromSeconds(30),\n testLaunchTimeout: TimeSpan.FromSeconds(30),\n signalAppEnd: false,\n extraAppArguments: new[] { \"--foo=bar\", \"--xyz\" },\n extraEnvVariables: new[] { (\"appArg1\", \"value1\") });\n\n // Verify\n Assert.Equal(TestExecutingResult.Succeeded, result);\n Assert.Equal(\"Tests run: 1194 Passed: 1191 Inconclusive: 0 Failed: 0 Ignored: 0\", resultMessage);\n\n var expectedArgs = GetExpectedDeviceMlaunchArgs(\n useTunnel: useTunnel,\n extraArgs: \"-setenv=appArg1=value1 -argument=--foo=bar -argument=--xyz \");\n\n _processManager\n .Verify(\n x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.Is>(d => d[\"appArg1\"] == \"value1\"),\n It.IsAny(),\n It.IsAny()),\n Times.Once);\n\n _listener.Verify(x => x.InitializeAndGetPort(), Times.AtLeastOnce);\n _listener.Verify(x => x.StartAsync(), Times.AtLeastOnce);\n _listener.Verify(x => x.Dispose(), Times.AtLeastOnce);\n\n // verify that we do close the tunnel when it was used\n // we dont want to leak a process\n if (useTunnel)\n {\n _tunnelBore.Verify(t => t.Close(s_mockDevice.DeviceIdentifier));\n }\n\n _snapshotReporter.Verify(x => x.StartCaptureAsync(), Times.AtLeastOnce);\n\n deviceSystemLog.Verify(x => x.Dispose(), Times.AtLeastOnce);\n }", + "start_line": 157, + "end_line": 253, + "start_byte": 6076, + "end_byte": 9872 + }, + { + "name": "TestOnSimulatorTest", + "code": "[Theory]\n [InlineData(false)]\n [InlineData(true)]\n public async Task TestOnSimulatorTest(bool useTunnel)\n {\n var testResultFilePath = Path.GetTempFileName();\n var listenerLogFile = Mock.Of(x => x.FullPath == testResultFilePath);\n File.WriteAllLines(testResultFilePath, new[] { \"Some result here\", \"Tests run: 124\", \"Some result there\" });\n\n _logs\n .Setup(x => x.Create(\"test-ios-simulator-64-mocked_timestamp.log\", \"TestLog\", It.IsAny()))\n .Returns(listenerLogFile);\n\n var captureLog = new Mock();\n captureLog.SetupGet(x => x.FullPath).Returns(_simulatorLogPath);\n\n var captureLogFactory = new Mock();\n captureLogFactory\n .Setup(x => x.Create(\n Path.Combine(_logs.Object.Directory, _mockSimulator.Name + \".log\"),\n _mockSimulator.SystemLog,\n false,\n It.IsAny()))\n .Returns(captureLog.Object);\n\n _listenerFactory.Setup(f => f.UseTunnel).Returns(useTunnel);\n\n // Act\n var appTester = new AppTester(\n _processManager.Object,\n _listenerFactory.Object,\n _snapshotReporterFactory,\n captureLogFactory.Object,\n Mock.Of(),\n _testReporterFactory,\n new XmlResultParser(),\n _mainLog.Object,\n _logs.Object,\n _helpers.Object);\n\n var (result, resultMessage) = await appTester.TestApp(\n _appBundleInfo,\n new TestTargetOs(TestTarget.Simulator_tvOS, null),\n _mockSimulator,\n null,\n TimeSpan.FromSeconds(30),\n TimeSpan.FromSeconds(30),\n signalAppEnd: false,\n extraAppArguments: new string[] { \"--foo=bar\", \"--xyz\" },\n extraEnvVariables: new[] { (\"appArg1\", \"value1\") });\n\n // Verify\n Assert.Equal(TestExecutingResult.Succeeded, result);\n Assert.Equal(\"Tests run: 1194 Passed: 1191 Inconclusive: 0 Failed: 0 Ignored: 0\", resultMessage);\n\n var expectedArgs = GetExpectedSimulatorMlaunchArgs();\n\n _processManager\n .Verify(\n x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs),\n _mainLog.Object,\n It.IsAny(),\n It.IsAny>(),\n It.IsAny(),\n It.IsAny()),\n Times.Once);\n\n _processManager\n .Verify(\n x => x.ExecuteXcodeCommandAsync(\n \"simctl\",\n It.Is>(args => args.Contains(\"log\") && args.Contains(_mockSimulator.UDID) && args.Contains(\"stream\") && args.Any(a => a.Contains(BundleExecutable))),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()),\n Times.Once);\n\n _listener.Verify(x => x.InitializeAndGetPort(), Times.AtLeastOnce);\n _listener.Verify(x => x.StartAsync(), Times.AtLeastOnce);\n _listener.Verify(x => x.Dispose(), Times.AtLeastOnce);\n\n captureLog.Verify(x => x.StartCapture(), Times.AtLeastOnce);\n }", + "start_line": 70, + "end_line": 155, + "start_byte": 2621, + "end_byte": 6070 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/AppOperations/AppRunTestBase.cs": [ + { + "name": "Dispose", + "code": "public void Dispose()\n {\n try\n {\n Directory.Delete(s_outputPath, true);\n }\n catch\n {\n // Concurrency can cause these\n }\n finally\n {\n GC.SuppressFinalize(this);\n }\n }", + "start_line": 117, + "end_line": 131, + "start_byte": 4852, + "end_byte": 5119 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/AppOperations/AppUninstallerTests.cs": [ + { + "name": "UninstallFromDeviceTest", + "code": "[Fact]\n public async Task UninstallFromDeviceTest()\n {\n var device = Mock.Of(x => x.Name == DeviceName && x.UDID == UDID);\n\n // Act\n var result = await _appUninstaller.UninstallDeviceApp(device, AppBundleId);\n\n // Verify\n Assert.Equal(0, result.ExitCode);\n\n var expectedArgs = $\"--uninstalldevbundleid {StringUtils.FormatArguments(AppBundleId)} --devname {UDID}\";\n\n _processManager.Verify(x => x.ExecuteCommandAsync(\n It.Is(args => args.AsCommandLine() == expectedArgs),\n _mainLog.Object,\n It.IsAny(),\n null,\n It.IsAny(),\n It.IsAny()));\n }", + "start_line": 59, + "end_line": 79, + "start_byte": 2043, + "end_byte": 2769 + }, + { + "name": "UninstallFromSimulatorTest", + "code": "[Fact]\n public async Task UninstallFromSimulatorTest()\n {\n var simulator = Mock.Of(x => x.Name == DeviceName && x.UDID == UDID);\n\n // Act\n var result = await _appUninstaller.UninstallSimulatorApp(simulator, AppBundleId);\n\n // Verify\n Assert.Equal(0, result.ExitCode);\n\n var expectedArgs = $\"uninstall {UDID} {StringUtils.FormatArguments(AppBundleId)}\";\n\n _processManager.Verify(x => x.ExecuteXcodeCommandAsync(\n \"simctl\",\n It.Is(args => string.Join(\" \", args) == expectedArgs),\n _mainLog.Object,\n It.IsAny(),\n It.IsAny()));\n }", + "start_line": 38, + "end_line": 57, + "start_byte": 1345, + "end_byte": 2037 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/Orchestration/TestOrchestratorTests.cs": [ + { + "name": "OrchestrateDeviceTestWithFailingTcpTest", + "code": "[Fact]\n public async Task OrchestrateDeviceTestWithFailingTcpTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n var extraArguments = new[] { \"--some arg1\", \"--some arg2\" };\n\n _appTester\n .Setup(x => x.TestApp(\n _appBundleInformation,\n testTarget,\n _device.Object,\n null,\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n false,\n extraArguments,\n It.IsAny>(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ReturnsAsync((TestExecutingResult.Crashed, \"Test execution timed out\"))\n .Verifiable();\n\n _appTester\n .SetupGet(x => x.ListenerConnected)\n .Returns(false);\n\n KnownIssue? issue = new KnownIssue(\"App crashed\", null, (int)ExitCode.TCP_CONNECTION_FAILED);\n _errorKnowledgeBase\n .Setup(x => x.IsKnownTestIssue(It.IsAny(), out issue))\n .Returns(true);\n\n // Act\n var result = await _testOrchestrator.OrchestrateTest(\n AppPath,\n testTarget,\n DeviceName,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n CommunicationChannel.UsbTunnel,\n XmlResultJargon.xUnit,\n Array.Empty(),\n Array.Empty(),\n includeWirelessDevices: true,\n resetSimulator: false,\n enableLldb: false,\n signalAppEnd: false,\n Array.Empty<(string, string)>(),\n extraArguments,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.TCP_CONNECTION_FAILED, result);\n }", + "start_line": 476, + "end_line": 532, + "start_byte": 15713, + "end_byte": 17652 + }, + { + "name": "OrchestrateMacCatalystTestTest", + "code": "[Fact]\n public async Task OrchestrateMacCatalystTestTest()\n {\n // Setup\n _appInstaller.Reset();\n _appUninstaller.Reset();\n _deviceFinder.Reset();\n\n var testTarget = new TestTargetOs(TestTarget.MacCatalyst, null);\n\n var envVars = new[] { (\"envVar1\", \"value1\"), (\"envVar2\", \"value2\") };\n\n _appTester\n .Setup(x => x.TestMacCatalystApp(\n _appBundleInformation,\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n true,\n It.IsAny>(),\n envVars,\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ReturnsAsync((TestExecutingResult.Failed, \"Tests failed\"))\n .Verifiable();\n\n // Act\n var result = await _testOrchestrator.OrchestrateTest(\n AppPath,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n CommunicationChannel.UsbTunnel,\n XmlResultJargon.xUnit,\n Array.Empty(),\n Array.Empty(),\n includeWirelessDevices: false,\n resetSimulator: true,\n enableLldb: false,\n signalAppEnd: true,\n envVars,\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.TESTS_FAILED, result);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n\n _appTester.VerifyAll();\n _deviceFinder.VerifyNoOtherCalls();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n }", + "start_line": 418, + "end_line": 474, + "start_byte": 13906, + "end_byte": 15707 + }, + { + "name": "OrchestrateFailedDeviceTestTest", + "code": "[Fact]\n public async Task OrchestrateFailedDeviceTestTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n var extraArguments = new[] { \"--some arg1\", \"--some arg2\" };\n\n _appTester\n .Setup(x => x.TestApp(\n _appBundleInformation,\n testTarget,\n _device.Object,\n null,\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n true,\n extraArguments,\n It.IsAny>(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ReturnsAsync((TestExecutingResult.TimedOut, SuccessResultLine))\n .Verifiable();\n\n // Act\n var result = await _testOrchestrator.OrchestrateTest(\n AppPath,\n testTarget,\n DeviceName,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n CommunicationChannel.UsbTunnel,\n XmlResultJargon.xUnit,\n Array.Empty(),\n Array.Empty(),\n includeWirelessDevices: true,\n resetSimulator: false,\n enableLldb: false,\n signalAppEnd: true,\n Array.Empty<(string, string)>(),\n extraArguments,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.TIMED_OUT, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, DeviceName, It.IsAny(), true, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _device.Object, It.IsAny()),\n Times.Once);\n\n _appTester.VerifyAll();\n }", + "start_line": 355, + "end_line": 416, + "start_byte": 11837, + "end_byte": 13900 + }, + { + "name": "OrchestrateTimedOutSimulatorSearchTestTest", + "code": "[Fact]\n public async Task OrchestrateTimedOutSimulatorSearchTestTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n _deviceFinder.Reset();\n _deviceFinder\n .Setup(x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()))\n .ThrowsAsync(new OperationCanceledException());\n\n // Act\n var result = await _testOrchestrator.OrchestrateTest(\n AppPath,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n CommunicationChannel.UsbTunnel,\n XmlResultJargon.xUnit,\n Array.Empty(),\n Array.Empty(),\n includeWirelessDevices: false,\n resetSimulator: false,\n enableLldb: true,\n signalAppEnd: false,\n Array.Empty<(string, string)>(),\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.APP_LAUNCH_TIMEOUT, result);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n }", + "start_line": 318, + "end_line": 353, + "start_byte": 10639, + "end_byte": 11831 + }, + { + "name": "OrchestrateTimedOutSimulatorTestTest", + "code": "[Fact]\n public async Task OrchestrateTimedOutSimulatorTestTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n _appTester\n .Setup(x => x.TestApp(\n _appBundleInformation,\n testTarget,\n _simulator.Object,\n null,\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n false,\n It.IsAny>(),\n It.IsAny>(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ReturnsAsync((TestExecutingResult.Crashed, \"App never reported back\"))\n .Verifiable();\n\n var failure = new KnownIssue(\"Some failure\", suggestedExitCode: (int)ExitCode.APP_CRASH);\n _errorKnowledgeBase\n .Setup(x => x.IsKnownTestIssue(It.IsAny(), out failure))\n .Returns(true)\n .Verifiable();\n\n var cts = new CancellationTokenSource();\n\n _deviceFinder.Reset();\n _deviceFinder\n .Setup(x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()))\n .Callback(() => cts.Cancel())\n .ReturnsAsync(new DevicePair(_simulator.Object, null));\n\n // Act\n var result = await _testOrchestrator.OrchestrateTest(\n AppPath,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n CommunicationChannel.UsbTunnel,\n XmlResultJargon.xUnit,\n Array.Empty(),\n Array.Empty(),\n includeWirelessDevices: false,\n resetSimulator: false,\n enableLldb: true,\n signalAppEnd: false,\n Array.Empty<(string, string)>(),\n Array.Empty(),\n cts.Token);\n\n // Verify\n Assert.Equal(ExitCode.APP_LAUNCH_TIMEOUT, result);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n }", + "start_line": 254, + "end_line": 316, + "start_byte": 8423, + "end_byte": 10633 + }, + { + "name": "OrchestrateFailedSimulatorTestTest", + "code": "[Fact]\n public async Task OrchestrateFailedSimulatorTestTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n _appTester\n .Setup(x => x.TestApp(\n _appBundleInformation,\n testTarget,\n _simulator.Object,\n null,\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n false,\n It.IsAny>(),\n It.IsAny>(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ReturnsAsync((TestExecutingResult.Crashed, \"App never reported back\"))\n .Verifiable();\n\n var failure = new KnownIssue(\"Some failure\", suggestedExitCode: (int)ExitCode.APP_CRASH);\n _errorKnowledgeBase\n .Setup(x => x.IsKnownTestIssue(It.IsAny(), out failure))\n .Returns(true)\n .Verifiable();\n\n // Act\n var result = await _testOrchestrator.OrchestrateTest(\n AppPath,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n CommunicationChannel.UsbTunnel,\n XmlResultJargon.xUnit,\n Array.Empty(),\n Array.Empty(),\n includeWirelessDevices: false,\n resetSimulator: false,\n enableLldb: true,\n signalAppEnd: false,\n Array.Empty<(string, string)>(),\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.APP_CRASH, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _simulator.Object, It.IsAny()),\n Times.Once);\n\n _errorKnowledgeBase.VerifyAll();\n _appTester.VerifyAll();\n }", + "start_line": 186, + "end_line": 252, + "start_byte": 6081, + "end_byte": 8417 + }, + { + "name": "OrchestrateDeviceTestTest", + "code": "[Fact]\n public async Task OrchestrateDeviceTestTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n var extraArguments = new[] { \"--some arg1\", \"--some arg2\" };\n\n _appTester\n .Setup(x => x.TestApp(\n _appBundleInformation,\n testTarget,\n _device.Object,\n null,\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n false,\n extraArguments,\n It.IsAny>(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ReturnsAsync((TestExecutingResult.Succeeded, SuccessResultLine))\n .Verifiable();\n\n // Act\n var result = await _testOrchestrator.OrchestrateTest(\n AppPath,\n testTarget,\n DeviceName,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n CommunicationChannel.UsbTunnel,\n XmlResultJargon.xUnit,\n Array.Empty(),\n Array.Empty(),\n includeWirelessDevices: true,\n resetSimulator: false,\n enableLldb: false,\n signalAppEnd: false,\n Array.Empty<(string, string)>(),\n extraArguments,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, DeviceName, It.IsAny(), true, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _device.Object, It.IsAny()),\n Times.Once);\n\n _appTester.VerifyAll();\n }", + "start_line": 123, + "end_line": 184, + "start_byte": 4017, + "end_byte": 6075 + }, + { + "name": "OrchestrateSimulatorTestTest", + "code": "[Fact]\n public async Task OrchestrateSimulatorTestTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n var envVars = new[] { (\"envVar1\", \"value1\"), (\"envVar2\", \"value2\") };\n\n _appTester\n .Setup(x => x.TestApp(\n _appBundleInformation,\n testTarget,\n _simulator.Object,\n null,\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n false,\n It.IsAny>(),\n envVars,\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ReturnsAsync((TestExecutingResult.Succeeded, SuccessResultLine))\n .Verifiable();\n\n // Act\n var result = await _testOrchestrator.OrchestrateTest(\n AppPath,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n CommunicationChannel.UsbTunnel,\n XmlResultJargon.xUnit,\n Array.Empty(),\n Array.Empty(),\n includeWirelessDevices: false,\n resetSimulator: true,\n enableLldb: false,\n signalAppEnd: false,\n envVars,\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(true);\n VerifySimulatorCleanUp(true);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _simulator.Object, It.IsAny()),\n Times.Once);\n\n _appTester.VerifyAll();\n }", + "start_line": 60, + "end_line": 121, + "start_byte": 1977, + "end_byte": 4011 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/Orchestration/SimulatorResetOrchestratorTests.cs": [ + { + "name": "TryMacCatalystResetTest", + "code": "[Fact]\n public async Task TryMacCatalystResetTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.MacCatalyst, null);\n _deviceFinder.Reset();\n\n // Act\n var result = await _simulatorResetOrchestrator.OrchestrateSimulatorReset(\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.INVALID_ARGUMENTS, result);\n\n _deviceFinder.VerifyNoOtherCalls();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n }", + "start_line": 86, + "end_line": 106, + "start_byte": 2524, + "end_byte": 3139 + }, + { + "name": "TryDeviceResetTest", + "code": "[Fact]\n public async Task TryDeviceResetTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"13.5\");\n _deviceFinder.Reset();\n\n // Act\n var result = await _simulatorResetOrchestrator.OrchestrateSimulatorReset(\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.INVALID_ARGUMENTS, result);\n\n _deviceFinder.VerifyNoOtherCalls();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n }", + "start_line": 64, + "end_line": 84, + "start_byte": 1907, + "end_byte": 2518 + }, + { + "name": "OrchestrateSimulatorResetTest", + "code": "[Fact]\n public async Task OrchestrateSimulatorResetTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n // Act\n var result = await _simulatorResetOrchestrator.OrchestrateSimulatorReset(\n testTarget,\n SimulatorName,\n TimeSpan.FromMinutes(30),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, SimulatorName, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(true);\n VerifySimulatorCleanUp(false);\n\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n }", + "start_line": 37, + "end_line": 62, + "start_byte": 1098, + "end_byte": 1901 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/Orchestration/UninstallOrchestratorTests.cs": [ + { + "name": "OrchestrateDeviceUninstallationWhenNoDeviceTest", + "code": "[Fact]\n public async Task OrchestrateDeviceUninstallationWhenNoDeviceTest()\n {\n // Setup\n _deviceFinder.Reset();\n _deviceFinder\n .Setup(x => x.FindDevice(\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ThrowsAsync(new NoDeviceFoundException());\n\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n // Act\n var result = await _uninstallOrchestrator.OrchestrateAppUninstall(\n BundleIdentifier,\n testTarget,\n deviceName: null,\n TimeSpan.FromMinutes(30),\n includeWirelessDevices: false,\n resetSimulator: false,\n enableLldb: false,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.DEVICE_NOT_FOUND, result);\n }", + "start_line": 215, + "end_line": 245, + "start_byte": 7201, + "end_byte": 8195 + }, + { + "name": "OrchestrateMacCatalystUninstallationTest", + "code": "[Fact]\n public async Task OrchestrateMacCatalystUninstallationTest()\n {\n // Setup\n _appInstaller.Reset();\n _appUninstaller.Reset();\n _deviceFinder.Reset();\n\n var testTarget = new TestTargetOs(TestTarget.MacCatalyst, null);\n\n // Act\n await _uninstallOrchestrator.OrchestrateAppUninstall(\n BundleIdentifier,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n includeWirelessDevices: false,\n resetSimulator: false,\n enableLldb: false,\n new CancellationToken());\n\n // Verify\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n _deviceFinder.VerifyNoOtherCalls();\n }", + "start_line": 185, + "end_line": 213, + "start_byte": 6361, + "end_byte": 7195 + }, + { + "name": "OrchestrateSimulatorUninstallationWithResetTest", + "code": "[Fact]\n public async Task OrchestrateSimulatorUninstallationWithResetTest()\n {\n // Setup\n _appUninstaller.SetReturnsDefault(Task.FromResult(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n }));\n\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n // Act\n var result = await _uninstallOrchestrator.OrchestrateAppUninstall(\n BundleIdentifier,\n testTarget,\n SimulatorName,\n TimeSpan.FromMinutes(30),\n includeWirelessDevices: false,\n resetSimulator: true,\n enableLldb: false,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, SimulatorName, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(true);\n VerifySimulatorCleanUp(true);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()),\n Times.Never);\n\n // Verify that when resetting the device, we don't try to uninstall unnecessarily after\n _appUninstaller.Verify(\n x => x.UninstallSimulatorApp(It.IsAny(), It.IsAny(), It.IsAny()),\n Times.Never);\n\n _appUninstaller.Verify(\n x => x.UninstallDeviceApp(It.IsAny(), It.IsAny(), It.IsAny()),\n Times.Never);\n }", + "start_line": 137, + "end_line": 183, + "start_byte": 4632, + "end_byte": 6355 + }, + { + "name": "OrchestrateDeviceUninstallationTest", + "code": "[Fact]\n public async Task OrchestrateDeviceUninstallationTest()\n {\n // Setup\n _appUninstaller.SetReturnsDefault(Task.FromResult(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n }));\n\n var testTarget = new TestTargetOs(TestTarget.Device_tvOS, \"14.2\");\n\n // Act\n var result = await _uninstallOrchestrator.OrchestrateAppUninstall(\n BundleIdentifier,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n includeWirelessDevices: false,\n resetSimulator: false,\n enableLldb: false,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()),\n Times.Never);\n\n _appUninstaller.Verify(\n x => x.UninstallSimulatorApp(It.IsAny(), It.IsAny(), It.IsAny()),\n Times.Never);\n\n _appUninstaller.Verify(\n x => x.UninstallDeviceApp(_device.Object, BundleIdentifier, It.IsAny()),\n Times.Once);\n }", + "start_line": 90, + "end_line": 135, + "start_byte": 3046, + "end_byte": 4626 + }, + { + "name": "OrchestrateSimulatorUninstallationTest", + "code": "[Fact]\n public async Task OrchestrateSimulatorUninstallationTest()\n {\n // Setup\n _appUninstaller.SetReturnsDefault(Task.FromResult(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n }));\n\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n // Act\n var result = await _uninstallOrchestrator.OrchestrateAppUninstall(\n BundleIdentifier,\n testTarget,\n SimulatorName,\n TimeSpan.FromMinutes(30),\n includeWirelessDevices: false,\n resetSimulator: false,\n enableLldb: false,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, SimulatorName, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()),\n Times.Never);\n\n _appUninstaller.Verify(\n x => x.UninstallSimulatorApp(_simulator.Object, BundleIdentifier, It.IsAny()),\n Times.Once);\n\n _appUninstaller.Verify(\n x => x.UninstallDeviceApp(It.IsAny(), It.IsAny(), It.IsAny()),\n Times.Never);\n\n _simulator\n .Verify(x => x.Boot(It.IsAny(), It.IsAny()), Times.AtLeastOnce);\n\n _simulator\n .Verify(x => x.GetAppBundlePath(It.IsAny(), BundleIdentifier, It.IsAny()), Times.AtLeastOnce);\n }", + "start_line": 37, + "end_line": 88, + "start_byte": 1159, + "end_byte": 3040 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/Orchestration/OrchestratorTestBase.cs": [ + { + "name": "VerifyDiagnosticData", + "code": "protected void VerifyDiagnosticData(TestTargetOs target)\n {\n Assert.Equal(target.Platform.IsSimulator() ? _simulator.Object.Name : _device.Object.Name, _diagnosticsData.Device);\n Assert.Contains(target.OSVersion!, _diagnosticsData.TargetOS);\n }", + "start_line": 123, + "end_line": 127, + "start_byte": 4971, + "end_byte": 5235 + }, + { + "name": "VerifySimulatorCleanUp", + "code": "protected void VerifySimulatorCleanUp(bool shouldBeCleanedUp)\n {\n _simulator.Verify(\n x => x.KillEverything(It.IsAny()),\n shouldBeCleanedUp ? Times.Once : Times.Never);\n }", + "start_line": 116, + "end_line": 121, + "start_byte": 4753, + "end_byte": 4965 + }, + { + "name": "VerifySimulatorReset", + "code": "protected void VerifySimulatorReset(bool shouldBeReset)\n {\n _simulator.Verify(\n x => x.PrepareSimulator(It.IsAny(), It.IsAny()),\n shouldBeReset ? Times.Once : Times.Never);\n }", + "start_line": 109, + "end_line": 114, + "start_byte": 4521, + "end_byte": 4747 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/Orchestration/InstallOrchestratorTests.cs": [ + { + "name": "SetupUninstall", + "code": "private void SetupUninstall(IDevice device, int exitCode = 0)\n {\n if (device is ISimulatorDevice simulator)\n {\n _appUninstaller\n .Setup(x => x.UninstallSimulatorApp(simulator, BundleIdentifier, It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = exitCode,\n TimedOut = false,\n });\n }\n else if (device is IHardwareDevice phone)\n {\n _appUninstaller\n .Setup(x => x.UninstallDeviceApp(phone, BundleIdentifier, It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = exitCode,\n TimedOut = false,\n });\n }\n }", + "start_line": 264, + "end_line": 286, + "start_byte": 8668, + "end_byte": 9504 + }, + { + "name": "SetupInstall", + "code": "private void SetupInstall(IDevice device, int exitCode = 0)\n {\n _appInstaller\n .Setup(x => x.InstallApp(_appBundleInformation, It.IsAny(), device, It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = exitCode,\n TimedOut = false,\n });\n }", + "start_line": 253, + "end_line": 262, + "start_byte": 8289, + "end_byte": 8662 + }, + { + "name": "OrchestrateDeviceInstallationWhenNoDeviceTest", + "code": "[Fact]\n public async Task OrchestrateDeviceInstallationWhenNoDeviceTest()\n {\n // Setup\n _deviceFinder.Reset();\n _deviceFinder\n .Setup(x => x.FindDevice(\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ThrowsAsync(new NoDeviceFoundException());\n\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n // Act\n var result = await _installOrchestrator.OrchestrateInstall(\n testTarget,\n null,\n AppPath,\n TimeSpan.FromMinutes(30),\n includeWirelessDevices: false,\n resetSimulator: false,\n enableLldb: true,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.DEVICE_NOT_FOUND, result);\n }", + "start_line": 221, + "end_line": 251, + "start_byte": 7320, + "end_byte": 8283 + }, + { + "name": "OrchestrateMacCatalystInstallationTest", + "code": "[Fact]\n public async Task OrchestrateMacCatalystInstallationTest()\n {\n // Setup\n _appInstaller.Reset();\n _appUninstaller.Reset();\n _deviceFinder.Reset();\n\n var testTarget = new TestTargetOs(TestTarget.MacCatalyst, null);\n\n // Act\n var result = await _installOrchestrator.OrchestrateInstall(\n testTarget,\n null,\n AppPath,\n TimeSpan.FromMinutes(30),\n includeWirelessDevices: false,\n resetSimulator: false,\n enableLldb: true,\n new CancellationToken());\n\n // Verify\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()),\n Times.Never);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n _deviceFinder.VerifyNoOtherCalls();\n }", + "start_line": 187, + "end_line": 219, + "start_byte": 6281, + "end_byte": 7314 + }, + { + "name": "OrchestrateFailedDeviceInstallationTest", + "code": "[Fact]\n public async Task OrchestrateFailedDeviceInstallationTest()\n {\n // Setup\n SetupInstall(_device.Object, 1);\n SetupUninstall(_device.Object, 1); // This can fail as this is the first purge of the app before we install it\n\n var failure = new KnownIssue(\"Some failure\", suggestedExitCode: (int)ExitCode.APP_NOT_SIGNED);\n _errorKnowledgeBase\n .Setup(x => x.IsKnownInstallIssue(It.IsAny(), out failure))\n .Returns(true)\n .Verifiable();\n\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n // Act\n var result = await _installOrchestrator.OrchestrateInstall(\n testTarget,\n null,\n AppPath,\n TimeSpan.FromMinutes(30),\n includeWirelessDevices: false,\n resetSimulator: false,\n enableLldb: true,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.APP_NOT_SIGNED, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _device.Object, It.IsAny()),\n Times.Once);\n }", + "start_line": 145, + "end_line": 185, + "start_byte": 4807, + "end_byte": 6275 + }, + { + "name": "OrchestrateDeviceInstallationTest", + "code": "[Fact]\n public async Task OrchestrateDeviceInstallationTest()\n {\n // Setup\n SetupInstall(_device.Object);\n SetupUninstall(_device.Object, 1); // This can fail as this is the first purge of the app before we install it\n\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n // Act\n var result = await _installOrchestrator.OrchestrateInstall(\n testTarget,\n null,\n AppPath,\n TimeSpan.FromMinutes(30),\n includeWirelessDevices: false,\n resetSimulator: false,\n enableLldb: true,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _device.Object, It.IsAny()),\n Times.Once);\n }", + "start_line": 109, + "end_line": 143, + "start_byte": 3623, + "end_byte": 4801 + }, + { + "name": "OrchestrateSimulatorInstallationWithResetTest", + "code": "[Fact]\n public async Task OrchestrateSimulatorInstallationWithResetTest()\n {\n // Setup\n SetupInstall(_simulator.Object);\n SetupUninstall(_simulator.Object, 1); // This can fail as this is the first purge of the app before we install it\n\n var testTarget = new TestTargetOs(TestTarget.Simulator_tvOS, \"13.5\");\n\n // Act\n var result = await _installOrchestrator.OrchestrateInstall(\n testTarget,\n null,\n AppPath,\n TimeSpan.FromMinutes(30),\n includeWirelessDevices: true,\n resetSimulator: true,\n enableLldb: true,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), true, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(true);\n VerifySimulatorCleanUp(false); // Install doesn't end with a cleanup so that the app stays behind\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _simulator.Object, It.IsAny()),\n Times.Once);\n }", + "start_line": 73, + "end_line": 107, + "start_byte": 2351, + "end_byte": 3617 + }, + { + "name": "OrchestrateSimulatorInstallationTest", + "code": "[Fact]\n public async Task OrchestrateSimulatorInstallationTest()\n {\n // Setup\n SetupInstall(_simulator.Object);\n SetupUninstall(_simulator.Object, 1); // This can fail as this is the first purge of the app before we install it\n\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n // Act\n var result = await _installOrchestrator.OrchestrateInstall(\n testTarget,\n null,\n AppPath,\n TimeSpan.FromMinutes(30),\n includeWirelessDevices: false,\n resetSimulator: false,\n enableLldb: false,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _simulator.Object, It.IsAny()),\n Times.Once);\n }", + "start_line": 37, + "end_line": 71, + "start_byte": 1149, + "end_byte": 2345 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/Orchestration/JustTestOrchestratorTests.cs": [ + { + "name": "OrchestrateMacCatalystJustTestTest", + "code": "[Fact]\n public async Task OrchestrateMacCatalystJustTestTest()\n {\n // Setup\n _appInstaller.Reset();\n _appUninstaller.Reset();\n _deviceFinder.Reset();\n\n var testTarget = new TestTargetOs(TestTarget.MacCatalyst, null);\n\n var envVars = new[] { (\"envVar1\", \"value1\"), (\"envVar2\", \"value2\") };\n\n _appTester\n .Setup(x => x.TestMacCatalystApp(\n It.Is(info => info.BundleIdentifier == BundleIdentifier),\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n true,\n It.IsAny>(),\n envVars,\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ReturnsAsync((TestExecutingResult.Failed, \"Tests failed\"))\n .Verifiable();\n\n // Act\n var result = await _justTestOrchestrator.OrchestrateTest(\n BundleIdentifier,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n CommunicationChannel.UsbTunnel,\n XmlResultJargon.xUnit,\n Array.Empty(),\n Array.Empty(),\n includeWirelessDevices: false,\n enableLldb: false,\n signalAppEnd: true,\n envVars,\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.TESTS_FAILED, result);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n\n _appTester.VerifyAll();\n _deviceFinder.VerifyNoOtherCalls();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n }", + "start_line": 297, + "end_line": 352, + "start_byte": 10353, + "end_byte": 12194 + }, + { + "name": "OrchestrateFailedDeviceJustTestTest", + "code": "[Fact]\n public async Task OrchestrateFailedDeviceJustTestTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n var extraArguments = new[] { \"--some arg1\", \"--some arg2\" };\n\n _appTester\n .Setup(x => x.TestApp(\n It.Is(info => info.BundleIdentifier == BundleIdentifier),\n testTarget,\n _device.Object,\n null,\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n true,\n extraArguments,\n It.IsAny>(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ReturnsAsync((TestExecutingResult.TimedOut, SuccessResultLine))\n .Verifiable();\n\n // Act\n var result = await _justTestOrchestrator.OrchestrateTest(\n BundleIdentifier,\n testTarget,\n DeviceName,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n CommunicationChannel.UsbTunnel,\n XmlResultJargon.xUnit,\n Array.Empty(),\n Array.Empty(),\n includeWirelessDevices: true,\n enableLldb: false,\n signalAppEnd: true,\n Array.Empty<(string, string)>(),\n extraArguments,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.TIMED_OUT, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, DeviceName, It.IsAny(), true, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n _appTester.VerifyAll();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n }", + "start_line": 238, + "end_line": 295, + "start_byte": 8325, + "end_byte": 10347 + }, + { + "name": "OrchestrateFailedSimulatorJustTestTest", + "code": "[Fact]\n public async Task OrchestrateFailedSimulatorJustTestTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n _appTester\n .Setup(x => x.TestApp(\n _appBundleInformation,\n testTarget,\n _simulator.Object,\n null,\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n false,\n It.IsAny>(),\n It.IsAny>(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ReturnsAsync((TestExecutingResult.Crashed, \"App never reported back\"))\n .Verifiable();\n\n var failure = new KnownIssue(\"Some failure\", suggestedExitCode: (int)ExitCode.APP_CRASH);\n _errorKnowledgeBase\n .Setup(x => x.IsKnownTestIssue(It.IsAny(), out failure))\n .Returns(true)\n .Verifiable();\n\n // Act\n var result = await _justTestOrchestrator.OrchestrateTest(\n BundleIdentifier,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n CommunicationChannel.UsbTunnel,\n XmlResultJargon.xUnit,\n Array.Empty(),\n Array.Empty(),\n includeWirelessDevices: false,\n enableLldb: true,\n signalAppEnd: false,\n Array.Empty<(string, string)>(),\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.APP_CRASH, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n _errorKnowledgeBase.VerifyAll();\n _appTester.VerifyAll();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n\n _simulator.Verify(x => x.Boot(_mainLog.Object, It.IsAny()), Times.Once);\n _simulator.Verify(x => x.GetAppBundlePath(_mainLog.Object, BundleIdentifier, It.IsAny()), Times.Once);\n }", + "start_line": 171, + "end_line": 236, + "start_byte": 5853, + "end_byte": 8319 + }, + { + "name": "OrchestrateDeviceJustTestTest", + "code": "[Fact]\n public async Task OrchestrateDeviceJustTestTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n var extraArguments = new[] { \"--some arg1\", \"--some arg2\" };\n\n _appTester\n .Setup(x => x.TestApp(\n It.Is(info => info.BundleIdentifier == BundleIdentifier),\n testTarget,\n _device.Object,\n null,\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n false,\n extraArguments,\n It.IsAny>(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ReturnsAsync((TestExecutingResult.Succeeded, SuccessResultLine))\n .Verifiable();\n\n // Act\n var result = await _justTestOrchestrator.OrchestrateTest(\n BundleIdentifier,\n testTarget,\n DeviceName,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n CommunicationChannel.UsbTunnel,\n XmlResultJargon.xUnit,\n Array.Empty(),\n Array.Empty(),\n includeWirelessDevices: true,\n enableLldb: false,\n signalAppEnd: false,\n Array.Empty<(string, string)>(),\n extraArguments,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, DeviceName, It.IsAny(), true, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n _appTester.VerifyAll();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n }", + "start_line": 112, + "end_line": 169, + "start_byte": 3830, + "end_byte": 5847 + }, + { + "name": "OrchestrateSimulatorJustTestTest", + "code": "[Fact]\n public async Task OrchestrateSimulatorJustTestTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n var envVars = new[] { (\"envVar1\", \"value1\"), (\"envVar2\", \"value2\") };\n\n _appTester\n .Setup(x => x.TestApp(\n _appBundleInformation,\n testTarget,\n _simulator.Object,\n null,\n TimeSpan.FromMinutes(30),\n It.IsAny(),\n false,\n It.IsAny>(),\n envVars,\n It.IsAny(),\n It.IsAny(),\n It.IsAny(),\n It.IsAny()))\n .ReturnsAsync((TestExecutingResult.Succeeded, SuccessResultLine))\n .Verifiable();\n\n // Act\n var result = await _justTestOrchestrator.OrchestrateTest(\n BundleIdentifier,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n CommunicationChannel.UsbTunnel,\n XmlResultJargon.xUnit,\n Array.Empty(),\n Array.Empty(),\n includeWirelessDevices: false,\n enableLldb: false,\n signalAppEnd: false,\n envVars,\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n _appTester.VerifyAll();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n\n _simulator.Verify(x => x.Boot(_mainLog.Object, It.IsAny()), Times.Once);\n _simulator.Verify(x => x.GetAppBundlePath(_mainLog.Object, BundleIdentifier, It.IsAny()), Times.Once);\n }", + "start_line": 50, + "end_line": 110, + "start_byte": 1657, + "end_byte": 3824 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/Orchestration/RunOrchestratorTests.cs": [ + { + "name": "OrchestrateNoWaitSimulatorRunTest", + "code": "[Fact]\n public async Task OrchestrateNoWaitSimulatorRunTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n var extraArguments = new[] { \"--some arg1\", \"--some arg2\" };\n\n _appRunner\n .Setup(x => x.RunApp(\n _appBundleInformation,\n testTarget,\n _simulator.Object,\n null,\n TimeSpan.FromMinutes(30),\n false,\n false,\n extraArguments,\n It.IsAny>(),\n It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n })\n .Verifiable();\n\n // Act\n var result = await _runOrchestrator.OrchestrateRun(\n AppPath,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n expectedExitCode: 100,\n includeWirelessDevices: true,\n resetSimulator: true,\n enableLldb: false,\n signalAppEnd: false,\n waitForExit: false,\n Array.Empty<(string, string)>(),\n extraArguments,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), true, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(true);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _simulator.Object, It.IsAny()),\n Times.Once);\n\n _appUninstaller.Verify(\n x => x.UninstallSimulatorApp(_simulator.Object, BundleIdentifier, It.IsAny()),\n Times.Never); // No preparation uninstall (because of reset), and then not at the end\n\n _appRunner.VerifyAll();\n _iOSExitCodeDetector.VerifyNoOtherCalls();\n }", + "start_line": 530, + "end_line": 595, + "start_byte": 16854, + "end_byte": 19054 + }, + { + "name": "OrchestrateNoWaitDeviceRunTest", + "code": "[Fact]\n public async Task OrchestrateNoWaitDeviceRunTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n var extraArguments = new[] { \"--some arg1\", \"--some arg2\" };\n\n _appRunner\n .Setup(x => x.RunApp(\n _appBundleInformation,\n testTarget,\n _device.Object,\n null,\n TimeSpan.FromMinutes(30),\n false,\n false,\n extraArguments,\n It.IsAny>(),\n It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n })\n .Verifiable();\n\n // Act\n var result = await _runOrchestrator.OrchestrateRun(\n AppPath,\n testTarget,\n DeviceName,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n expectedExitCode: 100,\n includeWirelessDevices: true,\n resetSimulator: true,\n enableLldb: false,\n signalAppEnd: false,\n waitForExit: false,\n Array.Empty<(string, string)>(),\n extraArguments,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, DeviceName, It.IsAny(), true, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _device.Object, It.IsAny()),\n Times.Once);\n\n _appUninstaller.Verify(\n x => x.UninstallDeviceApp(_device.Object, BundleIdentifier, It.IsAny()),\n Times.Once); // Once in preparation, but not a second time after we're done\n\n _appRunner.VerifyAll();\n _iOSExitCodeDetector.VerifyNoOtherCalls();\n }", + "start_line": 463, + "end_line": 528, + "start_byte": 14665, + "end_byte": 16848 + }, + { + "name": "OrchestrateMacCatalystRunWithNoExitCodeTest", + "code": "[Fact]\n public async Task OrchestrateMacCatalystRunWithNoExitCodeTest()\n {\n // Setup\n _appInstaller.Reset();\n _appUninstaller.Reset();\n _deviceFinder.Reset();\n\n var testTarget = new TestTargetOs(TestTarget.MacCatalyst, null);\n\n var envVars = new[] { (\"envVar1\", \"value1\"), (\"envVar2\", \"value2\") };\n\n _macCatalystExitCodeDetector\n .Setup(x => x.DetectExitCode(_appBundleInformation, It.IsAny()))\n .Returns((int?)null)\n .Verifiable();\n\n _appRunner\n .Setup(x => x.RunMacCatalystApp(\n _appBundleInformation,\n TimeSpan.FromMinutes(30),\n true,\n true,\n It.IsAny>(),\n envVars,\n It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n })\n .Verifiable();\n\n // Act\n var result = await _runOrchestrator.OrchestrateRun(\n AppPath,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n expectedExitCode: 100,\n includeWirelessDevices: false,\n resetSimulator: true,\n enableLldb: false,\n signalAppEnd: true,\n waitForExit: true,\n envVars,\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.RETURN_CODE_NOT_SET, result);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n\n _macCatalystExitCodeDetector.VerifyAll();\n _appRunner.VerifyAll();\n _deviceFinder.VerifyNoOtherCalls();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n }", + "start_line": 400, + "end_line": 461, + "start_byte": 12747, + "end_byte": 14659 + }, + { + "name": "OrchestrateMacCatalystRunTest", + "code": "[Fact]\n public async Task OrchestrateMacCatalystRunTest()\n {\n // Setup\n _appInstaller.Reset();\n _appUninstaller.Reset();\n _deviceFinder.Reset();\n\n var testTarget = new TestTargetOs(TestTarget.MacCatalyst, null);\n\n var envVars = new[] { (\"envVar1\", \"value1\"), (\"envVar2\", \"value2\") };\n\n _macCatalystExitCodeDetector\n .Setup(x => x.DetectExitCode(_appBundleInformation, It.IsAny()))\n .Returns(100)\n .Verifiable();\n\n _appRunner\n .Setup(x => x.RunMacCatalystApp(\n _appBundleInformation,\n TimeSpan.FromMinutes(30),\n true,\n true,\n It.IsAny>(),\n envVars,\n It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n })\n .Verifiable();\n\n // Act\n var result = await _runOrchestrator.OrchestrateRun(\n AppPath,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n expectedExitCode: 100,\n includeWirelessDevices: false,\n resetSimulator: true,\n enableLldb: false,\n signalAppEnd: true,\n waitForExit: true,\n envVars,\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n\n _macCatalystExitCodeDetector.VerifyAll();\n _appRunner.VerifyAll();\n _deviceFinder.VerifyNoOtherCalls();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n }", + "start_line": 337, + "end_line": 398, + "start_byte": 10862, + "end_byte": 12741 + }, + { + "name": "OrchestrateFailedDeviceRunTest", + "code": "[Fact]\n public async Task OrchestrateFailedDeviceRunTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n _iOSExitCodeDetector\n .Setup(x => x.DetectExitCode(_appBundleInformation, It.IsAny()))\n .Returns(200)\n .Verifiable();\n\n var extraArguments = new[] { \"--some arg1\", \"--some arg2\" };\n\n _appRunner\n .Setup(x => x.RunApp(\n _appBundleInformation,\n testTarget,\n _device.Object,\n null,\n TimeSpan.FromMinutes(30),\n true,\n true,\n extraArguments,\n It.IsAny>(),\n It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n })\n .Verifiable();\n\n var failure = new KnownIssue(\"Some failure\", suggestedExitCode: (int)ExitCode.DEVICE_FAILURE);\n _errorKnowledgeBase\n .Setup(x => x.IsKnownTestIssue(It.IsAny(), out failure))\n .Returns(true)\n .Verifiable();\n\n // Act\n var result = await _runOrchestrator.OrchestrateRun(\n AppPath,\n testTarget,\n DeviceName,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n expectedExitCode: 100,\n includeWirelessDevices: true,\n resetSimulator: false,\n enableLldb: false,\n signalAppEnd: true,\n waitForExit: true,\n Array.Empty<(string, string)>(),\n extraArguments,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.DEVICE_FAILURE, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, DeviceName, It.IsAny(), true, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _device.Object, It.IsAny()),\n Times.Once);\n\n _iOSExitCodeDetector.VerifyAll();\n _appRunner.VerifyAll();\n }", + "start_line": 263, + "end_line": 335, + "start_byte": 8458, + "end_byte": 10856 + }, + { + "name": "OrchestrateFailedSimulatorRunTest", + "code": "[Fact]\n public async Task OrchestrateFailedSimulatorRunTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n _appRunner\n .Setup(x => x.RunApp(\n _appBundleInformation,\n testTarget,\n _simulator.Object,\n null,\n TimeSpan.FromMinutes(30),\n false,\n true,\n It.IsAny>(),\n It.IsAny>(),\n It.IsAny()))\n .ThrowsAsync(new Exception())\n .Verifiable();\n\n var failure = new KnownIssue(\"Some failure\", suggestedExitCode: (int)ExitCode.SIMULATOR_FAILURE);\n _errorKnowledgeBase\n .Setup(x => x.IsKnownTestIssue(It.IsAny(), out failure))\n .Returns(true)\n .Verifiable();\n\n // Act\n var result = await _runOrchestrator.OrchestrateRun(\n AppPath,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n expectedExitCode: 100,\n includeWirelessDevices: false,\n resetSimulator: false,\n enableLldb: true,\n signalAppEnd: false,\n waitForExit: true,\n Array.Empty<(string, string)>(),\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SIMULATOR_FAILURE, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _simulator.Object, It.IsAny()),\n Times.Once);\n\n _errorKnowledgeBase.VerifyAll();\n _appRunner.VerifyAll();\n }", + "start_line": 200, + "end_line": 261, + "start_byte": 6368, + "end_byte": 8452 + }, + { + "name": "OrchestrateDeviceRunTest", + "code": "[Fact]\n public async Task OrchestrateDeviceRunTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n _iOSExitCodeDetector\n .Setup(x => x.DetectExitCode(_appBundleInformation, It.IsAny()))\n .Returns(100)\n .Verifiable();\n\n var extraArguments = new[] { \"--some arg1\", \"--some arg2\" };\n\n _appRunner\n .Setup(x => x.RunApp(\n _appBundleInformation,\n testTarget,\n _device.Object,\n null,\n TimeSpan.FromMinutes(30),\n false,\n true,\n extraArguments,\n It.IsAny>(),\n It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n })\n .Verifiable();\n\n // Act\n var result = await _runOrchestrator.OrchestrateRun(\n AppPath,\n testTarget,\n DeviceName,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n expectedExitCode: 100,\n includeWirelessDevices: true,\n resetSimulator: false,\n enableLldb: false,\n signalAppEnd: false,\n waitForExit: true,\n Array.Empty<(string, string)>(),\n extraArguments,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, DeviceName, It.IsAny(), true, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _device.Object, It.IsAny()),\n Times.Once);\n\n _iOSExitCodeDetector.VerifyAll();\n _appRunner.VerifyAll();\n }", + "start_line": 132, + "end_line": 198, + "start_byte": 4246, + "end_byte": 6362 + }, + { + "name": "OrchestrateSimulatorRunTest", + "code": "[Fact]\n public async Task OrchestrateSimulatorRunTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n var envVars = new[] { (\"envVar1\", \"value1\"), (\"envVar2\", \"value2\") };\n\n _iOSExitCodeDetector\n .Setup(x => x.DetectExitCode(_appBundleInformation, It.IsAny()))\n .Returns(100)\n .Verifiable();\n\n _appRunner\n .Setup(x => x.RunApp(\n _appBundleInformation,\n testTarget,\n _simulator.Object,\n null,\n TimeSpan.FromMinutes(30),\n false,\n true,\n It.IsAny>(),\n envVars,\n It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n })\n .Verifiable();\n\n // Act\n var result = await _runOrchestrator.OrchestrateRun(\n AppPath,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n expectedExitCode: 100,\n includeWirelessDevices: false,\n resetSimulator: true,\n enableLldb: false,\n signalAppEnd: false,\n waitForExit: true,\n envVars,\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(true);\n VerifySimulatorCleanUp(true);\n VerifyDiagnosticData(testTarget);\n\n _appInstaller.Verify(\n x => x.InstallApp(_appBundleInformation, testTarget, _simulator.Object, It.IsAny()),\n Times.Once);\n\n _iOSExitCodeDetector.VerifyAll();\n _appRunner.VerifyAll();\n }", + "start_line": 64, + "end_line": 130, + "start_byte": 2148, + "end_byte": 4240 + } + ], + "tests/Microsoft.DotNet.XHarness.Apple.Tests/Orchestration/JustRunOrchestratorTests.cs": [ + { + "name": "OrchestrateMacCatalystJustRunTest", + "code": "[Fact]\n public async Task OrchestrateMacCatalystJustRunTest()\n {\n // Setup\n _appInstaller.Reset();\n _appUninstaller.Reset();\n _deviceFinder.Reset();\n\n var testTarget = new TestTargetOs(TestTarget.MacCatalyst, null);\n\n var envVars = new[] { (\"envVar1\", \"value1\"), (\"envVar2\", \"value2\") };\n\n _macCatalystExitCodeDetector\n .Setup(x => x.DetectExitCode(It.Is(info => info.BundleIdentifier == BundleIdentifier), It.IsAny()))\n .Returns(100)\n .Verifiable();\n\n _appRunner\n .Setup(x => x.RunMacCatalystApp(\n It.Is(info => info.BundleIdentifier == BundleIdentifier),\n TimeSpan.FromMinutes(30),\n true,\n true,\n It.IsAny>(),\n envVars,\n It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n })\n .Verifiable();\n\n // Act\n var result = await _justRunOrchestrator.OrchestrateRun(\n BundleIdentifier,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n expectedExitCode: 100,\n includeWirelessDevices: false,\n enableLldb: false,\n signalAppEnd: true,\n waitForExit: true,\n envVars,\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n\n _macCatalystExitCodeDetector.VerifyAll();\n _appRunner.VerifyAll();\n _deviceFinder.VerifyNoOtherCalls();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n }", + "start_line": 322, + "end_line": 382, + "start_byte": 10890, + "end_byte": 12866 + }, + { + "name": "OrchestrateFailedDeviceJustRunTest", + "code": "[Fact]\n public async Task OrchestrateFailedDeviceJustRunTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n _iOSExitCodeDetector\n .Setup(x => x.DetectExitCode(It.Is(info => info.BundleIdentifier == BundleIdentifier), It.IsAny()))\n .Returns(200)\n .Verifiable();\n\n var extraArguments = new[] { \"--some arg1\", \"--some arg2\" };\n\n _appRunner\n .Setup(x => x.RunApp(\n It.Is(info => info.BundleIdentifier == BundleIdentifier),\n testTarget,\n _device.Object,\n null,\n TimeSpan.FromMinutes(30),\n true,\n true,\n extraArguments,\n It.IsAny>(),\n It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n })\n .Verifiable();\n\n var failure = new KnownIssue(\"Some failure\", suggestedExitCode: (int)ExitCode.DEVICE_FAILURE);\n _errorKnowledgeBase\n .Setup(x => x.IsKnownTestIssue(It.IsAny(), out failure))\n .Returns(true)\n .Verifiable();\n\n // Act\n var result = await _justRunOrchestrator.OrchestrateRun(\n BundleIdentifier,\n testTarget,\n DeviceName,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n expectedExitCode: 100,\n includeWirelessDevices: true,\n enableLldb: false,\n signalAppEnd: true,\n waitForExit: true,\n Array.Empty<(string, string)>(),\n extraArguments,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.DEVICE_FAILURE, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, DeviceName, It.IsAny(), true, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _iOSExitCodeDetector.VerifyAll();\n _appRunner.VerifyAll();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n }", + "start_line": 251, + "end_line": 320, + "start_byte": 8469, + "end_byte": 10884 + }, + { + "name": "OrchestrateFailedSimulatorJustRunTest", + "code": "[Fact]\n public async Task OrchestrateFailedSimulatorJustRunTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n _appRunner\n .Setup(x => x.RunApp(\n _appBundleInformation,\n testTarget,\n _simulator.Object,\n null,\n TimeSpan.FromMinutes(30),\n false,\n true,\n It.IsAny>(),\n It.IsAny>(),\n It.IsAny()))\n .ThrowsAsync(new Exception())\n .Verifiable();\n\n var failure = new KnownIssue(\"Some failure\", suggestedExitCode: (int)ExitCode.SIMULATOR_FAILURE);\n _errorKnowledgeBase\n .Setup(x => x.IsKnownTestIssue(It.IsAny(), out failure))\n .Returns(true)\n .Verifiable();\n\n // Act\n var result = await _justRunOrchestrator.OrchestrateRun(\n BundleIdentifier,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n expectedExitCode: 100,\n includeWirelessDevices: false,\n enableLldb: true,\n signalAppEnd: false,\n waitForExit: true,\n Array.Empty<(string, string)>(),\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SIMULATOR_FAILURE, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _errorKnowledgeBase.VerifyAll();\n _appRunner.VerifyAll();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n\n _simulator.Verify(x => x.Boot(_mainLog.Object, It.IsAny()), Times.Once);\n _simulator.Verify(x => x.GetAppBundlePath(_mainLog.Object, BundleIdentifier, It.IsAny()), Times.Once);\n }", + "start_line": 188, + "end_line": 249, + "start_byte": 6248, + "end_byte": 8463 + }, + { + "name": "OrchestrateDeviceJustRunTest", + "code": "[Fact]\n public async Task OrchestrateDeviceJustRunTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Device_iOS, \"14.2\");\n\n _iOSExitCodeDetector\n .Setup(x => x.DetectExitCode(It.Is(info => info.BundleIdentifier == BundleIdentifier), It.IsAny()))\n .Returns(100)\n .Verifiable();\n\n var extraArguments = new[] { \"--some arg1\", \"--some arg2\" };\n\n _appRunner\n .Setup(x => x.RunApp(\n It.Is(info => info.BundleIdentifier == BundleIdentifier),\n testTarget,\n _device.Object,\n null,\n TimeSpan.FromMinutes(30),\n false,\n true,\n extraArguments,\n It.IsAny>(),\n It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n })\n .Verifiable();\n\n // Act\n var result = await _justRunOrchestrator.OrchestrateRun(\n BundleIdentifier,\n testTarget,\n DeviceName,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n expectedExitCode: 100,\n includeWirelessDevices: true,\n enableLldb: false,\n signalAppEnd: false,\n waitForExit: true,\n Array.Empty<(string, string)>(),\n extraArguments,\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, DeviceName, It.IsAny(), true, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _iOSExitCodeDetector.VerifyAll();\n _appRunner.VerifyAll();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n }", + "start_line": 123, + "end_line": 186, + "start_byte": 4109, + "end_byte": 6242 + }, + { + "name": "OrchestrateSimulatorJustRunTest", + "code": "[Fact]\n public async Task OrchestrateSimulatorJustRunTest()\n {\n // Setup\n var testTarget = new TestTargetOs(TestTarget.Simulator_iOS64, \"13.5\");\n\n var envVars = new[] { (\"envVar1\", \"value1\"), (\"envVar2\", \"value2\") };\n\n _iOSExitCodeDetector\n .Setup(x => x.DetectExitCode(_appBundleInformation, It.IsAny()))\n .Returns(100)\n .Verifiable();\n\n _appRunner\n .Setup(x => x.RunApp(\n _appBundleInformation,\n testTarget,\n _simulator.Object,\n null,\n TimeSpan.FromMinutes(30),\n false,\n true,\n It.IsAny>(),\n envVars,\n It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult\n {\n ExitCode = 0,\n TimedOut = false,\n })\n .Verifiable();\n\n // Act\n var result = await _justRunOrchestrator.OrchestrateRun(\n BundleIdentifier,\n testTarget,\n null,\n TimeSpan.FromMinutes(30),\n TimeSpan.FromMinutes(3),\n expectedExitCode: 100,\n includeWirelessDevices: false,\n enableLldb: false,\n signalAppEnd: false,\n waitForExit: true,\n envVars,\n Array.Empty(),\n new CancellationToken());\n\n // Verify\n Assert.Equal(ExitCode.SUCCESS, result);\n\n _deviceFinder.Verify(\n x => x.FindDevice(testTarget, null, It.IsAny(), false, true, It.IsAny()),\n Times.Once);\n\n VerifySimulatorReset(false);\n VerifySimulatorCleanUp(false);\n VerifyDiagnosticData(testTarget);\n\n _iOSExitCodeDetector.VerifyAll();\n _appRunner.VerifyAll();\n _appInstaller.VerifyNoOtherCalls();\n _appUninstaller.VerifyNoOtherCalls();\n\n _simulator.Verify(x => x.Boot(_mainLog.Object, It.IsAny()), Times.Once);\n _simulator.Verify(x => x.GetAppBundlePath(_mainLog.Object, BundleIdentifier, It.IsAny()), Times.Once);\n }", + "start_line": 55, + "end_line": 121, + "start_byte": 1877, + "end_byte": 4103 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Hardware/HardwareDeviceLoaderTests.cs": [ + { + "name": "FindAndCacheDevicesWithFailingMlaunchTest", + "code": "[Fact]\n public async Task FindAndCacheDevicesWithFailingMlaunchTest()\n {\n string processPath = null;\n MlaunchArguments passedArguments = null;\n\n // Moq.SetupSequence doesn't allow custom callbacks so we need to count ourselves\n var calls = 0;\n\n // moq It.Is is not working as nicelly as we would like it, we capture data and use asserts\n _processManager.Setup(p => p.RunAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny()))\n .Returns, int, CancellationToken?, bool?>((p, args, log, t, env, verbosity, token, d) =>\n {\n calls++;\n\n if (calls == 1)\n {\n // Mlaunch can sometimes time out and we are testing that a subsequent Load will trigger it again\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 137, TimedOut = true });\n }\n\n processPath = p.StartInfo.FileName;\n passedArguments = args;\n\n // we get the temp file that was passed as the args, and write our sample xml, which will be parsed to get the devices :)\n var tempPath = args.Where(a => a is ListDevicesArgument).First().AsCommandLineArgument();\n tempPath = tempPath.Substring(tempPath.IndexOf('=') + 1).Replace(\"\\\"\", string.Empty);\n\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(\"devices.xml\", StringComparison.Ordinal)).FirstOrDefault();\n using (var outputStream = new StreamWriter(tempPath))\n using (var sampleStream = new StreamReader(GetType().Assembly.GetManifestResourceStream(name)))\n {\n string line;\n while ((line = sampleStream.ReadLine()) != null)\n outputStream.WriteLine(line);\n }\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 0, TimedOut = false });\n });\n\n await Assert.ThrowsAsync(async () => await _devices.LoadDevices(_executionLog.Object));\n\n Assert.Empty(_devices.ConnectedDevices);\n Assert.Equal(1, calls);\n await _devices.LoadDevices(_executionLog.Object);\n Assert.Equal(2, calls);\n Assert.NotEmpty(_devices.ConnectedDevices);\n await _devices.LoadDevices(_executionLog.Object);\n Assert.Equal(2, calls);\n await _devices.LoadDevices(_executionLog.Object);\n Assert.Equal(2, calls);\n }", + "start_line": 123, + "end_line": 173, + "start_byte": 5598, + "end_byte": 8335 + }, + { + "name": "LoadAsyncProcessSuccess", + "code": "[Theory]\n [InlineData(true)]\n [InlineData(false)]\n public async Task LoadAsyncProcessSuccess(bool extraData)\n {\n string processPath = null;\n MlaunchArguments passedArguments = null;\n\n // moq It.Is is not working as nicelly as we would like it, we capture data and use asserts\n _processManager.Setup(p => p.RunAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny()))\n .Returns, int, CancellationToken?, bool?>((p, args, log, t, env, verbosity, token, d) =>\n {\n processPath = p.StartInfo.FileName;\n passedArguments = args;\n\n // we get the temp file that was passed as the args, and write our sample xml, which will be parsed to get the devices :)\n var tempPath = args.Where(a => a is ListDevicesArgument).First().AsCommandLineArgument();\n tempPath = tempPath.Substring(tempPath.IndexOf('=') + 1).Replace(\"\\\"\", string.Empty);\n\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(\"devices.xml\", StringComparison.Ordinal)).FirstOrDefault();\n using (var outputStream = new StreamWriter(tempPath))\n using (var sampleStream = new StreamReader(GetType().Assembly.GetManifestResourceStream(name)))\n {\n string line;\n while ((line = sampleStream.ReadLine()) != null)\n {\n outputStream.WriteLine(line);\n }\n }\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 0, TimedOut = false });\n });\n\n await _devices.LoadDevices(_executionLog.Object, listExtraData: extraData);\n\n // assert the devices that are expected from the sample xml\n MlaunchArgument listDevArg = passedArguments.Where(a => a is ListDevicesArgument).FirstOrDefault();\n Assert.NotNull(listDevArg);\n\n MlaunchArgument outputFormatArg = passedArguments.Where(a => a is XmlOutputFormatArgument).FirstOrDefault();\n Assert.NotNull(outputFormatArg);\n\n if (extraData)\n {\n MlaunchArgument listExtraDataArg = passedArguments.Where(a => a is ListExtraDataArgument).FirstOrDefault();\n Assert.NotNull(listExtraDataArg);\n }\n\n Assert.Equal(2, _devices.Connected64BitIOS.Count());\n Assert.Single(_devices.Connected32BitIOS);\n Assert.Empty(_devices.ConnectedTV);\n }", + "start_line": 71, + "end_line": 121, + "start_byte": 2889, + "end_byte": 5592 + }, + { + "name": "LoadAsyncProcessErrorTest", + "code": "[Theory]\n [InlineData(false)] // no timeout\n [InlineData(true)] // timeoout\n public async Task LoadAsyncProcessErrorTest(bool timeout)\n {\n string processPath = null;\n MlaunchArguments passedArguments = null;\n\n // moq It.Is is not working as nicelly as we would like it, we capture data and use asserts\n _processManager.Setup(p => p.RunAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny()))\n .Returns, int, CancellationToken?, bool?>((p, args, log, t, env, verbosity, token, d) =>\n {\n // we are going set the used args to validate them later, will always return an error from this method\n processPath = p.StartInfo.FileName;\n passedArguments = args;\n if (!timeout)\n {\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 1, TimedOut = false });\n }\n else\n {\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 0, TimedOut = true });\n }\n });\n\n await Assert.ThrowsAsync(async () =>\n {\n await _devices.LoadDevices(_executionLog.Object);\n });\n\n MlaunchArgument listDevArg = passedArguments.Where(a => a is ListDevicesArgument).FirstOrDefault();\n Assert.NotNull(listDevArg);\n\n MlaunchArgument outputFormatArg = passedArguments.Where(a => a is XmlOutputFormatArgument).FirstOrDefault();\n Assert.NotNull(outputFormatArg);\n }", + "start_line": 34, + "end_line": 69, + "start_byte": 1102, + "end_byte": 2883 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Hardware/TCCDatabaseTests.cs": [ + { + "name": "AgreeToPromptsAsyncSuccessTest", + "code": "[Theory]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.iOS-12-1\", 3)]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.iOS-10-1\", 2)]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.iOS-7-1\", 1)]\n public async Task AgreeToPromptsAsyncSuccessTest(string runtime, int dbVersion)\n {\n string bundleIdentifier = \"my-bundle-identifier\";\n var services = new string[] {\n \"kTCCServiceAll\",\n \"kTCCServiceAddressBook\",\n \"kTCCServiceCalendar\",\n \"kTCCServiceCamera\",\n \"kTCCServicePhotos\",\n \"kTCCServiceMediaLibrary\",\n \"kTCCServiceMicrophone\",\n \"kTCCServiceUbiquity\",\n \"kTCCServiceWillow\"\n };\n var expectedArgs = new StringBuilder(\"\\n\");\n // assert the sql used depending on the version\n foreach (var id in new[] { bundleIdentifier, bundleIdentifier + \".watchkitapp\" })\n {\n switch (dbVersion)\n {\n case 1:\n foreach (var s in services)\n {\n expectedArgs.AppendFormat(\"DELETE FROM access WHERE service = '{0}' AND client = '{1}';\\n\", s, id);\n expectedArgs.AppendFormat(\"INSERT INTO access VALUES('{0}','{1}',0,1,0,NULL);\\n\", s, id);\n }\n break;\n case 2:\n foreach (var s in services)\n {\n expectedArgs.AppendFormat(\"DELETE FROM access WHERE service = '{0}' AND client = '{1}';\\n\", s, id);\n expectedArgs.AppendFormat(\"INSERT INTO access VALUES('{0}','{1}',0,1,0,NULL,NULL);\\n\", s, id);\n }\n break;\n case 3:\n foreach (var s in services)\n {\n expectedArgs.AppendFormat(\"INSERT OR REPLACE INTO access VALUES('{0}','{1}',0,1,0,NULL,NULL,NULL,'UNUSED',NULL,NULL,{2});\\n\", s, id, DateTimeOffset.Now.ToUnixTimeSeconds());\n }\n break;\n }\n }\n string processName = null;\n IList args = new List();\n _processManager.Setup(p => p.ExecuteCommandAsync(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), null, null))\n .Returns, ILog, TimeSpan, Dictionary, CancellationToken?>((p, a, l, t, e, c) =>\n {\n processName = p;\n args = a;\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 0, TimedOut = false });\n });\n\n await _database.AgreeToPromptsAsync(runtime, _dataPath, _udid, _executionLog.Object, bundleIdentifier);\n\n Assert.Equal(\"sqlite3\", processName);\n // assert that the sql is present\n Assert.Contains(_dataPath, args);\n Assert.Contains(expectedArgs.ToString(), args);\n }", + "start_line": 83, + "end_line": 145, + "start_byte": 3905, + "end_byte": 6955 + }, + { + "name": "AgreeToPropmtsAsyncTimeoutsTest", + "code": "[Fact]\n public async Task AgreeToPropmtsAsyncTimeoutsTest()\n {\n string processName = null;\n // set the process manager to always return a failure so that we do eventually get a timeout\n _processManager.Setup(p => p.ExecuteCommandAsync(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), null, null))\n .Returns, ILog, TimeSpan, Dictionary, CancellationToken?>((p, a, l, t, e, c) =>\n {\n processName = p;\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 1, TimedOut = true });\n });\n // try to accept and fail because we always timeout\n await _database.AgreeToPromptsAsync(_simRuntime, _dataPath, _udid, _executionLog.Object, \"my-bundle-id\", \"your-bundle-id\");\n\n // verify that we did write in the logs and that we did call sqlite3\n Assert.Equal(\"sqlite3\", processName);\n _executionLog.Verify(l => l.WriteLine(\"Failed to edit TCC.db, the test run might hang due to permission request dialogs\"), Times.AtLeastOnce);\n }", + "start_line": 64, + "end_line": 81, + "start_byte": 2771, + "end_byte": 3899 + }, + { + "name": "AgreeToPromptsAsyncNoIdentifiers", + "code": "[Fact]\n public async Task AgreeToPromptsAsyncNoIdentifiers()\n {\n // we should write in the log that we did not managed to agree to it\n _executionLog.Setup(l => l.WriteLine(It.IsAny()));\n await _database.AgreeToPromptsAsync(_simRuntime, _dataPath, _udid, _executionLog.Object);\n _executionLog.Verify(l => l.WriteLine(\"No bundle identifiers given when requested permission editing.\"));\n }", + "start_line": 55, + "end_line": 62, + "start_byte": 2334, + "end_byte": 2765 + }, + { + "name": "GetTCCFormatUnknownTest", + "code": "[Fact]\n public void GetTCCFormatUnknownTest() => Assert.Throws(() => _database.GetTCCFormat(\"unknown-sim-runtime\"));", + "start_line": 52, + "end_line": 53, + "start_byte": 2184, + "end_byte": 2328 + }, + { + "name": "GetTCCFormatTest", + "code": "[Theory]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.iOS-12-1\", 3)]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.iOS-10-1\", 2)]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.iOS-9-1\", 2)]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.iOS-7-1\", 1)]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.tvOS-12-3\", 3)]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.tvOS-8-1\", 2)]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.watchOS-5-1\", 3)]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.watchOS-4-1\", 2)]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.iOS-14-0\", 4)]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.tvOS-14-0\", 4)]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.watchOS-7-0\", 4)]\n public void GetTCCFormatTest(string runtime, int expected) => Assert.Equal(expected, _database.GetTCCFormat(runtime));", + "start_line": 38, + "end_line": 50, + "start_byte": 1301, + "end_byte": 2178 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Hardware/DefaultSimulatorSelectorTests.cs": [ + { + "name": "SelectSimulatorTest", + "code": "[Fact]\n public void SelectSimulatorTest()\n {\n var simulator1 = new SimulatorDevice(_processManager.Object, _tccDatabase.Object)\n {\n Name = \"Simulator 1\",\n UDID = \"udid1\",\n State = DeviceState.Shutdown,\n };\n\n var simulator2 = new SimulatorDevice(_processManager.Object, _tccDatabase.Object)\n {\n Name = \"Simulator 2\",\n UDID = \"udid2\",\n State = DeviceState.Booted,\n };\n\n var simulator3 = new SimulatorDevice(_processManager.Object, _tccDatabase.Object)\n {\n Name = \"Simulator 3\",\n UDID = \"udid3\",\n State = DeviceState.Booting,\n };\n\n var simulator = _simulatorSelector.SelectSimulator(new[] { simulator1, simulator2, simulator3 });\n\n // The Booted one\n Assert.Equal(simulator2, simulator);\n }", + "start_line": 25, + "end_line": 53, + "start_byte": 868, + "end_byte": 1747 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Hardware/SimulatorDeviceTest.cs": [ + { + "name": "KillEverythingAsyncTest", + "code": "[Fact(Skip = \"Running this test will actually kill simulators on the machine\")]\n public async Task KillEverythingAsyncTest()\n {\n Func, bool> verifyKillAll = (args) =>\n {\n var toKill = new List { \"-9\", \"iPhone Simulator\", \"iOS Simulator\", \"Simulator\", \"Simulator (Watch)\", \"com.apple.CoreSimulator.CoreSimulatorService\", \"ibtoold\" };\n return args.Where(a => toKill.Contains(a)).Count() == toKill.Count;\n };\n\n var simulator = new SimulatorDevice(_processManager.Object, new TCCDatabase(_processManager.Object));\n await simulator.KillEverything(_executionLog.Object);\n\n // verify that all the diff process have been killed making sure args are correct\n _processManager.Verify(p => p.ExecuteCommandAsync(It.Is(s => s == \"launchctl\"), It.Is(args => args.Where(a => a == \"remove\" || a == \"com.apple.CoreSimulator.CoreSimulatorService\").Count() == 2), It.IsAny(), It.IsAny(), null, null));\n _processManager.Verify(p => p.ExecuteCommandAsync(It.Is(s => s == \"killall\"), It.Is>(a => verifyKillAll(a)), It.IsAny(), It.IsAny(), null, null));\n }", + "start_line": 72, + "end_line": 87, + "start_byte": 3463, + "end_byte": 4677 + }, + { + "name": "ShutdownAsyncTest", + "code": "[Fact]\n public async Task ShutdownAsyncTest()\n {\n await _simulator.Shutdown(_executionLog.Object);\n // just call and verify the correct args are pass\n _processManager.Verify(h => h.ExecuteXcodeCommandAsync(It.Is(s => s == \"simctl\"), It.Is(args => args.Where(a => a == _simulator.UDID || a == \"shutdown\").Count() == 2), It.IsAny(), It.IsAny(), It.IsAny()));\n }", + "start_line": 64, + "end_line": 70, + "start_byte": 3015, + "end_byte": 3457 + }, + { + "name": "EraseAsyncTest", + "code": "[Fact]\n public async Task EraseAsyncTest()\n {\n // just call and verify the correct args are pass\n await _simulator.Erase(_executionLog.Object);\n _processManager.Verify(h => h.ExecuteXcodeCommandAsync(It.Is(s => s == \"simctl\"), It.Is(args => args.Where(a => a == _simulator.UDID || a == \"shutdown\").Count() == 2), It.IsAny(), It.IsAny(), It.IsAny()));\n _processManager.Verify(h => h.ExecuteXcodeCommandAsync(It.Is(s => s == \"simctl\"), It.Is(args => args.Where(a => a == _simulator.UDID || a == \"erase\").Count() == 2), It.IsAny(), It.IsAny(), It.IsAny()));\n _processManager.Verify(h => h.ExecuteXcodeCommandAsync(It.Is(s => s == \"simctl\"), It.Is(args => args.Where(a => a == _simulator.UDID || a == \"boot\").Count() == 2), It.IsAny(), It.IsAny(), It.IsAny()));\n _processManager.Verify(h => h.ExecuteXcodeCommandAsync(It.Is(s => s == \"simctl\"), It.Is(args => args.Where(a => a == _simulator.UDID || a == \"shutdown\").Count() == 2), It.IsAny(), It.IsAny(), It.IsAny()));\n\n }", + "start_line": 52, + "end_line": 62, + "start_byte": 1778, + "end_byte": 3009 + }, + { + "name": "OSVersionTest", + "code": "[Theory]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.iOS-12-1\", \"iOS 12.1\")]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.iOS-10-1\", \"iOS 10.1\")]\n public void OSVersionTest(string runtime, string expected)\n {\n _simulator.SimRuntime = runtime;\n Assert.Equal(expected, _simulator.OSVersion);\n }", + "start_line": 43, + "end_line": 50, + "start_byte": 1442, + "end_byte": 1772 + }, + { + "name": "IsWatchSimulatorTest", + "code": "[Theory]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.watchOS-5-1\", true)]\n [InlineData(\"com.apple.CoreSimulator.SimRuntime.iOS-7-1\", false)]\n public void IsWatchSimulatorTest(string runtime, bool expectation)\n {\n _simulator.SimRuntime = runtime;\n Assert.Equal(expectation, _simulator.IsWatchSimulator);\n }", + "start_line": 34, + "end_line": 41, + "start_byte": 1097, + "end_byte": 1436 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Hardware/SimulatorLoaderTests.cs": [ + { + "name": "FindSimulatorsWithFailingMlaunchTest", + "code": "[Fact]\n public async Task FindSimulatorsWithFailingMlaunchTest()\n {\n // Moq.SetupSequence doesn't allow custom callbacks so we need to count ourselves\n var calls = 0;\n\n _processManager\n .Setup(p => p.ExecuteCommandAsync(It.Is(args => args.Any(a => a is ListSimulatorsArgument)), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()))\n .Returns, int, CancellationToken?>((args, log, t, env, verbosity, token) =>\n {\n calls++;\n\n if (calls == 1)\n {\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 137, TimedOut = true });\n }\n\n // we get the temp file that was passed as the args, and write our sample xml, which will be parsed to get the devices :)\n var tempPath = args.Where(a => a is ListSimulatorsArgument).First().AsCommandLineArgument();\n tempPath = tempPath.Substring(tempPath.IndexOf('=') + 1).Replace(\"\\\"\", string.Empty);\n\n CopySampleData(tempPath);\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 0, TimedOut = false });\n });\n\n await Assert.ThrowsAsync(async () => await _simulatorLoader.LoadDevices(_executionLog.Object));\n Assert.Empty(_simulatorLoader.AvailableDevices);\n Assert.Equal(1, calls);\n await _simulatorLoader.LoadDevices(_executionLog.Object);\n Assert.Equal(2, calls);\n Assert.NotEmpty(_simulatorLoader.AvailableDevices);\n await _simulatorLoader.LoadDevices(_executionLog.Object);\n Assert.Equal(2, calls);\n await _simulatorLoader.LoadDevices(_executionLog.Object);\n Assert.Equal(2, calls);\n }", + "start_line": 302, + "end_line": 337, + "start_byte": 15883, + "end_byte": 17789 + }, + { + "name": "FindSimulatorsWithSucceedingMlaunchTest", + "code": "[Theory]\n [InlineData(0, true)]\n [InlineData(137, false)]\n [InlineData(1, true)]\n public async Task FindSimulatorsWithSucceedingMlaunchTest(int mlaunchExitCode, bool mlaunchTimedout)\n {\n _processManager\n .Setup(h => h.ExecuteXcodeCommandAsync(\"simctl\", It.Is(args => args[0] == \"create\"), _executionLog.Object, TimeSpan.FromMinutes(1), It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult() { ExitCode = 0 });\n\n // moq It.Is is not working as nicelly as we would like it, we capture data and use asserts\n _processManager\n .Setup(p => p.ExecuteCommandAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()))\n .Returns, int, CancellationToken?>((args, log, t, env, verbosity, token) =>\n {\n // we get the temp file that was passed as the args, and write our sample xml, which will be parsed to get the devices :)\n var tempPath = args.Where(a => a is ListSimulatorsArgument).First().AsCommandLineArgument();\n tempPath = tempPath.Substring(tempPath.IndexOf('=') + 1).Replace(\"\\\"\", string.Empty);\n\n CopySampleData(tempPath);\n return Task.FromResult(new ProcessExecutionResult { ExitCode = mlaunchExitCode, TimedOut = mlaunchTimedout });\n });\n\n await _simulatorLoader.LoadDevices(_executionLog.Object);\n var (simulator, companion) = await _simulatorLoader.FindSimulators(TestTarget.Simulator_iOS64, _executionLog.Object, false, false);\n\n Assert.NotNull(simulator);\n }", + "start_line": 270, + "end_line": 297, + "start_byte": 13826, + "end_byte": 15588 + }, + { + "name": "SelectDevicesDeviceAndCompanionTest", + "code": "[Fact]\n public void SelectDevicesDeviceAndCompanionTest()\n {\n // moq It.Is is not working as nicelly as we would like it, we capture data and use asserts\n _processManager\n .Setup(p => p.ExecuteCommandAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()))\n .Returns, int, CancellationToken?>((args, log, t, env, verbosity, token) =>\n {\n // We get the temp file that was passed as the args, and write our sample xml, which will be parsed to get the devices :)\n var tempPath = args.Where(a => a is ListSimulatorsArgument).First().AsCommandLineArgument();\n tempPath = tempPath.Substring(tempPath.IndexOf('=') + 1).Replace(\"\\\"\", string.Empty);\n\n CopySampleData(tempPath);\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 0, TimedOut = false });\n });\n\n var devices = _simulatorLoader.SelectDevices(TestTarget.Simulator_watchOS, _executionLog.Object, false).ToList();\n\n Assert.Equal(2, devices.Count);\n Assert.True(devices.First().IsWatchSimulator);\n Assert.False(devices.Last().IsWatchSimulator);\n }", + "start_line": 245, + "end_line": 266, + "start_byte": 12294, + "end_byte": 13644 + }, + { + "name": "SelectDevicesDeviceOnlyTest", + "code": "[Theory]\n [InlineData(TestTarget.Simulator_iOS64)]\n [InlineData(TestTarget.Simulator_tvOS)]\n public void SelectDevicesDeviceOnlyTest(TestTarget testTarget)\n {\n // moq It.Is is not working as nicelly as we would like it, we capture data and use asserts\n _processManager\n .Setup(p => p.ExecuteCommandAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()))\n .Returns, int, CancellationToken?>((args, log, t, env, verbosity, token) =>\n {\n // We get the temp file that was passed as the args, and write our sample xml, which will be parsed to get the devices :)\n var tempPath = args.Where(a => a is ListSimulatorsArgument).First().AsCommandLineArgument();\n tempPath = tempPath.Substring(tempPath.IndexOf('=') + 1).Replace(\"\\\"\", string.Empty);\n\n CopySampleData(tempPath);\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 0, TimedOut = false });\n });\n\n var devices = _simulatorLoader.SelectDevices(testTarget, _executionLog.Object, false).ToList();\n\n Assert.Single(devices);\n }", + "start_line": 221, + "end_line": 242, + "start_byte": 10928, + "end_byte": 12246 + }, + { + "name": "FindAsyncExactVersionFound", + "code": "[Fact]\n public async Task FindAsyncExactVersionFound()\n {\n MlaunchArguments passedArguments = null;\n\n _processManager\n .Setup(h => h.ExecuteXcodeCommandAsync(\"simctl\", It.Is(args => args[0] == \"create\"), _executionLog.Object, TimeSpan.FromMinutes(1), It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult() { ExitCode = 0 });\n\n // moq It.Is is not working as nicelly as we would like it, we capture data and use asserts\n _processManager\n .Setup(p => p.ExecuteCommandAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()))\n .Returns, int, CancellationToken?>((args, log, t, env, verbosity, token) =>\n {\n passedArguments = args;\n\n // we get the temp file that was passed as the args, and write our sample xml, which will be parsed to get the devices :)\n var tempPath = args.Where(a => a is ListSimulatorsArgument).First().AsCommandLineArgument();\n tempPath = tempPath.Substring(tempPath.IndexOf('=') + 1).Replace(\"\\\"\", string.Empty);\n\n CopySampleData(tempPath);\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 0, TimedOut = false });\n });\n\n await _simulatorLoader.LoadDevices(_executionLog.Object);\n\n var (simulator, _) = await _simulatorLoader.FindSimulators(new TestTargetOs(TestTarget.Simulator_iOS64, SdkVersions.MaxiOSSimulator), _executionLog.Object, false, false);\n Assert.NotNull(simulator);\n }", + "start_line": 190, + "end_line": 218, + "start_byte": 9149, + "end_byte": 10880 + }, + { + "name": "FindAsyncExactVersionNotFound", + "code": "[Fact]\n public async Task FindAsyncExactVersionNotFound()\n {\n MlaunchArguments passedArguments = null;\n\n _processManager\n .Setup(h => h.ExecuteXcodeCommandAsync(\"simctl\", It.Is(args => args[0] == \"create\"), _executionLog.Object, TimeSpan.FromMinutes(1), It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult() { ExitCode = 0 });\n\n // moq It.Is is not working as nicelly as we would like it, we capture data and use asserts\n _processManager\n .Setup(p => p.ExecuteCommandAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()))\n .Returns, int, CancellationToken?>((args, log, t, env, verbosity, token) =>\n {\n passedArguments = args;\n\n // we get the temp file that was passed as the args, and write our sample xml, which will be parsed to get the devices :)\n var tempPath = args.Where(a => a is ListSimulatorsArgument).First().AsCommandLineArgument();\n tempPath = tempPath.Substring(tempPath.IndexOf('=') + 1).Replace(\"\\\"\", string.Empty);\n\n CopySampleData(tempPath);\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 0, TimedOut = false });\n });\n\n await _simulatorLoader.LoadDevices(_executionLog.Object);\n\n await Assert.ThrowsAsync(async () => await _simulatorLoader.FindSimulators(new TestTargetOs(TestTarget.Simulator_iOS64, \"12.8\"), _executionLog.Object, false, false));\n }", + "start_line": 161, + "end_line": 188, + "start_byte": 7424, + "end_byte": 9143 + }, + { + "name": "FindAsyncDoNotCreateTest", + "code": "[Theory]\n [InlineData(TestTarget.Simulator_iOS64, false)]\n [InlineData(TestTarget.Simulator_tvOS, false)]\n [InlineData(TestTarget.Simulator_watchOS, true)]\n public async Task FindAsyncDoNotCreateTest(TestTarget target, bool shouldFindCompanion)\n {\n MlaunchArguments passedArguments = null;\n\n _processManager\n .Setup(h => h.ExecuteXcodeCommandAsync(\"simctl\", It.Is(args => args[0] == \"create\"), _executionLog.Object, TimeSpan.FromMinutes(1), It.IsAny()))\n .ReturnsAsync(new ProcessExecutionResult() { ExitCode = 0 });\n\n // moq It.Is is not working as nicelly as we would like it, we capture data and use asserts\n _processManager\n .Setup(p => p.ExecuteCommandAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()))\n .Returns, int, CancellationToken?>((args, log, t, env, verbosity, token) =>\n {\n passedArguments = args;\n\n // we get the temp file that was passed as the args, and write our sample xml, which will be parsed to get the devices :)\n var tempPath = args.Where(a => a is ListSimulatorsArgument).First().AsCommandLineArgument();\n tempPath = tempPath.Substring(tempPath.IndexOf('=') + 1).Replace(\"\\\"\", string.Empty);\n\n CopySampleData(tempPath);\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 0, TimedOut = false });\n });\n\n await _simulatorLoader.LoadDevices(_executionLog.Object);\n var (simulator, companion) = await _simulatorLoader.FindSimulators(target, _executionLog.Object, false, false);\n\n Assert.NotNull(simulator);\n\n if (shouldFindCompanion)\n {\n Assert.NotNull(companion);\n }\n else\n {\n Assert.Null(companion);\n }\n }", + "start_line": 119, + "end_line": 159, + "start_byte": 5385, + "end_byte": 7418 + }, + { + "name": "LoadAsyncProcessSuccess", + "code": "[Fact]\n public async Task LoadAsyncProcessSuccess()\n {\n MlaunchArguments passedArguments = null;\n\n // moq It.Is is not working as nicelly as we would like it, we capture data and use asserts\n _processManager.Setup(p => p.ExecuteCommandAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()))\n .Returns, int, CancellationToken?>((args, log, t, env, verbosity, token) =>\n {\n passedArguments = args;\n\n // we get the temp file that was passed as the args, and write our sample xml, which will be parsed to get the devices :)\n var tempPath = args.Where(a => a is ListSimulatorsArgument).First().AsCommandLineArgument();\n tempPath = tempPath.Substring(tempPath.IndexOf('=') + 1).Replace(\"\\\"\", string.Empty);\n\n CopySampleData(tempPath);\n return Task.FromResult(new ProcessExecutionResult { ExitCode = 0, TimedOut = false });\n });\n\n await _simulatorLoader.LoadDevices(_executionLog.Object);\n\n MlaunchArgument listSimArg = passedArguments.Where(a => a is ListSimulatorsArgument).FirstOrDefault();\n Assert.NotNull(listSimArg);\n\n MlaunchArgument outputFormatArg = passedArguments.Where(a => a is XmlOutputFormatArgument).FirstOrDefault();\n Assert.NotNull(outputFormatArg);\n\n Assert.Equal(76, _simulatorLoader.AvailableDevices.Count());\n }", + "start_line": 89, + "end_line": 117, + "start_byte": 3787, + "end_byte": 5379 + }, + { + "name": "CopySampleData", + "code": "private void CopySampleData(string tempPath)\n {\n var name = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(\"simulators.xml\", StringComparison.Ordinal)).FirstOrDefault();\n using (var outputStream = new StreamWriter(tempPath))\n using (var sampleStream = new StreamReader(GetType().Assembly.GetManifestResourceStream(name)))\n {\n string line;\n while ((line = sampleStream.ReadLine()) != null)\n {\n line = line.Replace(\"{{MAX-IOS.VERSION}}\", SdkVersions.MaxiOSDeploymentTarget);\n line = line.Replace(\"{{MAX-IOS-VERSION}}\", SdkVersions.MaxiOSDeploymentTarget.Replace(\".\", \"-\"));\n\n line = line.Replace(\"{{MAX-WATCH.VERSION}}\", SdkVersions.MaxWatchDeploymentTarget);\n line = line.Replace(\"{{MAX-WATCH-VERSION}}\", SdkVersions.MaxWatchDeploymentTarget.Replace(\".\", \"-\"));\n\n line = line.Replace(\"{{MAX-TVOS.VERSION}}\", SdkVersions.MaxTVOSDeploymentTarget);\n line = line.Replace(\"{{MAX-TVOS-VERSION}}\", SdkVersions.MaxTVOSDeploymentTarget.Replace(\".\", \"-\"));\n\n outputStream.WriteLine(line);\n }\n }\n }", + "start_line": 66, + "end_line": 87, + "start_byte": 2584, + "end_byte": 3781 + }, + { + "name": "LoadAsyncProcessErrorTest", + "code": "[Fact]\n public async Task LoadAsyncProcessErrorTest()\n {\n MlaunchArguments passedArguments = null;\n\n // moq It.Is is not working as nicelly as we would like it, we capture data and use asserts\n _processManager\n .Setup(p => p.ExecuteCommandAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()))\n .Returns, int, CancellationToken?>((args, log, t, env, verbosity, token) =>\n {\n // we are going set the used args to validate them later, will always return an error from this method\n passedArguments = args;\n return Task.FromResult(new ProcessExecutionResult\n {\n ExitCode = 1,\n TimedOut = false\n });\n });\n\n await Assert.ThrowsAsync(async () =>\n {\n await _simulatorLoader.LoadDevices(_executionLog.Object);\n });\n\n // validate the execution of mlaunch\n MlaunchArgument listSimArg = passedArguments.Where(a => a is ListSimulatorsArgument).FirstOrDefault();\n Assert.NotNull(listSimArg);\n\n MlaunchArgument outputFormatArg = passedArguments.Where(a => a is XmlOutputFormatArgument).FirstOrDefault();\n Assert.NotNull(outputFormatArg);\n }", + "start_line": 34, + "end_line": 64, + "start_byte": 1116, + "end_byte": 2578 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Hardware/DeviceTest.cs": [ + { + "name": "Supports32BTest", + "code": "[Theory]\n [MemberData(nameof(Supports32bDevices), MemberType = typeof(DevicesDataTestSource))]\n public void Supports32BTest(IHardwareDevice device, bool expected) => Assert.Equal(expected, device.Supports32Bit);", + "start_line": 244, + "end_line": 246, + "start_byte": 11637, + "end_byte": 11862 + }, + { + "name": "Supports64bTest", + "code": "[Theory]\n [MemberData(nameof(Supports64bDevices), MemberType = typeof(DevicesDataTestSource))]\n public void Supports64bTest(IHardwareDevice device, bool expected) => Assert.Equal(expected, device.Supports64Bit);", + "start_line": 240, + "end_line": 242, + "start_byte": 11402, + "end_byte": 11627 + }, + { + "name": "DevicePlatformTest", + "code": "[Theory]\n [MemberData(nameof(DevicePlatformDevices), MemberType = typeof(DevicesDataTestSource))]\n public void DevicePlatformTest(IHardwareDevice device, DevicePlatform expected) => Assert.Equal(expected, device.DevicePlatform);", + "start_line": 236, + "end_line": 238, + "start_byte": 11150, + "end_byte": 11392 + }, + { + "name": "DebugSpeedTest", + "code": "[Theory]\n [MemberData(nameof(DebugSpeedDevices), MemberType = typeof(DevicesDataTestSource))]\n public void DebugSpeedTest(IHardwareDevice device, int expected) => Assert.Equal(expected, device.DebugSpeed);", + "start_line": 232, + "end_line": 234, + "start_byte": 10921, + "end_byte": 11140 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Utilities/PListExtensionsTests.cs": [ + { + "name": "SetNullCFBundleName", + "code": "[Fact]\n public void SetNullCFBundleName() => Assert.Throws(() => _plist.SetCFBundleName(null));", + "start_line": 94, + "end_line": 95, + "start_byte": 3072, + "end_byte": 3193 + }, + { + "name": "SetCFBundleName", + "code": "[Fact]\n public void SetCFBundleName()\n {\n var bundleName = \"MySuper.app\";\n _plist.SetCFBundleName(bundleName);\n Assert.Equal(bundleName, _plist.GetCFBundleName());\n }", + "start_line": 86, + "end_line": 92, + "start_byte": 2870, + "end_byte": 3066 + }, + { + "name": "SetNullCFBundleIdentifier", + "code": "[Fact]\n public void SetNullCFBundleIdentifier() => Assert.Throws(() => _plist.SetCFBundleIdentifier(null));", + "start_line": 83, + "end_line": 84, + "start_byte": 2731, + "end_byte": 2864 + }, + { + "name": "SetCFBundleIdentifier", + "code": "[Fact]\n public void SetCFBundleIdentifier()\n {\n var bundleIdentifier = \"my.company.super.app\";\n _plist.SetCFBundleIdentifier(bundleIdentifier);\n Assert.Equal(bundleIdentifier, _plist.GetCFBundleIdentifier());\n }", + "start_line": 75, + "end_line": 81, + "start_byte": 2484, + "end_byte": 2725 + }, + { + "name": "SetNullCFBundleDisplayName", + "code": "[Fact]\n public void SetNullCFBundleDisplayName() => Assert.Throws(() => _plist.SetCFBundleDisplayName(null));", + "start_line": 72, + "end_line": 73, + "start_byte": 2343, + "end_byte": 2478 + }, + { + "name": "SetCFBundleDisplayName", + "code": "[Fact]\n public void SetCFBundleDisplayName()\n {\n var displayName = \"MySuperApp\";\n _plist.SetCFBundleDisplayName(displayName);\n Assert.Equal(displayName, _plist.GetCFBundleDisplayName());\n }", + "start_line": 64, + "end_line": 70, + "start_byte": 2118, + "end_byte": 2337 + }, + { + "name": "SetNullMinimummacOSVersion", + "code": "[Fact]\n public void SetNullMinimummacOSVersion() => Assert.Throws(() => _plist.SetMinimummacOSVersion(null));", + "start_line": 61, + "end_line": 62, + "start_byte": 1977, + "end_byte": 2112 + }, + { + "name": "SetMinimummacOSVersion", + "code": "[Fact]\n public void SetMinimummacOSVersion()\n {\n var version = \"MyMaccMinVersion\";\n _plist.SetMinimummacOSVersion(version);\n Assert.Equal(version, _plist.GetMinimummacOSVersion());\n }", + "start_line": 53, + "end_line": 59, + "start_byte": 1758, + "end_byte": 1971 + }, + { + "name": "SetNullMinimumOSVersion", + "code": "[Fact]\n public void SetNullMinimumOSVersion() => Assert.Throws(() => _plist.SetMinimumOSVersion(null));", + "start_line": 50, + "end_line": 51, + "start_byte": 1623, + "end_byte": 1752 + }, + { + "name": "SetMinimumOSVersion", + "code": "[Fact]\n public void SetMinimumOSVersion()\n {\n var version = \"MyMinVersion\";\n _plist.SetMinimumOSVersion(version);\n Assert.Equal(version, _plist.GetMinimumOSVersion());\n }", + "start_line": 42, + "end_line": 48, + "start_byte": 1417, + "end_byte": 1617 + }, + { + "name": "CreateResultSample", + "code": "private XmlDocument CreateResultSample()\n {\n var name = GetType().Assembly.GetManifestResourceNames()\n .FirstOrDefault(a => a.EndsWith(\"Info.plist\", StringComparison.Ordinal));\n var tempPath = Path.GetTempFileName();\n var byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); // I hate BOM\n using var sampleStream = new StreamReader(GetType().Assembly.GetManifestResourceStream(name));\n\n // create the document with the plist and return it\n var doc = new XmlDocument();\n var settings = new XmlReaderSettings()\n {\n XmlResolver = null,\n DtdProcessing = DtdProcessing.Parse,\n };\n using var reader = XmlReader.Create(sampleStream, settings);\n doc.Load(reader);\n return doc;\n }", + "start_line": 22, + "end_line": 40, + "start_byte": 596, + "end_byte": 1411 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Utilities/ProjectFileExtensionsTests.cs": [ + { + "name": "MissingMtouchArchPropertyInCsprojIsHandled", + "code": "[Fact]\n public void MissingMtouchArchPropertyInCsprojIsHandled()\n {\n var assembly = GetType().Assembly;\n var name = assembly.GetManifestResourceNames().Where(a => a.EndsWith(\"MtouchArchMissingEverywhere.xml\", StringComparison.Ordinal)).First();\n var reader = new StreamReader(assembly.GetManifestResourceStream(name)!);\n var csproj = CreateDoc(reader.ReadToEnd());\n\n var arch = csproj.GetMtouchArch(\"iPhoneSimulator\", \"Debug\");\n Assert.Null(arch);\n }", + "start_line": 75, + "end_line": 85, + "start_byte": 3872, + "end_byte": 4373 + }, + { + "name": "MissingMtouchArchPropertyInConfigurationIsHandled", + "code": "[Fact]\n public void MissingMtouchArchPropertyInConfigurationIsHandled()\n {\n var assembly = GetType().Assembly;\n var name = assembly.GetManifestResourceNames().Where(a => a.EndsWith(\"MtouchArchMissingInConfiguration.xml\", StringComparison.Ordinal)).First();\n var reader = new StreamReader(assembly.GetManifestResourceStream(name)!);\n var csproj = CreateDoc(reader.ReadToEnd());\n\n var arch = csproj.GetMtouchArch(\"iPhoneSimulator\", \"Debug\");\n Assert.Null(arch);\n }", + "start_line": 63, + "end_line": 73, + "start_byte": 3353, + "end_byte": 3866 + }, + { + "name": "MtouchArchPropertyIsDetected", + "code": "[Fact]\n public void MtouchArchPropertyIsDetected()\n {\n var assembly = GetType().Assembly;\n var name = assembly.GetManifestResourceNames().Where(a => a.EndsWith(\"MtouchArchMissingInConfiguration.xml\", StringComparison.Ordinal)).First();\n var reader = new StreamReader(assembly.GetManifestResourceStream(name)!);\n var csproj = CreateDoc(reader.ReadToEnd());\n\n var arch = csproj.GetMtouchArch(\"iPhone\", \"Release64\");\n\n Assert.Equal(\"ARM64\", arch);\n }", + "start_line": 50, + "end_line": 61, + "start_byte": 2849, + "end_byte": 3347 + }, + { + "name": "GetInfoPListNode", + "code": "[Fact]\n public void GetInfoPListNode()\n {\n // Exact Include\n Assert.NotNull(ProjectFileExtensions.GetInfoPListNode(GetMSBuildProject(\"\")));\n Assert.NotNull(ProjectFileExtensions.GetInfoPListNode(GetMSBuildProject(\"\")));\n Assert.NotNull(ProjectFileExtensions.GetInfoPListNode(GetMSBuildProject(\"\")));\n Assert.Null(ProjectFileExtensions.GetInfoPListNode(GetMSBuildProject(\"\")));\n\n // With LogicalName\n Assert.NotNull(ProjectFileExtensions.GetInfoPListNode(GetMSBuildProject(\"Info.plist\")));\n Assert.NotNull(ProjectFileExtensions.GetInfoPListNode(GetMSBuildProject(\"Info.plist\")));\n Assert.NotNull(ProjectFileExtensions.GetInfoPListNode(GetMSBuildProject(\"Info.plist\")));\n Assert.Null(ProjectFileExtensions.GetInfoPListNode(GetMSBuildProject(\"Info.plist\")));\n\n // With Link\n Assert.NotNull(ProjectFileExtensions.GetInfoPListNode(GetMSBuildProject(\"Info.plist\")));\n Assert.NotNull(ProjectFileExtensions.GetInfoPListNode(GetMSBuildProject(\"Info.plist\")));\n Assert.NotNull(ProjectFileExtensions.GetInfoPListNode(GetMSBuildProject(\"Info.plist\")));\n Assert.Null(ProjectFileExtensions.GetInfoPListNode(GetMSBuildProject(\"Info.plist\")));\n }", + "start_line": 28, + "end_line": 48, + "start_byte": 708, + "end_byte": 2843 + }, + { + "name": "GetMSBuildProject", + "code": "private static XmlDocument GetMSBuildProject(string snippet)\n {\n return CreateDoc($@\"\n\n{snippet}\n\n\");\n }", + "start_line": 19, + "end_line": 26, + "start_byte": 416, + "end_byte": 702 + }, + { + "name": "CreateDoc", + "code": "private static XmlDocument CreateDoc(string xml)\n {\n var doc = new XmlDocument();\n doc.LoadXmlWithoutNetworkAccess(xml);\n return doc;\n }", + "start_line": 12, + "end_line": 17, + "start_byte": 247, + "end_byte": 410 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Execution/MlaunchArgumentsTests.cs": [ + { + "name": "MlaunchArgumentsEqualityTest", + "code": "[Fact]\n public void MlaunchArgumentsEqualityTest()\n {\n var args1 = new MlaunchArgument[] {\n new ListDevicesArgument (\"foo\"),\n new ListSimulatorsArgument (\"bar\")\n };\n var args2 = new MlaunchArgument[] {\n new ListDevicesArgument (\"foo\"),\n new ListSimulatorsArgument (\"bar\")\n };\n var args3 = new MlaunchArgument[] {\n new ListDevicesArgument (\"foo\"),\n new ListSimulatorsArgument (\"xyz\")\n };\n\n Assert.Equal(args1, args2);\n Assert.NotEqual(args1, args3);\n }", + "start_line": 114, + "end_line": 132, + "start_byte": 4318, + "end_byte": 4936 + }, + { + "name": "MlaunchArgumentEqualityTest", + "code": "[Fact]\n public void MlaunchArgumentEqualityTest()\n {\n var arg1 = new DownloadCrashReportToArgument(\"/path/with spaces.txt\");\n var arg2 = new DownloadCrashReportToArgument(\"/path/with spaces.txt\");\n var arg3 = new DownloadCrashReportToArgument(\"/path/with.txt\");\n\n Assert.Equal(arg1, arg2);\n Assert.NotEqual(arg1, arg3);\n }", + "start_line": 103, + "end_line": 112, + "start_byte": 3946, + "end_byte": 4312 + }, + { + "name": "MlaunchArgumentAndProcessManagerTest", + "code": "[Fact]\n public void MlaunchArgumentAndProcessManagerTest()\n {\n var oldArgs = new List() {\n \"--download-crash-report-to=/path/with spaces.txt\",\n \"--sdkroot\",\n \"/path to xcode/spaces\",\n \"--devname\",\n \"Premek's iPhone\",\n };\n\n var newArgs = new MlaunchArguments() {\n new DownloadCrashReportToArgument (\"/path/with spaces.txt\"),\n new SdkRootArgument (\"/path to xcode/spaces\"),\n new DeviceNameArgument (\"Premek's iPhone\"),\n };\n\n var oldWayOfPassingArgs = StringUtils.FormatArguments(oldArgs);\n var newWayOfPassingArgs = newArgs.AsCommandLine();\n\n Assert.Equal(oldWayOfPassingArgs, newWayOfPassingArgs);\n }", + "start_line": 80, + "end_line": 101, + "start_byte": 3147, + "end_byte": 3940 + }, + { + "name": "AsCommandLineTest", + "code": "[Theory]\n [MemberData(nameof(CommandLineDataTestSource.CommandLineArgs), MemberType = typeof(CommandLineDataTestSource))]\n public void AsCommandLineTest(MlaunchArgument[] args, string expected) => Assert.Equal(expected, new MlaunchArguments(args).AsCommandLine());", + "start_line": 76, + "end_line": 78, + "start_byte": 2871, + "end_byte": 3141 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Listeners/SimpleListenerFactoryTest.cs": [ + { + "name": "UseTcpTunnel", + "code": "[Fact]\n public void UseTcpTunnel()\n {\n var f = new SimpleListenerFactory(null);\n Assert.False(f.UseTunnel, \"Do not use tunnel.\");\n f = new SimpleListenerFactory(Mock.Of());\n Assert.True(f.UseTunnel, \"Use tunnel.\");\n }", + "start_line": 63, + "end_line": 70, + "start_byte": 2086, + "end_byte": 2353 + }, + { + "name": "CreateWatchOSDevice", + "code": "[Fact]\n public void CreateWatchOSDevice()\n {\n var (transport, listener, listenerTmpFile) = _factory.Create(RunMode.WatchOS, _log.Object, _log.Object, false, true, true);\n Assert.Equal(ListenerTransport.Http, transport);\n Assert.IsType(listener);\n Assert.Null(listenerTmpFile);\n }", + "start_line": 54, + "end_line": 61, + "start_byte": 1744, + "end_byte": 2080 + }, + { + "name": "CreateWatchOSSimulator", + "code": "[Fact]\n public void CreateWatchOSSimulator()\n {\n var logFullPath = \"myfullpath.txt\";\n _ = _log.Setup(l => l.FullPath).Returns(logFullPath);\n\n var (transport, listener, listenerTmpFile) = _factory.Create(RunMode.WatchOS, _log.Object, _log.Object, true, true, true);\n Assert.Equal(ListenerTransport.File, transport);\n Assert.IsType(listener);\n Assert.NotNull(listenerTmpFile);\n Assert.Equal(logFullPath + \".tmp\", listenerTmpFile);\n\n _log.Verify(l => l.FullPath, Times.Once);\n\n }", + "start_line": 38, + "end_line": 52, + "start_byte": 1177, + "end_byte": 1738 + }, + { + "name": "CreateNotWatchListener", + "code": "[Fact]\n public void CreateNotWatchListener()\n {\n var (transport, listener, listenerTmpFile) = _factory.Create(RunMode.iOS, _log.Object, _log.Object, true, true, true);\n Assert.Equal(ListenerTransport.Tcp, transport);\n Assert.IsType(listener);\n Assert.Null(listenerTmpFile);\n }", + "start_line": 29, + "end_line": 36, + "start_byte": 839, + "end_byte": 1171 + }, + { + "name": "ConstructorAllowsNullTunnelBore", + "code": "[Fact]\n public void ConstructorAllowsNullTunnelBore()\n {\n _ = new SimpleListenerFactory(null); // if it throws, test fails ;)\n }", + "start_line": 23, + "end_line": 27, + "start_byte": 689, + "end_byte": 833 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Listeners/SimpleFileListenerTest.cs": [ + { + "name": "FileContentIsCopied", + "code": "[Theory]\n [InlineData(\"Tests run: \", false)]\n [InlineData(\"\", true)]\n public void FileContentIsCopied(string endLine, bool isXml)\n {\n var lines = new[] { \"first line\", \"second line\", \"last line\" };\n\n // Create a listener, set the writer and ensure that what we write in the file is present in the final path\n using (var sourceWriter = new StreamWriter(_path))\n {\n using var listener = new SimpleFileListener(_path, _log.Object, _testLog.Object, isXml);\n listener.InitializeAndGetPort();\n listener.StartAsync();\n\n // Write a number of lines and ensure that those are called in the mock\n sourceWriter.WriteLine(\"[Runner executing:\");\n foreach (var line in lines)\n {\n sourceWriter.WriteLine(line);\n }\n\n sourceWriter.WriteLine(endLine);\n sourceWriter.Flush();\n }\n\n Thread.Sleep(200);\n\n // Verify that the expected lines were added\n foreach (var line in lines)\n {\n _testLog.Verify(l => l.WriteLine(It.Is(ll => ll.Trim() == line.Trim())), Times.AtLeastOnce);\n }\n\n _log.Verify(l => l.WriteLine(It.Is(ll => ll == \"Tests have finished executing\")), Times.AtLeastOnce);\n }", + "start_line": 55, + "end_line": 89, + "start_byte": 1329, + "end_byte": 2651 + }, + { + "name": "ConstructorNullPathTest", + "code": "[Fact]\n public void ConstructorNullPathTest() => Assert.Throws(() => new SimpleFileListener(null, _log.Object, _testLog.Object, false));", + "start_line": 52, + "end_line": 53, + "start_byte": 1161, + "end_byte": 1323 + }, + { + "name": "Dispose", + "code": "public void Dispose()\n {\n if (File.Exists(_path))\n {\n try\n {\n File.Delete(_path);\n }\n finally\n {\n }\n }\n\n GC.SuppressFinalize(this);\n }", + "start_line": 36, + "end_line": 50, + "start_byte": 906, + "end_byte": 1155 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Listeners/SimpleTcpListenerTest.cs": [ + { + "name": "ContentIsSentOverTcp", + "code": "[Fact(Skip = \"Test is flaky - https://github.com/dotnet/xharness/issues/52\")]\n public void ContentIsSentOverTcp()\n {\n var tempResult = Path.GetTempFileName();\n // create a stream to be used and write the data there\n var lines = new string[] { \"first line\", \"second line\", \"last line\" };\n // setup the expected data to be written\n _testLog.Setup(l => l.Write(It.IsAny(), 0, It.IsAny())).Callback((buffer, start, end) =>\n {\n using (var resultStream = File.Create(tempResult))\n {// opening closing a lot, but for the test we do not care\n resultStream.Write(buffer, start, end);\n resultStream.Flush();\n }\n });\n // create a linstener that will start in an other thread, connect to it\n // and send the data.\n var listener = new SimpleTcpListener(_log.Object, _testLog.Object, true, true);\n listener.InitializeAndGetPort();\n var connectionPort = listener.Port;\n listener.StartAsync();\n // create a tcp client which will write the logs, then verity that\n // the expected data was provided\n var client = new TcpClient();\n client.Connect(\"localhost\", connectionPort);\n using (var networkStream = client.GetStream())\n using (var streamWriter = new StreamWriter(networkStream))\n {\n foreach (var line in lines)\n {\n streamWriter.WriteLine(line);\n streamWriter.Flush();\n }\n }\n listener.Cancel();\n bool firstLineFound = false;\n bool secondLineFound = false;\n bool lastLineFound = false;\n // read the data in the tempResult and ensure lines are present\n using (var reader = new StreamReader(tempResult))\n {\n string line;\n while ((line = reader.ReadLine()) != null)\n {\n if (line.EndsWith(lines[0]))\n {\n firstLineFound = true;\n }\n\n if (line.EndsWith(lines[1]))\n {\n secondLineFound = true;\n }\n\n if (line.EndsWith(lines[2]))\n {\n lastLineFound = true;\n }\n }\n }\n Assert.True(firstLineFound, \"first line\");\n Assert.True(secondLineFound, \"second line\");\n Assert.True(lastLineFound, \"last line\");\n }", + "start_line": 25, + "end_line": 88, + "start_byte": 718, + "end_byte": 3217 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Logging/LogsTest.cs": [ + { + "name": "AddFileDescriptionNull", + "code": "[Fact]\n public void AddFileDescriptionNull()\n {\n var fullPath = Path.Combine(_directory, _fileName);\n File.WriteAllText(fullPath, \"foo\");\n using (var logs = new Logs(_directory))\n {\n logs.Create(fullPath, null);\n Assert.Single(logs);\n }\n }", + "start_line": 127, + "end_line": 137, + "start_byte": 3620, + "end_byte": 3925 + }, + { + "name": "AddFilePathNullTest", + "code": "[Fact]\n public void AddFilePathNullTest()\n {\n using (var logs = new Logs(_directory))\n {\n Assert.Throws(() => logs.AddFile(null, _description));\n }\n }", + "start_line": 118, + "end_line": 125, + "start_byte": 3400, + "end_byte": 3614 + }, + { + "name": "AddFileNotInDirTest", + "code": "[Fact]\n public void AddFileNotInDirTest()\n {\n var dir1 = Path.Combine(_directory, \"dir1\");\n var dir2 = Path.Combine(_directory, \"dir2\");\n\n Directory.CreateDirectory(dir1);\n Directory.CreateDirectory(dir2);\n\n var filePath = Path.Combine(dir1, \"test-file.txt\");\n File.WriteAllText(filePath, \"Hello world!\");\n\n using (var logs = new Logs(dir2))\n {\n var newPath = Path.Combine(dir2, Path.GetFileNameWithoutExtension(_fileName));\n var fileLog = logs.AddFile(filePath, _description);\n Assert.StartsWith(newPath, fileLog.FullPath); // assert new path\n Assert.True(File.Exists(fileLog.FullPath), \"copy\");\n }\n }", + "start_line": 97, + "end_line": 116, + "start_byte": 2676, + "end_byte": 3394 + }, + { + "name": "AddFileTest", + "code": "[Fact]\n public void AddFileTest()\n {\n var fullPath = Path.Combine(_directory, _fileName);\n File.WriteAllText(fullPath, \"foo\");\n\n using (var logs = new Logs(_directory))\n {\n var fileLog = logs.AddFile(fullPath, _description);\n Assert.Equal(fullPath, fileLog.FullPath); // path && fullPath are the same\n Assert.Equal(Path.Combine(_directory, _fileName), fileLog.FullPath);\n Assert.Equal(_description, fileLog.Description);\n }\n }", + "start_line": 82, + "end_line": 95, + "start_byte": 2156, + "end_byte": 2670 + }, + { + "name": "CreateFileNullDescriptionTest", + "code": "[Fact]\n public void CreateFileNullDescriptionTest()\n {\n using (var logs = new Logs(_directory))\n {\n string description = null;\n logs.CreateFile(_fileName, description);\n Assert.Single(logs);\n }\n }", + "start_line": 71, + "end_line": 80, + "start_byte": 1891, + "end_byte": 2150 + }, + { + "name": "CreateFileNullPathTest", + "code": "[Fact]\n public void CreateFileNullPathTest()\n {\n using (var logs = new Logs(_directory))\n {\n _fileName = null;\n var description = \"My description\";\n Assert.Throws(() => logs.CreateFile(_fileName, description));\n }\n }", + "start_line": 60, + "end_line": 69, + "start_byte": 1583, + "end_byte": 1885 + }, + { + "name": "CreateFileTest", + "code": "[Fact]\n public void CreateFileTest()\n {\n using (var logs = new Logs(_directory))\n {\n var file = logs.CreateFile(_fileName, _description);\n Assert.True(File.Exists(file), \"exists\");\n Assert.Equal(_fileName, Path.GetFileName(file));\n Assert.Single(logs);\n }\n }", + "start_line": 48, + "end_line": 58, + "start_byte": 1245, + "end_byte": 1577 + }, + { + "name": "ConstructorNullDirTest", + "code": "[Fact]\n public void ConstructorNullDirTest() => Assert.Throws(() => new Logs(null));", + "start_line": 45, + "end_line": 46, + "start_byte": 1129, + "end_byte": 1239 + }, + { + "name": "ConstructorTest", + "code": "[Fact]\n public void ConstructorTest()\n {\n using (var logs = new Logs(_directory))\n {\n Assert.Equal(_directory, logs.Directory);\n }\n }", + "start_line": 36, + "end_line": 43, + "start_byte": 949, + "end_byte": 1123 + }, + { + "name": "Dispose", + "code": "public void Dispose()\n {\n if (Directory.Exists(_directory))\n {\n Directory.Delete(_directory, true);\n }\n GC.SuppressFinalize(this);\n }", + "start_line": 27, + "end_line": 34, + "start_byte": 765, + "end_byte": 943 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Logging/LogFileTest.cs": [ + { + "name": "WriteNotAppendTest", + "code": "[Fact]\n public void WriteNotAppendTest()\n {\n const string oldLine = \"Hello world!\";\n const string newLine = \"Hola mundo!\";\n\n // create a log, write to it and assert that we have the expected data\n File.WriteAllLines(_path, new[] { oldLine });\n\n using (var log = new LogFile(_description, _path, false))\n {\n log.WriteLine(newLine);\n log.Flush();\n }\n\n bool oldLineFound = false;\n bool newLineFound = false;\n\n using (var reader = new StreamReader(_path))\n {\n string line;\n while ((line = reader.ReadLine()) != null)\n {\n if (line == oldLine)\n {\n oldLineFound = true;\n }\n\n if (line.EndsWith(newLine)) // consider timestamp\n {\n newLineFound = true;\n }\n }\n }\n\n Assert.False(oldLineFound, \"old line\");\n Assert.True(newLineFound, \"new line\");\n }", + "start_line": 90, + "end_line": 127, + "start_byte": 2299, + "end_byte": 3336 + }, + { + "name": "WriteTest", + "code": "[Fact]\n public void WriteTest()\n {\n const string oldLine = \"Hello world!\";\n const string newLine = \"Hola mundo!\";\n\n // create a log, write to it and assert that we have the expected data\n File.WriteAllLines(_path, new[] { oldLine });\n\n using (var log = new LogFile(_description, _path))\n {\n log.WriteLine(newLine);\n log.Flush();\n }\n\n bool oldLineFound = false;\n bool newLineFound = false;\n\n using (var reader = new StreamReader(_path))\n {\n string line;\n while ((line = reader.ReadLine()) != null)\n {\n if (line == oldLine)\n {\n oldLineFound = true;\n }\n\n if (line.EndsWith(newLine)) // consider time stamp\n {\n newLineFound = true;\n }\n }\n }\n\n Assert.True(oldLineFound, \"old line\");\n Assert.True(newLineFound, \"new line\");\n }", + "start_line": 51, + "end_line": 88, + "start_byte": 1272, + "end_byte": 2293 + }, + { + "name": "ConstructorNullDescriptionTest", + "code": "[Fact]\n public void ConstructorNullDescriptionTest()\n {\n using var log = new LogFile(null, _path);\n }", + "start_line": 45, + "end_line": 49, + "start_byte": 1149, + "end_byte": 1266 + }, + { + "name": "ConstructorNullPathTest", + "code": "[Fact]\n public void ConstructorNullPathTest() => Assert.Throws(() => { var log = new LogFile(_description, null); });", + "start_line": 42, + "end_line": 43, + "start_byte": 1000, + "end_byte": 1143 + }, + { + "name": "ConstructorTest", + "code": "[Fact]\n public void ConstructorTest()\n {\n using (var log = new LogFile(_description, _path))\n {\n Assert.Equal(_description, log.Description);\n Assert.Equal(_path, log.FullPath);\n }\n }", + "start_line": 32, + "end_line": 40, + "start_byte": 759, + "end_byte": 994 + }, + { + "name": "Dispose", + "code": "public void Dispose()\n {\n if (File.Exists(_path))\n {\n File.Delete(_path);\n }\n GC.SuppressFinalize(this);\n }", + "start_line": 23, + "end_line": 30, + "start_byte": 601, + "end_byte": 753 + } + ], + "tests/Microsoft.DotNet.XHarness.iOS.Shared.Tests/Logging/CaptureLogTest.cs": [ + { + "name": "CaptureEntireFile", + "code": "[Fact]\n public void CaptureEntireFile()\n {\n var ignoredLine = \"This line should not be captured\";\n var logLines = new List() { \"first line\", \"second line\", \"third line\" };\n\n File.WriteAllLines(_sourcePath, new[] { ignoredLine });\n\n using var captureLog = new CaptureLog(_destinationPath, _sourcePath, true);\n captureLog.StartCapture();\n\n File.AppendAllLines(_destinationPath, logLines.Take(1));\n captureLog.Flush();\n Assert.Contains(logLines.First(), File.ReadAllText(_destinationPath));\n\n File.AppendAllLines(_destinationPath, logLines.Skip(1));\n\n captureLog.StopCapture();\n\n // Get the stream and assert we do have the correct lines\n using var captureStream = captureLog.GetReader();\n string logLine;\n logLines.Add(ignoredLine);\n while ((logLine = captureStream.ReadLine()) != null)\n {\n if (!string.IsNullOrEmpty(logLine))\n {\n Assert.Contains(logLine, logLines);\n }\n }\n }", + "start_line": 159, + "end_line": 189, + "start_byte": 4801, + "end_byte": 5858 + }, + { + "name": "CaptureEverythingAtOnce", + "code": "[Fact]\n public void CaptureEverythingAtOnce()\n {\n var logLines = new[] { \"first line\", \"second line\", \"third line\" };\n File.WriteAllText(_sourcePath, string.Empty);\n\n using var captureLog = new CaptureLog(_destinationPath, _sourcePath, false);\n\n captureLog.StartCapture();\n File.AppendAllLines(_sourcePath, logLines);\n captureLog.StopCapture();\n\n // get the stream and assert we do have the correct lines\n using var captureStream = captureLog.GetReader();\n string logLine;\n while ((logLine = captureStream.ReadLine()) != null)\n {\n if (!string.IsNullOrEmpty(logLine))\n {\n Assert.Contains(logLine, logLines);\n }\n }\n }", + "start_line": 135, + "end_line": 157, + "start_byte": 4039, + "end_byte": 4795 + }, + { + "name": "CaptureWrongOrder", + "code": "[Fact]\n public void CaptureWrongOrder()\n {\n Assert.Throws(() =>\n {\n using var captureLog = new CaptureLog(_destinationPath, _sourcePath, false);\n captureLog.StopCapture();\n });\n }", + "start_line": 125, + "end_line": 133, + "start_byte": 3775, + "end_byte": 4033 + }, + { + "name": "CaptureMissingFileTest", + "code": "[Fact]\n public void CaptureMissingFileTest()\n {\n using (var captureLog = new CaptureLog(_destinationPath, _sourcePath, false))\n {\n Assert.Equal(_destinationPath, captureLog.FullPath);\n captureLog.StartCapture();\n captureLog.StopCapture();\n }\n\n // Read the data that was added to the capture path and ensure that we do have the name of the missing file\n using (var reader = new StreamReader(_destinationPath))\n {\n var line = reader.ReadLine();\n Assert.Contains(_sourcePath, line);\n }\n }", + "start_line": 107, + "end_line": 123, + "start_byte": 3170, + "end_byte": 3769 + }, + { + "name": "CapturePieceByPiece", + "code": "[Fact]\n public void CapturePieceByPiece()\n {\n var ignoredLine = \"This line should not be captured\";\n var logLines = new[] { \"first line\", \"second line\", \"third line\" };\n\n File.WriteAllLines(_sourcePath, new[] { ignoredLine });\n\n using var captureLog = new CaptureLog(_destinationPath, _sourcePath, false);\n captureLog.StartCapture();\n\n File.AppendAllLines(_destinationPath, logLines.Take(1));\n captureLog.Flush();\n Assert.Contains(logLines.First(), File.ReadAllText(_destinationPath));\n\n File.AppendAllLines(_destinationPath, logLines.Skip(1));\n\n captureLog.StopCapture();\n\n // Get the stream and assert we do have the correct lines\n using var captureStream = captureLog.GetReader();\n string logLine;\n while ((logLine = captureStream.ReadLine()) != null)\n {\n Assert.NotEqual(ignoredLine, logLine);\n\n if (!string.IsNullOrEmpty(logLine))\n {\n Assert.Contains(logLine, logLines);\n }\n }\n }", + "start_line": 74, + "end_line": 105, + "start_byte": 2100, + "end_byte": 3164 + }, + { + "name": "CapturePartOfTheFileOnly", + "code": "[Fact]\n public void CapturePartOfTheFileOnly()\n {\n var ignoredLine = \"This line should not be captured\";\n var logLines = new[] { \"first line\", \"second line\", \"third line\" };\n File.WriteAllLines(_sourcePath, new[] { ignoredLine });\n\n using var captureLog = new CaptureLog(_destinationPath, _sourcePath, false);\n\n captureLog.StartCapture();\n File.AppendAllLines(_sourcePath, logLines);\n captureLog.StopCapture();\n File.AppendAllLines(_sourcePath, new[] { ignoredLine });\n\n // get the stream and assert we do have the correct lines\n using var captureStream = captureLog.GetReader();\n string logLine;\n while ((logLine = captureStream.ReadLine()) != null)\n {\n Assert.NotEqual(ignoredLine, logLine);\n\n if (!string.IsNullOrEmpty(logLine))\n {\n Assert.Contains(logLine, logLines);\n }\n }\n }", + "start_line": 46, + "end_line": 72, + "start_byte": 1148, + "end_byte": 2094 + }, + { + "name": "ConstructorNullFilePath", + "code": "[Fact]\n public void ConstructorNullFilePath()\n {\n Assert.Throws(() =>\n {\n var captureLog = new CaptureLog(null, _sourcePath, false);\n });\n }", + "start_line": 37, + "end_line": 44, + "start_byte": 938, + "end_byte": 1142 + }, + { + "name": "Dispose", + "code": "public void Dispose()\n {\n if (File.Exists(_sourcePath))\n {\n File.Delete(_sourcePath);\n }\n\n GC.SuppressFinalize(this);\n }", + "start_line": 27, + "end_line": 35, + "start_byte": 767, + "end_byte": 932 + } + ], + "tests/Microsoft.DotNet.XHarness.TestRunners.Tests/xUnit/XUnitFilterTests.cs": [ + { + "name": "ApplyWrongTypeToAssembly", + "code": "[Theory]\n [InlineData(XUnitFilterType.Namespace)]\n [InlineData(XUnitFilterType.Single)]\n [InlineData(XUnitFilterType.Trait)]\n [InlineData(XUnitFilterType.TypeName)]\n internal void ApplyWrongTypeToAssembly(XUnitFilterType type)\n {\n // build and assembly for the given type\n XUnitFilter? filter = null;\n switch (type)\n {\n case XUnitFilterType.Namespace:\n filter = XUnitFilter.CreateNamespaceFilter(\"foo\", true);\n break;\n case XUnitFilterType.Single:\n filter = XUnitFilter.CreateSingleFilter(\"foo\", true);\n break;\n case XUnitFilterType.Trait:\n filter = XUnitFilter.CreateTraitFilter(\"foo\", null, true);\n break;\n case XUnitFilterType.TypeName:\n filter = XUnitFilter.CreateClassFilter(\"foo\", true);\n break;\n default:\n Assert.Fail(\"Unexpected filter type\");\n break;\n }\n var assebly = new TestAssemblyInfo(Assembly.GetAssembly(typeof(XUnitFilterType)), \"path\");\n Assert.Throws(() => filter?.IsExcluded(assebly));\n }", + "start_line": 607, + "end_line": 636, + "start_byte": 24976, + "end_byte": 26186 + }, + { + "name": "CreateTraitFilter", + "code": "[Theory]\n [InlineData(\"MyTrait\", \"MyTraitValue\", true)]\n [InlineData(\"MyTrait\", \"MyTraitValue\", false)]\n [InlineData(\"MyTrait\", null, false)]\n public void CreateTraitFilter(string trait, string? traitValue, bool excluded)\n {\n var filter = XUnitFilter.CreateTraitFilter(trait, traitValue, excluded);\n Assert.Equal(trait, filter.SelectorName);\n if (traitValue == null)\n {\n Assert.Equal(string.Empty, filter.SelectorValue);\n }\n else\n {\n Assert.Equal(traitValue, filter.SelectorValue);\n }\n Assert.Null(filter.AssemblyName);\n Assert.Equal(excluded, filter.Exclude);\n Assert.Equal(XUnitFilterType.Trait, filter.FilterType);\n }", + "start_line": 586, + "end_line": 605, + "start_byte": 24233, + "end_byte": 24970 + }, + { + "name": "CreateTraitFilterNullTrait", + "code": "[Fact]\n public void CreateTraitFilterNullTrait()\n {\n Assert.Throws(() => XUnitFilter.CreateTraitFilter(null!, \"value\", true));\n Assert.Throws(() => XUnitFilter.CreateTraitFilter(\"\", \"value\", true));\n }", + "start_line": 579, + "end_line": 584, + "start_byte": 23965, + "end_byte": 24227 + }, + { + "name": "CreateClassFilter", + "code": "[Theory]\n [InlineData(\"MyClass\", \"MyAssembly\", true)]\n [InlineData(\"MyClass\", \"MyAssembly\", false)]\n [InlineData(\"MyClass\", null, false)]\n public void CreateClassFilter(string className, string? assemblyName, bool excluded)\n {\n var filter = XUnitFilter.CreateClassFilter(className, excluded, assemblyName);\n Assert.Equal(className, filter.SelectorValue);\n Assert.Equal(assemblyName, filter.AssemblyName);\n Assert.Equal(excluded, filter.Exclude);\n Assert.Equal(XUnitFilterType.TypeName, filter.FilterType);\n }", + "start_line": 566, + "end_line": 577, + "start_byte": 23398, + "end_byte": 23959 + }, + { + "name": "CreateClassFilterNullClassName", + "code": "[Fact]\n public void CreateClassFilterNullClassName()\n {\n Assert.Throws(() => XUnitFilter.CreateClassFilter(null!, true));\n Assert.Throws(() => XUnitFilter.CreateClassFilter(\"\", true));\n }", + "start_line": 559, + "end_line": 564, + "start_byte": 23144, + "end_byte": 23392 + }, + { + "name": "CreateNamespaceFilter", + "code": "[Theory]\n [InlineData(\"MyNameSpace\", \"MyAssembly\", true)]\n [InlineData(\"MyNameSpace\", \"MyAssembly\", false)]\n [InlineData(\"MyNameSpace\", null, false)]\n public void CreateNamespaceFilter(string nameSpace, string? assemblyName, bool excluded)\n {\n var filter = XUnitFilter.CreateNamespaceFilter(nameSpace, excluded, assemblyName);\n Assert.Equal(nameSpace, filter.SelectorValue);\n Assert.Equal(assemblyName, filter.AssemblyName);\n Assert.Equal(excluded, filter.Exclude);\n Assert.Equal(XUnitFilterType.Namespace, filter.FilterType);\n }", + "start_line": 546, + "end_line": 557, + "start_byte": 22556, + "end_byte": 23138 + }, + { + "name": "CreateNamespaceFilterNullNameSpace", + "code": "[Fact]\n public void CreateNamespaceFilterNullNameSpace()\n {\n Assert.Throws(() => XUnitFilter.CreateNamespaceFilter(null!, true));\n Assert.Throws(() => XUnitFilter.CreateNamespaceFilter(\"\", true));\n }", + "start_line": 539, + "end_line": 544, + "start_byte": 22290, + "end_byte": 22550 + }, + { + "name": "CreateAssemblyFilterMissingExtension", + "code": "[Fact]\n public void CreateAssemblyFilterMissingExtension() => Assert.Throws(() => XUnitFilter.CreateAssemblyFilter(\"MissinExtension\", true));", + "start_line": 536, + "end_line": 537, + "start_byte": 22121, + "end_byte": 22284 + }, + { + "name": "CreateAssemblyFilter", + "code": "[Theory]\n [InlineData(\"MyTestAssembly.exe\", true)]\n [InlineData(\"MySecondAssembly.dll\", true)]\n [InlineData(\"MyTestAssembly.dll\", false)]\n public void CreateAssemblyFilter(string assemblyName, bool excluded)\n {\n var filter = XUnitFilter.CreateAssemblyFilter(assemblyName, excluded);\n Assert.Null(filter.SelectorName);\n Assert.Equal(assemblyName, filter.AssemblyName);\n Assert.Equal(excluded, filter.Exclude);\n Assert.Equal(XUnitFilterType.Assembly, filter.FilterType);\n }", + "start_line": 523, + "end_line": 534, + "start_byte": 21591, + "end_byte": 22115 + }, + { + "name": "CreateAssemblyFilterNullAssemblyName", + "code": "[Fact]\n public void CreateAssemblyFilterNullAssemblyName()\n {\n Assert.Throws(() => XUnitFilter.CreateAssemblyFilter(null!, true));\n Assert.Throws(() => XUnitFilter.CreateAssemblyFilter(\"\", true));\n }", + "start_line": 516, + "end_line": 521, + "start_byte": 21325, + "end_byte": 21585 + }, + { + "name": "CreateSingleFilter", + "code": "[Theory]\n [InlineData(\"TestMethod\", \"TestAssembly\", true)]\n [InlineData(\"TestMethod\", \"TestAssembly\", false)]\n [InlineData(\"TestMethod\", null, false)]\n public void CreateSingleFilter(string methodName, string? assemblyName, bool excluded)\n {\n var filter = XUnitFilter.CreateSingleFilter(methodName, excluded, assemblyName);\n Assert.Equal(methodName, filter.SelectorValue);\n Assert.Equal(assemblyName, filter.AssemblyName);\n Assert.Equal(excluded, filter.Exclude);\n Assert.Equal(XUnitFilterType.Single, filter.FilterType);\n }", + "start_line": 503, + "end_line": 514, + "start_byte": 20742, + "end_byte": 21319 + }, + { + "name": "CreateSingleFilterNullTestName", + "code": "[Fact]\n public void CreateSingleFilterNullTestName()\n {\n Assert.Throws(() => XUnitFilter.CreateSingleFilter(null!, true));\n Assert.Throws(() => XUnitFilter.CreateSingleFilter(\"\", true));\n }", + "start_line": 496, + "end_line": 501, + "start_byte": 20486, + "end_byte": 20736 + }, + { + "name": "ApplyAssemblyFilter", + "code": "[Theory]\n [MemberData(nameof(AssemblyFilters), MemberType = typeof(FiltersTestData))]\n internal void ApplyAssemblyFilter(XUnitFilter filter, TestAssemblyInfo info, bool excluded, string logMessage)\n {\n var logOutut = new StringBuilder();\n Action? log = (s) =>\n {\n logOutut.AppendLine(s);\n };\n var testExcluded = filter.IsExcluded(info, log);\n Assert.Equal(excluded, testExcluded);\n // validate with the log\n Assert.StartsWith(logMessage, logOutut.ToString().Trim());\n }", + "start_line": 480, + "end_line": 493, + "start_byte": 19866, + "end_byte": 20474 + }, + { + "name": "ApplyFilters", + "code": "[Theory]\n [MemberData(nameof(TraitFilters), MemberType = typeof(FiltersTestData))]\n [MemberData(nameof(TypeNameFilters), MemberType = typeof(FiltersTestData))]\n [MemberData(nameof(SingleFilters), MemberType = typeof(FiltersTestData))]\n [MemberData(nameof(NamespaceFilters), MemberType = typeof(FiltersTestData))]\n internal void ApplyFilters(XUnitFilter filter, ITestCase testCase, bool excluded, string logMessage)\n {\n var logOutut = new StringBuilder();\n Action? log = (s) =>\n {\n logOutut.AppendLine(s);\n };\n var testExcluded = filter.IsExcluded(testCase, log);\n Assert.Equal(excluded, testExcluded);\n // validate with the log\n Assert.StartsWith(logMessage, logOutut.ToString().Trim());\n }", + "start_line": 462, + "end_line": 478, + "start_byte": 19006, + "end_byte": 19856 + } + ], + "tests/Microsoft.DotNet.XHarness.TestRunners.Tests/xUnit/XUnitFiltersCollectionTests.cs": [ + { + "name": "TestCaseFilters", + "code": "[Fact]\n public void TestCaseFilters()\n {\n var collection = new XUnitFiltersCollection();\n var assemblies = new[] { \"MyFirstAssembly.dll\", \"SecondAssembly.dll\", \"ThirdAssembly.exe\", };\n collection.AddRange(assemblies.Select(a => XUnitFilter.CreateAssemblyFilter(a, true)));\n\n var classes = new[] { \"FirstClass\", \"SecondClass\", \"ThirdClass\" };\n collection.AddRange(classes.Select(c => XUnitFilter.CreateClassFilter(c, true)));\n\n var methods = new[] { \"FirstMethod\", \"SecondMethod\" };\n collection.AddRange(methods.Select(m => XUnitFilter.CreateSingleFilter(m, true)));\n\n var namespaces = new[] { \"Namespace\" };\n collection.AddRange(namespaces.Select(n => XUnitFilter.CreateNamespaceFilter(n, true)));\n\n Assert.Equal(collection.Count - assemblies.Length, collection.TestCaseFilters.Count());\n }", + "start_line": 350, + "end_line": 367, + "start_byte": 14395, + "end_byte": 15264 + }, + { + "name": "AssemblyFilters", + "code": "[Fact]\n public void AssemblyFilters()\n {\n var collection = new XUnitFiltersCollection();\n\n var assemblies = new[] { \"MyFirstAssembly.dll\", \"SecondAssembly.dll\", \"ThirdAssembly.exe\", };\n collection.AddRange(assemblies.Select(a => XUnitFilter.CreateAssemblyFilter(a, true)));\n\n var classes = new[] { \"FirstClass\", \"SecondClass\", \"ThirdClass\" };\n collection.AddRange(classes.Select(c => XUnitFilter.CreateClassFilter(c, true)));\n\n var methods = new[] { \"FirstMethod\", \"SecondMethod\" };\n collection.AddRange(methods.Select(m => XUnitFilter.CreateSingleFilter(m, true)));\n\n var namespaces = new[] { \"Namespace\" };\n collection.AddRange(namespaces.Select(n => XUnitFilter.CreateNamespaceFilter(n, true)));\n\n Assert.Equal(assemblies.Length, collection.AssemblyFilters.Count());\n }", + "start_line": 330, + "end_line": 348, + "start_byte": 13538, + "end_byte": 14389 + }, + { + "name": "IsExcludedAsAssembly", + "code": "[Theory]\n [MemberData(nameof(AssemblyFilters), MemberType = typeof(FiltersTestData))]\n internal void IsExcludedAsAssembly(XUnitFiltersCollection collection, TestAssemblyInfo assemblyInfo, bool excluded)\n {\n var wasExcluded = collection.IsExcluded(assemblyInfo);\n Assert.Equal(excluded, wasExcluded);\n }", + "start_line": 321, + "end_line": 327, + "start_byte": 13174, + "end_byte": 13526 + }, + { + "name": "IsExcludedTestCase", + "code": "[Theory]\n [MemberData(nameof(TestCaseFilters), MemberType = typeof(FiltersTestData))]\n internal void IsExcludedTestCase(XUnitFiltersCollection collection, ITestCase testCase, bool excluded)\n {\n var wasExcluded = collection.IsExcluded(testCase);\n Assert.Equal(excluded, wasExcluded);\n }", + "start_line": 313, + "end_line": 319, + "start_byte": 12829, + "end_byte": 13164 + } + ], + "tests/Microsoft.DotNet.XHarness.TestRunners.Tests/NUnit/TestStatusExtensionsTests.cs": [ + { + "name": "IsExcludedAsAssembly", + "code": "[Theory]\n [MemberData(nameof(ToXmlResultValueTests), MemberType = typeof(TestStatusExtensionsTestData))]\n public void IsExcludedAsAssembly(TestStatus status, XmlResultJargon jargon, string expectedResult)\n => Assert.Equal(status.ToXmlResultValue(jargon), expectedResult);", + "start_line": 45, + "end_line": 48, + "start_byte": 2298, + "end_byte": 2594 + } + ], + "tests/Microsoft.DotNet.XHarness.TestRunners.Tests/NUnit/NUnit3XmlOutputWriterTests.cs": [ + { + "name": "Dispose", + "code": "public void Dispose()\n {\n File.Delete(_tempPath);\n GC.SuppressFinalize(this);\n }", + "start_line": 94, + "end_line": 98, + "start_byte": 3576, + "end_byte": 3676 + }, + { + "name": "SeveralTetRunTest", + "code": "[Fact]\n public void SeveralTetRunTest()\n {\n // same logic as with the other tests, but with more than one test run\n var firstTestRun = new Mock();\n firstTestRun.Setup(t => t.Result).Returns(GetTestRunSample());\n var secondTestRun = new Mock();\n secondTestRun.Setup(t => t.Result).Returns(GetTestRunSample());\n _resultSummary.Setup(rs => rs.GetEnumerator())\n .Returns(new List { firstTestRun.Object, secondTestRun.Object }.GetEnumerator());\n\n using (var writer = new StreamWriter(_tempPath))\n {\n var nunit3Writer = new NUnit3XmlOutputWriter(DateTime.Now);\n nunit3Writer.WriteResultFile(_resultSummary.Object, writer);\n }\n\n // read the file and make sure that is correct\n var doc = new XmlDocument();\n doc.Load(_tempPath);\n var runs = doc.SelectNodes(\".//test-run\");\n Assert.Equal(1, runs.Count);\n var enviroment = doc.SelectNodes(\".//environment\");\n Assert.Equal(1, enviroment.Count);\n }", + "start_line": 68, + "end_line": 92, + "start_byte": 2500, + "end_byte": 3570 + }, + { + "name": "SingleTestRunTest", + "code": "[Fact]\n public void SingleTestRunTest()\n {\n var testRun = new Mock();\n testRun.Setup(t => t.Result).Returns(GetTestRunSample());\n // set the expectations of the mock, the important thing, we want to return a single test-run node\n _resultSummary.Setup(rs => rs.GetEnumerator())\n .Returns(new List { testRun.Object }.GetEnumerator());\n\n using (var writer = new StreamWriter(_tempPath))\n {\n var nunit3Writer = new NUnit3XmlOutputWriter(DateTime.Now);\n nunit3Writer.WriteResultFile(_resultSummary.Object, writer);\n }\n\n // read the file and make sure that is correct\n var doc = new XmlDocument();\n doc.Load(_tempPath);\n // we just need to make sure we have a single test-run node and a single env node, the rest\n // was generated by nunit\n var runs = doc.SelectNodes(\".//test-run\");\n Assert.Equal(1, runs.Count);\n var enviroment = doc.SelectNodes(\".//environment\");\n Assert.Equal(1, enviroment.Count);\n }", + "start_line": 42, + "end_line": 66, + "start_byte": 1421, + "end_byte": 2494 + }, + { + "name": "GetTestRunSample", + "code": "private XmlNode GetTestRunSample()\n {\n var resourcenames = GetType().Assembly.GetManifestResourceNames();\n // load the test-run node from the sample file\n var name = GetType().Assembly\n .GetManifestResourceNames().FirstOrDefault(a => a.EndsWith(SampleFileName, StringComparison.Ordinal));\n var doc = new XmlDocument();\n using var sampleStream = new StreamReader(GetType().Assembly.GetManifestResourceStream(name));\n doc.Load(sampleStream);\n return doc.SelectNodes(\"test-run\")[0];\n }", + "start_line": 30, + "end_line": 40, + "start_byte": 867, + "end_byte": 1415 + } + ], + "tests/Microsoft.DotNet.XHarness.Common.Tests/Utilities/StringUtilsTests.cs": [ + { + "name": "FormatArgumentsTest", + "code": "[Fact(Skip = \"Only works on OSX/Linux\")]\n public void FormatArgumentsTest()\n {\n var p = new Process();\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.FileName = \"/bin/echo\";\n\n var complexInput = \"'\";\n\n p.StartInfo.Arguments = StringUtils.FormatArguments(\"-n\", \"foo\", complexInput, \"bar\");\n p.Start();\n var output = p.StandardOutput.ReadToEnd();\n Assert.Equal($\"foo {complexInput} bar\", output);\n }", + "start_line": 31, + "end_line": 45, + "start_byte": 1152, + "end_byte": 1669 + }, + { + "name": "QuoteForProcessTest", + "code": "[Theory]\n [InlineData(\"foo bar\", \"foo bar\")]\n [InlineData(\"foo \\\"bar\\\"\", \"foo \\\\\\\"bar\\\\\\\"\")]\n [InlineData(\"foo bar's\", \"foo bar\\\\\\'s\")]\n [InlineData(\"foo $bar's\", \"foo $bar\\\\\\'s\")]\n public void QuoteForProcessTest(string input, string expected) => Assert.Equal(s_shellQuoteChar + expected + s_shellQuoteChar, StringUtils.Quote(input));", + "start_line": 24, + "end_line": 29, + "start_byte": 796, + "end_byte": 1146 + }, + { + "name": "NoEscapingNeeded", + "code": "[Fact]\n public void NoEscapingNeeded() => Assert.Equal(\"foo\", StringUtils.Quote(\"foo\"));", + "start_line": 21, + "end_line": 22, + "start_byte": 699, + "end_byte": 790 + } + ], + "tests/Microsoft.DotNet.XHarness.Common.Tests/Execution/ProcessManagerTests.cs": [ + { + "name": "ProcessShouldBeKilled", + "code": "[Fact(Skip = \"ping is not available in AzDO so this is rather for local development\")]\n public async Task ProcessShouldBeKilled()\n {\n var pm = ProcessManagerFactory.CreateProcessManager();\n\n var process = new Process();\n process.StartInfo.FileName = \"ping\";\n process.StartInfo.Arguments = \"-t 127.0.0.1\";\n var log = new MemoryLog();\n\n var result = await pm.RunAsync(process, log, TimeSpan.FromSeconds(3));\n\n Assert.True(result.TimedOut);\n }", + "start_line": 16, + "end_line": 29, + "start_byte": 489, + "end_byte": 987 + } + ], + "tests/Microsoft.DotNet.XHarness.Common.Tests/Logging/ScanLogTest.cs": [ + { + "name": "TagIsFoundInSeveralMessages", + "code": "[Fact]\n public void TagIsFoundInSeveralMessages()\n {\n bool found = false;\n var log = new ScanLog(\"123\", () => found = true);\n log.Write(\"abc1\");\n log.Write(\"2\");\n log.Write(\"3cdef\");\n Assert.True(found);\n }", + "start_line": 25, + "end_line": 34, + "start_byte": 843, + "end_byte": 1100 + }, + { + "name": "TagIsFoundInLog", + "code": "[Theory]\n [InlineData(\"This is a log message\", \"log\", true)]\n [InlineData(\"emessag\", \"message\", false)]\n [InlineData(\"This is a log message\", \"This is a log message\", true)]\n [InlineData(\"This is a log message.\", \".\", true)]\n public void TagIsFoundInLog(string message, string tag, bool shouldFind)\n {\n bool found = false;\n var log = new ScanLog(tag, () => found = true);\n log.Write(message);\n Assert.Equal(shouldFind, found);\n }", + "start_line": 12, + "end_line": 23, + "start_byte": 359, + "end_byte": 837 + } + ], + "tests/Microsoft.DotNet.XHarness.Common.Tests/Logging/ConsoleLogTest.cs": [ + { + "name": "Dispose", + "code": "public void Dispose()\n {\n _log.Dispose();\n Console.SetOut(_sdoutWriter); // get back to write to the console\n File.Delete(_testFile);\n GC.SuppressFinalize(this);\n }", + "start_line": 47, + "end_line": 53, + "start_byte": 1584, + "end_byte": 1782 + }, + { + "name": "TestWrite", + "code": "[Fact(Skip = \"Flakey test that gets in the way by messing around with Console.Out\")]\n public void TestWrite()\n {\n var message = \"This is a log message\";\n using (var testStream = new FileStream(_testFile, FileMode.OpenOrCreate, FileAccess.Write))\n using (var writer = new StreamWriter(testStream))\n {\n Console.SetOut(writer);\n // simply test that we do write in the file. We need to close the stream to be able to read it\n _log.WriteLine(message);\n }\n\n using (var testStream = new FileStream(_testFile, FileMode.OpenOrCreate, FileAccess.Read))\n using (var reader = new StreamReader(testStream))\n {\n var line = reader.ReadLine();\n Assert.EndsWith(message, line); // consider the time stamp\n }\n\n }", + "start_line": 26, + "end_line": 45, + "start_byte": 757, + "end_byte": 1578 + } + ], + "tests/Microsoft.DotNet.XHarness.Common.Tests/Logging/CallbackLogTest.cs": [ + { + "name": "OnWriteTest", + "code": "[Fact]\n public void OnWriteTest()\n {\n var message = \"This is a log message\";\n bool called = false;\n string data = null;\n\n Action cb = (d) =>\n {\n called = true;\n data = d;\n };\n\n var log = new CallbackLog(cb);\n log.Write(message);\n Assert.True(called, \"Callback was not called\");\n Assert.NotNull(data);\n Assert.EndsWith(message, data); // TODO: take time stamp into account\n }", + "start_line": 13, + "end_line": 31, + "start_byte": 377, + "end_byte": 867 + } + ], + "eng/common/cross/install-debs.py": [ + { + "name": "finalize_setup", + "code": "def finalize_setup(rootfsdir):\n lib_dir = os.path.join(rootfsdir, 'lib')\n usr_lib_dir = os.path.join(rootfsdir, 'usr', 'lib')\n\n if os.path.exists(lib_dir):\n if os.path.islink(lib_dir):\n os.remove(lib_dir)\n else:\n os.makedirs(usr_lib_dir, exist_ok=True)\n\n for item in os.listdir(lib_dir):\n src = os.path.join(lib_dir, item)\n dest = os.path.join(usr_lib_dir, item)\n\n if os.path.isdir(src):\n shutil.copytree(src, dest, dirs_exist_ok=True)\n else:\n shutil.copy2(src, dest)\n\n shutil.rmtree(lib_dir)\n\n os.symlink(usr_lib_dir, lib_dir)", + "start_line": 273, + "end_line": 294, + "start_byte": 10473, + "end_byte": 11168 + }, + { + "name": "extract_deb_file", + "code": "def extract_deb_file(deb_file, tmp_dir, extract_dir, ar_tool):\n \"\"\"Extract .deb file contents\"\"\"\n\n os.makedirs(extract_dir, exist_ok=True)\n\n with tempfile.TemporaryDirectory(dir=tmp_dir) as tmp_subdir:\n result = subprocess.run(f\"{ar_tool} t {os.path.abspath(deb_file)}\", cwd=tmp_subdir, check=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n tar_filename = None\n for line in result.stdout.decode().splitlines():\n if line.startswith(\"data.tar\"):\n tar_filename = line.strip()\n break\n\n if not tar_filename:\n raise FileNotFoundError(f\"Could not find 'data.tar.*' in {deb_file}.\")\n\n tar_file_path = os.path.join(tmp_subdir, tar_filename)\n print(f\"Extracting {tar_filename} from {deb_file}..\")\n\n subprocess.run(f\"{ar_tool} p {os.path.abspath(deb_file)} {tar_filename} > {tar_file_path}\", check=True, shell=True)\n\n file_extension = os.path.splitext(tar_file_path)[1].lower()\n\n if file_extension == \".xz\":\n mode = \"r:xz\"\n elif file_extension == \".gz\":\n mode = \"r:gz\"\n elif file_extension == \".zst\":\n # zstd is not supported by standard library yet\n decompressed_tar_path = tar_file_path.replace(\".zst\", \"\")\n with open(tar_file_path, \"rb\") as zst_file, open(decompressed_tar_path, \"wb\") as decompressed_file:\n dctx = zstandard.ZstdDecompressor()\n dctx.copy_stream(zst_file, decompressed_file)\n\n tar_file_path = decompressed_tar_path\n mode = \"r\"\n else:\n raise ValueError(f\"Unsupported compression format: {file_extension}\")\n\n with tarfile.open(tar_file_path, mode) as tar:\n tar.extractall(path=extract_dir, filter='fully_trusted')", + "start_line": 230, + "end_line": 271, + "start_byte": 8651, + "end_byte": 10471 + }, + { + "name": "install_packages", + "code": "def install_packages(mirror, packages_info, aliases, tmp_dir, extract_dir, ar_tool, desired_packages):\n \"\"\"Downloads .deb files and extracts them.\"\"\"\n resolved_packages = resolve_dependencies(packages_info, aliases, desired_packages)\n print(f\"Resolved packages (including dependencies): {resolved_packages}\")\n\n packages_to_download = {}\n\n for pkg in resolved_packages:\n if pkg in packages_info:\n packages_to_download[pkg] = packages_info[pkg]\n\n if pkg in aliases:\n for alias in aliases[pkg]:\n if alias in packages_info:\n packages_to_download[alias] = packages_info[alias]\n\n asyncio.run(download_deb_files_parallel(mirror, packages_to_download, tmp_dir))\n\n package_to_deb_file_map = {}\n for pkg in resolved_packages:\n pkg_info = packages_info.get(pkg)\n if pkg_info:\n deb_filename = pkg_info.get(\"Filename\")\n if deb_filename:\n deb_file_path = os.path.join(tmp_dir, os.path.basename(deb_filename))\n package_to_deb_file_map[pkg] = deb_file_path\n\n for pkg in reversed(resolved_packages):\n deb_file = package_to_deb_file_map.get(pkg)\n if deb_file and os.path.exists(deb_file):\n extract_deb_file(deb_file, tmp_dir, extract_dir, ar_tool)\n\n print(\"All done!\")", + "start_line": 196, + "end_line": 228, + "start_byte": 7308, + "end_byte": 8649 + }, + { + "name": "parse_package_index", + "code": "def parse_package_index(content):\n \"\"\"Parses the Packages.gz file and returns package information.\"\"\"\n packages = {}\n aliases = {}\n entries = re.split(r'\\n\\n+', content)\n\n for entry in entries:\n fields = dict(re.findall(r'^(\\S+): (.+)$', entry, re.MULTILINE))\n if \"Package\" in fields:\n package_name = fields[\"Package\"]\n version = fields.get(\"Version\")\n filename = fields.get(\"Filename\")\n depends = fields.get(\"Depends\")\n provides = fields.get(\"Provides\", None)\n\n # Only update if package_name is not in packages or if the new version is higher\n if package_name not in packages or compare_debian_versions(version, packages[package_name][\"Version\"]) > 0:\n packages[package_name] = {\n \"Version\": version,\n \"Filename\": filename,\n \"Depends\": depends\n }\n\n # Update aliases if package provides any alternatives\n if provides:\n provides_list = [x.strip() for x in provides.split(\",\")]\n for alias in provides_list:\n # Strip version specifiers\n alias_name = re.sub(r'\\s*\\(=.*\\)', '', alias)\n if alias_name not in aliases:\n aliases[alias_name] = []\n if package_name not in aliases[alias_name]:\n aliases[alias_name].append(package_name)\n\n return packages, aliases", + "start_line": 160, + "end_line": 194, + "start_byte": 5746, + "end_byte": 7306 + }, + { + "name": "resolve_dependencies", + "code": "def resolve_dependencies(packages, aliases, desired_packages):\n \"\"\"Recursively resolves dependencies for the desired packages.\"\"\"\n resolved = []\n to_process = deque(desired_packages)\n\n while to_process:\n current = to_process.popleft()\n resolved_package = current if current in packages else aliases.get(current, [None])[0]\n\n if not resolved_package:\n print(f\"Error: Package '{current}' was not found in the available packages.\")\n sys.exit(1)\n\n if resolved_package not in resolved:\n resolved.append(resolved_package)\n\n deps = packages.get(resolved_package, {}).get(\"Depends\", \"\")\n if deps:\n deps = [dep.split(' ')[0] for dep in deps.split(', ') if dep]\n for dep in deps:\n if dep not in resolved and dep not in to_process and dep in packages:\n to_process.append(dep)\n\n return resolved", + "start_line": 135, + "end_line": 158, + "start_byte": 4792, + "end_byte": 5744 + }, + { + "name": "compare_debian_versions", + "code": "def compare_debian_versions(version1, version2):\n \"\"\"Compare two Debian package versions.\"\"\"\n epoch1, upstream1, revision1 = parse_debian_version(version1)\n epoch2, upstream2, revision2 = parse_debian_version(version2)\n\n if epoch1 != epoch2:\n return epoch1 - epoch2\n\n result = compare_upstream_version(upstream1, upstream2)\n if result != 0:\n return result\n\n return compare_upstream_version(revision1, revision2)", + "start_line": 121, + "end_line": 133, + "start_byte": 4344, + "end_byte": 4790 + }, + { + "name": "compare_upstream_version", + "code": "def compare_upstream_version(v1, v2):\n \"\"\"Compare upstream or revision parts using Debian rules.\"\"\"\n def tokenize(version):\n tokens = re.split(r'([0-9]+|[A-Za-z]+)', version)\n return [int(x) if x.isdigit() else x for x in tokens if x]\n\n tokens1 = tokenize(v1)\n tokens2 = tokenize(v2)\n\n for token1, token2 in zip(tokens1, tokens2):\n if type(token1) == type(token2):\n if token1 != token2:\n return (token1 > token2) - (token1 < token2)\n else:\n return -1 if isinstance(token1, str) else 1\n\n return len(tokens1) - len(tokens2)", + "start_line": 103, + "end_line": 119, + "start_byte": 3738, + "end_byte": 4342 + }, + { + "name": "tokenize", + "code": "def tokenize(version):\n tokens = re.split(r'([0-9]+|[A-Za-z]+)', version)\n return [int(x) if x.isdigit() else x for x in tokens if x]", + "start_line": 105, + "end_line": 107, + "start_byte": 3845, + "end_byte": 3992 + }, + { + "name": "parse_debian_version", + "code": "def parse_debian_version(version):\n \"\"\"Parse a Debian package version into epoch, upstream version, and revision.\"\"\"\n match = re.match(r'^(?:(\\d+):)?([^-]+)(?:-(.+))?$', version)\n if not match:\n raise ValueError(f\"Invalid Debian version format: {version}\")\n epoch, upstream, revision = match.groups()\n return int(epoch) if epoch else 0, upstream, revision or \"\"", + "start_line": 95, + "end_line": 101, + "start_byte": 3353, + "end_byte": 3736 + }, + { + "name": "fetch_and_decompress", + "code": "async def fetch_and_decompress(session, url):\n \"\"\"Fetch and decompress the Packages.gz file.\"\"\"\n try:\n async with session.get(url) as response:\n if response.status == 200:\n compressed_data = await response.read()\n decompressed_data = gzip.decompress(compressed_data).decode('utf-8')\n print(f\"Downloaded index: {url}\")\n return decompressed_data\n else:\n print(f\"Skipped index: {url} (doesn't exist)\")\n return None\n except Exception as e:\n print(f\"Error fetching {url}: {e}\")", + "start_line": 80, + "end_line": 93, + "start_byte": 2744, + "end_byte": 3351 + }, + { + "name": "download_package_index_parallel", + "code": "async def download_package_index_parallel(mirror, arch, suites):\n \"\"\"Download package index files for specified suites and components entirely in memory.\"\"\"\n tasks = []\n timeout = aiohttp.ClientTimeout(total=60)\n\n async with aiohttp.ClientSession(timeout=timeout) as session:\n for suite in suites:\n for component in [\"main\", \"universe\"]:\n url = f\"{mirror}/dists/{suite}/{component}/binary-{arch}/Packages.gz\"\n tasks.append(fetch_and_decompress(session, url))\n\n results = await asyncio.gather(*tasks, return_exceptions=True)\n\n merged_content = \"\"\n for result in results:\n if isinstance(result, str):\n if merged_content:\n merged_content += \"\\n\\n\"\n merged_content += result\n\n return merged_content", + "start_line": 58, + "end_line": 78, + "start_byte": 1928, + "end_byte": 2742 + }, + { + "name": "download_deb_files_parallel", + "code": "async def download_deb_files_parallel(mirror, packages, tmp_dir):\n \"\"\"Download .deb files in parallel.\"\"\"\n os.makedirs(tmp_dir, exist_ok=True)\n\n tasks = []\n timeout = aiohttp.ClientTimeout(total=60)\n async with aiohttp.ClientSession(timeout=timeout) as session:\n for pkg, info in packages.items():\n filename = info.get(\"Filename\")\n if filename:\n url = f\"{mirror}/{filename}\"\n dest_path = os.path.join(tmp_dir, os.path.basename(filename))\n tasks.append(asyncio.create_task(download_file(session, url, dest_path)))\n\n await asyncio.gather(*tasks)", + "start_line": 42, + "end_line": 56, + "start_byte": 1287, + "end_byte": 1926 + }, + { + "name": "download_file", + "code": "async def download_file(session, url, dest_path, max_retries=3, retry_delay=2, timeout=60):\n \"\"\"Asynchronous file download with retries.\"\"\"\n attempt = 0\n while attempt < max_retries:\n try:\n async with session.get(url, timeout=aiohttp.ClientTimeout(total=timeout)) as response:\n if response.status == 200:\n with open(dest_path, \"wb\") as f:\n content = await response.read()\n f.write(content)\n print(f\"Downloaded {url} at {dest_path}\")\n return\n else:\n print(f\"Failed to download {url}, Status Code: {response.status}\")\n break\n except (asyncio.CancelledError, asyncio.TimeoutError, aiohttp.ClientError) as e:\n print(f\"Error downloading {url}: {type(e).__name__} - {e}. Retrying...\")\n\n attempt += 1\n await asyncio.sleep(retry_delay)\n\n print(f\"Failed to download {url} after {max_retries} attempts.\")", + "start_line": 19, + "end_line": 40, + "start_byte": 258, + "end_byte": 1285 + } + ] +} \ No newline at end of file