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
5 changes: 5 additions & 0 deletions docs/Changelog-Platform.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ See full log [of v4.3.3...v4.4.0](https://github.com/microsoft/testfx/compare/v4
* Add `--report-azdo-groups <on|off>` and `--report-azdo-annotations <on|off>` toggles to Azure DevOps report extension by @Evangelink in [#9542](https://github.com/microsoft/testfx/pull/9542)
* Re-print errored assemblies in dotnet test end-of-run recap by @Evangelink in [#9545](https://github.com/microsoft/testfx/pull/9545)
* Add server-initiated session cancellation to the dotnet test IPC protocol by @Evangelink in [#9549](https://github.com/microsoft/testfx/pull/9549)
* Report the Azure DevOps test run URL when `--publish-azdo-test-results` creates the run, so results can be followed while the tests are still running, and clarify that the build's Tests tab only lists the run once it completes in [#10191](https://github.com/microsoft/testfx/issues/10191)

### Changed

* Send `pipelineReference` (stage, phase and job, with their attempt numbers) and `startedDate` when `--publish-azdo-test-results` creates an Azure DevOps test run, so the run is attributed to the stage and job that produced it in multi-stage pipelines instead of only to the build

### Fixed

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,33 @@ internal sealed record AzureDevOpsPublishConfiguration(
int BuildId,
string RunName,
string AutomatedTestStorage,
string ResultsDirectory);
string ResultsDirectory)
{
/// <summary>
/// Gets the stage/phase/job the test run belongs to, when running in a pipeline that exposes it.
/// </summary>
/// <remarks>
/// Declared as a property rather than a positional parameter so that adding it does not change the
/// record's constructor and deconstructor signatures.
/// </remarks>
public AzureDevOpsPipelineReference? PipelineReference { get; init; }
}

/// <summary>
/// Identifies the pipeline stage, phase and job that produced a test run.
/// </summary>
/// <remarks>
/// Azure DevOps uses this to attribute the run to the right stage/job of a multi-stage pipeline. Without
/// it, the run is only linked to the build as a whole, so per-stage test reporting is unavailable.
/// Every part is optional because the corresponding pipeline variables are not always defined.
/// </remarks>
internal sealed record AzureDevOpsPipelineReference(
string? StageName,
int? StageAttempt,
string? PhaseName,
int? PhaseAttempt,
string? JobName,
int? JobAttempt);

internal sealed record AzureDevOpsTestCaseResult(
[property: JsonPropertyName("automatedTestName")] string AutomatedTestName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,33 @@ public async Task<int> CreateTestRunAsync(AzureDevOpsPublishConfiguration config
HttpMethod.Post,
BuildRunsUri(configuration.CollectionUri, configuration.Project),
configuration.AccessToken,
new CreateTestRunRequest(configuration.RunName, true, new BuildReference(configuration.BuildId), AzureDevOpsLivePublishingConstants.InProgressTestRunState));
new CreateTestRunRequest(
configuration.RunName,
true,
new BuildReference(configuration.BuildId),
AzureDevOpsLivePublishingConstants.InProgressTestRunState,
_clock.UtcNow,
BuildPipelineReference(configuration)));

CreateTestRunResponse response = await SendAsync<CreateTestRunResponse>(request, cancellationToken).ConfigureAwait(false);
return response.Id > 0
? response.Id
: throw new InvalidOperationException(AzureDevOpsResources.AzureDevOpsLivePublishingInvalidResponse);
}

/// <remarks>
/// Azure DevOps requires <c>pipelineReference.pipelineId</c> to match <c>build.id</c>; without the
/// stage/phase/job references the run cannot be attributed to a stage of a multi-stage pipeline.
/// </remarks>
private static PipelineReference? BuildPipelineReference(AzureDevOpsPublishConfiguration configuration)
=> configuration.PipelineReference is not { } pipelineReference
? null
: new PipelineReference(
configuration.BuildId,
pipelineReference.StageName is null ? null : new StageReference(pipelineReference.StageName, pipelineReference.StageAttempt),
pipelineReference.PhaseName is null ? null : new PhaseReference(pipelineReference.PhaseName, pipelineReference.PhaseAttempt),
pipelineReference.JobName is null ? null : new JobReference(pipelineReference.JobName, pipelineReference.JobAttempt));

[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "Response types are internal, fixed, and controlled by this extension.")]
[UnconditionalSuppressMessage("Aot", "IL3050", Justification = "Response types are internal, fixed, and controlled by this extension.")]
public async Task<IReadOnlyList<int>?> PublishTestResultsAsync(AzureDevOpsPublishConfiguration configuration, int runId, IReadOnlyList<AzureDevOpsTestCaseResult> results, CancellationToken cancellationToken)
Expand Down Expand Up @@ -415,10 +434,30 @@ private sealed record CreateTestRunRequest(
[property: JsonPropertyName("name")] string Name,
[property: JsonPropertyName("automated")] bool Automated,
[property: JsonPropertyName("build")] BuildReference Build,
[property: JsonPropertyName("state")] string State);
[property: JsonPropertyName("state")] string State,
[property: JsonPropertyName("startedDate")] DateTimeOffset StartedDate,
[property: JsonPropertyName("pipelineReference")] PipelineReference? PipelineReference);

