Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable Nullable Reference Types in Test Projects #44862

Merged
merged 8 commits into from
Dec 16, 2024
2 changes: 1 addition & 1 deletion test/Common/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ partial class Program
public static int Main(string[] args)
{
var testCommandLine = TestCommandLine.HandleCommandLine(args);
var newArgs = testCommandLine.RemainingArgs.ToList();
List<string> newArgs = testCommandLine.RemainingArgs?.ToList() ?? new List<string>();

// Help argument needs to be the first one to xunit, so don't insert assembly location in that case
if (testCommandLine.ShouldShowHelp)
Expand Down
11 changes: 8 additions & 3 deletions test/HelixTasks/CreateLocalHelixTestLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,23 @@ namespace Microsoft.DotNet.SdkCustomHelix.Sdk
public sealed class CreateLocalHelixTestLayout : Build.Utilities.Task
{
[Required]
public ITaskItem[] HelixCorrelationPayload { get; set; }
public ITaskItem[]? HelixCorrelationPayload { get; set; }

[Required]
public string TestOutputDirectory { get; set; }
public string? TestOutputDirectory { get; set; }

public override bool Execute()
{
if (HelixCorrelationPayload is null)
{
return false;
};

foreach (var payload in HelixCorrelationPayload)
{
var copyfrom = new DirectoryInfo(payload.GetMetadata("PayloadDirectory"));
var relativeDestinationPathOnHelix = payload.GetMetadata("Destination");
var destination = new DirectoryInfo(Path.Combine(TestOutputDirectory, relativeDestinationPathOnHelix));
var destination = new DirectoryInfo(Path.Combine(TestOutputDirectory ?? string.Empty, relativeDestinationPathOnHelix));

if (Directory.Exists(destination.FullName))
{
Expand Down
1 change: 1 addition & 0 deletions test/HelixTasks/HelixTasks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<TargetFrameworks Condition=" '$([MSBuild]::IsOSPlatform(`Windows`))' == 'false' ">net8.0</TargetFrameworks>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<RootNamespace>Microsoft.DotNet.SDK.Build.Helix</RootNamespace>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
Expand Down
29 changes: 17 additions & 12 deletions test/HelixTasks/SDKCustomCreateXUnitWorkItemsWithTestExclusion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class SDKCustomCreateXUnitWorkItemsWithTestExclusion : Build.Utilities.Ta
/// The two required parameters will be automatically created if XUnitProject.Identity is set to the path of the XUnit csproj file
/// </summary>
[Required]
public ITaskItem[] XUnitProjects { get; set; }
public ITaskItem[]? XUnitProjects { get; set; }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rainersigwald Have ya'll enabled nullable for any msbuild tasks? Is it possible for these to be null or does MSBuild force them to have a value always? Do they have to be marked Required to not be null?


/// <summary>
/// The path to the dotnet executable on the Helix agent. Defaults to "dotnet"
Expand All @@ -40,15 +40,15 @@ public class SDKCustomCreateXUnitWorkItemsWithTestExclusion : Build.Utilities.Ta
/// Optional timeout for all created workitems
/// Defaults to 300s
/// </summary>
public string XUnitWorkItemTimeout { get; set; }
public string? XUnitWorkItemTimeout { get; set; }

public string XUnitArguments { get; set; }
public string? XUnitArguments { get; set; }

/// <summary>
/// An array of ITaskItems of type HelixWorkItem
/// </summary>
[Output]
public ITaskItem[] XUnitWorkItems { get; set; }
public ITaskItem[]? XUnitWorkItems { get; set; }

/// <summary>
/// The main method of this MSBuild task which calls the asynchronous execution method and
Expand All @@ -71,8 +71,13 @@ public override bool Execute()
/// <returns></returns>
private async Task ExecuteAsync()
{
if(XUnitProjects is null)
{
return;
}

XUnitWorkItems = (await Task.WhenAll(XUnitProjects.Select(PrepareWorkItem)))
.SelectMany(i => i)
.SelectMany(i => i ?? new())
.Where(wi => wi != null)
.ToArray();
return;
Expand All @@ -83,7 +88,7 @@ private async Task ExecuteAsync()
/// </summary>
/// <param name="publishPath">The non-relative path to the publish directory.</param>
/// <returns>An ITaskItem instance representing the prepared HelixWorkItem.</returns>
private async Task<List<ITaskItem>> PrepareWorkItem(ITaskItem xunitProject)
private async Task<List<ITaskItem>?> PrepareWorkItem(ITaskItem xunitProject)
{
// Forces this task to run asynchronously
await Task.Yield();
Expand Down Expand Up @@ -164,12 +169,12 @@ private async Task<List<ITaskItem>> PrepareWorkItem(ITaskItem xunitProject)
Log.LogMessage($"Creating work item with properties Identity: {assemblyName}, PayloadDirectory: {publishDirectory}, Command: {command}");

partitionedWorkItem.Add(new Microsoft.Build.Utilities.TaskItem(assemblyPartitionInfo.DisplayName + testIdentityDifferentiator, new Dictionary<string, string>()
{
{ "Identity", assemblyPartitionInfo.DisplayName + testIdentityDifferentiator},
{ "PayloadDirectory", publishDirectory },
{ "Command", command },
{ "Timeout", timeout.ToString() },
}));
{
{ "Identity", assemblyPartitionInfo.DisplayName + testIdentityDifferentiator},
{ "PayloadDirectory", publishDirectory },
{ "Command", command },
{ "Timeout", timeout.ToString() },
}));
}

return partitionedWorkItem;
Expand Down
24 changes: 13 additions & 11 deletions test/HelixTasks/TarGzFileCreateFromDirectory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ public sealed class TarGzFileCreateFromDirectory : ToolTask
/// The path to the directory to be archived.
/// </summary>
[Required]
public string SourceDirectory { get; set; }
public string? SourceDirectory { get; set; }

/// <summary>
/// The path of the archive to be created.
/// </summary>
[Required]
public string DestinationArchive { get; set; }
public string? DestinationArchive { get; set; }

/// <summary>
/// Indicates if the destination archive should be overwritten if it already exists.
Expand All @@ -33,7 +33,7 @@ public sealed class TarGzFileCreateFromDirectory : ToolTask
/// <summary>
/// An item group of regular expressions for content to exclude from the archive.
/// </summary>
public ITaskItem[] ExcludePatterns { get; set; }
public ITaskItem[]? ExcludePatterns { get; set; }

public bool IgnoreExitCode { get; set; }

Expand Down Expand Up @@ -69,16 +69,18 @@ protected override bool ValidateParameters()
retVal = false;
}
}
if (SourceDirectory is not null)
{
SourceDirectory = Path.GetFullPath(SourceDirectory);

SourceDirectory = Path.GetFullPath(SourceDirectory);

SourceDirectory = SourceDirectory.EndsWith(Path.DirectorySeparatorChar.ToString())
? SourceDirectory
: SourceDirectory + Path.DirectorySeparatorChar;
SourceDirectory = SourceDirectory.EndsWith(Path.DirectorySeparatorChar.ToString())
? SourceDirectory
: SourceDirectory + Path.DirectorySeparatorChar;
}

if (!Directory.Exists(SourceDirectory))
{
Log.LogError($"SourceDirectory '{SourceDirectory} does not exist.");
Log.LogError($"SourceDirectory '{SourceDirectory}' does not exist.");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good find.


retVal = false;
}
Expand Down Expand Up @@ -113,9 +115,9 @@ protected override string GenerateCommandLineCommands()

private string GetSourceSpecification()
{
if (IncludeBaseDirectory)
if (SourceDirectory is not null && IncludeBaseDirectory)
{
var parentDirectory = Directory.GetParent(SourceDirectory).Parent.FullName;
var parentDirectory = Directory.GetParent(SourceDirectory)?.Parent?.FullName;

var sourceDirectoryName = Path.GetFileName(Path.GetDirectoryName(SourceDirectory));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -341,16 +341,16 @@ public async Task EndToEnd_NoAPI_ProjectType(string projectType, bool addPackage
{
File.Copy(Path.Combine(TestContext.Current.TestExecutionDirectory, "NuGet.config"), Path.Combine(newProjectDir.FullName, "NuGet.config"));

(string packagePath, string packageVersion) = ToolsetUtils.GetContainersPackagePath();
(string? packagePath, string? packageVersion) = ToolsetUtils.GetContainersPackagePath();

new DotnetCommand(_testOutput, "nuget", "add", "source", Path.GetDirectoryName(packagePath), "--name", "local-temp")
new DotnetCommand(_testOutput, "nuget", "add", "source", Path.GetDirectoryName(packagePath) ?? string.Empty, "--name", "local-temp")
.WithEnvironmentVariable("NUGET_PACKAGES", privateNuGetAssets.FullName)
.WithWorkingDirectory(newProjectDir.FullName)
.Execute()
.Should().Pass();

// Add package to the project
new DotnetCommand(_testOutput, "add", "package", "Microsoft.NET.Build.Containers", "-f", ToolsetInfo.CurrentTargetFramework, "-v", packageVersion)
new DotnetCommand(_testOutput, "add", "package", "Microsoft.NET.Build.Containers", "-f", ToolsetInfo.CurrentTargetFramework, "-v", packageVersion ?? string.Empty)
.WithEnvironmentVariable("NUGET_PACKAGES", privateNuGetAssets.FullName)
.WithWorkingDirectory(newProjectDir.FullName)
.Execute()
Expand Down Expand Up @@ -509,16 +509,16 @@ public void EndToEnd_NoAPI_Console()

File.Copy(Path.Combine(TestContext.Current.TestExecutionDirectory, "NuGet.config"), Path.Combine(newProjectDir.FullName, "NuGet.config"));

(string packagePath, string packageVersion) = ToolsetUtils.GetContainersPackagePath();
(string? packagePath, string? packageVersion) = ToolsetUtils.GetContainersPackagePath();

new DotnetCommand(_testOutput, "nuget", "add", "source", Path.GetDirectoryName(packagePath), "--name", "local-temp")
new DotnetCommand(_testOutput, "nuget", "add", "source", Path.GetDirectoryName(packagePath) ?? string.Empty, "--name", "local-temp")
.WithEnvironmentVariable("NUGET_PACKAGES", privateNuGetAssets.FullName)
.WithWorkingDirectory(newProjectDir.FullName)
.Execute()
.Should().Pass();

// Add package to the project
new DotnetCommand(_testOutput, "add", "package", "Microsoft.NET.Build.Containers", "-f", _oldFramework , "-v", packageVersion)
new DotnetCommand(_testOutput, "add", "package", "Microsoft.NET.Build.Containers", "-f", _oldFramework , "-v", packageVersion ?? string.Empty)
.WithEnvironmentVariable("NUGET_PACKAGES", privateNuGetAssets.FullName)
.WithWorkingDirectory(newProjectDir.FullName)
.Execute()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ public void PackageContentTest()
$"tasks/{netTFM}/Valleysoft.DockerCredsProvider.dll"
};

(string packageFilePath, string packageVersion) = ToolsetUtils.GetContainersPackagePath();
using ZipArchive archive = new(File.OpenRead(packageFilePath), ZipArchiveMode.Read, false);
(string? packageFilePath, string? packageVersion) = ToolsetUtils.GetContainersPackagePath();
using ZipArchive archive = new(File.OpenRead(packageFilePath ?? string.Empty), ZipArchiveMode.Read, false);

IEnumerable<string> actualEntries = archive.Entries
.Select(e => e.FullName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Microsoft.NET.Build.Containers.IntegrationTests;

public sealed class ProjectInitializer
{
private static readonly string _combinedTargetsLocation;
private static readonly string? _combinedTargetsLocation;

static ProjectInitializer()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,18 @@ internal static string GetRuntimeGraphFilePath()
/// Gets path to built Microsoft.NET.Build.Containers.*.nupkg prepared for tests.
/// </summary>
/// <returns></returns>
internal static (string PackagePath, string PackageVersion) GetContainersPackagePath()
internal static (string? PackagePath, string? PackageVersion) GetContainersPackagePath()
{
string packageDir = Path.Combine(TestContext.Current.TestExecutionDirectory, "Container", "package");

//until the package is stabilized, the package version matches TestContext.Current.ToolsetUnderTest.SdkVersion
//after the package is stabilized, the package version doesn't have -prefix (-dev, -ci) anymore
//so one of those is expected
string[] expectedPackageVersions = new[] { TestContext.Current.ToolsetUnderTest.SdkVersion, TestContext.Current.ToolsetUnderTest.SdkVersion.Split('-')[0] };
string?[] expectedPackageVersions = new[] { TestContext.Current.ToolsetUnderTest?.SdkVersion, TestContext.Current.ToolsetUnderTest?.SdkVersion?.Split('-')[0] };

foreach (string expectedVersion in expectedPackageVersions)
foreach (string? expectedVersion in expectedPackageVersions)
{
string fullFileName = Path.Combine(packageDir, $"Microsoft.NET.Build.Containers.{expectedVersion}.nupkg");
string? fullFileName = Path.Combine(packageDir, $"Microsoft.NET.Build.Containers.{expectedVersion}.nupkg");
if (File.Exists(fullFileName))
{
return (fullFileName, expectedVersion);
Expand Down
Loading
Loading