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
6 changes: 6 additions & 0 deletions src/Platform/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@
<PropertyGroup>
<!-- Platform and extensions use TestingPlatform version, not MSTest version. -->
<VersionPrefix>$(TestingPlatformVersionPrefix)</VersionPrefix>

<!-- Exclusive upper bound used as a safety net on the in-repo Microsoft.Testing.Platform package
dependency of the extensions (see Directory.Build.targets): the next major after the current
Testing Platform version. For a 2.x platform this evaluates to 3.0.0, producing a [self, 3.0.0)
dependency range so an extension built against 2.x never silently resolves a breaking next major. -->
<TestingPlatformNextMajorVersion Condition=" '$(TestingPlatformNextMajorVersion)' == '' ">$([MSBuild]::Add($(TestingPlatformVersionPrefix.Split('.')[0]), 1)).0.0</TestingPlatformNextMajorVersion>
</PropertyGroup>

<!-- Build config -->
Expand Down
29 changes: 29 additions & 0 deletions src/Platform/Directory.Build.targets
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<Project>

<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.targets', '$(MSBuildThisFileDirectory)../'))" />

<!--
Add a [self, nextMajor) upper bound on the in-repo Microsoft.Testing.Platform package dependency that
the extensions emit through their ProjectReference to Microsoft.Testing.Platform.csproj.

By default NuGet packs a project reference as an open-ended minimum-version dependency (e.g.
"2.4.0" == "[2.4.0, )"). That lets an extension built against Testing Platform 2.x silently resolve a
future breaking 3.0.0. Because the extensions and the platform are versioned and ship in lockstep, we
cap the dependency at the next major as a safety net: "[2.4.0, 3.0.0)".