private sealed record BuildReference([property: JsonPropertyName("id")] int Id);

private sealed record PipelineReference(
[property: JsonPropertyName("pipelineId")] int PipelineId,
[property: JsonPropertyName("stageReference")] StageReference? StageReference,
[property: JsonPropertyName("phaseReference")] PhaseReference? PhaseReference,
[property: JsonPropertyName("jobReference")] JobReference? JobReference);

private sealed record StageReference(
[property: JsonPropertyName("stageName")] string StageName,
[property: JsonPropertyName("attempt")] int? Attempt);

private sealed record PhaseReference(
[property: JsonPropertyName("phaseName")] string PhaseName,
[property: JsonPropertyName("attempt")] int? Attempt);

private sealed record JobReference(
[property: JsonPropertyName("jobName")] string JobName,
[property: JsonPropertyName("attempt")] int? Attempt);

private sealed record CreateTestRunResponse([property: JsonPropertyName("id")] int Id);

private sealed record UpdateTestRunStateRequest([property: JsonPropertyName("state")] string State);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,41 @@ private bool TryCreatePublishConfiguration([NotNullWhen(true)] out AzureDevOpsPu
runName = configuredRunName;
}

publishConfiguration = new AzureDevOpsPublishConfiguration(collectionUri!, project!, accessToken!, buildId, runName, automatedTestStorage, resultsDirectory);
publishConfiguration = new AzureDevOpsPublishConfiguration(collectionUri!, project!, accessToken!, buildId, runName, automatedTestStorage, resultsDirectory)
{
PipelineReference = CreatePipelineReference(stageName, jobName),
};
return true;
}

private AzureDevOpsPipelineReference? CreatePipelineReference(string? stageName, string? jobName)
{
string? phaseName = _environment.GetEnvironmentVariable("SYSTEM_PHASENAME");
int? stageAttempt = GetOptionalEnvironmentVariableAsInt32("SYSTEM_STAGEATTEMPT");
int? phaseAttempt = GetOptionalEnvironmentVariableAsInt32("SYSTEM_PHASEATTEMPT");
int? jobAttempt = GetOptionalEnvironmentVariableAsInt32("SYSTEM_JOBATTEMPT");

// Azure DevOps rejects a reference that names nothing, and a run without any stage/job context is
// better linked to the build alone than to an empty reference.
return RoslynString.IsNullOrWhiteSpace(stageName) && RoslynString.IsNullOrWhiteSpace(phaseName) && RoslynString.IsNullOrWhiteSpace(jobName)
? null
: new AzureDevOpsPipelineReference(
NullIfWhiteSpace(stageName),
stageAttempt,
NullIfWhiteSpace(phaseName),
phaseAttempt,
NullIfWhiteSpace(jobName),
jobAttempt);
}

private int? GetOptionalEnvironmentVariableAsInt32(string variableName)
=> int.TryParse(_environment.GetEnvironmentVariable(variableName), NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)
? value
: null;

private static string? NullIfWhiteSpace(string? value)
=> RoslynString.IsNullOrWhiteSpace(value) ? null : value;

