Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/docs/execution/ci-cd-reporting.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,14 @@ test:

The `trx2junit` tool converts TRX output to JUnit XML that GitLab can parse.

### Source Locations in JUnit XML

Each `<testcase>` in TUnit's JUnit report has `file` and `line` attributes that point to the test's source, so tools that read JUnit XML can show a failure at its source line. The XML format comes from the test reports of [JUnit](https://docs.junit.org/6.1.3/overview.html), the Java test framework.

```xml
<testcase name="Add_ReturnsSum" classname="Calculator.Tests.MathTests" time="0.012" file="tests/Calculator.Tests/MathTests.cs" line="12" />
```

## Unobserved Task Exceptions

A task that faults when nothing awaits it, such as a fire-and-forget `Task.Run` or the losing branch of a `Task.WhenAny`, raises `TaskScheduler.UnobservedTaskException` when the runtime garbage-collects it. TUnit keeps the process alive and records each of these exceptions for the session:
Expand Down
3 changes: 2 additions & 1 deletion src/TUnit.Engine/Reporters/JUnitReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ public async Task AfterRunAsync(int exitCode, CancellationToken cancellation)
}

// Generate JUnit XML
var xmlContent = JUnitXmlWriter.GenerateXml(lastUpdates, Filter, _unobservedTaskExceptions.ToArray());
var xmlContent = JUnitXmlWriter.GenerateXml(lastUpdates, Filter, _unobservedTaskExceptions.ToArray(),
SourceControlContext.Detect(Environment.GetEnvironmentVariable));