This runs after NuGet's _GetProjectReferenceVersions, which populates @(_ProjectReferencesWithVersions)
(identity = referenced project's full path, so %(Filename) is the project name) with the resolved
%(ProjectVersion). We only rewrite the Microsoft.Testing.Platform entry, and only when it is still a
bare version (not already a range), so the change is idempotent.
-->
<Target Name="_AddTestingPlatformDependencyUpperBound"
Comment thread
Evangelink marked this conversation as resolved.
Resolved
AfterTargets="_GetProjectReferenceVersions"
Condition=" '$(TestingPlatformNextMajorVersion)' != '' ">
<ItemGroup>
<_ProjectReferencesWithVersions Condition=" '%(Filename)' == 'Microsoft.Testing.Platform' and !$([System.String]::new('%(ProjectVersion)').StartsWith('[')) ">
<ProjectVersion>[%(ProjectVersion), $(TestingPlatformNextMajorVersion))</ProjectVersion>
</_ProjectReferencesWithVersions>
</ItemGroup>
</Target>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.IO.Compression;

namespace Microsoft.Testing.Platform.Acceptance.IntegrationTests;

/// <summary>
/// Guards the pack-time target in <c>src/Platform/Directory.Build.targets</c> that caps the packed
/// <c>Microsoft.Testing.Platform</c> package dependency of the in-repo extensions at a <c>[self, nextMajor)</c>
/// range. That target hooks NuGet-internal targets (<c>_GetProjectReferenceVersions</c> /
/// <c>_ProjectReferencesWithVersions</c>); if a future NuGet SDK renames them, the target would silently stop
/// firing and the dependency would revert to an open-ended minimum-version (<c>2.4.0</c> == <c>[2.4.0, )</c>).
/// These tests inspect the actually-produced <c>.nupkg</c> files so such a regression fails the build.
/// </summary>
[TestClass]
public sealed class PackageDependencyUpperBoundTests
{
private const string PlatformPackageId = "Microsoft.Testing.Platform";

// The exclusive upper bound the pack-time target applies is the next major after the current Testing
// Platform version. Read the source of truth (eng/Versions.props) rather than a packed version so the test
// stays independent of which packages happen to be present.
private static readonly string ExpectedUpperBound = $"{GetTestingPlatformMajorVersion() + 1}.0.0";

public TestContext TestContext { get; set; } = null!;

/// <summary>
/// Every package that declares a direct <c>Microsoft.Testing.Platform</c> dependency must express it as a
/// closed <c>[min, max)</c> range whose upper bound is the next major, never an open-ended minimum version.
/// At least one such package is expected, so an empty artifacts folder (or a target that silently dropped
/// all dependencies) fails rather than vacuously passing.
/// </summary>
[TestMethod]
public void PackedExtensions_CapMicrosoftTestingPlatformDependency_AtNextMajor()
{
List<string> checkedPackages = [];
List<string> violations = [];

foreach (string nupkg in EnumerateProducedPackages())
{
foreach (string version in GetPlatformDependencyVersions(nupkg))
{
string packageName = Path.GetFileName(nupkg);
checkedPackages.Add($"{packageName} -> {version}");

// Expected shape: "[<min>, <nextMajor>)". A bare version like "2.4.0" (no brackets) means the
// upper-bound target did not run — exactly the regression we are guarding against.
if (!version.StartsWith('[') || !version.EndsWith($", {ExpectedUpperBound})", StringComparison.Ordinal))
{
violations.Add($"{packageName}: expected a '[<min>, {ExpectedUpperBound})' range but found '{version}'.");
}
}
}

Assert.IsNotEmpty(
checkedPackages,
$"Expected at least one produced package to declare a '{PlatformPackageId}' dependency, but none was found. " +
$"Ensure the solution was packed (build with '-pack') before running this test. Searched:{Environment.NewLine}" +
$" {Constants.ArtifactsPackagesShipping}{Environment.NewLine} {Constants.ArtifactsPackagesNonShipping}");

Assert.IsEmpty(
violations,
$"The following packages do not cap their '{PlatformPackageId}' dependency at '[<min>, {ExpectedUpperBound})':{Environment.NewLine}" +
string.Join(Environment.NewLine, violations));
}

private static int GetTestingPlatformMajorVersion()
{
var versionsProps = XDocument.Load(Path.Combine(Constants.Root, "eng", "Versions.props"));
string versionPrefix = versionsProps.Descendants()
.Single(e => e.Name.LocalName == "TestingPlatformVersionPrefix")
.Value;
return int.Parse(versionPrefix.Split('.')[0], CultureInfo.InvariantCulture);
}

private static IEnumerable<string> EnumerateProducedPackages()
{
foreach (string folder in new[] { Constants.ArtifactsPackagesShipping, Constants.ArtifactsPackagesNonShipping })
{
if (!Directory.Exists(folder))
{
continue;
}

// Only the Microsoft.Testing.* family can depend on Microsoft.Testing.Platform; scoping the search
// keeps unrelated packages (and the platform package itself, which has no self-dependency) out.
foreach (string nupkg in Directory.EnumerateFiles(folder, "Microsoft.Testing.*.nupkg", SearchOption.TopDirectoryOnly))
{
yield return nupkg;
}
}
}

private static IEnumerable<string> GetPlatformDependencyVersions(string nupkgPath)
{
using ZipArchive archive = ZipFile.OpenRead(nupkgPath);
ZipArchiveEntry? nuspecEntry = archive.Entries.FirstOrDefault(e => e.FullName.EndsWith(".nuspec", StringComparison.OrdinalIgnoreCase));
if (nuspecEntry is null)
{
yield break;
}

XDocument nuspec;
using (Stream stream = nuspecEntry.Open())
{
nuspec = XDocument.Load(stream);
}

// Match by LocalName to ignore the nuspec XML namespace, and target the exact dependency id so
// siblings such as 'Microsoft.Testing.Platform.MSBuild' or 'Microsoft.Testing.Platform.AI' are excluded.
foreach (XElement dependency in nuspec.Descendants().Where(e => e.Name.LocalName == "dependency"))
{
if (string.Equals((string?)dependency.Attribute("id"), PlatformPackageId, StringComparison.Ordinal)
&& (string?)dependency.Attribute("version") is { } version)
{
yield return version;
}
}
}
}