Skip to content

Commit

Permalink
[wasm] Wasm.Build.Tests - some refactoring, and rationalizing (#88357)
Browse files Browse the repository at this point in the history
  • Loading branch information
radical committed Jul 12, 2023
1 parent 1dd0fa2 commit d3d910e
Show file tree
Hide file tree
Showing 19 changed files with 661 additions and 322 deletions.
20 changes: 20 additions & 0 deletions src/mono/wasm/Wasm.Build.Tests/AssertTestMainJsAppBundleOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

#nullable enable

namespace Wasm.Build.Tests;

public record AssertTestMainJsAppBundleOptions
(
string BundleDir,
string ProjectName,
string Config,
string MainJS,
bool HasV8Script,
GlobalizationMode? GlobalizationMode,
string PredefinedIcudt = "",
bool UseWebcil = true,
bool IsBrowserProject = true,
bool IsPublish = false
);
2 changes: 1 addition & 1 deletion src/mono/wasm/Wasm.Build.Tests/Blazor/AppsettingsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,4 @@ await BlazorRunForBuildWithDotnetRun("debug", onConsoleMessage: msg =>
Assert.True(existsChecked, "File '/appsettings.json' wasn't found");
Assert.True(contentChecked, "Content of '/appsettings.json' is not matched");
}
}
}
4 changes: 2 additions & 2 deletions src/mono/wasm/Wasm.Build.Tests/Blazor/BuildPublishTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ public void DefaultTemplate_WithoutWorkload(string config)

// Build
BlazorBuildInternal(id, config, publish: false);
AssertBlazorBootJson(config, isPublish: false, isNet7AndBelow: false);
AssertBlazorBootJson(config, isPublish: false);

// Publish
BlazorBuildInternal(id, config, publish: true);
AssertBlazorBootJson(config, isPublish: true, isNet7AndBelow: false);
AssertBlazorBootJson(config, isPublish: true);
}

[Theory]
Expand Down
8 changes: 6 additions & 2 deletions src/mono/wasm/Wasm.Build.Tests/Blazor/MiscTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,12 @@ public void NativeBuild_WithDeployOnBuild_UsedByVS(string config, bool nativeRel

var expectedFileType = nativeRelink ? NativeFilesType.Relinked : NativeFilesType.AOT;

AssertDotNetNativeFiles(expectedFileType, config, forPublish: true, targetFramework: DefaultTargetFrameworkForBlazor);
AssertBlazorBundle(config, isPublish: true, dotnetWasmFromRuntimePack: false);
AssertBlazorBundle(new BlazorBuildOptions
(
Id: id,
Config: config,
ExpectedFileType: expectedFileType
), isPublish: true);

if (expectedFileType == NativeFilesType.AOT)
{
Expand Down
66 changes: 0 additions & 66 deletions src/mono/wasm/Wasm.Build.Tests/Blazor/MiscTests2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,70 +66,4 @@ private CommandResult PublishForRequiresWorkloadTest(string config, string extra
$"-bl:{publishLogPath}",
$"-p:Configuration={config}");
}

[Theory]
[InlineData("Debug")]
[InlineData("Release")]
public void Net50Projects_NativeReference(string config)
=> BuildNet50Project(config, aot: false, expectError: true, @"<NativeFileReference Include=""native-lib.o"" />");

public static TheoryData<string, bool, bool> Net50TestData = new()
{
{ "Debug", /*aot*/ true, /*expectError*/ true },
{ "Debug", /*aot*/ false, /*expectError*/ false },
{ "Release", /*aot*/ true, /*expectError*/ true },
{ "Release", /*aot*/ false, /*expectError*/ false }
};

// FIXME: test for WasmBuildNative=true?
[Theory]
[MemberData(nameof(Net50TestData))]
public void Net50Projects_AOT(string config, bool aot, bool expectError)
=> BuildNet50Project(config, aot: aot, expectError: expectError);

private void BuildNet50Project(string config, bool aot, bool expectError, string? extraItems=null)
{
string id = $"Blazor_net50_{config}_{aot}_{Path.GetRandomFileName()}";
InitBlazorWasmProjectDir(id);

string directoryBuildTargets = @"<Project>
<Target Name=""PrintAllProjects"" BeforeTargets=""Build"">
<Message Text=""** UsingBrowserRuntimeWorkload: '$(UsingBrowserRuntimeWorkload)'"" Importance=""High"" />
</Target>
</Project>";

File.WriteAllText(Path.Combine(_projectDir!, "Directory.Build.props"), "<Project />");
File.WriteAllText(Path.Combine(_projectDir!, "Directory.Build.targets"), directoryBuildTargets);

string logPath = Path.Combine(s_buildEnv.LogRootPath, id);
Utils.DirectoryCopy(Path.Combine(BuildEnvironment.TestAssetsPath, "Blazor_net50"), Path.Combine(_projectDir!));

string projectFile = Path.Combine(_projectDir!, "Blazor_net50.csproj");
AddItemsPropertiesToProject(projectFile, extraItems: extraItems);

string publishLogPath = Path.Combine(logPath, $"{id}.binlog");
CommandResult result = new DotNetCommand(s_buildEnv, _testOutput)
.WithWorkingDirectory(_projectDir!)
.WithEnvironmentVariable("NUGET_PACKAGES", _nugetPackagesDir)
.ExecuteWithCapturedOutput("publish",
$"-bl:{publishLogPath}",
(aot ? "-p:RunAOTCompilation=true" : ""),
$"-p:Configuration={config}");

if (expectError)
{
result.EnsureExitCode(1);
Assert.Contains("are only supported for projects targeting net6.0+", result.Output);
}
else
{
result.EnsureSuccessful();
Assert.Contains("** UsingBrowserRuntimeWorkload: 'false'", result.Output);

string binFrameworkDir = FindBlazorBinFrameworkDir(config, forPublish: true, framework: "net5.0");
AssertBlazorBootJson(config, isPublish: true, isNet7AndBelow: true, binFrameworkDir: binFrameworkDir);
// dotnet.wasm here would be from 5.0 nuget like:
// /Users/radical/.nuget/packages/microsoft.netcore.app.runtime.browser-wasm/5.0.9/runtimes/browser-wasm/native/dotnet.wasm
}
}
}
88 changes: 88 additions & 0 deletions src/mono/wasm/Wasm.Build.Tests/BlazorWasmProjectProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
using System.Runtime.Serialization.Json;
using Microsoft.NET.Sdk.WebAssembly;

