Skip to content

Commit

Permalink
Enable Nullable Reference Types in Test Projects
Browse files Browse the repository at this point in the history
  • Loading branch information
v-wuzhai committed Nov 14, 2024
1 parent 32524ee commit 1a475e9
Show file tree
Hide file tree
Showing 80 changed files with 463 additions and 466 deletions.
4 changes: 2 additions & 2 deletions 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();
var newArgs = testCommandLine.RemainingArgs?.ToList()!;

// Help argument needs to be the first one to xunit, so don't insert assembly location in that case
if (testCommandLine.ShouldShowHelp)
Expand Down Expand Up @@ -66,7 +66,7 @@ private static int ShowSdkInfo()
{
var log = new StringTestLogger();
var command = new DotnetCommand(log, "--info");
var testDirectory = TestDirectory.Create(Path.Combine(TestContext.Current.TestExecutionDirectory, "sdkinfo"));
var testDirectory = TestDirectory.Create(Path.Combine(TestContext.Current?.TestExecutionDirectory!, "sdkinfo"));

command.WorkingDirectory = testDirectory.Path;

Expand Down
8 changes: 4 additions & 4 deletions test/HelixTasks/CreateLocalHelixTestLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,18 @@ 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()
{
foreach (var payload in HelixCorrelationPayload)
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!, 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
26 changes: 13 additions & 13 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; }

/// <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,8 @@ public override bool Execute()
/// <returns></returns>
private async Task ExecuteAsync()
{
XUnitWorkItems = (await Task.WhenAll(XUnitProjects.Select(PrepareWorkItem)))
.SelectMany(i => i)
XUnitWorkItems = (await Task.WhenAll(XUnitProjects?.Select(PrepareWorkItem)!))
.SelectMany(i => i!)
.Where(wi => wi != null)
.ToArray();
return;
Expand All @@ -83,7 +83,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 @@ -166,12 +166,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 != 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.");

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

private string GetSourceSpecification()
{
if (IncludeBaseDirectory)
if (IncludeBaseDirectory && SourceDirectory != null)
{
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 @@ -246,7 +246,7 @@ public async System.Threading.Tasks.Task CreateNewImage_RootlessBaseImage()
await registry.PushAsync(builtImage, sourceReference, destinationReference, cancellationToken: default).ConfigureAwait(false);

// Build an application image on top of the rootless base runtime image.
DirectoryInfo newProjectDir = new(Path.Combine(TestSettings.TestArtifactsDirectory, nameof(CreateNewImage_RootlessBaseImage)));
DirectoryInfo newProjectDir = new(Path.Combine(TestSettings.TestArtifactsDirectory!, nameof(CreateNewImage_RootlessBaseImage)));

if (newProjectDir.Exists)
{
Expand Down Expand Up @@ -307,7 +307,7 @@ private static (IBuildEngine buildEngine, List<string?> errors) SetupBuildEngine
return (buildEngine, errors);
}

private static string GetTestDirectoryName([CallerMemberName] string testName = "DefaultTest") => Path.Combine(TestSettings.TestArtifactsDirectory, testName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"));
private static string GetTestDirectoryName([CallerMemberName] string testName = "DefaultTest") => Path.Combine(TestSettings.TestArtifactsDirectory!, testName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"));

private static string FormatBuildMessages(List<string?> messages) => string.Join("\r\n", messages);
}
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public async Task ApiEndToEndWithArchiveWritingAndLoad()
BuiltImage builtImage = imageBuilder.Build();

// Write the image to disk
var archiveFile = Path.Combine(TestSettings.TestArtifactsDirectory,
var archiveFile = Path.Combine(TestSettings.TestArtifactsDirectory!,
nameof(ApiEndToEndWithArchiveWritingAndLoad), "app.tar.gz");
var sourceReference = new SourceImageReference(registry, DockerRegistryManager.RuntimeBaseImage, DockerRegistryManager.Net9PreviewImageTag);
var destinationReference = new DestinationImageReference(new ArchiveFileRegistry(archiveFile), NewImageName(), new[] { "latest", "1.0" });
Expand All @@ -178,7 +178,7 @@ public async Task ApiEndToEndWithArchiveWritingAndLoad()

private string BuildLocalApp([CallerMemberName] string testName = "TestName", string tfm = ToolsetInfo.CurrentTargetFramework, string rid = "linux-x64")
{
string workingDirectory = Path.Combine(TestSettings.TestArtifactsDirectory, testName);
string workingDirectory = Path.Combine(TestSettings.TestArtifactsDirectory!, testName);

DirectoryInfo d = new(Path.Combine(workingDirectory, "MinimalTestApp"));
if (d.Exists)
Expand Down Expand Up @@ -213,7 +213,7 @@ private string BuildLocalApp([CallerMemberName] string testName = "TestName", st
public async Task EndToEnd_MultiProjectSolution()
{
ILogger logger = _loggerFactory.CreateLogger(nameof(EndToEnd_MultiProjectSolution));
DirectoryInfo newSolutionDir = new(Path.Combine(TestSettings.TestArtifactsDirectory, $"CreateNewImageTest_EndToEnd_MultiProjectSolution"));
DirectoryInfo newSolutionDir = new(Path.Combine(TestSettings.TestArtifactsDirectory!, $"CreateNewImageTest_EndToEnd_MultiProjectSolution"));

if (newSolutionDir.Exists)
{
Expand Down Expand Up @@ -298,8 +298,8 @@ public async Task EndToEnd_MultiProjectSolution()
[InlineData("worker", true)]
public async Task EndToEnd_NoAPI_ProjectType(string projectType, bool addPackageReference)
{
DirectoryInfo newProjectDir = new(Path.Combine(TestSettings.TestArtifactsDirectory, $"CreateNewImageTest_{projectType}_{addPackageReference}"));
DirectoryInfo privateNuGetAssets = new(Path.Combine(TestSettings.TestArtifactsDirectory, "ContainerNuGet"));
DirectoryInfo newProjectDir = new(Path.Combine(TestSettings.TestArtifactsDirectory!, $"CreateNewImageTest_{projectType}_{addPackageReference}"));
DirectoryInfo privateNuGetAssets = new(Path.Combine(TestSettings.TestArtifactsDirectory!, "ContainerNuGet"));

if (newProjectDir.Exists)
{
Expand All @@ -324,9 +324,9 @@ public async Task EndToEnd_NoAPI_ProjectType(string projectType, bool addPackage

if (addPackageReference)
{
File.Copy(Path.Combine(TestContext.Current.TestExecutionDirectory, "NuGet.config"), Path.Combine(newProjectDir.FullName, "NuGet.config"));
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")
.WithEnvironmentVariable("NUGET_PACKAGES", privateNuGetAssets.FullName)
Expand Down Expand Up @@ -471,8 +471,8 @@ public async Task EndToEnd_NoAPI_ProjectType(string projectType, bool addPackage
[DockerAvailableFact(Skip = "https://github.com/dotnet/sdk/issues/42850")]
public void EndToEnd_NoAPI_Console()
{
DirectoryInfo newProjectDir = new(Path.Combine(TestSettings.TestArtifactsDirectory, "CreateNewImageTest"));
DirectoryInfo privateNuGetAssets = new(Path.Combine(TestSettings.TestArtifactsDirectory, "ContainerNuGet"));
DirectoryInfo newProjectDir = new(Path.Combine(TestSettings.TestArtifactsDirectory!, "CreateNewImageTest"));
DirectoryInfo privateNuGetAssets = new(Path.Combine(TestSettings.TestArtifactsDirectory!, "ContainerNuGet"));

if (newProjectDir.Exists)
{
Expand All @@ -495,9 +495,9 @@ public void EndToEnd_NoAPI_Console()
.Execute()
.Should().Pass();

File.Copy(Path.Combine(TestContext.Current.TestExecutionDirectory, "NuGet.config"), Path.Combine(newProjectDir.FullName, "NuGet.config"));
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")
.WithEnvironmentVariable("NUGET_PACKAGES", privateNuGetAssets.FullName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,6 @@ public void GenerateCommandLineCommands_LabelGeneration()

private static string GetPathToContainerize()
{
return Path.Combine(TestContext.Current.TestExecutionDirectory, "Container", "containerize");
return Path.Combine(TestContext.Current?.TestExecutionDirectory!, "Container", "containerize");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public void SanityTest_ContainerizeDependencies()
"..\\..\\Cli\\Microsoft.DotNet.Cli.Utils\\Microsoft.DotNet.Cli.Utils.csproj"
};

string projectFilePath = Path.Combine(TestContext.Current.TestExecutionDirectory, "Container", "ProjectFiles", "containerize.csproj");
string projectFilePath = Path.Combine(TestContext.Current?.TestExecutionDirectory!, "Container", "ProjectFiles", "containerize.csproj");
XDocument project = XDocument.Load(projectFilePath);
XNamespace ns = project.Root?.Name.Namespace ?? throw new InvalidOperationException("Project file is empty");

Expand Down Expand Up @@ -52,7 +52,7 @@ public void SanityTest_NET_Build_ContainersDependencies()
"..\\..\\Cli\\Microsoft.DotNet.Cli.Utils\\Microsoft.DotNet.Cli.Utils.csproj"
};

string projectFilePath = Path.Combine(TestContext.Current.TestExecutionDirectory, "Container", "ProjectFiles", "Microsoft.NET.Build.Containers.csproj");
string projectFilePath = Path.Combine(TestContext.Current?.TestExecutionDirectory!, "Container", "ProjectFiles", "Microsoft.NET.Build.Containers.csproj");
XDocument project = XDocument.Load(projectFilePath);
XNamespace ns = project.Root?.Name.Namespace ?? throw new InvalidOperationException("Project file is empty");

Expand Down Expand Up @@ -131,7 +131,7 @@ public void PackageContentTest()
$"tasks/{netTFM}/Valleysoft.DockerCredsProvider.dll"
};

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

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

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

static ProjectInitializer()
{
var artifactPackagingDirectory = Path.Combine(TestContext.Current.TestExecutionDirectory, "Container", "packaging");
var artifactPackagingDirectory = Path.Combine(TestContext.Current?.TestExecutionDirectory!, "Container", "packaging");
var targetsFile = Path.Combine(artifactPackagingDirectory, "Microsoft.NET.Build.Containers.targets");
var propsFile = Path.ChangeExtension(targetsFile, ".props");
_combinedTargetsLocation = CombineFiles(propsFile, targetsFile);
Expand All @@ -27,7 +27,7 @@ private static string CombineFiles(string propsFile, string targetsFile)
var combinedContent = new List<string>();
combinedContent.AddRange(propsContent[..^1]);
combinedContent.AddRange(targetsContent[1..]);
var tempTargetLocation = Path.Combine(TestSettings.TestArtifactsDirectory, "Containers", "Microsoft.NET.Build.Containers.targets");
var tempTargetLocation = Path.Combine(TestSettings.TestArtifactsDirectory!, "Containers", "Microsoft.NET.Build.Containers.targets");
string? directoryName = Path.GetDirectoryName(tempTargetLocation);
Assert.NotNull(directoryName);
Directory.CreateDirectory(directoryName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ internal static class TestSettings
/// <summary>
/// Gets temporary location for test artifacts.
/// </summary>
internal static string TestArtifactsDirectory
internal static string? TestArtifactsDirectory
{
get
{
Expand All @@ -23,7 +23,7 @@ internal static string TestArtifactsDirectory
{
if (_testArtifactsDir == null)
{
string tmpDir = Path.Combine(TestContext.Current.TestExecutionDirectory, "ContainersTests", DateTime.Now.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture));
string tmpDir = Path.Combine(TestContext.Current?.TestExecutionDirectory!, "ContainersTests", DateTime.Now.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture));
if (!Directory.Exists(tmpDir))
{
Directory.CreateDirectory(tmpDir);
Expand Down
Loading

0 comments on commit 1a475e9

Please sign in to comment.