private string? GetRequiredEnvironmentVariable(string variableName, List<string> missingVariables)
{
string? value = _environment.GetEnvironmentVariable(variableName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,22 @@ public async Task OnTestSessionStartingAsync(ITestSessionContext testSessionCont
testSessionContext.CancellationToken).ConfigureAwait(false);
CurrentRunId = _coordinatedRun.RunId;

// Results stream into the run as tests complete, but the build's Tests tab only lists the run
// once it is finalized. Point users at the run itself so they can watch results arrive live,
// and say when the Tests tab catches up so an empty tab mid-run is not mistaken for a failure.
// Only the process that created the run reports it: every other process shares the same run id
// and would just repeat the same line.
if (_coordinatedRun.IsOwner)
{
await DisplayAsync(
string.Format(
CultureInfo.InvariantCulture,
AzureDevOpsResources.AzureDevOpsLivePublishingRunCreated,
CurrentRunId.Value,
BuildTestRunUrl(publishConfiguration, CurrentRunId.Value)),
testSessionContext.CancellationToken).ConfigureAwait(false);
}

// Start a background loop that flushes pending results on the time-based interval even
// when no new TestNodeUpdateMessages arrive (e.g. at the tail end of a slow test run).
_backgroundFlushCts = new CancellationTokenSource();
Expand Down Expand Up @@ -177,19 +193,37 @@ public async Task OnTestSessionStartingAsync(ITestSessionContext testSessionCont
private async Task WarnAsync(string message, CancellationToken cancellationToken)
{
TryLogWarning(message);
await DisplayCoreAsync(new WarningMessageOutputDeviceData(message), cancellationToken).ConfigureAwait(false);
}

/// <summary>
/// Reports informational live-publishing progress on the output device.
/// </summary>
/// <remarks>
/// Sent as a <see cref="SessionMessageOutputDeviceData"/> rather than plain text because the
/// <c>dotnet test</c> pipe deliberately discards informational text, and <c>dotnet test</c> is the
/// usual way this extension runs in a pipeline. Never throws, for the same reason as <see cref="WarnAsync"/>.
/// </remarks>
private Task DisplayAsync(string message, CancellationToken cancellationToken)
=> DisplayCoreAsync(new SessionMessageOutputDeviceData(message), cancellationToken);

private async Task DisplayCoreAsync(IOutputDeviceData data, CancellationToken cancellationToken)
{
try
{
await _outputDevice.DisplayAsync(this, new WarningMessageOutputDeviceData(message), cancellationToken).ConfigureAwait(false);
await _outputDevice.DisplayAsync(this, data, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
// The message is already in the diagnostic log; losing the console copy is preferable to
// failing the test run from inside a diagnostic helper.
// The message is already in the diagnostic log (for warnings); losing the console copy is
// preferable to failing the test run from inside a diagnostic helper.
TryLogWarning($"{AzureDevOpsResources.AzureDevOpsLivePublishingWarningDisplayFailed} {ex.Message}");
}
}

private static string BuildTestRunUrl(AzureDevOpsPublishConfiguration configuration, int runId)
=> $"{configuration.CollectionUri.TrimEnd('/')}/{Uri.EscapeDataString(configuration.Project)}/_TestManagement/Runs?runId={runId}&_a=resultQuery";

/// <summary>
/// Logs a warning, swallowing any failure from the logging providers.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,27 @@ Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestResultsPublisher.A
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestResultsPublisher.AzureDevOpsTestResultsPublisher(Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions, Microsoft.Testing.Platform.Configurations.IConfiguration! configuration, Microsoft.Testing.Platform.Helpers.IEnvironment! environment, Microsoft.Testing.Platform.Helpers.IFileSystem! fileSystem, Microsoft.Testing.Platform.OutputDevice.IOutputDevice! outputDevice, Microsoft.Testing.Platform.Services.ITestApplicationModuleInfo! testApplicationModuleInfo, Microsoft.Testing.Platform.Services.ITestApplicationProcessExitCode! testApplicationProcessExitCode, Microsoft.Testing.Extensions.AzureDevOpsReport.IAzureDevOpsTestResultsClient! client, Microsoft.Testing.Platform.Helpers.ITask! task, Microsoft.Testing.Platform.Helpers.IClock! clock, Microsoft.Testing.Platform.Logging.ILoggerFactory! loggerFactory) -> void
*REMOVED*Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestResultsPublisher.AzureDevOpsTestResultsPublisher(Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions, Microsoft.Testing.Platform.Configurations.IConfiguration! configuration, Microsoft.Testing.Platform.Helpers.IEnvironment! environment, Microsoft.Testing.Platform.Helpers.IFileSystem! fileSystem, Microsoft.Testing.Platform.Services.ITestApplicationModuleInfo! testApplicationModuleInfo, Microsoft.Testing.Platform.Services.ITestApplicationProcessExitCode! testApplicationProcessExitCode, Microsoft.Testing.Extensions.AzureDevOpsReport.IAzureDevOpsTestResultsClient! client, Microsoft.Testing.Platform.Helpers.ITask! task, Microsoft.Testing.Platform.Helpers.IClock! clock, Microsoft.Testing.Platform.Logging.ILogger! logger, Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestResultsPublisherOptions! options) -> void
*REMOVED*Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestResultsPublisher.AzureDevOpsTestResultsPublisher(Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions, Microsoft.Testing.Platform.Configurations.IConfiguration! configuration, Microsoft.Testing.Platform.Helpers.IEnvironment! environment, Microsoft.Testing.Platform.Helpers.IFileSystem! fileSystem, Microsoft.Testing.Platform.Services.ITestApplicationModuleInfo! testApplicationModuleInfo, Microsoft.Testing.Platform.Services.ITestApplicationProcessExitCode! testApplicationProcessExitCode, Microsoft.Testing.Extensions.AzureDevOpsReport.IAzureDevOpsTestResultsClient! client, Microsoft.Testing.Platform.Helpers.ITask! task, Microsoft.Testing.Platform.Helpers.IClock! clock, Microsoft.Testing.Platform.Logging.ILoggerFactory! loggerFactory) -> void
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.<Clone>$() -> Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference!
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.AzureDevOpsPipelineReference(string? StageName, int? StageAttempt, string? PhaseName, int? PhaseAttempt, string? JobName, int? JobAttempt) -> void
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.Deconstruct(out string? StageName, out int? StageAttempt, out string? PhaseName, out int? PhaseAttempt, out string? JobName, out int? JobAttempt) -> void
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.Equals(Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference? other) -> bool
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.JobAttempt.get -> int?
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.JobAttempt.init -> void
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.JobName.get -> string?
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.JobName.init -> void
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.PhaseAttempt.get -> int?
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.PhaseAttempt.init -> void
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.PhaseName.get -> string?
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.PhaseName.init -> void
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.StageAttempt.get -> int?
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.StageAttempt.init -> void
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.StageName.get -> string?
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.StageName.init -> void
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPublishConfiguration.PipelineReference.get -> Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference?
Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPublishConfiguration.PipelineReference.init -> void
override Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.Equals(object? obj) -> bool
override Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.GetHashCode() -> int
override Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.ToString() -> string!
static Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.operator !=(Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference? left, Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference? right) -> bool
static Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference.operator ==(Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference? left, Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsPipelineReference? right) -> bool
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,10 @@
<data name="AzureDevOpsLivePublishingRunAttachmentFailed" xml:space="preserve">
<value>Azure DevOps live publishing failed to upload a test run attachment.</value>
</data>
<data name="AzureDevOpsLivePublishingRunCreated" xml:space="preserve">
<value>Azure DevOps live publishing is streaming results to test run {0}, which you can follow while the tests are still running at {1}. The build's Tests tab lists the run once it completes.</value>
<comment>{0} is the Azure DevOps test run id. {1} is the URL of the test run.</comment>
</data>
<data name="AzureDevOpsLivePublishingRunIdFileMismatch" xml:space="preserve">
<value>Azure DevOps live publishing found an azdo-runid.&lt;buildId&gt;.json file for a different Azure DevOps project.</value>
<comment>{Locked="azdo-runid.&lt;buildId&gt;.json"}</comment>
Expand Down Expand Up @@ -322,7 +326,7 @@
<comment>{Locked="--publish-azdo-run-name"}{Locked="--publish-azdo-test-results"}</comment>
</data>
<data name="PublishAzdoTestResultsOptionDescription" xml:space="preserve">
<value>Publish test results live to the Azure DevOps Tests tab.</value>
<value>Publish test results to an Azure DevOps test run as tests complete. The run is listed in the build's Tests tab once the test session finishes.</value>
</data>
<data name="QuarantinedAnnotation" xml:space="preserve">
<value>[quarantined]</value>
Expand Down
Loading