diff --git a/.chronus/changes/python-browser-wheel-assets-2026-09-28.md b/.chronus/changes/python-browser-wheel-assets-2026-09-28.md new file mode 100644 index 00000000000..5aa7d5491e1 --- /dev/null +++ b/.chronus/changes/python-browser-wheel-assets-2026-09-28.md @@ -0,0 +1,7 @@ +--- +changeKind: fix +packages: + - "@typespec/http-client-python" +--- + +Retry Playground Python generation with published runtime and CFS-built Python wheels when public package services are unavailable. diff --git a/packages/http-client-python/emitter/src/browser-runtime.ts b/packages/http-client-python/emitter/src/browser-runtime.ts new file mode 100644 index 00000000000..6589245f855 --- /dev/null +++ b/packages/http-client-python/emitter/src/browser-runtime.ts @@ -0,0 +1,85 @@ +import pkgJson from "../../package.json" with { type: "json" }; +import { + BLOB_STORAGE_BASE_URL, + PACKAGE_NAME, + PYGEN_WHEEL_FILENAME, + PYODIDE_VERSION, +} from "./constants.js"; +import type { PyodideInterface } from "./pyodide-loader.js"; +import { loadPyodide } from "./pyodide-loader.js"; + +function getBrowserPygenWheelUrl(): string { + return `${BLOB_STORAGE_BASE_URL}/${PACKAGE_NAME}/${pkgJson.version}/generator/dist/${PYGEN_WHEEL_FILENAME}`; +} + +let browserPyodidePromise: Promise | undefined; + +/** + * Boot the Pyodide runtime lazily, on the first browser emit. + * + * This must not happen when the module is imported: hosts like the TypeSpec playground import every + * available emitter up front, and booting Pyodide downloads a full CPython WebAssembly runtime plus + * its wheels (~10MB, ~290MB of resident memory). Doing that eagerly pushed the playground past the + * per-tab memory budget on mobile browsers, which made the page fail to load. + */ +export function getBrowserPyodide(): Promise | null { + if (typeof window === "undefined") { + return null; + } + if (browserPyodidePromise === undefined) { + browserPyodidePromise = setupPyodideCallBrowser().catch((error) => { + // Clear the cached promise so a later emit can retry after a transient failure. + browserPyodidePromise = undefined; + throw error; + }); + } + return browserPyodidePromise; +} + +async function setupPyodideCallBrowser(): Promise { + let pyodide: PyodideInterface | undefined; + try { + pyodide = await loadPyodide({ + indexURL: `https://cdn.jsdelivr.net/pyodide/v${PYODIDE_VERSION}/full/`, + }); + pyodide.FS.mkdirTree("/generator"); + await pyodide.loadPackage("micropip"); + await pyodide.pyimport("micropip").install(getBrowserPygenWheelUrl()); + return pyodide; + } catch (publicError) { + try { + const assetsUrl = `${BLOB_STORAGE_BASE_URL}/${PACKAGE_NAME}/${pkgJson.version}/generator/dist`; + pyodide ??= await loadPyodide({ indexURL: `${assetsUrl}/pyodide/` }); + pyodide.FS.mkdirTree("/generator"); + const response = await fetch(`${assetsUrl}/browser-wheels.json`); + if (!response.ok) { + throw new Error(`Failed to load browser Python wheels: ${response.status}`); + } + const wheels: unknown = await response.json(); + if ( + !Array.isArray(wheels) || + wheels.length < 3 || + !wheels.every( + (name) => + typeof name === "string" && + /^[A-Za-z0-9_]+-[A-Za-z0-9_.-]+-(?:py3|py2\.py3)-none-any\.whl$/.test(name), + ) || + !wheels[0].startsWith("packaging-") || + !wheels[1].startsWith("micropip-") + ) { + throw new Error("Invalid browser Python wheel manifest"); + } + const urls = wheels.map((name) => `${assetsUrl}/browser-wheels/${name}`); + await pyodide.loadPackage(urls.slice(0, 2)); + await pyodide + .pyimport("micropip") + .install.callKwargs([...urls.slice(2), getBrowserPygenWheelUrl()], { deps: false }); + return pyodide; + } catch (hostedError) { + throw new AggregateError( + [publicError, hostedError], + `Public Python runtime failed (${String(publicError)}); hosted fallback failed (${String(hostedError)})`, + ); + } + } +} diff --git a/packages/http-client-python/emitter/src/emitter.ts b/packages/http-client-python/emitter/src/emitter.ts index c68517f99f4..ec7bdcc7cdf 100644 --- a/packages/http-client-python/emitter/src/emitter.ts +++ b/packages/http-client-python/emitter/src/emitter.ts @@ -1,26 +1,15 @@ import { createSdkContext } from "@azure-tools/typespec-client-generator-core"; import type { EmitContext } from "@typespec/compiler"; import { emitFile, joinPaths, listServices, NoTarget } from "@typespec/compiler"; -import pkgJson from "../../package.json" with { type: "json" }; +import { getBrowserPyodide } from "./browser-runtime.js"; import { emitCodeModel } from "./code-model.js"; -import { - BLOB_STORAGE_BASE_URL, - PACKAGE_NAME, - PYGEN_WHEEL_FILENAME, - PYODIDE_VERSION, -} from "./constants.js"; import type { PythonEmitterOptions, PythonSdkContext } from "./lib.js"; import { reportDiagnostic } from "./lib.js"; import { runNodeEmit } from "./node-runner.js"; import type { PyodideInterface } from "./pyodide-loader.js"; -import { loadPyodide } from "./pyodide-loader.js"; import { getRootNamespace, md2Rst } from "./utils.js"; import { dumpCodeModelToYaml } from "./yaml-utils.js"; -function getBrowserPygenWheelUrl(): string { - return `${BLOB_STORAGE_BASE_URL}/${PACKAGE_NAME}/${pkgJson.version}/generator/dist/${PYGEN_WHEEL_FILENAME}`; -} - function addDefaultOptions(sdkContext: PythonSdkContext) { const defaultOptions = { "package-version": "1.0.0b1", @@ -258,30 +247,6 @@ async function onEmitMain(context: EmitContext) { } } -let browserPyodidePromise: Promise | undefined; - -/** - * Boot the Pyodide runtime lazily, on the first browser emit. - * - * This must not happen when the module is imported: hosts like the TypeSpec playground import every - * available emitter up front, and booting Pyodide downloads a full CPython WebAssembly runtime plus - * its wheels (~10MB, ~290MB of resident memory). Doing that eagerly pushed the playground past the - * per-tab memory budget on mobile browsers, which made the page fail to load. - */ -function getBrowserPyodide(): Promise | null { - if (typeof window === "undefined") { - return null; - } - if (browserPyodidePromise === undefined) { - browserPyodidePromise = setupPyodideCallBrowser().catch((error) => { - // Clear the cached promise so a later emit can retry after a transient failure. - browserPyodidePromise = undefined; - throw error; - }); - } - return browserPyodidePromise; -} - function clearMemfsDirectory(pyodide: PyodideInterface, dir: string): void { const entries: string[] = pyodide.FS.readdir(dir).filter( (entry: string) => entry !== "." && entry !== "..", @@ -297,17 +262,3 @@ function clearMemfsDirectory(pyodide: PyodideInterface, dir: string): void { } } } - -async function setupPyodideCallBrowser() { - const pyodide = await loadPyodide({ - indexURL: `https://cdn.jsdelivr.net/pyodide/v${PYODIDE_VERSION}/full/`, - }); - - // use default MEMFS for browser, since NODEFS is not supported - pyodide.FS.mkdirTree("/generator"); - await pyodide.loadPackage("micropip"); - const micropip = pyodide.pyimport("micropip"); - await micropip.install(getBrowserPygenWheelUrl()); - - return pyodide; -} diff --git a/packages/http-client-python/emitter/test/browser-pyodide.test.ts b/packages/http-client-python/emitter/test/browser-pyodide.test.ts index 09bad2b8471..327900e3424 100644 --- a/packages/http-client-python/emitter/test/browser-pyodide.test.ts +++ b/packages/http-client-python/emitter/test/browser-pyodide.test.ts @@ -1,5 +1,7 @@ +import { expectDiagnostics } from "@typespec/compiler/testing"; import { strictEqual } from "assert"; -import { afterEach, describe, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import pkgJson from "../../package.json" with { type: "json" }; const loadPyodide = vi.hoisted(() => vi.fn()); @@ -7,19 +9,142 @@ vi.mock("../src/pyodide-loader.js", () => ({ loadPyodide })); describe("typespec-python: browser pyodide bootstrap", () => { afterEach(() => { - delete (globalThis as any).window; + vi.unstubAllGlobals(); loadPyodide.mockReset(); vi.resetModules(); }); - // Hosts like the TypeSpec playground import every available emitter up front. Booting Pyodide at - // module scope downloaded a full CPython WebAssembly runtime on every page load, which pushed the - // page past the per-tab memory budget on mobile browsers and prevented it from loading. - it("does not boot pyodide when the emitter is imported in a browser", async () => { - (globalThis as any).window = globalThis; + it("does not load a browser runtime outside the browser", async () => { + const { getBrowserPyodide } = await import("../src/browser-runtime.js"); - await import("../src/emitter.js"); + strictEqual(getBrowserPyodide(), null); + expect(loadPyodide).not.toHaveBeenCalled(); + }); + + const assetsUrl = `https://typespec.blob.core.windows.net/pkgs/@typespec/http-client-python/${pkgJson.version}/generator/dist`; + const wheels = [ + "packaging-23.2-py3-none-any.whl", + "micropip-0.6.0-py3-none-any.whl", + "PyYAML-6.0.1-py3-none-any.whl", + "colorama-0.4.6-py2.py3-none-any.whl", + ]; + + function runtime() { + return { + FS: { + mkdirTree: vi.fn(), + writeFile: vi.fn(), + readdir: vi.fn().mockReturnValue([".", ".."]), + }, + loadPackage: vi.fn().mockResolvedValue(undefined), + pyimport: vi.fn().mockReturnValue({ + install: Object.assign(vi.fn().mockResolvedValue(undefined), { + callKwargs: vi.fn().mockResolvedValue(undefined), + }), + }), + toPy: vi.fn().mockReturnValue({ destroy: vi.fn() }), + runPythonAsync: vi.fn().mockResolvedValue(undefined), + }; + } + + async function emit() { + vi.resetModules(); + vi.stubGlobal("window", globalThis); + const { EmitterTester } = await import("./test-host.js"); + const [, diagnostics] = await EmitterTester.compileAndDiagnose( + "@service namespace Service { op read(): string; }", + ); + return diagnostics; + } + + it("does not request fallback assets when public packages are available", async () => { + const pyodide = runtime(); + loadPyodide.mockResolvedValue(pyodide); + const fetchAssets = vi.fn(); + vi.stubGlobal("fetch", fetchAssets); + + expectDiagnostics(await emit(), []); + expect(loadPyodide).toHaveBeenCalledExactlyOnceWith({ + indexURL: "https://cdn.jsdelivr.net/pyodide/v0.26.2/full/", + }); + expect(pyodide.loadPackage).toHaveBeenCalledExactlyOnceWith("micropip"); + expect(pyodide.pyimport().install).toHaveBeenCalledExactlyOnceWith( + `${assetsUrl}/pygen-0.1.0-py3-none-any.whl`, + ); + expect(fetchAssets).not.toHaveBeenCalled(); + }); + + it("loads hosted runtime and CFS-built wheels after a CDN failure", async () => { + const pyodide = runtime(); + loadPyodide.mockRejectedValueOnce(new Error("CDN blocked")).mockResolvedValueOnce(pyodide); + vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => wheels })); + + expectDiagnostics(await emit(), []); + expect(loadPyodide).toHaveBeenNthCalledWith(2, { indexURL: `${assetsUrl}/pyodide/` }); + expect(pyodide.loadPackage).toHaveBeenCalledWith([ + `${assetsUrl}/browser-wheels/${wheels[0]}`, + `${assetsUrl}/browser-wheels/${wheels[1]}`, + ]); + expect(pyodide.pyimport().install.callKwargs).toHaveBeenCalledExactlyOnceWith( + [ + ...wheels.slice(2).map((name) => `${assetsUrl}/browser-wheels/${name}`), + `${assetsUrl}/pygen-0.1.0-py3-none-any.whl`, + ], + { deps: false }, + ); + }); + + it("reuses the runtime when loading public micropip fails", async () => { + const pyodide = runtime(); + pyodide.loadPackage.mockRejectedValueOnce(new Error("Package CDN blocked")); + loadPyodide.mockResolvedValue(pyodide); + vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => wheels })); + + expectDiagnostics(await emit(), []); + expect(loadPyodide).toHaveBeenCalledOnce(); + expect(pyodide.pyimport().install).not.toHaveBeenCalled(); + expect(pyodide.pyimport().install.callKwargs).toHaveBeenCalledOnce(); + }); + + it("reuses the runtime after public Python package installation fails", async () => { + const pyodide = runtime(); + pyodide.pyimport().install.mockRejectedValueOnce(new Error("PyPI blocked")); + loadPyodide.mockResolvedValue(pyodide); + vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => wheels })); + + expectDiagnostics(await emit(), []); + expect(loadPyodide).toHaveBeenCalledOnce(); + expect(pyodide.pyimport().install.callKwargs).toHaveBeenLastCalledWith( + expect.arrayContaining([`${assetsUrl}/pygen-0.1.0-py3-none-any.whl`]), + { deps: false }, + ); + }); + + it.each([ + { ok: false, status: 404 }, + { ok: true, json: async () => ["../invalid.whl"] }, + { ok: true, json: async () => [wheels[1]] }, + ])("reports invalid or missing fallback wheels", async (response) => { + const pyodide = runtime(); + loadPyodide.mockRejectedValueOnce(new Error("CDN blocked")).mockResolvedValueOnce(pyodide); + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response)); + + expectDiagnostics(await emit(), { + code: "@typespec/http-client-python/unknown-error", + message: /CDN blocked.*(?:404|Invalid browser Python wheel manifest)/s, + }); + expect(pyodide.pyimport().install).not.toHaveBeenCalled(); + expect(pyodide.pyimport().install.callKwargs).not.toHaveBeenCalled(); + }); + + it("reports both failures when the public and hosted runtimes cannot load", async () => { + loadPyodide + .mockRejectedValueOnce(new Error("CDN blocked")) + .mockRejectedValueOnce(new Error("Hosted runtime unavailable")); - strictEqual(loadPyodide.mock.calls.length, 0); + expectDiagnostics(await emit(), { + code: "@typespec/http-client-python/unknown-error", + message: /CDN blocked.*Hosted runtime unavailable/s, + }); }); }); diff --git a/packages/http-client-python/eng/pipeline/publish.yml b/packages/http-client-python/eng/pipeline/publish.yml index d134468d578..145d8fd7891 100644 --- a/packages/http-client-python/eng/pipeline/publish.yml +++ b/packages/http-client-python/eng/pipeline/publish.yml @@ -32,3 +32,4 @@ extends: EnableCadlRanchReport: false PythonVersion: "3.11" UploadPlaygroundBundle: true + PlaygroundBundleBuildScript: build:playground diff --git a/packages/http-client-python/eng/scripts/setup/build-playground-assets.ts b/packages/http-client-python/eng/scripts/setup/build-playground-assets.ts new file mode 100644 index 00000000000..8bc87bab420 --- /dev/null +++ b/packages/http-client-python/eng/scripts/setup/build-playground-assets.ts @@ -0,0 +1,8 @@ +import { rm } from "node:fs/promises"; +import { runPython3 } from "./run-python3.js"; + +try { + await runPython3("./eng/scripts/setup/build_playground_assets.py"); +} finally { + await rm("./venv_build_wheel", { recursive: true, force: true }); +} diff --git a/packages/http-client-python/eng/scripts/setup/build_playground_assets.py b/packages/http-client-python/eng/scripts/setup/build_playground_assets.py new file mode 100644 index 00000000000..e92ff176b4c --- /dev/null +++ b/packages/http-client-python/eng/scripts/setup/build_playground_assets.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import json +import os +import shutil +import subprocess +import sys +import tarfile +from email.parser import BytesParser +from tempfile import TemporaryDirectory +from zipfile import ZipFile + +if not sys.version_info >= (3, 10, 0): + raise Exception("Autorest for Python extension requires Python 3.10 at least") + +try: + from package_manager import detect_package_manager, PackageManagerNotFoundError + + detect_package_manager() # Just check if we have a package manager +except (ImportError, ModuleNotFoundError, PackageManagerNotFoundError): + raise Exception("Your Python installation doesn't have a suitable package manager (pip or uv) available") + + +# Now we have a package manager (pip or uv) and Py >= 3.10, go to work + +from pathlib import Path + +from package_manager import create_venv_with_package_manager, get_install_command + +# eng/scripts/setup/build_playground_assets.py -> need to go up 4 levels to get to package root +_ROOT_DIR = Path(__file__).parent.parent.parent.parent + + +def main(): + venv_path = _ROOT_DIR / "venv_build_wheel" + venv_context = create_venv_with_package_manager(venv_path) + build_browser_assets(venv_context) + + +def build_browser_assets(venv_context): + dist = _ROOT_DIR / "generator" / "dist" + runtime = _ROOT_DIR / "node_modules" / "pyodide" + version = json.loads((_ROOT_DIR / "package.json").read_text())["dependencies"]["pyodide"] + if json.loads((runtime / "package.json").read_text())["version"] != version: + raise RuntimeError(f"Expected installed Pyodide {version}") + packages = json.loads((runtime / "pyodide-lock.json").read_text())["packages"] + environment = { + **os.environ, + "PIP_INDEX_URL": "https://packagefeedproxy.microsoft.io/pypi/simple/", + "PIP_EXTRA_INDEX_URL": "", + "PIP_CONFIG_FILE": os.devnull, + "UV_DEFAULT_INDEX": "https://packagefeedproxy.microsoft.io/pypi/simple/", + "PYYAML_FORCE_LIBYAML": "0", + } + subprocess.run( + get_install_command(detect_package_manager(), venv_context) + ["pip", "setuptools", "wheel"], + env=environment, + check=True, + ) + pip = [venv_context.env_exe, "-m", "pip", "download"] + with TemporaryDirectory() as temp: + root = Path(temp) + wheels = root / "wheels" + wheels.mkdir() + # These optional native extensions are unavailable in browser Python. + for name in ("pyyaml", "markupsafe"): + package_version = packages[name]["version"] + source_dir = root / name + source_dir.mkdir() + subprocess.run( + pip + + [ + f"{name}=={package_version}", + "--no-deps", + "--no-binary=:all:", + "--no-build-isolation", + "-d", + str(source_dir), + ], + env=environment, + check=True, + ) + archives = list(source_dir.glob("*.tar.gz")) + if len(archives) != 1: + raise RuntimeError(f"Expected one source archive for {name}") + with tarfile.open(archives[0]) as archive: + for entry in archive: + target = (source_dir / entry.name).resolve() + if not target.is_relative_to(source_dir.resolve()) or not (entry.isfile() or entry.isdir()): + raise RuntimeError(f"Unsafe source archive for {name}") + archive.extractall(source_dir) + sources = [path for path in source_dir.iterdir() if path.is_dir()] + if len(sources) != 1: + raise RuntimeError(f"Expected one source directory for {name}") + if name == "markupsafe": + setup = sources[0] / "setup.py" + text = setup.read_text() + extension = 'ext_modules = [Extension("markupsafe._speedups", ["src/markupsafe/_speedups.c"])]' + if text.count(extension) != 1: + raise RuntimeError("Unexpected MarkupSafe extension configuration") + setup.write_text(text.replace(extension, "ext_modules = []")) + subprocess.run( + [venv_context.env_exe, "setup.py", "bdist_wheel", "--dist-dir", str(wheels)], + cwd=sources[0], + env=environment, + check=True, + ) + with ZipFile(dist / "pygen-0.1.0-py3-none-any.whl") as wheel: + metadata = BytesParser().parsebytes(wheel.read("pygen-0.1.0.dist-info/METADATA")) + requirements = metadata.get_all("Requires-Dist", []) + requirements += [f"{name}=={packages[name]['version']}" for name in ("packaging", "micropip", "click")] + subprocess.run( + pip + + [ + *requirements, + "--find-links", + str(wheels), + "--only-binary=:all:", + "--platform", + "any", + "--python-version", + "3.12", + "--implementation", + "py", + "--abi", + "none", + "-d", + str(wheels), + ], + env=environment, + check=True, + ) + filenames = sorted(path.name for path in wheels.glob("*.whl")) + if not filenames or any( + not name.endswith(("-py3-none-any.whl", "-py2.py3-none-any.whl")) for name in filenames + ): + raise RuntimeError(f"Browser dependencies must be pure-Python wheels: {filenames}") + bootstrap = [f"{name}-{packages[name]['version']}-py3-none-any.whl" for name in ("packaging", "micropip")] + if not all(name in filenames for name in bootstrap): + raise RuntimeError("Missing browser bootstrap wheels") + wheel_dir = dist / "browser-wheels" + wheel_dir.mkdir(exist_ok=True) + for stale in wheel_dir.glob("*.whl"): + stale.unlink() + for name in filenames: + shutil.copyfile(wheels / name, wheel_dir / name) + (dist / "browser-wheels.json").write_text( + json.dumps(bootstrap + [name for name in filenames if name not in bootstrap]) + ) + runtime_dir = dist / "pyodide" + runtime_dir.mkdir(exist_ok=True) + for name in ("pyodide.js", "pyodide.asm.js", "pyodide.asm.wasm", "python_stdlib.zip", "pyodide-lock.json"): + shutil.copyfile(runtime / name, runtime_dir / name) + + +if __name__ == "__main__": + main() diff --git a/packages/http-client-python/package.json b/packages/http-client-python/package.json index 5a56b3aa13c..9363eb5fe60 100644 --- a/packages/http-client-python/package.json +++ b/packages/http-client-python/package.json @@ -35,6 +35,7 @@ "scripts": { "clean": "rimraf ./dist ./temp ./venv ./tests/generated", "build": "tsc -p ./emitter/tsconfig.build.json && tsx ./eng/scripts/setup/build.ts", + "build:playground": "npm run build && tsx ./eng/scripts/setup/build-playground-assets.ts", "watch": "tsc -p ./emitter/tsconfig.build.json --watch", "install": "tsx ./eng/scripts/setup/install.ts", "prepare": "tsx ./eng/scripts/setup/prepare.ts", @@ -62,6 +63,9 @@ "dist/**", "!dist/test/**", "generator/**", + "!generator/dist/browser-wheels/**", + "!generator/dist/browser-wheels.json", + "!generator/dist/pyodide/**", "eng/scripts/**", "emitter" ], @@ -86,6 +90,30 @@ { "path": "generator/dist/pygen-*.whl", "contentType": "application/zip" + }, + { + "path": "generator/dist/browser-wheels/*.whl", + "contentType": "application/zip" + }, + { + "path": "generator/dist/browser-wheels.json", + "contentType": "application/json" + }, + { + "path": "generator/dist/pyodide/*.js", + "contentType": "application/javascript" + }, + { + "path": "generator/dist/pyodide/*.wasm", + "contentType": "application/wasm" + }, + { + "path": "generator/dist/pyodide/*.zip", + "contentType": "application/zip" + }, + { + "path": "generator/dist/pyodide/*.json", + "contentType": "application/json" } ], "bundlePeerDependencies": [ diff --git a/packages/http-client-python/tests/unit/test_browser_assets_build.py b/packages/http-client-python/tests/unit/test_browser_assets_build.py new file mode 100644 index 00000000000..f2f5affde96 --- /dev/null +++ b/packages/http-client-python/tests/unit/test_browser_assets_build.py @@ -0,0 +1,53 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import importlib +from pathlib import Path +from unittest.mock import Mock + +import pytest + + +@pytest.fixture +def testserver(): + """Build-script tests do not use the HTTP mock server.""" + + +@pytest.fixture +def builders(monkeypatch): + monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2] / "eng" / "scripts" / "setup")) + wheel = importlib.import_module("build_pygen_wheel") + assets = importlib.import_module("build_playground_assets") + for name in ("create_venv_with_package_manager", "install_packages", "python_run"): + monkeypatch.setattr(wheel, name, Mock()) + for name in ("create_venv_with_package_manager", "build_browser_assets"): + monkeypatch.setattr(assets, name, Mock()) + if hasattr(wheel, "build_browser_assets"): + monkeypatch.setattr(wheel, "build_browser_assets", assets.build_browser_assets) + return wheel, assets + + +def test_normal_wheel_build_does_not_prepare_browser_assets(builders, monkeypatch): + wheel, assets = builders + monkeypatch.setattr("sys.argv", ["build_pygen_wheel.py"]) + + wheel.main() + + wheel.python_run.assert_called_once_with( + wheel.create_venv_with_package_manager.return_value, + "build", + ["--wheel"], + additional_dir="generator", + ) + assets.build_browser_assets.assert_not_called() + + +def test_playground_asset_build_is_separate_from_wheel_build(builders): + wheel, assets = builders + + assets.main() + + assets.build_browser_assets.assert_called_once_with(assets.create_venv_with_package_manager.return_value) + wheel.python_run.assert_not_called()