#nullable enable

namespace Wasm.Build.Tests;

public class BlazorWasmProjectProvider(string projectDir, ITestOutputHelper testOutput)
: WasmSdkBasedProjectProvider(projectDir, testOutput)
{
public void AssertBlazorBootJson(
string binFrameworkDir,
bool expectFingerprintOnDotnetJs = false,
bool isPublish = false,
RuntimeVariant runtimeType = RuntimeVariant.SingleThreaded)
{
string bootJsonPath = Path.Combine(binFrameworkDir, "blazor.boot.json");
Assert.True(File.Exists(bootJsonPath), $"Expected to find {bootJsonPath}");

BootJsonData bootJson = ParseBootData(bootJsonPath);
var bootJsonEntries = bootJson.resources.runtime.Keys.Where(k => k.StartsWith("dotnet.", StringComparison.Ordinal)).ToArray();

var expectedEntries = new SortedDictionary<string, Action<string>>();
IReadOnlySet<string> expected = GetDotNetFilesExpectedSet(runtimeType, isPublish);

var knownSet = GetAllKnownDotnetFilesToFingerprintMap(runtimeType);
foreach (string expectedFilename in expected)
{
if (Path.GetExtension(expectedFilename) == ".map")
continue;

bool expectFingerprint = knownSet[expectedFilename];
expectedEntries[expectedFilename] = item =>
{
string prefix = Path.GetFileNameWithoutExtension(expectedFilename);
string extension = Path.GetExtension(expectedFilename).Substring(1);
if (ShouldCheckFingerprint(expectedFilename: expectedFilename,
expectFingerprintOnDotnetJs: expectFingerprintOnDotnetJs,
expectFingerprintForThisFile: expectFingerprint))
{
Assert.Matches($"{prefix}{s_dotnetVersionHashRegex}{extension}", item);
}
else
{
Assert.Equal(expectedFilename, item);
}
string absolutePath = Path.Combine(binFrameworkDir, item);
Assert.True(File.Exists(absolutePath), $"Expected to find '{absolutePath}'");
};
}
// FIXME: maybe use custom code so the details can show up in the log
Assert.Collection(bootJsonEntries.Order(), expectedEntries.Values.ToArray());
}

public static BootJsonData ParseBootData(string bootJsonPath)
{
using FileStream stream = File.OpenRead(bootJsonPath);
stream.Position = 0;
var serializer = new DataContractJsonSerializer(
typeof(BootJsonData),
new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true });

var config = (BootJsonData?)serializer.ReadObject(stream);
Assert.NotNull(config);
return config;
}

public string FindBlazorBinFrameworkDir(string config, bool forPublish, string framework)
{
string basePath = Path.Combine(ProjectDir, "bin", config, framework);
if (forPublish)
basePath = FindSubDirIgnoringCase(basePath, "publish");

return Path.Combine(basePath, "wwwroot", "_framework");
}
}
30 changes: 30 additions & 0 deletions src/mono/wasm/Wasm.Build.Tests/BuildProjectOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;

#nullable enable

namespace Wasm.Build.Tests;

public record BuildProjectOptions
(
Action? InitProject = null,
bool? DotnetWasmFromRuntimePack = null,
GlobalizationMode? GlobalizationMode = null,
string? PredefinedIcudt = null,
bool UseCache = true,
bool ExpectSuccess = true,
bool AssertAppBundle = true,
bool CreateProject = true,
bool Publish = true,
bool BuildOnlyAfterPublish = true,
bool HasV8Script = true,
string? Verbosity = null,
string? Label = null,
string? TargetFramework = null,
string? MainJS = null,
bool IsBrowserProject = true,
IDictionary<string, string>? ExtraBuildEnvironmentVariables = null
);
Loading

0 comments on commit d3d910e

Please sign in to comment.