if (string.IsNullOrEmpty(xmlContent))
{
Expand Down
31 changes: 24 additions & 7 deletions src/TUnit.Engine/Xml/JUnitXmlWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Xml;
using Microsoft.Testing.Platform.Extensions.Messages;
using TUnit.Engine.Exceptions;
using TUnit.Engine.Reporters;

namespace TUnit.Engine.Xml;

Expand Down Expand Up @@ -62,7 +63,8 @@ private static string SanitizeForXmlSlow(string value)
public static string GenerateXml(
IEnumerable<TestNodeUpdateMessage> testUpdates,
string? filter,
IReadOnlyList<Exception>? unobservedTaskExceptions = null)
IReadOnlyList<Exception>? unobservedTaskExceptions = null,
SourceControlContext? sourceControl = null)
{
// Get the last state for each test
var lastStates = GetLastStates(testUpdates);
Expand Down Expand Up @@ -108,7 +110,7 @@ public static string GenerateXml(
xmlWriter.WriteAttributeString("timestamp", summary.Timestamp.ToString("o", CultureInfo.InvariantCulture));

// Write test suite
WriteTestSuite(xmlWriter, lastStates.Values, assemblyName, targetFramework, summary, filter, unobservedTaskExceptions);
WriteTestSuite(xmlWriter, lastStates.Values, assemblyName, targetFramework, summary, filter, unobservedTaskExceptions, sourceControl ?? SourceControlContext.Empty);

xmlWriter.WriteEndElement(); // testsuites
xmlWriter.WriteEndDocument();
Expand All @@ -123,7 +125,8 @@ private static void WriteTestSuite(
string targetFramework,
TestSummary summary,
string? filter,
IReadOnlyList<Exception>? unobservedTaskExceptions)
IReadOnlyList<Exception>? unobservedTaskExceptions,
SourceControlContext sourceControl)
{
writer.WriteStartElement("testsuite");
writer.WriteAttributeString("name", SanitizeForXml(assemblyName));
Expand All @@ -141,7 +144,7 @@ private static void WriteTestSuite(
// Write test cases
foreach (var test in tests)
{
WriteTestCase(writer, test);
WriteTestCase(writer, test, sourceControl);
}

// Unobserved task exceptions belong to no single test, so they go in the suite-level
Expand Down Expand Up @@ -190,14 +193,15 @@ private static void WriteProperties(XmlWriter writer, string targetFramework, st
writer.WriteEndElement(); // properties
}

private static void WriteTestCase(XmlWriter writer, TestNodeUpdateMessage test)
private static void WriteTestCase(XmlWriter writer, TestNodeUpdateMessage test, SourceControlContext sourceControl)
{
var testNode = test.TestNode;

// Get state, timing, and method identifier in a single pass
// Get state, timing, method identifier, and file location in a single pass
TestNodeStateProperty? stateProperty = null;
TimingProperty? timingProperty = null;
TestMethodIdentifierProperty? testMethodIdentifier = null;
TestFileLocationProperty? fileLocation = null;
foreach (var prop in testNode.Properties.AsEnumerable())
{
if (stateProperty is null && prop is TestNodeStateProperty s)
Expand All @@ -212,8 +216,12 @@ private static void WriteTestCase(XmlWriter writer, TestNodeUpdateMessage test)
{
testMethodIdentifier = m;
}
else if (fileLocation is null && prop is TestFileLocationProperty f)
{
fileLocation = f;
}

if (stateProperty is not null && timingProperty is not null && testMethodIdentifier is not null)
if (stateProperty is not null && timingProperty is not null && testMethodIdentifier is not null && fileLocation is not null)
{
break;
}
Expand All @@ -230,6 +238,15 @@ private static void WriteTestCase(XmlWriter writer, TestNodeUpdateMessage test)
writer.WriteAttributeString("classname", SanitizeForXml(className));
writer.WriteAttributeString("time", duration.TotalSeconds.ToString("F3", CultureInfo.InvariantCulture));

// Line numbers are 1-based; a test with no known source location has line 0 and gets neither attribute.
if (fileLocation is { LineSpan.Start.Line: > 0 } && !string.IsNullOrEmpty(fileLocation.FilePath))
{
var filePath = SourcePathResolver.ToRepoRelativePath(fileLocation.FilePath, sourceControl.Workspace, sourceControl.RepositorySlug)
Comment thread
thomhurst marked this conversation as resolved.
Resolved
?? fileLocation.FilePath;
writer.WriteAttributeString("file", SanitizeForXml(filePath));
writer.WriteAttributeString("line", fileLocation.LineSpan.Start.Line.ToString(CultureInfo.InvariantCulture));
}

// Write state-specific child elements
switch (stateProperty)
{
Expand Down
42 changes: 40 additions & 2 deletions tests/TUnit.UnitTests/JUnitXmlWriterTests.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
using System.Xml.Linq;
using Microsoft.Testing.Platform.Extensions.Messages;
using Microsoft.Testing.Platform.TestHost;
using TUnit.Engine.Reporters;
using TUnit.Engine.Xml;

namespace TUnit.UnitTests;

public class JUnitXmlWriterTests
{
private static TestNodeUpdateMessage PassedTest() => new(
private static TestNodeUpdateMessage PassedTest(params IProperty[] properties) => new(
new SessionUid("session"),
new TestNode
{
Uid = new TestNodeUid("test-1"),
DisplayName = "Adds",
Properties = new PropertyBag(PassedTestNodeStateProperty.CachedInstance),
Properties = new PropertyBag([PassedTestNodeStateProperty.CachedInstance, .. properties]),
});

private static TestFileLocationProperty Location(string filePath, int line) =>
new(filePath, new LinePositionSpan(new LinePosition(line, 5), new LinePosition(line + 4, 6)));

private static XElement SingleTestCase(string xml) => XDocument.Parse(xml).Descendants("testcase").Single();

[Test]
public async Task Writes_UnobservedTaskExceptions_To_Suite_SystemErr()
{
Expand All @@ -33,4 +40,35 @@ public async Task Omits_Suite_SystemErr_Without_UnobservedTaskExceptions()

await Assert.That(xml).DoesNotContain("system-err");
}

[Test]
[Arguments(@"C:\src\shop\tests\MathTests.cs", null, null, @"C:\src\shop\tests\MathTests.cs")]
[Arguments("/home/runner/work/shop/shop/tests/MathTests.cs", "/home/runner/work/shop/shop", "octo/shop", "tests/MathTests.cs")]
[Arguments(@"D:\a\shop\shop\tests\MathTests.cs", @"D:\a\shop\shop", "octo/shop", "tests/MathTests.cs")]
[Arguments("/_/tests/MathTests.cs", "/builds/octo/shop", "octo/shop", "tests/MathTests.cs")]
public async Task Writes_TestCase_File_And_Line_From_Test_Location(string filePath, string? workspace, string? repo, string expectedFile)
{
var sourceControl = new SourceControlContext(null, null, null, repo, workspace, null);

var xml = JUnitXmlWriter.GenerateXml([PassedTest(Location(filePath, 12))], filter: null, sourceControl: sourceControl);

var testCase = SingleTestCase(xml);
await Assert.That(testCase.Attribute("file")?.Value).IsEqualTo(expectedFile);
await Assert.That(testCase.Attribute("line")?.Value).IsEqualTo("12");
}

[Test]
[Arguments(null, 0)]
[Arguments("Unknown", 0)]
[Arguments("", 7)]
public async Task Omits_TestCase_File_And_Line_Without_Known_Location(string? filePath, int line)
{
var test = filePath is null ? PassedTest() : PassedTest(Location(filePath, line));

var xml = JUnitXmlWriter.GenerateXml([test], filter: null);

var testCase = SingleTestCase(xml);
await Assert.That(testCase.Attribute("file")).IsNull();
await Assert.That(testCase.Attribute("line")).IsNull();
}
}
Loading