diff --git a/src/mono/sample/wasm/browser-bench/Wasm.Browser.Bench.Sample.csproj b/src/mono/sample/wasm/browser-bench/Wasm.Browser.Bench.Sample.csproj index be2adc12017035..9f6eee956b5136 100644 --- a/src/mono/sample/wasm/browser-bench/Wasm.Browser.Bench.Sample.csproj +++ b/src/mono/sample/wasm/browser-bench/Wasm.Browser.Bench.Sample.csproj @@ -58,7 +58,7 @@ diff --git a/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs b/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs index db8a45889b58cd..2dbc48098d5378 100644 --- a/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs +++ b/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs @@ -26,7 +26,7 @@ namespace Wasm.Build.Tests { public abstract class BuildTestBase : IClassFixture, IDisposable { - public const string DefaultTargetFramework = "net10.0"; + public static readonly string DefaultTargetFramework = $"net{Environment.Version.Major}.0"; protected static readonly bool s_skipProjectCleanup; protected static readonly string s_xharnessRunnerCommand; protected string? _projectDir; @@ -55,7 +55,7 @@ public abstract class BuildTestBase : IClassFixture s_buildEnv.IsWorkload; public static bool IsNotUsingWorkloads => !s_buildEnv.IsWorkload; public static string GetNuGetConfigPathFor(string targetFramework) => - Path.Combine(BuildEnvironment.TestDataPath, "nuget10.config"); + Path.Combine(BuildEnvironment.TestDataPath, "nuget.config"); static BuildTestBase() { @@ -143,8 +143,9 @@ protected void InitPaths(string id, string? projectParentDir = null) Directory.CreateDirectory(_logPath); } - protected void InitProjectDir(string dir, bool addNuGetSourceForLocalPackages = false, string targetFramework = DefaultTargetFramework) + protected void InitProjectDir(string dir, bool addNuGetSourceForLocalPackages = false, string? targetFramework = null) { + targetFramework ??= DefaultTargetFramework; Directory.CreateDirectory(dir); File.WriteAllText(Path.Combine(dir, "Directory.Build.props"), s_buildEnv.DirectoryBuildPropsContents); File.WriteAllText(Path.Combine(dir, "Directory.Build.targets"), s_buildEnv.DirectoryBuildTargetsContents); @@ -164,7 +165,7 @@ protected void InitProjectDir(string dir, bool addNuGetSourceForLocalPackages = } } - protected const string SimpleProjectTemplate = + protected static readonly string SimpleProjectTemplate = @$" {DefaultTargetFramework} @@ -178,8 +179,9 @@ protected void InitProjectDir(string dir, bool addNuGetSourceForLocalPackages = ##INSERT_AT_END## "; - protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProperties="", string extraItems="", string insertAtEnd="", string projectTemplate=SimpleProjectTemplate) + protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProperties="", string extraItems="", string insertAtEnd="") { + string projectTemplate = SimpleProjectTemplate; if (buildArgs.AOT) { extraProperties = $"{extraProperties}\ntrue"; @@ -217,8 +219,7 @@ protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProp options.InitProject?.Invoke(); File.WriteAllText(Path.Combine(_projectDir, $"{buildArgs.ProjectName}.csproj"), buildArgs.ProjectFileContents); - File.Copy(Path.Combine(AppContext.BaseDirectory, - options.TargetFramework == "net7.0" ? "data/test-main-7.0.js" : "test-main.js"), + File.Copy(Path.Combine(AppContext.BaseDirectory, "test-main.js"), Path.Combine(_projectDir, "test-main.js")); } else if (_projectDir is null) @@ -461,15 +462,17 @@ private string FindSubDirIgnoringCase(string parentDir, string dirName) return first ?? Path.Combine(parentDir, dirName); } - protected string GetBinDir(string config, string targetFramework=DefaultTargetFramework, string? baseDir=null) + protected string GetBinDir(string config, string? targetFramework = null, string? baseDir=null) { + targetFramework ??= DefaultTargetFramework; var dir = baseDir ?? _projectDir; Assert.NotNull(dir); return Path.Combine(dir!, "bin", config, targetFramework, BuildEnvironment.DefaultRuntimeIdentifier); } - protected string GetObjDir(string config, string targetFramework=DefaultTargetFramework, string? baseDir=null) + protected string GetObjDir(string config, string? targetFramework = null, string? baseDir=null) { + targetFramework ??= DefaultTargetFramework; var dir = baseDir ?? _projectDir; Assert.NotNull(dir); return Path.Combine(dir!, "obj", config, targetFramework, BuildEnvironment.DefaultRuntimeIdentifier); diff --git a/src/mono/wasi/Wasi.Build.Tests/WasiLibraryModeTests.cs b/src/mono/wasi/Wasi.Build.Tests/WasiLibraryModeTests.cs index 18f66e81e6da7e..552b74de0976f0 100644 --- a/src/mono/wasi/Wasi.Build.Tests/WasiLibraryModeTests.cs +++ b/src/mono/wasi/Wasi.Build.Tests/WasiLibraryModeTests.cs @@ -31,7 +31,7 @@ public void LibraryModeBuild(string sdk, bool hasWasmAppBundle) $""" - net10.0 + {DefaultTargetFramework} wasi-wasm true Library diff --git a/src/mono/wasm/Wasm.Build.Tests/Blazor/BlazorWasmTestBase.cs b/src/mono/wasm/Wasm.Build.Tests/Blazor/BlazorWasmTestBase.cs index 23f8d6e43b0aa6..f37ff2ade6f7b6 100644 --- a/src/mono/wasm/Wasm.Build.Tests/Blazor/BlazorWasmTestBase.cs +++ b/src/mono/wasm/Wasm.Build.Tests/Blazor/BlazorWasmTestBase.cs @@ -67,8 +67,9 @@ protected override void OnAfterRender(bool firstRender) protected void UpdateHomePage() => UpdateFile(Path.Combine("Pages", "Home.razor"), blazorHomePageReplacements); - public void InitBlazorWasmProjectDir(string id, string targetFramework = DefaultTargetFrameworkForBlazor) + public void InitBlazorWasmProjectDir(string id, string? targetFramework = null) { + targetFramework ??= DefaultTargetFrameworkForBlazor; InitPaths(id); if (Directory.Exists(_projectDir)) Directory.Delete(_projectDir, recursive: true); @@ -220,6 +221,6 @@ public override async Task RunForPublishWithWebServer(RunOptions runO return serverEnvironment; } - public string GetBlazorBinFrameworkDir(Configuration config, bool forPublish, string framework = DefaultTargetFrameworkForBlazor, string? projectDir = null) - => _provider.GetBinFrameworkDir(config: config, forPublish: forPublish, framework: framework, projectDir: projectDir); + public string GetBlazorBinFrameworkDir(Configuration config, bool forPublish, string? framework = null, string? projectDir = null) + => _provider.GetBinFrameworkDir(config: config, forPublish: forPublish, framework: framework ?? DefaultTargetFrameworkForBlazor, projectDir: projectDir); } diff --git a/src/mono/wasm/Wasm.Build.Tests/BrowserStructures/BuildOptions.cs b/src/mono/wasm/Wasm.Build.Tests/BrowserStructures/BuildOptions.cs index 76a9053d9de493..d206a65108f095 100644 --- a/src/mono/wasm/Wasm.Build.Tests/BrowserStructures/BuildOptions.cs +++ b/src/mono/wasm/Wasm.Build.Tests/BrowserStructures/BuildOptions.cs @@ -13,7 +13,7 @@ public BuildOptions( bool IsPublish = false, bool AOT = false, NativeFilesType ExpectedFileType = NativeFilesType.FromRuntimePack, - string TargetFramework = BuildTestBase.DefaultTargetFramework, + string? TargetFramework = null, GlobalizationMode GlobalizationMode = GlobalizationMode.Sharded, string CustomIcuFile = "", bool UseCache = true, @@ -29,9 +29,9 @@ public BuildOptions( bool FeaturePerfTracing = false ) : base( IsPublish, + TargetFramework ?? BuildTestBase.DefaultTargetFramework, AOT, ExpectedFileType, - TargetFramework, GlobalizationMode, CustomIcuFile, UseCache, diff --git a/src/mono/wasm/Wasm.Build.Tests/BrowserStructures/MSBuildOptions.cs b/src/mono/wasm/Wasm.Build.Tests/BrowserStructures/MSBuildOptions.cs index 13506f5eee71e9..509a7f7f266801 100644 --- a/src/mono/wasm/Wasm.Build.Tests/BrowserStructures/MSBuildOptions.cs +++ b/src/mono/wasm/Wasm.Build.Tests/BrowserStructures/MSBuildOptions.cs @@ -10,9 +10,9 @@ namespace Wasm.Build.Tests; public abstract record MSBuildOptions ( bool IsPublish, + string TargetFramework, bool AOT = false, NativeFilesType ExpectedFileType = NativeFilesType.FromRuntimePack, - string TargetFramework = BuildTestBase.DefaultTargetFramework, GlobalizationMode GlobalizationMode = GlobalizationMode.Sharded, string CustomIcuFile = "", bool UseCache = true, diff --git a/src/mono/wasm/Wasm.Build.Tests/BrowserStructures/PublishOptions.cs b/src/mono/wasm/Wasm.Build.Tests/BrowserStructures/PublishOptions.cs index 8d8d543d1bcc52..3e5634f338bb18 100644 --- a/src/mono/wasm/Wasm.Build.Tests/BrowserStructures/PublishOptions.cs +++ b/src/mono/wasm/Wasm.Build.Tests/BrowserStructures/PublishOptions.cs @@ -16,7 +16,7 @@ public PublishOptions( bool IsPublish = true, bool AOT = false, NativeFilesType ExpectedFileType = NativeFilesType.FromRuntimePack, - string TargetFramework = BuildTestBase.DefaultTargetFramework, + string? TargetFramework = null, GlobalizationMode GlobalizationMode = GlobalizationMode.Sharded, string CustomIcuFile = "", bool UseCache = true, @@ -34,9 +34,9 @@ public PublishOptions( bool FeaturePerfTracing = false ) : base( IsPublish, + TargetFramework ?? BuildTestBase.DefaultTargetFramework, AOT, ExpectedFileType, - TargetFramework, GlobalizationMode, CustomIcuFile, UseCache, diff --git a/src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs b/src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs index 6a6cb7103631e2..4155c5fbfe1d8b 100644 --- a/src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs +++ b/src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs @@ -26,9 +26,11 @@ namespace Wasm.Build.Tests { public abstract class BuildTestBase : IClassFixture, IDisposable { - public const string DefaultTargetFramework = "net10.0"; - public const string DefaultTargetFrameworkForBlazor = "net10.0"; - public const string TargetFrameworkForTasks = "net10.0"; + public static readonly string DefaultTargetFramework = $"net{Environment.Version.Major}.0"; + public static readonly string PreviousTargetFramework = $"net{Environment.Version.Major - 1}.0"; + public static readonly string Previous2TargetFramework = $"net{Environment.Version.Major - 2}.0"; + public static readonly string DefaultTargetFrameworkForBlazor = $"net{Environment.Version.Major}.0"; + public static readonly string TargetFrameworkForTasks = $"net{Environment.Version.Major}.0"; private const string DefaultEnvironmentLocale = "en-US"; protected static readonly string s_unicodeChars = "\u9FC0\u8712\u679B\u906B\u486B\u7149"; protected static readonly bool s_skipProjectCleanup; @@ -62,7 +64,7 @@ public abstract class BuildTestBase : IClassFixture s_buildEnv.IsWorkloadWithMultiThreadingForDefaultFramework; public static bool UseWebcil => s_buildEnv.UseWebcil; public static string GetNuGetConfigPathFor(string targetFramework) - => Path.Combine(BuildEnvironment.TestDataPath, targetFramework == "net10.0" ? "nuget10.config" : "nuget9.config"); + => Path.Combine(BuildEnvironment.TestDataPath, "nuget.config"); public TProvider GetProvider() where TProvider : ProjectProviderBase => (TProvider)_providerOfBaseType; @@ -230,8 +232,9 @@ private string GetBinlogMessageContext(TextNode node) return (_logPath, _nugetPackagesDir); } - protected void InitProjectDir(string dir, bool addNuGetSourceForLocalPackages = true, string targetFramework = DefaultTargetFramework) + protected void InitProjectDir(string dir, bool addNuGetSourceForLocalPackages = true, string? targetFramework = null) { + targetFramework ??= DefaultTargetFramework; if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); Directory.CreateDirectory(dir); diff --git a/src/mono/wasm/Wasm.Build.Tests/Common/BuildEnvironment.cs b/src/mono/wasm/Wasm.Build.Tests/Common/BuildEnvironment.cs index 0b71e4d663015e..e21004e5aab04e 100644 --- a/src/mono/wasm/Wasm.Build.Tests/Common/BuildEnvironment.cs +++ b/src/mono/wasm/Wasm.Build.Tests/Common/BuildEnvironment.cs @@ -162,18 +162,18 @@ public BuildEnvironment() Directory.CreateDirectory(TmpPath); } - public string GetRuntimePackVersion(string tfm = BuildTestBase.DefaultTargetFramework) + public string GetRuntimePackVersion(string tfm) => s_runtimePackVersions.TryGetValue(tfm, out string? version) ? version : throw new ArgumentException($"No runtime pack version found for tfm={tfm} ."); - public string GetRuntimePackDir(string tfm = BuildTestBase.DefaultTargetFramework, RuntimeVariant runtimeType = RuntimeVariant.SingleThreaded) + public string GetRuntimePackDir(string tfm, RuntimeVariant runtimeType = RuntimeVariant.SingleThreaded) => Path.Combine(WorkloadPacksDir, runtimeType is RuntimeVariant.SingleThreaded ? $"Microsoft.NETCore.App.Runtime.Mono.{DefaultRuntimeIdentifier}" : $"Microsoft.NETCore.App.Runtime.Mono.multithread.{DefaultRuntimeIdentifier}", GetRuntimePackVersion(tfm)); - public string GetRuntimeNativeDir(string tfm = BuildTestBase.DefaultTargetFramework, RuntimeVariant runtimeType = RuntimeVariant.SingleThreaded) + public string GetRuntimeNativeDir(string tfm, RuntimeVariant runtimeType = RuntimeVariant.SingleThreaded) => Path.Combine(GetRuntimePackDir(tfm, runtimeType), "runtimes", DefaultRuntimeIdentifier, "native"); public bool IsMultiThreadingRuntimePackAvailableFor(string tfm) => IsWorkload && File.Exists(Path.Combine(GetRuntimeNativeDir(tfm, RuntimeVariant.MultiThreaded), "dotnet.native.worker.mjs")); diff --git a/src/mono/wasm/Wasm.Build.Tests/NonWasmTemplateBuildTests.cs b/src/mono/wasm/Wasm.Build.Tests/NonWasmTemplateBuildTests.cs index 55d4f9e34887a1..c6e0134797e771 100644 --- a/src/mono/wasm/Wasm.Build.Tests/NonWasmTemplateBuildTests.cs +++ b/src/mono/wasm/Wasm.Build.Tests/NonWasmTemplateBuildTests.cs @@ -1,6 +1,7 @@ // 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.IO; using System.Linq; @@ -23,10 +24,10 @@ public NonWasmTemplateBuildTests(ITestOutputHelper output, SharedBuildPerTestCla // So, copy the reference for latest TFM, and add that back with the // TFM=DefaultTargetFramework // - // This is useful for the case when we are on tfm=net10.0, but sdk, and packages - // are really 10.0 . - private const string s_latestTargetFramework = "net10.0"; - private const string s_previousTargetFramework = "net9.0"; + // This is useful for the case when we are on latest TFM, but sdk, and packages + // are really the previous version . + private static readonly string s_latestTargetFramework = $"net{Environment.Version.Major}.0"; + private static readonly string s_previousTargetFramework = $"net{Environment.Version.Major - 1}.0"; private static string s_directoryBuildTargetsForPreviousTFM = $$""" @@ -69,7 +70,6 @@ public NonWasmTemplateBuildTests(ITestOutputHelper output, SharedBuildPerTestCla ( EnvironmentVariables.WorkloadsTestPreviousVersions ? [ - "net6.0", s_previousTargetFramework, s_latestTargetFramework ] @@ -83,7 +83,6 @@ public void NonWasmConsoleBuild_WithoutWorkload(Configuration config, string ext => NonWasmConsoleBuild(config, extraBuildArgs, targetFramework, - // net6 is sdk would be needed to run the app shouldRun: targetFramework == s_latestTargetFramework); [Theory] @@ -92,7 +91,6 @@ public void NonWasmConsoleBuild_WithWorkload(Configuration config, string extraB => NonWasmConsoleBuild(config, extraBuildArgs, targetFramework, - // net6 is sdk would be needed to run the app shouldRun: targetFramework == s_latestTargetFramework); private void NonWasmConsoleBuild(Configuration config, diff --git a/src/mono/wasm/Wasm.Build.Tests/Templates/WasmTemplateTests.cs b/src/mono/wasm/Wasm.Build.Tests/Templates/WasmTemplateTests.cs index eb56d5393aed52..679d645130f3b1 100644 --- a/src/mono/wasm/Wasm.Build.Tests/Templates/WasmTemplateTests.cs +++ b/src/mono/wasm/Wasm.Build.Tests/Templates/WasmTemplateTests.cs @@ -108,12 +108,12 @@ private async Task BrowserRunTwiceWithAndThenWithoutBuildAsync(Configuration con public static IEnumerable BrowserBuildAndRunTestData() { yield return new object?[] { "", BuildTestBase.DefaultTargetFramework, DefaultRuntimeAssetsRelativePath }; - yield return new object?[] { "-f net10.0", "net10.0", DefaultRuntimeAssetsRelativePath }; + yield return new object?[] { $"-f {DefaultTargetFramework}", DefaultTargetFramework, DefaultRuntimeAssetsRelativePath }; if (EnvironmentVariables.WorkloadsTestPreviousVersions) { - yield return new object?[] { "-f net9.0", "net9.0", DefaultRuntimeAssetsRelativePath }; - yield return new object?[] { "-f net8.0", "net8.0", DefaultRuntimeAssetsRelativePath }; + yield return new object?[] { $"-f {PreviousTargetFramework}", PreviousTargetFramework, DefaultRuntimeAssetsRelativePath }; + yield return new object?[] { $"-f {Previous2TargetFramework}", Previous2TargetFramework, DefaultRuntimeAssetsRelativePath }; } // ActiveIssue("https://github.com/dotnet/runtime/issues/90979") diff --git a/src/mono/wasm/Wasm.Build.Tests/Templates/WasmTemplateTestsBase.cs b/src/mono/wasm/Wasm.Build.Tests/Templates/WasmTemplateTestsBase.cs index 3b70408b34732d..bbdfcf6d92e51f 100644 --- a/src/mono/wasm/Wasm.Build.Tests/Templates/WasmTemplateTestsBase.cs +++ b/src/mono/wasm/Wasm.Build.Tests/Templates/WasmTemplateTestsBase.cs @@ -225,8 +225,9 @@ protected void DeleteFile(string pathRelativeToProjectDir) } } - protected void UpdateBrowserMainJs(string targetFramework = DefaultTargetFramework, string runtimeAssetsRelativePath = DefaultRuntimeAssetsRelativePath) + protected void UpdateBrowserMainJs(string? targetFramework = null, string runtimeAssetsRelativePath = DefaultRuntimeAssetsRelativePath) { + targetFramework ??= DefaultTargetFramework; string mainJsPath = Path.Combine(_projectDir, "wwwroot", "main.js"); string mainJsContent = File.ReadAllText(mainJsPath); Version targetFrameworkVersion = new Version(targetFramework.Replace("net", "")); @@ -366,8 +367,8 @@ void OnErrorMessage(string msg) } } - public string GetBinFrameworkDir(Configuration config, bool forPublish, string framework = DefaultTargetFramework, string? projectDir = null) => - _provider.GetBinFrameworkDir(config, forPublish, framework, projectDir); + public string GetBinFrameworkDir(Configuration config, bool forPublish, string? framework = null, string? projectDir = null) => + _provider.GetBinFrameworkDir(config, forPublish, framework ?? DefaultTargetFramework, projectDir); public BuildPaths GetBuildPaths(Configuration config, bool forPublish) => _provider.GetBuildPaths(config, forPublish); diff --git a/src/mono/wasm/Wasm.Build.Tests/data/nuget10.config b/src/mono/wasm/Wasm.Build.Tests/data/nuget.config similarity index 86% rename from src/mono/wasm/Wasm.Build.Tests/data/nuget10.config rename to src/mono/wasm/Wasm.Build.Tests/data/nuget.config index bd07cf50b12f61..681e028857c2dc 100644 --- a/src/mono/wasm/Wasm.Build.Tests/data/nuget10.config +++ b/src/mono/wasm/Wasm.Build.Tests/data/nuget.config @@ -7,6 +7,7 @@ + diff --git a/src/mono/wasm/Wasm.Build.Tests/data/nuget9.config b/src/mono/wasm/Wasm.Build.Tests/data/nuget9.config deleted file mode 100644 index 8de8b907205ca6..00000000000000 --- a/src/mono/wasm/Wasm.Build.Tests/data/nuget9.config +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/src/mono/wasm/Wasm.Build.Tests/data/test-main-7.0.js b/src/mono/wasm/Wasm.Build.Tests/data/test-main-7.0.js deleted file mode 100644 index 3b32add2f39e57..00000000000000 --- a/src/mono/wasm/Wasm.Build.Tests/data/test-main-7.0.js +++ /dev/null @@ -1,355 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// -*- mode: js; js-indent-level: 4; -*- -// -// Run runtime tests under a JS shell or a browser -// -"use strict"; - - -/***************************************************************************** - * Please don't use this as template for startup code. - * There are simpler and better samples like src\mono\sample\wasm\browser\main.js - * This one is not ES6 nor CJS, doesn't use top level await and has edge case polyfills. - * It handles strange things which happen with XHarness. - ****************************************************************************/ - - -//glue code to deal with the differences between chrome, ch, d8, jsc and sm. -const is_browser = typeof window != "undefined"; -const is_node = !is_browser && typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node === 'string'; - -if (is_node && process.versions.node.split(".")[0] < 14) { - throw new Error(`NodeJS at '${process.execPath}' has too low version '${process.versions.node}'`); -} - -if (is_node) { - // the emscripten 3.1.34 stopped handling these when MODULARIZE is enabled - process.on('uncaughtException', function(ex) { - // ignore UnhandledPromiseRejection exceptions with exit status - if (ex !== 'unwind' && (ex.name !== "UnhandledPromiseRejection" || !ex.message.includes('"#"'))) { - throw ex; - } - }); -} - -if (typeof globalThis.crypto === 'undefined') { - // **NOTE** this is a simple insecure polyfill for testing purposes only - // /dev/random doesn't work on js shells, so define our own - // See library_fs.js:createDefaultDevices () - globalThis.crypto = { - getRandomValues: function (buffer) { - for (let i = 0; i < buffer.length; i++) - buffer[i] = (Math.random() * 256) | 0; - } - } -} - -let v8args; -if (typeof arguments !== "undefined") { - // this must be captured in top level scope in V8 - v8args = arguments; -} - -async function getArgs() { - let queryArguments = []; - if (is_node) { - queryArguments = process.argv.slice(2); - } else if (is_browser) { - // We expect to be run by tests/runtime/run.js which passes in the arguments using http parameters - const url = new URL(decodeURI(window.location)); - let urlArguments = [] - for (let param of url.searchParams) { - if (param[0] == "arg") { - urlArguments.push(param[1]); - } - } - queryArguments = urlArguments; - } else if (v8args !== undefined) { - queryArguments = Array.from(v8args); - } else if (typeof scriptArgs !== "undefined") { - queryArguments = Array.from(scriptArgs); - } else if (typeof WScript !== "undefined" && WScript.Arguments) { - queryArguments = Array.from(WScript.Arguments); - } - - let runArgs; - if (queryArguments.length > 0) { - runArgs = processArguments(queryArguments); - } else { - const response = fetch('/runArgs.json') - if (!response.ok) { - console.debug(`could not load /args.json: ${response.status}. Ignoring`); - } - runArgs = await response.json(); - } - runArgs = initRunArgs(runArgs); - - return runArgs; -} - -function initRunArgs(runArgs) { - // set defaults - runArgs.applicationArguments = runArgs.applicationArguments === undefined ? [] : runArgs.applicationArguments; - runArgs.profilers = runArgs.profilers === undefined ? [] : runArgs.profilers; - runArgs.workingDirectory = runArgs.workingDirectory === undefined ? '/' : runArgs.workingDirectory; - runArgs.environmentVariables = runArgs.environmentVariables === undefined ? {} : runArgs.environmentVariables; - runArgs.runtimeArgs = runArgs.runtimeArgs === undefined ? [] : runArgs.runtimeArgs; - runArgs.enableGC = runArgs.enableGC === undefined ? true : runArgs.enableGC; - runArgs.diagnosticTracing = runArgs.diagnosticTracing === undefined ? false : runArgs.diagnosticTracing; - runArgs.debugging = runArgs.debugging === undefined ? false : runArgs.debugging; - runArgs.configSrc = runArgs.configSrc === undefined ? './mono-config.json' : runArgs.configSrc; - // default'ing to true for tests, unless debugging - runArgs.forwardConsole = runArgs.forwardConsole === undefined ? !runArgs.debugging : runArgs.forwardConsole; - - return runArgs; -} - -function processArguments(incomingArguments) { - const runArgs = initRunArgs({}); - - console.log("Incoming arguments: " + incomingArguments.join(' ')); - while (incomingArguments && incomingArguments.length > 0) { - const currentArg = incomingArguments[0]; - if (currentArg.startsWith("--profile=")) { - const arg = currentArg.substring("--profile=".length); - runArgs.profilers.push(arg); - } else if (currentArg.startsWith("--setenv=")) { - const arg = currentArg.substring("--setenv=".length); - const parts = arg.split('='); - if (parts.length != 2) - set_exit_code(1, "Error: malformed argument: '" + currentArg); - runArgs.environmentVariables[parts[0]] = parts[1]; - } else if (currentArg.startsWith("--runtime-arg=")) { - const arg = currentArg.substring("--runtime-arg=".length); - runArgs.runtimeArgs.push(arg); - } else if (currentArg == "--disable-on-demand-gc") { - runArgs.enableGC = false; - } else if (currentArg == "--diagnostic-tracing") { - runArgs.diagnosticTracing = true; - } else if (currentArg.startsWith("--working-dir=")) { - const arg = currentArg.substring("--working-dir=".length); - runArgs.workingDirectory = arg; - } else if (currentArg == "--debug") { - runArgs.debugging = true; - } else if (currentArg == "--no-forward-console") { - runArgs.forwardConsole = false; - } else if (currentArg.startsWith("--fetch-random-delay=")) { - const arg = currentArg.substring("--fetch-random-delay=".length); - if (is_browser) { - const delayms = Number.parseInt(arg) || 100; - const originalFetch = globalThis.fetch; - globalThis.fetch = async (url, options) => { - // random sleep - const ms = delayms + (Math.random() * delayms); - console.log(`fetch ${url} started ${ms}`) - await new Promise(resolve => setTimeout(resolve, ms)); - console.log(`fetch ${url} delayed ${ms}`) - const res = await originalFetch(url, options); - console.log(`fetch ${url} done ${ms}`) - return res; - } - } else { - console.warn("--fetch-random-delay only works on browser") - } - } else if (currentArg.startsWith("--config-src=")) { - const arg = currentArg.substring("--config-src=".length); - runArgs.configSrc = arg; - } else { - break; - } - incomingArguments = incomingArguments.slice(1); - } - - runArgs.applicationArguments = incomingArguments; - // cheap way to let the testing infrastructure know we're running in a browser context (or not) - runArgs.environmentVariables["IsBrowserDomSupported"] = is_browser.toString().toLowerCase(); - runArgs.environmentVariables["IsNodeJS"] = is_node.toString().toLowerCase(); - - return runArgs; -} - -// we may have dependencies on NPM packages, depending on the test case -// some of them polyfill for browser built-in stuff -function loadNodeModules(config, require, modulesToLoad) { - modulesToLoad.split(',').forEach(module => { - const { 0: moduleName, 1: globalAlias } = module.split(':'); - - let message = `Loading npm '${moduleName}'`; - let moduleExport = require(moduleName); - - if (globalAlias) { - message += ` and attaching to global as '${globalAlias}'`; - globalThis[globalAlias] = moduleExport; - } else if (moduleName == "node-fetch") { - message += ' and attaching to global'; - globalThis.fetch = moduleExport.default; - globalThis.Headers = moduleExport.Headers; - globalThis.Request = moduleExport.Request; - globalThis.Response = moduleExport.Response; - } else if (moduleName == "node-abort-controller") { - message += ' and attaching to global'; - globalThis.AbortController = moduleExport.AbortController; - } - - console.log(message); - }); - // Must be after loading npm modules. - config.environmentVariables["IsWebSocketSupported"] = ("WebSocket" in globalThis).toString().toLowerCase(); -} - -let mono_exit = (code, reason) => { - console.log(`test-main failed early ${code} ${reason}`); -}; - -async function loadDotnet(file) { - return await import(file); -} - -const App = { - /** Runs a particular test in legacy interop tests - * @type {(method_name: string, args: any[]=, signature: any=) => return number} - */ - call_test_method: function (method_name, args, signature) { - // note: arguments here is the array of arguments passsed to this function - if ((arguments.length > 2) && (typeof (signature) !== "string")) - throw new Error("Invalid number of arguments for call_test_method"); - - const fqn = "[System.Private.Runtime.InteropServices.JavaScript.Tests]System.Runtime.InteropServices.JavaScript.Tests.HelperMarshal:" + method_name; - try { - const method = App.runtime.BINDING.bind_static_method(fqn, signature); - return method.apply(null, args || []); - } catch (exc) { - console.error("exception thrown in", fqn); - throw exc; - } - }, - - create_function(...args) { - const code = args.pop(); - const arg_count = args.length; - args.push("MONO"); - args.push("BINDING"); - args.push("INTERNAL"); - - const userFunction = new Function(...args, code); - return function (...args) { - args[arg_count + 0] = globalThis.App.runtime.MONO; - args[arg_count + 1] = globalThis.App.runtime.BINDING; - args[arg_count + 2] = globalThis.App.runtime.INTERNAL; - return userFunction(...args); - }; - }, - - invoke_js(js_code) { - const closedEval = function (Module, MONO, BINDING, INTERNAL, code) { - return eval(code); - }; - const res = closedEval(globalThis.App.runtime.Module, globalThis.App.runtime.MONO, globalThis.App.runtime.BINDING, globalThis.App.runtime.INTERNAL, js_code); - return (res === undefined || res === null || typeof res === "string") - ? null - : res.toString(); - } -}; -globalThis.App = App; // Necessary as System.Runtime.InteropServices.JavaScript.Tests.MarshalTests (among others) call the App.call_test_method directly - -async function run() { - try { - const { dotnet, exit, INTERNAL } = await loadDotnet('./dotnet.js'); - mono_exit = exit; - - const runArgs = await getArgs(); - if (runArgs.applicationArguments.length == 0) { - mono_exit(1, "Missing required --run argument"); - return; - } - console.log("Application arguments: " + runArgs.applicationArguments.join(' ')); - - dotnet - .withVirtualWorkingDirectory(runArgs.workingDirectory) - .withEnvironmentVariables(runArgs.environmentVariables) - .withDiagnosticTracing(runArgs.diagnosticTracing) - .withExitCodeLogging() - .withElementOnExit(); - - if (is_node) { - dotnet - .withEnvironmentVariable("NodeJSPlatform", process.platform) - .withAsyncFlushOnExit(); - - const modulesToLoad = runArgs.environmentVariables["NPM_MODULES"]; - if (modulesToLoad) { - dotnet.withModuleConfig({ - onConfigLoaded: (config) => { - loadNodeModules(config, INTERNAL.require, modulesToLoad) - } - }) - } - } - if (is_browser) { - dotnet.withEnvironmentVariable("IsWebSocketSupported", "true"); - } - if (runArgs.runtimeArgs.length > 0) { - dotnet.withRuntimeOptions(runArgs.runtimeArgs); - } - if (runArgs.debugging) { - dotnet.withDebugging(-1); - dotnet.withWaitingForDebugger(-1); - } - if (runArgs.forwardConsole) { - dotnet.withConsoleForwarding(); - } - App.runtime = await dotnet.create(); - App.runArgs = runArgs - - console.info("Initializing....."); - - for (let i = 0; i < runArgs.profilers.length; ++i) { - const init = App.runtime.Module.cwrap('mono_wasm_load_profiler_' + runArgs.profilers[i], 'void', ['string']); - init(""); - } - - - if (runArgs.applicationArguments[0] == "--regression") { - const exec_regression = App.runtime.Module.cwrap('mono_wasm_exec_regression', 'number', ['number', 'string']); - - let res = 0; - try { - res = exec_regression(10, runArgs.applicationArguments[1]); - console.log("REGRESSION RESULT: " + res); - } catch (e) { - console.error("ABORT: " + e); - console.error(e.stack); - res = 1; - } - - if (res) mono_exit(1, "REGRESSION TEST FAILED"); - - return; - } - - if (runArgs.applicationArguments[0] == "--run") { - // Run an exe - if (runArgs.applicationArguments.length == 1) { - mono_exit(1, "Error: Missing main executable argument."); - return; - } - try { - const main_assembly_name = runArgs.applicationArguments[1]; - const app_args = runArgs.applicationArguments.slice(2); - const result = await App.runtime.runMain(main_assembly_name, app_args); - mono_exit(result); - } catch (error) { - if (error.name != "ExitStatus") { - mono_exit(1, error); - } - } - } else { - mono_exit(1, "Unhandled argument: " + runArgs.applicationArguments[0]); - } - } catch (err) { - mono_exit(1, err) - } -} - -run(); \ No newline at end of file