diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b3c7aa53..1db0cb97 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -553,6 +553,18 @@ jobs: $env:DYNWINRT_REQUIRE_MYPY = '1' $env:DYNWINRT_REQUIRE_XML_NULLABILITY = '1' cargo test -p dynwinrt-codegen --test python_xml_nullability_test + - name: Test generated Python packaging frontends and src imports + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + python -m venv target\python-layout-tools + $python = (Resolve-Path target\python-layout-tools\Scripts\python.exe).Path + & $python -m pip install build mypy pyright poetry uv setuptools wheel --quiet + $wheel = @(Get-ChildItem artifacts\python-x64\payload -Filter *.whl -File) + & $python eng\release\python\test_generated_python_layout.py ` + --codegen $env:DYNWINRT_CODEGEN --runtime-wheel $wheel[0].FullName ` + --uv (Resolve-Path target\python-layout-tools\Scripts\uv.exe).Path ` + --work-dir (Join-Path $env:RUNNER_TEMP 'python-src-layout') - name: Test generated implementation and overload identities shell: pwsh run: | diff --git a/eng/coverage/test_python_coverage.py b/eng/coverage/test_python_coverage.py index 9aca4b74..58af71d4 100644 --- a/eng/coverage/test_python_coverage.py +++ b/eng/coverage/test_python_coverage.py @@ -17,8 +17,8 @@ HERE = Path(__file__).resolve().parent -STANDARD = Path("tests/e2e/e2e_generated/python_bindings") -IMPLEMENTATIONS = Path("tests/e2e/e2e_generated/implementations/python_bindings") +STANDARD = Path("tests/e2e/e2e_generated/python_bindings/src/python_bindings") +IMPLEMENTATIONS = Path("tests/e2e/e2e_generated/implementations/python_bindings/src/python_bindings") RUNTIME = Path("bindings/py/python/dynwinrt/_implementation.py") diff --git a/eng/release/python/test_generated_python_layout.py b/eng/release/python/test_generated_python_layout.py new file mode 100644 index 00000000..6b68b886 --- /dev/null +++ b/eng/release/python/test_generated_python_layout.py @@ -0,0 +1,290 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Exercise real codegen output through isolated packaging frontends and checkers. + +Run from a tools environment with build, mypy, pyright and poetry installed. +Consumers never import from the checkout or through MYPYPATH/PYTHONPATH. +""" + +import argparse +import hashlib +import importlib.metadata +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import zipfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--codegen", type=Path, required=True) + parser.add_argument("--runtime-wheel", type=Path, required=True) + parser.add_argument("--work-dir", type=Path, required=True) + parser.add_argument("--uv", default="uv") + parser.add_argument("--index-url", help="Optional test-local package mirror; no global configuration is changed") + parser.add_argument("--bootstrap", type=Path, action="append", default=[]) + parser.add_argument("--winappsdk-version", default="2.3") + args = parser.parse_args() + root = args.work_dir.resolve() + root.mkdir(parents=True, exist_ok=False) + codegen = root / "dynwinrt-codegen.exe" + shutil.copy2(args.codegen.resolve(), codegen) + runtime = args.runtime_wheel.resolve() + report = { + "python": sys.version, + "codegen_sha256": hashlib.sha256(codegen.read_bytes()).hexdigest(), + "runtime_sha256": hashlib.sha256(runtime.read_bytes()).hexdigest(), + "versions": { + name: importlib.metadata.version(name) + for name in ("pip", "build", "setuptools", "wheel", "mypy", "pyright", "poetry") + }, + "commands": [], + "cases": [], + } + environment = dict(os.environ) + for name in ("PYTHONPATH", "MYPYPATH", "VIRTUAL_ENV"): + environment.pop(name, None) + environment.update( + PIP_DISABLE_PIP_VERSION_CHECK="1", + UV_CACHE_DIR=str(root / "uv-cache"), + UV_PYTHON_DOWNLOADS="never", + POETRY_CACHE_DIR=str(root / "poetry-cache"), + POETRY_VIRTUALENVS_IN_PROJECT="true", + POETRY_KEYRING_ENABLED="false", + ) + if args.index_url: + environment.update(PIP_INDEX_URL=args.index_url, UV_DEFAULT_INDEX=args.index_url) + + def run(command, cwd=root, expected=0): + command = [str(arg) for arg in command] + result = subprocess.run( + command, cwd=cwd, env=environment, capture_output=True, text=True, + encoding="utf-8", errors="replace", timeout=600, + ) + report["commands"].append({ + "argv": command, "cwd": str(cwd), "exit": result.returncode, + "stdout": result.stdout, "stderr": result.stderr, + }) + if result.returncode != expected: + raise RuntimeError(f"{command}\n{result.stdout}\n{result.stderr}") + return result.stdout + + def generate(project, classes, bootstrap=()): + command = [ + codegen, "generate", "--lang", "py", "--class-name", classes, + "--output", project, + ] + if bootstrap: + command += ["--winappsdk-version", args.winappsdk_version] + for dll in bootstrap: + command += ["--winappsdk-bootstrap-path", dll.resolve()] + run(command) + + def venv(path): + run([sys.executable, "-m", "venv", path]) + return path / "Scripts" / "python.exe" + + def check(python, project, editable, added=False): + consumer = python.parent.parent.parent / ("added" if added else "consumer") + consumer.mkdir(exist_ok=True) + imports = ( + "from sdk_bindings.windows.foundation import Uri\n" + "from sdk_bindings.windows.foundation.uri import Uri as PerTypeUri\n" + "from sdk_bindings.windows__foundation__uri import Uri as FlatUri\n" + "from sdk_bindings import Uri as RootUri\n" + ) + valid = imports + ( + "from typing import assert_type\n" + "def consume(uri: Uri) -> str:\n" + " assert_type(uri.combine_uri('child'), Uri)\n" + " return uri.host\n" + "def facades(a: PerTypeUri, b: FlatUri, c: RootUri) -> None:\n" + " consume(a)\n consume(b)\n consume(c)\n" + ) + if added: + valid += ( + "from sdk_bindings.windows.globalization import Language\n" + "def language(value: Language) -> str:\n" + " return value.language_tag\n" + ) + (consumer / "valid.py").write_text(valid, encoding="utf-8") + (consumer / "invalid.py").write_text( + imports + "def reject(uri: Uri) -> None:\n uri.combine_uri(123)\n", + encoding="utf-8", + ) + for name, errors in (("valid", 0), ("invalid", 1)): + text = run([ + sys.executable, "-m", "mypy", "--strict", "--no-incremental", + "--python-executable", python, "--cache-dir", consumer / "m", + consumer / f"{name}.py", + ], cwd=consumer, expected=errors) + if errors: + assert text.count(": error:") == 1 and "[arg-type]" in text, text + text = run([ + sys.executable, "-m", "pyright", "--pythonpath", python, + "--outputjson", consumer / f"{name}.py", + ], cwd=consumer, expected=errors) + diagnostics = json.loads(text) + assert diagnostics["summary"]["errorCount"] == errors, text + if errors: + assert diagnostics["generalDiagnostics"][0]["rule"] == "reportArgumentType", text + probe = """ +import hashlib, importlib, importlib.metadata, json, pathlib, sys +from dynwinrt import RoApartment +from sdk_bindings.windows.foundation import Uri +from sdk_bindings.windows.foundation.uri import Uri as PerTypeUri +from sdk_bindings.windows__foundation__uri import Uri as FlatUri +from sdk_bindings import Uri as RootUri +assert Uri is PerTypeUri is FlatUri is RootUri +with RoApartment(): + assert Uri('https://example.com').host == 'example.com' +project = pathlib.Path(sys.argv[1]) +package = pathlib.Path(importlib.import_module('sdk_bindings').__file__).parent +assert (package / 'py.typed').is_file() +entries = [e for e in importlib.metadata.entry_points(group='dynwinrt.winappsdk') + if e.value == 'sdk_bindings._winappsdk:get_config'] +manifest = project / '.dynwinrt-winappsdk.json' +assert len(entries) == int(manifest.is_file()) +if manifest.is_file(): + root, config = entries[0].load()() + assert pathlib.Path(root) == package + expected = json.loads(manifest.read_text()) + assert config == expected['configuration'] + for name, digest in expected['files'].items(): + relative = pathlib.Path(name) + if relative.is_relative_to(pathlib.Path('src/sdk_bindings')): + data = (package / relative.relative_to('src/sdk_bindings')).read_bytes() + assert hashlib.sha256(data).hexdigest() == digest, name +if sys.argv[2] == 'editable': + pths = list(pathlib.Path(sys.prefix, 'Lib', 'site-packages').glob('*sdk_bindings*.pth')) + assert len(pths) == 1, pths + assert pths[0].read_text().strip() == str(project / 'src') +if sys.argv[3] == 'added': + from sdk_bindings.windows.globalization import Language + with RoApartment(): + assert Language('en-US').language_tag == 'en-US' +print(package) +""" + run([python, "-I", "-B", "-c", probe, project, + "editable" if editable else "wheel", "added" if added else "initial"], cwd=consumer) + + def inspect_wheel(wheel, project): + with zipfile.ZipFile(wheel) as archive: + names = archive.namelist() + installed = {} + for name in names: + parts = name.split("/") + if len(parts) > 2 and parts[0].endswith(".data") and parts[1] in ("purelib", "platlib"): + parts = parts[2:] + target = "/".join(parts) + assert not target.startswith(("src/", "_dynwinrt_build/")), name + assert target not in installed, target + installed[target] = name + assert "sdk_bindings/py.typed" in installed + assert "sdk_bindings/windows/foundation/uri.pyi" in installed + expected = project / ".dynwinrt-winappsdk.json" + if expected.is_file(): + bundle = json.loads(expected.read_text()) + platforms = sorted( + "win_amd64" if arch == "x64" else "win_arm64" + for arch in bundle["configuration"]["dlls"] + ) + assert wheel.name.endswith(f"-py3-none-{'.'.join(platforms)}.whl"), wheel + for name, digest in bundle["files"].items(): + if name.startswith("src/sdk_bindings/"): + assert hashlib.sha256(archive.read(installed[name[4:]])).hexdigest() == digest, name + else: + assert wheel.name.endswith("-py3-none-any.whl"), wheel + + try: + report["versions"]["uv"] = run([args.uv, "--version"]).strip() + variants = [("none", [])] + if args.bootstrap: + variants.append(("single", args.bootstrap[:1])) + if len(args.bootstrap) > 1: + variants.append(("dual", args.bootstrap)) + for variant, bootstrap in variants: + directory = root / variant + directory.mkdir() + project = directory / "sdk_bindings" + generate(project, "Windows.Foundation.Uri", bootstrap) + report["versions"]["codegen"] = json.loads( + (project / ".dynwinrt-generator.json").read_text() + )["generator_version"] + wheel_dir = directory / "wheels" + run([sys.executable, "-m", "build", "--wheel", "--outdir", wheel_dir, project]) + direct = next(wheel_dir.glob("*.whl")) + inspect_wheel(direct, project) + run([sys.executable, "-m", "build", "--sdist", "--outdir", wheel_dir, project]) + sdist = next(wheel_dir.glob("*.tar.gz")) + rebuilt = directory / "rebuilt" + run([sys.executable, "-m", "pip", "wheel", "--no-deps", "--wheel-dir", rebuilt, sdist]) + rebuilt_wheel = next(rebuilt.glob("*.whl")) + inspect_wheel(rebuilt_wheel, project) + editable_consumers = [] + for backend, wheel_version in (("68.0.0", "0.43.0"), ("84.2.1", "0.48.0")): + case = directory / f"setuptools-{backend}" + case.mkdir() + python = venv(case / "venv") + run([python, "-m", "pip", "install", f"setuptools=={backend}", + f"wheel=={wheel_version}", runtime]) + run([python, "-m", "pip", "wheel", "--no-build-isolation", "--no-deps", + "--wheel-dir", case / "wheels", project]) + inspect_wheel(next((case / "wheels").glob("*.whl")), project) + run([python, "-m", "pip", "install", "--no-build-isolation", "--editable", project]) + check(python, project, True) + editable_consumers.append(python) + report["cases"].append({"bundle": variant, "backend": backend, "wheel": wheel_version, "status": "passed"}) + for frontend in ("pip-wheel", "pip-sdist", "pip-editable", "uv-normal", "uv-editable", + "uv-sync", "poetry-normal", "poetry-editable"): + case = directory / frontend + case.mkdir() + editable = frontend in ("pip-editable", "uv-editable", "uv-sync", "poetry-editable") + if frontend == "uv-sync": + (case / "pyproject.toml").write_text( + '[project]\nname = "consumer"\nversion = "0.0.0"\n' + 'requires-python = ">=3.11,<3.15"\ndependencies = ["sdk-bindings", "dynwinrt"]\n' + '[tool.uv.sources]\n' + f'sdk-bindings = {{ path = {json.dumps(project.as_posix())}, editable = true }}\n' + f'dynwinrt = {{ path = {json.dumps(runtime.as_posix())} }}\n', + encoding="utf-8", + ) + run([args.uv, "sync", "--python", sys._base_executable], cwd=case) + python = case / ".venv" / "Scripts" / "python.exe" + elif frontend.startswith("poetry"): + (case / "pyproject.toml").write_text( + '[tool.poetry]\nname = "consumer"\nversion = "0.0.0"\npackage-mode = false\n' + '[tool.poetry.dependencies]\npython = ">=3.11,<3.15"\n' + f'sdk-bindings = {{ path = {json.dumps(project.as_posix())}, develop = {str(editable).lower()} }}\n' + f'dynwinrt = {{ path = {json.dumps(runtime.as_posix())} }}\n' + + (f'[[tool.poetry.source]]\nname = "test-mirror"\nurl = {json.dumps(args.index_url)}\npriority = "primary"\n' + if args.index_url else ""), + encoding="utf-8", + ) + run([sys.executable, "-m", "poetry", "env", "use", sys._base_executable], cwd=case) + run([sys.executable, "-m", "poetry", "install", "--no-interaction"], cwd=case) + python = case / ".venv" / "Scripts" / "python.exe" + else: + python = venv(case / "venv") + source = direct if frontend == "pip-wheel" else rebuilt_wheel if frontend == "pip-sdist" else project + installer = [args.uv, "pip", "install", "--python", python] if frontend.startswith("uv") else [python, "-m", "pip", "install"] + run(installer + [runtime] + (["--editable"] if editable else []) + [source]) + check(python, project, editable) + report["cases"].append({"bundle": variant, "frontend": frontend, "status": "passed"}) + if editable: + editable_consumers.append(python) + generate(project, "Windows.Globalization.Language") + for python in editable_consumers: + check(python, project, True, added=True) + report["cases"].append({"bundle": variant, "incremental_without_reinstall": "passed"}) + print(f"{variant}: packaging, frontends, typing and incremental regeneration passed", flush=True) + finally: + (root / "results.json").write_text(json.dumps(report, indent=2), encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/eng/release/python/test_generated_python_long_paths.ps1 b/eng/release/python/test_generated_python_long_paths.ps1 index eb5941eb..9dbe2058 100644 --- a/eng/release/python/test_generated_python_long_paths.ps1 +++ b/eng/release/python/test_generated_python_long_paths.ps1 @@ -19,6 +19,7 @@ if ($root.Length -ne 104) { throw "Long-path test root must be 104 characters, got $($root.Length)" } $source = Join-Path $root "source\generated_bindings" +$package = Join-Path $source "src\generated_bindings" $wheelDirectory = Join-Path $root "wheels" $sourceInstall = Join-Path $root "from-source" $install = Join-Path $root ("i" * (135 - $root.Length - 1)) @@ -33,15 +34,15 @@ try { --output $source if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - $modules = Get-ChildItem -LiteralPath $source -File -Filter *.py + $modules = Get-ChildItem -LiteralPath $package -File -Filter *.py $tooLong = $modules | Where-Object { $_.BaseName.Length -gt 56 } if ($tooLong) { throw "Generated Python module exceeds 56 UTF-16 code units: $($tooLong[0].Name)" } - $tooLong = Get-ChildItem -LiteralPath $source -File -Recurse | + $tooLong = Get-ChildItem -LiteralPath $package -File -Recurse | Where-Object { $_.Extension -in @(".py", ".pyi") -and - $_.FullName.Substring($source.Length + 1).Length -gt 60 + $_.FullName.Substring($package.Length + 1).Length -gt 60 } if ($tooLong) { throw "Generated Python relative source path exceeds 60 UTF-16 code units: $($tooLong[0].Name)" @@ -83,7 +84,7 @@ try { New-Item -ItemType Directory -Force -Path $cachedPackage | Out-Null foreach ($extension in @("py", "pyi")) { Copy-Item ` - -LiteralPath (Join-Path $source "$($shortModule.BaseName).$extension") ` + -LiteralPath (Join-Path $package "$($shortModule.BaseName).$extension") ` -Destination $cachedPackage } } @@ -128,7 +129,7 @@ try { } foreach ($extension in @("py", "pyi")) { if (-not (Test-Path -LiteralPath ( - Join-Path $source "$($shortModule.BaseName).$extension"))) { + Join-Path $package "$($shortModule.BaseName).$extension"))) { throw "Unrelated incremental generation removed $($shortModule.BaseName).$extension" } } diff --git a/eng/release/python/test_python_runtime_wheel.ps1 b/eng/release/python/test_python_runtime_wheel.ps1 index 7daee098..993ffad2 100644 --- a/eng/release/python/test_python_runtime_wheel.ps1 +++ b/eng/release/python/test_python_runtime_wheel.ps1 @@ -47,6 +47,11 @@ $generated = Join-Path $root 'generated_uri' --lang py --output $generated if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +$generatedInstall = Join-Path $root 'consumer' +New-Item $generatedInstall -ItemType Directory -Force | Out-Null +& $venvPython -m pip install --disable-pip-version-check --no-deps $generated +if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $test = @' import importlib.metadata import pathlib @@ -74,10 +79,18 @@ with RoApartment(1), projected_lifetime_scope(): print("isolated runtime consumer OK") '@ -Push-Location $root +Push-Location $generatedInstall try { & $venvPython -c $test $Architecture $PythonMinor $PythonPackageVersion if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $venvPython -m pip install --disable-pip-version-check --no-deps --editable $generated + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $venvPython -c $test $Architecture $PythonMinor $PythonPackageVersion + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $pth = @(Get-ChildItem (Join-Path $root 'venv\Lib\site-packages') -Filter '*generated_uri*.pth') + if ($pth.Count -ne 1 -or (Get-Content $pth[0].FullName -Raw).Trim() -ne (Join-Path $generated 'src')) { + throw 'Generated Python editable install must use a plain src path .pth' + } foreach ($mode in @(0, 1)) { & $venvPython -I (Join-Path $repoRoot 'tests\e2e\runners\py_async_events.py') ` --generated $generated --mode $mode diff --git a/eng/release/python/verify_generated_python_install.py b/eng/release/python/verify_generated_python_install.py index c685401f..d6147c1d 100644 --- a/eng/release/python/verify_generated_python_install.py +++ b/eng/release/python/verify_generated_python_install.py @@ -21,12 +21,14 @@ def package_files(root: Path) -> set[Path]: } -def generated_source_files(root: Path) -> set[Path]: +def generated_source_files(root: Path, package: str) -> set[Path]: inventory = root / ".dynwinrt-generated-files" + prefix = Path("src") / package files = { Path(line) for line in inventory.read_text(encoding="utf-8").splitlines() - if Path(line).suffix in {".py", ".pyi"} and Path(line).parts[0] != "_dynwinrt_build" + if Path(line).suffix in {".py", ".pyi"} + and Path(line).is_relative_to(prefix) } invalid = [path for path in files if path.is_absolute() or ".." in path.parts] if invalid: @@ -34,7 +36,7 @@ def generated_source_files(root: Path) -> set[Path]: missing = [path for path in files if not (root / path).is_file()] if missing: raise RuntimeError(f"Generated inventory references missing files: {missing[:10]}") - return files + return {path.relative_to(prefix) for path in files} def module_name(package: str, relative: Path) -> str: @@ -117,7 +119,7 @@ def main() -> None: source = args.source.resolve() installed = (args.install.resolve() / args.package) - expected = generated_source_files(source) + expected = generated_source_files(source, args.package) actual = package_files(installed) missing = sorted(expected - actual) if missing: @@ -137,10 +139,11 @@ def main() -> None: relative = Path(name) if relative.is_absolute() or ".." in relative.parts or not relative.parts: raise RuntimeError(f"Invalid Bootstrap inventory path: {name}") - if relative.parts[0] == "_dynwinrt_build" or name == "MANIFEST.in": - if (installed / relative).exists(): + if relative.is_relative_to(Path("src") / "_dynwinrt_build") or name == "MANIFEST.in": + if (args.install / "_dynwinrt_build").exists() or (installed / relative).exists(): raise RuntimeError(f"Build-only file was installed: {name}") continue + relative = relative.relative_to(Path("src") / args.package) actual_digest = hashlib.sha256((installed / relative).read_bytes()).hexdigest() if actual_digest != expected_digest: raise RuntimeError(f"Installed Bootstrap resource differs from generation: {name}") diff --git a/samples/python/README.md b/samples/python/README.md index 669d724c..ae4a2fa1 100644 --- a/samples/python/README.md +++ b/samples/python/README.md @@ -2,7 +2,15 @@ All Python samples use generated bindings and an installed `dynwinrt` runtime. Install `dynwinrt` and `dynwinrt-codegen` from PyPI, or build both from this -checkout, then follow the sample's README (usually `generate.ps1` before `run.ps1`). +checkout, then follow the sample's README. Most samples use `generate.ps1`, then +`python -m pip install -e .\generated`, then `run.ps1` with the same interpreter; +the async-events README provides direct generation and run commands. +Sources are under `generated\src\generated`; installed imports +remain `generated`. After upgrading from preview.23 or earlier, regenerate the +complete project and reinstall it instead of adding the old output parent to +the import path. +Samples share the import name `generated`; install the selected sample again +when switching samples in a shared interpreter. | Sample | Demonstrates | | --- | --- | diff --git a/samples/python/app-lifecycle-single-instance/README.md b/samples/python/app-lifecycle-single-instance/README.md index 39df90cf..bcc74462 100644 --- a/samples/python/app-lifecycle-single-instance/README.md +++ b/samples/python/app-lifecycle-single-instance/README.md @@ -32,3 +32,9 @@ installed runtime. The loopback succeeds only after the secondary process redirects its launch activation and the primary receives it. It prints `python-app-lifecycle-ok`. + +After generation, install the generated project into the same interpreter used +to run the sample: `python -m pip install -e .\generated` (use that interpreter's +full path when needed). The import remains `generated`; sources now live in +`generated\src\generated`, not directly in `generated`. When upgrading from +preview.23 or earlier, regenerate the complete output and reinstall it. diff --git a/samples/python/app-lifecycle-single-instance/generate.ps1 b/samples/python/app-lifecycle-single-instance/generate.ps1 index 0e782912..87ac7479 100644 --- a/samples/python/app-lifecycle-single-instance/generate.ps1 +++ b/samples/python/app-lifecycle-single-instance/generate.ps1 @@ -56,3 +56,5 @@ Copy-Item -LiteralPath $BootstrapDll ` Write-Host "Generated AppLifecycle bindings in $output" Write-Host "Copied the bootstrap DLL to $runtime" + +Write-Host "Install this generated project into the sample interpreter with: python -m pip install -e `"$output`"" diff --git a/samples/python/app-lifecycle-single-instance/run.ps1 b/samples/python/app-lifecycle-single-instance/run.ps1 index 83b50a03..f934ab9d 100644 --- a/samples/python/app-lifecycle-single-instance/run.ps1 +++ b/samples/python/app-lifecycle-single-instance/run.ps1 @@ -7,7 +7,7 @@ param( ) $ErrorActionPreference = "Stop" -if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\src\generated\__init__.py"))) { throw "Generated bindings were not found. Run generate.ps1 first." } if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot ".runtime\Microsoft.WindowsAppRuntime.Bootstrap.dll"))) { diff --git a/samples/python/app-notification/README.md b/samples/python/app-notification/README.md index 29ea0127..d92032bc 100644 --- a/samples/python/app-notification/README.md +++ b/samples/python/app-notification/README.md @@ -44,3 +44,9 @@ fails. Use `-Smoke` to validate support and build the notification payload without registering or displaying it. + +After generation, install the generated project into the same interpreter used +to run the sample: `python -m pip install -e .\generated` (use that interpreter's +full path when needed). The import remains `generated`; sources now live in +`generated\src\generated`, not directly in `generated`. When upgrading from +preview.23 or earlier, regenerate the complete output and reinstall it. diff --git a/samples/python/app-notification/generate.ps1 b/samples/python/app-notification/generate.ps1 index 8f09f901..d0e22080 100644 --- a/samples/python/app-notification/generate.ps1 +++ b/samples/python/app-notification/generate.ps1 @@ -60,3 +60,5 @@ Copy-Item -LiteralPath $BootstrapDll ` Write-Host "Generated AppNotification bindings in $output" Write-Host "Copied the bootstrap DLL to $runtime" + +Write-Host "Install this generated project into the sample interpreter with: python -m pip install -e `"$output`"" diff --git a/samples/python/app-notification/run.ps1 b/samples/python/app-notification/run.ps1 index d8ecb9ae..160b87e1 100644 --- a/samples/python/app-notification/run.ps1 +++ b/samples/python/app-notification/run.ps1 @@ -9,7 +9,7 @@ param( ) $ErrorActionPreference = "Stop" -if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\src\generated\__init__.py"))) { throw "Generated bindings were not found. Run generate.ps1 first." } if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot ".runtime\Microsoft.WindowsAppRuntime.Bootstrap.dll"))) { diff --git a/samples/python/async-events/README.md b/samples/python/async-events/README.md index 179cfc0a..0029dade 100644 --- a/samples/python/async-events/README.md +++ b/samples/python/async-events/README.md @@ -9,10 +9,16 @@ installed in your Python environment: ```powershell dynwinrt-codegen generate --class-name "Windows.Foundation.Collections.PropertySet,Windows.Storage.StorageFolder,Windows.Storage.FileIO" --lang py --output .\generated +python -m pip install -e .\generated python .\app.py python .\app.py --fail ``` +`generated` is the installable project; Python sources are in +`generated\src\generated`. Use the same interpreter for installation and running. +After upgrading from preview.23 or earlier, clean and regenerate the complete +output and reinstall it; the import name remains `generated`. + The application owns the asyncio loop. Inside its COM apartment and projection scope, it registers an async `PropertySet.MapChanged` handler, mutates the map on that same thread, and unsubscribes immediately. The accepted handler still diff --git a/samples/python/async-file-io/README.md b/samples/python/async-file-io/README.md index a911e7e2..8f47c90c 100644 --- a/samples/python/async-file-io/README.md +++ b/samples/python/async-file-io/README.md @@ -18,3 +18,9 @@ write, append, and read a temporary file. It demonstrates: The sample deletes its temporary directory when complete and prints `python-file-io-ok` on success. + +After generation, install the generated project into the same interpreter used +to run the sample: `python -m pip install -e .\generated` (use that interpreter's +full path when needed). The import remains `generated`; sources now live in +`generated\src\generated`, not directly in `generated`. When upgrading from +preview.23 or earlier, regenerate the complete output and reinstall it. diff --git a/samples/python/async-file-io/generate.ps1 b/samples/python/async-file-io/generate.ps1 index 71b14571..8313f2f8 100644 --- a/samples/python/async-file-io/generate.ps1 +++ b/samples/python/async-file-io/generate.ps1 @@ -52,3 +52,5 @@ if ($LASTEXITCODE -ne 0) { } Write-Host "Generated file I/O bindings in $output" + +Write-Host "Install this generated project into the sample interpreter with: python -m pip install -e `"$output`"" diff --git a/samples/python/async-file-io/run.ps1 b/samples/python/async-file-io/run.ps1 index 2eab6299..c05ff003 100644 --- a/samples/python/async-file-io/run.ps1 +++ b/samples/python/async-file-io/run.ps1 @@ -5,7 +5,7 @@ param( ) $ErrorActionPreference = "Stop" -if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\src\generated\__init__.py"))) { throw "Generated bindings were not found. Run generate.ps1 first." } if (-not [System.IO.Path]::IsPathRooted($Python)) { diff --git a/samples/python/cryptography/README.md b/samples/python/cryptography/README.md index b9649b78..8a030764 100644 --- a/samples/python/cryptography/README.md +++ b/samples/python/cryptography/README.md @@ -11,3 +11,9 @@ directions own their copy; no native buffer pointer escapes. .\generate.ps1 -Codegen ..\..\..\target\release\dynwinrt-codegen.exe .\run.ps1 -Python C:\path\to\python.exe -Text "Hello from dynwinrt." ``` + +After generation, install the generated project into the same interpreter used +to run the sample: `python -m pip install -e .\generated` (use that interpreter's +full path when needed). The import remains `generated`; sources now live in +`generated\src\generated`, not directly in `generated`. When upgrading from +preview.23 or earlier, regenerate the complete output and reinstall it. diff --git a/samples/python/cryptography/generate.ps1 b/samples/python/cryptography/generate.ps1 index c6d6e862..af0953ee 100644 --- a/samples/python/cryptography/generate.ps1 +++ b/samples/python/cryptography/generate.ps1 @@ -52,3 +52,5 @@ if ($LASTEXITCODE -ne 0) { } Write-Host "Generated cryptography bindings in $output" + +Write-Host "Install this generated project into the sample interpreter with: python -m pip install -e `"$output`"" diff --git a/samples/python/cryptography/run.ps1 b/samples/python/cryptography/run.ps1 index 41bff018..fae7a67d 100644 --- a/samples/python/cryptography/run.ps1 +++ b/samples/python/cryptography/run.ps1 @@ -6,7 +6,7 @@ param( ) $ErrorActionPreference = "Stop" -if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\src\generated\__init__.py"))) { throw "Generated bindings were not found. Run generate.ps1 first." } if (-not [System.IO.Path]::IsPathRooted($Python)) { diff --git a/samples/python/custom-winmd-codegen/README.md b/samples/python/custom-winmd-codegen/README.md index 69c0582a..328ea778 100644 --- a/samples/python/custom-winmd-codegen/README.md +++ b/samples/python/custom-winmd-codegen/README.md @@ -45,3 +45,9 @@ The default command imports every generated module and prints the first public symbols. Activation and method calls require the component that implements the WinMD to be installed, registered, or bootstrapped according to that component's deployment model. + +After generation, install the generated project into the same interpreter used +to run the sample: `python -m pip install -e .\generated` (use that interpreter's +full path when needed). The import remains `generated`; sources now live in +`generated\src\generated`, not directly in `generated`. When upgrading from +preview.23 or earlier, regenerate the complete output and reinstall it. diff --git a/samples/python/custom-winmd-codegen/generate.ps1 b/samples/python/custom-winmd-codegen/generate.ps1 index 985bba69..5f9565d3 100644 --- a/samples/python/custom-winmd-codegen/generate.ps1 +++ b/samples/python/custom-winmd-codegen/generate.ps1 @@ -65,3 +65,5 @@ if ($LASTEXITCODE -ne 0) { } Write-Host "Generated custom WinMD bindings in $output" + +Write-Host "Install this generated project into the sample interpreter with: python -m pip install -e `"$output`"" diff --git a/samples/python/custom-winmd-codegen/run.ps1 b/samples/python/custom-winmd-codegen/run.ps1 index 68f00127..fa7be971 100644 --- a/samples/python/custom-winmd-codegen/run.ps1 +++ b/samples/python/custom-winmd-codegen/run.ps1 @@ -7,7 +7,7 @@ param( ) $ErrorActionPreference = "Stop" -if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\src\generated\__init__.py"))) { throw "Generated bindings were not found. Run generate.ps1 first." } if (-not [System.IO.Path]::IsPathRooted($Python)) { diff --git a/samples/python/device-watcher/README.md b/samples/python/device-watcher/README.md index 653c5d85..71c457bc 100644 --- a/samples/python/device-watcher/README.md +++ b/samples/python/device-watcher/README.md @@ -16,3 +16,9 @@ and every subscription is removed before the apartment exits. The exact devices vary by machine. A successful run prints `python-device-watcher-ok` and counts by device kind. Pass `-ShowNames` to `run.ps1` to also print up to ten discovered device names. + +After generation, install the generated project into the same interpreter used +to run the sample: `python -m pip install -e .\generated` (use that interpreter's +full path when needed). The import remains `generated`; sources now live in +`generated\src\generated`, not directly in `generated`. When upgrading from +preview.23 or earlier, regenerate the complete output and reinstall it. diff --git a/samples/python/device-watcher/generate.ps1 b/samples/python/device-watcher/generate.ps1 index f42e0440..8394be47 100644 --- a/samples/python/device-watcher/generate.ps1 +++ b/samples/python/device-watcher/generate.ps1 @@ -52,3 +52,5 @@ if ($LASTEXITCODE -ne 0) { } Write-Host "Generated device watcher bindings in $output" + +Write-Host "Install this generated project into the sample interpreter with: python -m pip install -e `"$output`"" diff --git a/samples/python/device-watcher/run.ps1 b/samples/python/device-watcher/run.ps1 index 8ffa8421..28539f96 100644 --- a/samples/python/device-watcher/run.ps1 +++ b/samples/python/device-watcher/run.ps1 @@ -7,7 +7,7 @@ param( ) $ErrorActionPreference = "Stop" -if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\src\generated\__init__.py"))) { throw "Generated bindings were not found. Run generate.ps1 first." } if (-not [System.IO.Path]::IsPathRooted($Python)) { diff --git a/samples/python/interface-implementation/README.md b/samples/python/interface-implementation/README.md index 7a31c8cb..905dfe1c 100644 --- a/samples/python/interface-implementation/README.md +++ b/samples/python/interface-implementation/README.md @@ -23,8 +23,8 @@ cargo build -p dynwinrt-codegen The selected interpreter must have this checkout's runtime installed. Generation auto-detects the Windows SDK; `-Winmd` selects an explicit metadata -file. The generated package is imported from the sample directory and does -not need to be installed separately. +file. Install the generated project into that interpreter before running the +sample (an editable install makes subsequent regeneration visible). The common pattern is `with IBackgroundTask.implement(handler) as impl:`, then `impl.value.run(instance_view)`. The primary view is stable and managed @@ -44,3 +44,9 @@ another thread fail before entering Python. See [the public guide](../../../docs/guides/windows/winrt-interface-implementations.md) for the capability matrix, callback errors, native retention, and cycle/shutdown semantics. + +After generation, install the generated project into the same interpreter used +to run the sample: `python -m pip install -e .\generated` (use that interpreter's +full path when needed). The import remains `generated`; sources now live in +`generated\src\generated`, not directly in `generated`. When upgrading from +preview.23 or earlier, regenerate the complete output and reinstall it. diff --git a/samples/python/interface-implementation/generate.ps1 b/samples/python/interface-implementation/generate.ps1 index 33995f2d..4a4294e7 100644 --- a/samples/python/interface-implementation/generate.ps1 +++ b/samples/python/interface-implementation/generate.ps1 @@ -12,12 +12,13 @@ if (Test-Path -LiteralPath $Codegen -PathType Leaf) { } else { $Codegen = (Get-Command $Codegen -ErrorAction Stop).Source } +$output = Join-Path $PSScriptRoot "generated" $arguments = @( "generate", "--class-name", "Windows.ApplicationModel.Background.IBackgroundTask,Windows.ApplicationModel.Background.IBackgroundTaskInstance,Windows.Foundation.IStringable,Windows.Foundation.IClosable", "--lang", "py", - "--output", (Join-Path $PSScriptRoot "generated") + "--output", $output ) if ($Winmd) { $arguments += @("--winmd", (Resolve-Path -LiteralPath $Winmd).Path) @@ -26,3 +27,5 @@ if ($Winmd) { if ($LASTEXITCODE -ne 0) { throw "WinRT interface generation failed with exit code $LASTEXITCODE" } + +Write-Host "Install this generated project into the sample interpreter with: python -m pip install -e `"$output`"" diff --git a/samples/python/interface-implementation/run.ps1 b/samples/python/interface-implementation/run.ps1 index fa7082fb..050ead1d 100644 --- a/samples/python/interface-implementation/run.ps1 +++ b/samples/python/interface-implementation/run.ps1 @@ -4,7 +4,7 @@ param([string]$Python = "python") $ErrorActionPreference = "Stop" -if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\src\generated\__init__.py"))) { throw "Generated bindings were not found. Run generate.ps1 first." } if (Test-Path -LiteralPath $Python -PathType Leaf) { diff --git a/samples/python/ocr-image/README.md b/samples/python/ocr-image/README.md index 7ebe7e0d..9d101723 100644 --- a/samples/python/ocr-image/README.md +++ b/samples/python/ocr-image/README.md @@ -24,3 +24,9 @@ Custom images are accepted without assuming their contents. Use Windows must have an OCR language matching one of the current user's profile languages. + +After generation, install the generated project into the same interpreter used +to run the sample: `python -m pip install -e .\generated` (use that interpreter's +full path when needed). The import remains `generated`; sources now live in +`generated\src\generated`, not directly in `generated`. When upgrading from +preview.23 or earlier, regenerate the complete output and reinstall it. diff --git a/samples/python/ocr-image/generate.ps1 b/samples/python/ocr-image/generate.ps1 index 1eed5834..7a079536 100644 --- a/samples/python/ocr-image/generate.ps1 +++ b/samples/python/ocr-image/generate.ps1 @@ -52,3 +52,5 @@ if ($LASTEXITCODE -ne 0) { } Write-Host "Generated OCR bindings in $output" + +Write-Host "Install this generated project into the sample interpreter with: python -m pip install -e `"$output`"" diff --git a/samples/python/ocr-image/run.ps1 b/samples/python/ocr-image/run.ps1 index 8a993af2..ca667a56 100644 --- a/samples/python/ocr-image/run.ps1 +++ b/samples/python/ocr-image/run.ps1 @@ -8,7 +8,7 @@ param( $ErrorActionPreference = "Stop" $expectWasExplicit = $PSBoundParameters.ContainsKey("Expect") -if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\src\generated\__init__.py"))) { throw "Generated bindings were not found. Run generate.ps1 first." } if (-not $Image) { diff --git a/samples/python/text-to-speech/README.md b/samples/python/text-to-speech/README.md index 63054b02..a60ca91d 100644 --- a/samples/python/text-to-speech/README.md +++ b/samples/python/text-to-speech/README.md @@ -37,3 +37,9 @@ For non-interactive validation, synthesize the stream without playing it: `-Smoke` validates synthesis, not playback. In headless or remote sessions without an audio output, playback may time out because Windows cannot create a media sink. + +After generation, install the generated project into the same interpreter used +to run the sample: `python -m pip install -e .\generated` (use that interpreter's +full path when needed). The import remains `generated`; sources now live in +`generated\src\generated`, not directly in `generated`. When upgrading from +preview.23 or earlier, regenerate the complete output and reinstall it. diff --git a/samples/python/text-to-speech/generate.ps1 b/samples/python/text-to-speech/generate.ps1 index e44519f2..b7ac5192 100644 --- a/samples/python/text-to-speech/generate.ps1 +++ b/samples/python/text-to-speech/generate.ps1 @@ -52,3 +52,5 @@ if ($LASTEXITCODE -ne 0) { } Write-Host "Generated text-to-speech bindings in $output" + +Write-Host "Install this generated project into the sample interpreter with: python -m pip install -e `"$output`"" diff --git a/samples/python/text-to-speech/run.ps1 b/samples/python/text-to-speech/run.ps1 index 0f34c077..4b91568e 100644 --- a/samples/python/text-to-speech/run.ps1 +++ b/samples/python/text-to-speech/run.ps1 @@ -7,7 +7,7 @@ param( ) $ErrorActionPreference = "Stop" -if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\src\generated\__init__.py"))) { throw "Generated bindings were not found. Run generate.ps1 first." } diff --git a/samples/python/winui-hello-world/README.md b/samples/python/winui-hello-world/README.md index d2b38bff..5cc6902b 100644 --- a/samples/python/winui-hello-world/README.md +++ b/samples/python/winui-hello-world/README.md @@ -49,3 +49,9 @@ event unsubscription, projected object release, or balanced `RoApartment`. The DLL and its module-level static state are not unloaded when the window closes; in-process WinUI module unloading/hot replacement is not supported. See [Python WinUI lifetime policy](../../../bindings/py/README.md#experimental-winui-support). + +After generation, install the generated project into the same interpreter used +to run the sample: `python -m pip install -e .\generated` (use that interpreter's +full path when needed). The import remains `generated`; sources now live in +`generated\src\generated`, not directly in `generated`. When upgrading from +preview.23 or earlier, regenerate the complete output and reinstall it. diff --git a/samples/python/winui-hello-world/generate.ps1 b/samples/python/winui-hello-world/generate.ps1 index 494c878a..60d627d8 100644 --- a/samples/python/winui-hello-world/generate.ps1 +++ b/samples/python/winui-hello-world/generate.ps1 @@ -64,3 +64,5 @@ Copy-Item -LiteralPath $BootstrapDll ` Write-Host "Generated WinUI bindings in $output" Write-Host "Copied the bootstrap DLL to $runtime" + +Write-Host "Install this generated project into the sample interpreter with: python -m pip install -e `"$output`"" diff --git a/samples/python/winui-hello-world/run.ps1 b/samples/python/winui-hello-world/run.ps1 index b958ec2d..09ea3fbc 100644 --- a/samples/python/winui-hello-world/run.ps1 +++ b/samples/python/winui-hello-world/run.ps1 @@ -8,7 +8,7 @@ param( ) $ErrorActionPreference = "Stop" -if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\src\generated\__init__.py"))) { throw "Generated bindings were not found. Run generate.ps1 first." } if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot ".runtime\Microsoft.WindowsAppRuntime.Bootstrap.dll"))) { diff --git a/samples/python/winui-tic-tac-toe-code-only/README.md b/samples/python/winui-tic-tac-toe-code-only/README.md index dff897ca..7b568ba9 100644 --- a/samples/python/winui-tic-tac-toe-code-only/README.md +++ b/samples/python/winui-tic-tac-toe-code-only/README.md @@ -48,3 +48,9 @@ projected objects deterministically. `generated\`, `.runtime\`, and Python caches are local artifacts and are not tracked. + +After generation, install the generated project into the same interpreter used +to run the sample: `python -m pip install -e .\generated` (use that interpreter's +full path when needed). The import remains `generated`; sources now live in +`generated\src\generated`, not directly in `generated`. When upgrading from +preview.23 or earlier, regenerate the complete output and reinstall it. diff --git a/samples/python/winui-tic-tac-toe-code-only/generate.ps1 b/samples/python/winui-tic-tac-toe-code-only/generate.ps1 index 9b2a528f..adebbf41 100644 --- a/samples/python/winui-tic-tac-toe-code-only/generate.ps1 +++ b/samples/python/winui-tic-tac-toe-code-only/generate.ps1 @@ -67,3 +67,5 @@ Copy-Item -LiteralPath $BootstrapDll ` Write-Host "Generated bindings in $output" Write-Host "Copied the bootstrap DLL to $runtime" + +Write-Host "Install this generated project into the sample interpreter with: python -m pip install -e `"$output`"" diff --git a/samples/python/winui-tic-tac-toe-code-only/run.ps1 b/samples/python/winui-tic-tac-toe-code-only/run.ps1 index 20edef25..24a0d89a 100644 --- a/samples/python/winui-tic-tac-toe-code-only/run.ps1 +++ b/samples/python/winui-tic-tac-toe-code-only/run.ps1 @@ -5,7 +5,7 @@ param( ) $ErrorActionPreference = "Stop" -$generated = Join-Path $PSScriptRoot "generated\__init__.py" +$generated = Join-Path $PSScriptRoot "generated\src\generated\__init__.py" $bootstrap = Join-Path $PSScriptRoot ".runtime\Microsoft.WindowsAppRuntime.Bootstrap.dll" if (-not (Test-Path -LiteralPath $generated -PathType Leaf)) { diff --git a/samples/python/winui-tic-tac-toe/README.md b/samples/python/winui-tic-tac-toe/README.md index 9926092e..7b4d432c 100644 --- a/samples/python/winui-tic-tac-toe/README.md +++ b/samples/python/winui-tic-tac-toe/README.md @@ -43,3 +43,9 @@ source build. `generated\`, `.runtime\`, and Python caches are local build artifacts and are not tracked. + +After generation, install the generated project into the same interpreter used +to run the sample: `python -m pip install -e .\generated` (use that interpreter's +full path when needed). The import remains `generated`; sources now live in +`generated\src\generated`, not directly in `generated`. When upgrading from +preview.23 or earlier, regenerate the complete output and reinstall it. diff --git a/samples/python/winui-tic-tac-toe/generate.ps1 b/samples/python/winui-tic-tac-toe/generate.ps1 index 27c4935f..038a3a74 100644 --- a/samples/python/winui-tic-tac-toe/generate.ps1 +++ b/samples/python/winui-tic-tac-toe/generate.ps1 @@ -67,3 +67,5 @@ Copy-Item -LiteralPath $BootstrapDll ` Write-Host "Generated bindings in $output" Write-Host "Copied the bootstrap DLL to $runtime" + +Write-Host "Install this generated project into the sample interpreter with: python -m pip install -e `"$output`"" diff --git a/samples/python/winui-tic-tac-toe/run.ps1 b/samples/python/winui-tic-tac-toe/run.ps1 index 20edef25..24a0d89a 100644 --- a/samples/python/winui-tic-tac-toe/run.ps1 +++ b/samples/python/winui-tic-tac-toe/run.ps1 @@ -5,7 +5,7 @@ param( ) $ErrorActionPreference = "Stop" -$generated = Join-Path $PSScriptRoot "generated\__init__.py" +$generated = Join-Path $PSScriptRoot "generated\src\generated\__init__.py" $bootstrap = Join-Path $PSScriptRoot ".runtime\Microsoft.WindowsAppRuntime.Bootstrap.dll" if (-not (Test-Path -LiteralPath $generated -PathType Leaf)) { diff --git a/tests/e2e/check_generated_python.py b/tests/e2e/check_generated_python.py index d0610614..093d214b 100644 --- a/tests/e2e/check_generated_python.py +++ b/tests/e2e/check_generated_python.py @@ -19,6 +19,7 @@ import argparse import ast import builtins +import json import os import sys @@ -352,6 +353,10 @@ def expression(self, node, scopes): class PackageChecker: def __init__(self, root): + stamp = os.path.join(root, ".dynwinrt-generator.json") + if os.path.isfile(stamp): + with open(stamp, encoding="utf-8") as file: + root = os.path.join(root, "src", json.load(file)["layout"]["import_name"]) self.root = long_path(root) self.modules = {} self.problems = [] @@ -488,10 +493,11 @@ def main(): problems = [] for package in args.packages: - if not os.path.isfile(os.path.join(long_path(package), "_runtime.py")): + checker = PackageChecker(package) + if not os.path.isfile(os.path.join(checker.root, "_runtime.py")): print(f"{package}: not a generated Python package (no _runtime.py)", file=sys.stderr) return 2 - problems.extend(f"{package}: {problem}" for problem in PackageChecker(package).check()) + problems.extend(f"{package}: {problem}" for problem in checker.check()) for problem in problems[: args.limit]: print(problem) if len(problems) > args.limit: diff --git a/tests/e2e/e2e_test.ps1 b/tests/e2e/e2e_test.ps1 index 1d87fc47..3f7fc7a2 100644 --- a/tests/e2e/e2e_test.ps1 +++ b/tests/e2e/e2e_test.ps1 @@ -403,7 +403,7 @@ if ("py" -in $Lang) { Write-Host "`n--- Python static type check ---" -ForegroundColor Yellow $previousMypyPath = $env:MYPYPATH try { - $env:MYPYPATH = $e2eDir + $env:MYPYPATH = Join-Path $pyBindingsDir "src" & $pythonExe -m mypy --strict (Join-Path $PSScriptRoot "typecheck\python_generated_api.py") if ($LASTEXITCODE -ne 0) { Write-Error "Python static type check failed"; exit 1 } } finally { diff --git a/tests/e2e/implementation_test.ps1 b/tests/e2e/implementation_test.ps1 index 7af2fbe8..5ef8d9e5 100644 --- a/tests/e2e/implementation_test.ps1 +++ b/tests/e2e/implementation_test.ps1 @@ -87,13 +87,14 @@ foreach ($language in $Lang) { Write-Host "`n--- Implementation .pyi consumer typecheck ---" -ForegroundColor Yellow $previousMypyPath = $env:MYPYPATH try { + $sourceRoot = Join-Path $directory "src" # Long generic delegate facade names can exceed MAX_PATH in a # shared-worktree checkout. Use extended paths, not registry/OS # changes or suppressed import diagnostics. - $env:MYPYPATH = if ($env:OS -eq "Windows_NT" -and -not $out.StartsWith('\\?\')) { - if ($out.StartsWith('\\')) { '\\?\UNC\' + $out.Substring(2) } - else { '\\?\' + $out } - } else { $out } + $env:MYPYPATH = if ($env:OS -eq "Windows_NT" -and -not $sourceRoot.StartsWith('\\?\')) { + if ($sourceRoot.StartsWith('\\')) { '\\?\UNC\' + $sourceRoot.Substring(2) } + else { '\\?\' + $sourceRoot } + } else { $sourceRoot } & $Python -m mypy --strict (Join-Path $PSScriptRoot "typecheck\python_implementation_api.py") $typecheckResults[$language] = $LASTEXITCODE -eq 0 if ($LASTEXITCODE -ne 0) { $failed++ } diff --git a/tests/e2e/prebuilt_codegen.tests.ps1 b/tests/e2e/prebuilt_codegen.tests.ps1 index e84a6872..a466bb18 100644 --- a/tests/e2e/prebuilt_codegen.tests.ps1 +++ b/tests/e2e/prebuilt_codegen.tests.ps1 @@ -24,7 +24,15 @@ try { Copy-Item -LiteralPath (Join-Path $PSScriptRoot $file) -Destination $scripts } Set-Content -LiteralPath (Join-Path $scratch "metadata.winmd") -Value "external metadata boundary" - Set-Content -LiteralPath $python -Value '$global:LASTEXITCODE = 0' + @' +if ($env:TYPECHECK_TRACE) { + @{ arguments = @($args); mypyPath = $env:MYPYPATH } | ConvertTo-Json -Compress | + Add-Content -LiteralPath $env:TYPECHECK_TRACE +} +$global:LASTEXITCODE = if ($args.Count -ge 2 -and $args[0] -eq "-m" -and $args[1] -eq "mypy") { + [int]$env:TYPECHECK_EXIT +} else { 0 } +'@ | Set-Content -LiteralPath $python @' @{ kind = "prebuilt"; arguments = @($args) } | ConvertTo-Json -Compress | Add-Content -LiteralPath $env:CODEGEN_TRACE @@ -45,6 +53,11 @@ $env:DYNWINRT_WIN32_WINMD = Join-Path $PSScriptRoot "metadata.winmd" $env:DYNWINRT_WINDOWS_WINMD = $env:DYNWINRT_WIN32_WINMD $env:CODEGEN_TRACE = Join-Path $PSScriptRoot "trace.jsonl" $env:CODEGEN_STOP = $case.stop +$env:TYPECHECK_TRACE = if ($case.ContainsKey("typecheckExit")) { + Join-Path $PSScriptRoot "typecheck-trace.jsonl" +} else { $null } +$env:TYPECHECK_EXIT = $case.typecheckExit +$env:MYPYPATH = "preserved-mypy-path" $parameters = $case.parameters & (Join-Path $PSScriptRoot "tests\e2e\$($case.script)") @parameters exit $LASTEXITCODE @@ -113,6 +126,46 @@ exit $LASTEXITCODE "run -p dynwinrt-codegen --profile coverage --target x86_64-pc-windows-msvc --quiet -- generate *") { throw "Omitted prebuilt override changed the developer/profile fallback" } + + # Trace the real orchestrators past generation, including typecheck failure. + # Native calls remain stubs here; actual generated-package checks run in E2E. + foreach ($script in @("e2e_test.ps1", "implementation_test.ps1")) { + foreach ($typecheckExit in @(0, 29)) { + $typecheckTrace = Join-Path $scratch "typecheck-trace.jsonl" + if (Test-Path $typecheckTrace) { Remove-Item -LiteralPath $typecheckTrace } + $parameters = @{ Lang = @("py"); Python = $python; Codegen = $prebuilt; KeepGenerated = $true } + if ($script -eq "e2e_test.ps1") { + $parameters.Suite = "standard" + $parameters.SkipBuild = $true + } + $caseFile = Join-Path $scratch "typecheck-case.json" + @{ + script = $script; parameters = $parameters; stop = 0 + typecheckExit = $typecheckExit + } | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $caseFile + $output = & $shell -NoProfile -File (Join-Path $scratch "harness.ps1") $caseFile 2>&1 | Out-String + $expectedExit = if ($typecheckExit -eq 0) { 0 } else { 1 } + if ($LASTEXITCODE -ne $expectedExit) { + throw "Unexpected $script typecheck exit $LASTEXITCODE (expected $expectedExit): $output" + } + $records = @(Get-Content -LiteralPath $typecheckTrace | ForEach-Object { $_ | ConvertFrom-Json }) + $checks = @($records | Where-Object { $_.arguments[0] -eq "-m" -and $_.arguments[1] -eq "mypy" }) + $prefix = if ($script -eq "implementation_test.ps1") { "implementations\" } else { "" } + $expectedSource = Join-Path $scripts "e2e_generated\${prefix}python_bindings\src" + if ($checks.Count -ne 1 -or $checks[0].mypyPath.Replace('\\?\', '') -ne $expectedSource) { + throw "$script must check the generated project's src directory: $($checks | ConvertTo-Json -Depth 5)" + } + $native = @($records | Where-Object { $_.arguments[0] -like "*\runners\*.py" }) + if ($typecheckExit -eq 0 -or $script -eq "implementation_test.ps1") { + if ($native.Count -eq 0) { throw "$script did not reach the expected native runner boundary" } + if (@($native | Where-Object { $_.mypyPath -ne "preserved-mypy-path" }).Count -ne 0) { + throw "$script did not restore MYPYPATH after its typecheck" + } + } elseif ($native.Count -ne 0) { + throw "$script continued past its failing static typecheck" + } + } + } Write-Host "Prebuilt WinRT/COM/Win32/implementation generation and Cargo fallback regressions passed." } finally { if (Test-Path -LiteralPath $scratch) { Remove-Item -LiteralPath $scratch -Recurse -Force } diff --git a/tests/e2e/runners/dispatcher_implementation_py.py b/tests/e2e/runners/dispatcher_implementation_py.py index ba9c8a38..695d03bf 100644 --- a/tests/e2e/runners/dispatcher_implementation_py.py +++ b/tests/e2e/runners/dispatcher_implementation_py.py @@ -80,6 +80,8 @@ def import_generated(directory): directory = directory.resolve() + name = json.loads((directory / ".dynwinrt-generator.json").read_text())["layout"]["import_name"] + directory = directory / "src" / name assert (directory / "__init__.py").is_file(), f"Not a generated package: {directory}" # Support the same long-path generated facades as the regular E2E runner. parent = str(directory.parent) diff --git a/tests/e2e/runners/implementation_py.py b/tests/e2e/runners/implementation_py.py index 7769d596..34369bbb 100644 --- a/tests/e2e/runners/implementation_py.py +++ b/tests/e2e/runners/implementation_py.py @@ -1298,8 +1298,9 @@ def run_one(case_id, generated): ) # Generated generic facade names can otherwise exceed Windows # MAX_PATH in this worktree even though codegen emitted valid files. - sys.path.insert(0, import_search_path(generated.parent)) - g = importlib.import_module(generated.name) + sys.path.insert(0, import_search_path(generated / "src")) + name = json.loads((generated / ".dynwinrt-generator.json").read_text())["layout"]["import_name"] + g = importlib.import_module(name) with dw.RoApartment(1), ExitStack() as cleanup: if case_id not in PUBLIC_VIEW_GC_CASES: cleanup.enter_context(dw.projected_lifetime_scope()) diff --git a/tests/e2e/runners/py_apartment_owner_reinitialization.py b/tests/e2e/runners/py_apartment_owner_reinitialization.py index d2976d2d..ba4aef42 100644 --- a/tests/e2e/runners/py_apartment_owner_reinitialization.py +++ b/tests/e2e/runners/py_apartment_owner_reinitialization.py @@ -34,7 +34,7 @@ def run_case(generated, mode, scenario): parameter_types = [] uri_type = None else: - sys.path.insert(0, os.path.dirname(os.path.abspath(generated))) + sys.path.insert(0, os.path.join(os.path.abspath(generated), "src")) package = os.path.basename(os.path.abspath(generated)) metadata = importlib.import_module( f"{package}.windows__foundation__deferral_completed_handler" diff --git a/tests/e2e/runners/py_apartment_reentrancy.py b/tests/e2e/runners/py_apartment_reentrancy.py index b2a920af..83c5e99a 100644 --- a/tests/e2e/runners/py_apartment_reentrancy.py +++ b/tests/e2e/runners/py_apartment_reentrancy.py @@ -21,7 +21,7 @@ def blocked_close(action): def run_case(generated, mode, scenario): - sys.path.insert(0, os.path.dirname(os.path.abspath(generated))) + sys.path.insert(0, os.path.join(os.path.abspath(generated), "src")) import dynwinrt as dw from dynwinrt.dynwinrt import _dynwinrt_track_native from python_bindings import PropertySet diff --git a/tests/e2e/runners/py_async_events.py b/tests/e2e/runners/py_async_events.py index 61c7bed5..c6727487 100644 --- a/tests/e2e/runners/py_async_events.py +++ b/tests/e2e/runners/py_async_events.py @@ -8,6 +8,7 @@ from contextvars import ContextVar import gc import importlib +import json from pathlib import Path import sys import tempfile @@ -376,8 +377,9 @@ def main(): parser.add_argument("--mode", type=int, choices=(0, 1), required=True) options = parser.parse_args() generated = Path(options.generated).resolve() - sys.path.insert(0, str(generated.parent)) - g = importlib.import_module(generated.name) + sys.path.insert(0, str(generated / "src")) + name = json.loads((generated / ".dynwinrt-generator.json").read_text())["layout"]["import_name"] + g = importlib.import_module(name) import dynwinrt as dw async def run(): diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index c6e156c0..f2fb8f0d 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -128,7 +128,7 @@ def wrap_arg(val): def run_isolated_apartment_check(generated_dir, package, script, marker, *args): env = os.environ.copy() - parent = os.path.dirname(os.path.abspath(generated_dir)) + parent = os.path.join(os.path.abspath(generated_dir), "src") env['PYTHONPATH'] = os.pathsep.join(filter(None, (parent, env.get('PYTHONPATH')))) env['DYNWINRT_E2E_PACKAGE_PARENT'] = parent child = subprocess.run( @@ -3866,7 +3866,7 @@ def observe_value(sender, args): runtime_module = importlib.import_module(f'{pkg_name}._runtime') module_paths = [ path - for path in sorted(Path(generated_dir).glob('*.py')) + for path in sorted((Path(generated_dir) / 'src' / pkg_name).glob('*.py')) if path.name not in ('__init__.py', '_runtime.py') ] reference_modules = [] @@ -4184,10 +4184,10 @@ def main(): parser.add_argument('--output', default=None, help='Path to write results.json') args = parser.parse_args() - # Add parent of generated dir to sys.path so package imports work - # Generated files use relative imports (from .xxx import), so the dir must be a package - gen_parent = os.path.dirname(os.path.abspath(args.generated)) - gen_pkg = os.path.basename(os.path.abspath(args.generated)) + # This source-only harness deliberately avoids installing generated projects. + gen_parent = os.path.join(os.path.abspath(args.generated), "src") + with open(os.path.join(args.generated, ".dynwinrt-generator.json"), encoding="utf-8") as stamp: + gen_pkg = json.load(stamp)["layout"]["import_name"] sys.path.insert(0, gen_parent) # Init WinRT diff --git a/tests/e2e/runners/py_winui_lifetime.py b/tests/e2e/runners/py_winui_lifetime.py index 7791711b..c0e940ae 100644 --- a/tests/e2e/runners/py_winui_lifetime.py +++ b/tests/e2e/runners/py_winui_lifetime.py @@ -16,6 +16,7 @@ def run(sample_root, mode, require_owner_hook): sys.path.insert(0, str(sample_root)) + sys.path.insert(0, str(sample_root / "generated" / "src")) import dynwinrt as dw from dynwinrt import dynwinrt as native diff --git a/tests/e2e/runners/py_winui_runner.py b/tests/e2e/runners/py_winui_runner.py index e55880a1..f67e3b45 100644 --- a/tests/e2e/runners/py_winui_runner.py +++ b/tests/e2e/runners/py_winui_runner.py @@ -96,7 +96,7 @@ def load_type(package: str, namespace: str, name: str): def run(bindings_dir: Path, bootstrap_dll: Path, major: int, minor: int) -> None: os.environ["WINAPPSDK_BOOTSTRAP_DLL_PATH"] = str(bootstrap_dll) - sys.path.insert(0, str(bindings_dir.parent)) + sys.path.insert(0, str(bindings_dir / "src")) package = bindings_dir.name from dynwinrt import ( diff --git a/tests/e2e/runners/registration_identity_py.py b/tests/e2e/runners/registration_identity_py.py index 9f27fb03..536cc16f 100644 --- a/tests/e2e/runners/registration_identity_py.py +++ b/tests/e2e/runners/registration_identity_py.py @@ -46,7 +46,9 @@ def remove_property_changed(self, token): if __name__ == "__main__": - sys.path.insert(0, str(Path(sys.argv[1]).resolve())) + root = Path(sys.argv[1]).resolve() + for package in ("windows_py", "winui_py"): + sys.path.insert(0, str(root / package / "src")) with RoApartment(1): results = [check(name) for name in sys.argv[2].split(",")] print(json.dumps({ diff --git a/tools/dynwinrt-codegen/README.md b/tools/dynwinrt-codegen/README.md index b5f0f848..f40d091b 100644 --- a/tools/dynwinrt-codegen/README.md +++ b/tools/dynwinrt-codegen/README.md @@ -10,6 +10,12 @@ bindings for [dynwinrt](https://github.com/microsoft/dynwinrt): - Contract-driven Win32 DLL exports from `Windows.Win32.winmd` as JavaScript and TypeScript +Python output uses an installable `src/` project layout. Install the +`--output` directory normally or editable; do not add its parent to the import +path. Upgrading from preview.23 or earlier requires clean, complete regeneration +and reinstallation; installed imports and the runtime ABI are unchanged. See the +[Python layout and migration guide](python/README.md#generated-output). + The command is available for Windows x64 and ARM64. Generated JavaScript uses `@microsoft/dynwinrt`; generated Python uses `dynwinrt`. diff --git a/tools/dynwinrt-codegen/python/README.md b/tools/dynwinrt-codegen/python/README.md index 2d72b968..e5597505 100644 --- a/tools/dynwinrt-codegen/python/README.md +++ b/tools/dynwinrt-codegen/python/README.md @@ -181,6 +181,43 @@ The output is an installable Python package. Its generated `pyproject.toml` pins `dynwinrt` to the generator's exact version and requires CPython 3.11–3.14. `.pyi` files and a `py.typed` marker are emitted by default. +`--output` is the **installable project root**, not the import package directory: + +```text +generated_uri/ + pyproject.toml + setup.cfg + .dynwinrt-generator.json + .dynwinrt-generated-files + .dynwinrt-generated-types + src/ + generated_uri/ + __init__.py + __init__.pyi + py.typed + _runtime.py + _typing.pyi + windows/ + windows__foundation__uri.py + windows__foundation__uri.pyi +``` + +The import/distribution names still come from the normalized final output leaf +(`My Bindings` becomes import `my_bindings` and distribution `my-bindings`). +Setuptools uses the global `package-dir = { "" = "src" }` mapping. A default +editable install adds the source directory through an ordinary path `.pth`; +no dynamic editable finder, custom import hook, or strict/compat mode is needed. +Use `python -m pip install -e .\generated_uri` for development. uv supports +`uv pip install -e .\generated_uri` or a local editable dependency with `uv sync`; +Poetry supports a local path dependency with `develop = true`. Select that +environment in the editor and type checker. + +Bootstrap projects additionally keep `MANIFEST.in` and +`.dynwinrt-winappsdk.json` at the project root, and the build-only hook at +`src/_dynwinrt_build/wheel.py`. The provider, JSON configuration, DLLs and notices +are inside `src/`. The hook is included in sdists but excluded from +runtime wheels; neither `src` nor the hook becomes an installed runtime package. + Transitive metadata dependencies are resolved automatically. Namespace packages and imports mirror the metadata hierarchy, while public members use Python snake_case naming. XML documentation found beside the input metadata is @@ -238,7 +275,8 @@ No runtime API change or consumer cast is required. ### Producer version and regeneration -`.dynwinrt-generator.json` records `generator_version`, the complete generator +`.dynwinrt-generator.json` records the package layout/import identity and +`generator_version`, the complete generator package version, including any prerelease/preview suffix. This is a producer stamp, not the generated distribution version, runtime dependency version, or the type inventory's `schema_version`. @@ -255,8 +293,32 @@ or migrates incompatible output. Every generator upgrade therefore requires full regeneration, followed by rebuilding/reinstalling the affected packages with the matching runtime. -Unversioned development changes with the same package version are not detected -by this check; use fresh output for those changes too. +Unversioned development changes other than recorded layout changes are not +detected by this check; use fresh output for those changes too. + +### Breaking layout upgrade from preview.23 and earlier + +Older releases placed Python modules directly in `--output` and mapped a named +package to `"."`. Clean that dedicated output and regenerate the **whole** +selection with the new generator, then reinstall it with the matching runtime. +Old-layout output is rejected even when its producer version string matches; +do not move only some files or edit/remove the producer stamp to bypass the guard. +Installed namespace, flat-module and root imports, the installation command, +runtime version pin and native ABI are unchanged. + +Replace old examples that add `output.parent` to `sys.path`/`PYTHONPATH` with a +normal or editable installation. For deliberate uninstalled source use, the +search directory is now `/src`, not `` or its parent. Source-only +imports still do not provide distribution metadata for Bootstrap discovery. + +Regeneration at the same project path is atomic. An existing editable install +sees added types in a **new Python process** and in a new checker run without +reinstallation; already imported modules are not hot-reloaded. Reinstall after +moving/renaming the project, changing package/dependency versions, or adding or +changing entry points. If the output leaf is renamed, the next generation +relocates only recorded package files inside the transaction, rejects destination +conflicts, updates manifests and retains the semantic type inventory. It does +not leave a runtime alias under the previous import name. ### Closed-generic stub migration diff --git a/tools/dynwinrt-codegen/src/codegen/package.rs b/tools/dynwinrt-codegen/src/codegen/package.rs index 37d5ad22..27682dbc 100644 --- a/tools/dynwinrt-codegen/src/codegen/package.rs +++ b/tools/dynwinrt-codegen/src/codegen/package.rs @@ -118,13 +118,12 @@ pub fn render_python_pyproject_with_winappsdk( [tool.setuptools]\n\ {explicit_package_data}\ packages = [{packages}]\n\ - package-dir = {{ \"{import_name}\" = \".\" }}\n\ + package-dir = {{ \"\" = \"src\" }}\n\ \n\ {build_commands}\ [tool.setuptools.package-data]\n\ {package_data}\n", distribution_name = input.distribution_name, - import_name = input.import_name, packages = packages.join(", "), package_data = package_data.join("\n"), package_version = input.package_version, @@ -395,6 +394,7 @@ mod tests { \"contoso_winrt.windows.foundation\"]" )); assert!(out.contains("dependencies = [\"dynwinrt==0.4.5\"]")); + assert!(out.contains("package-dir = { \"\" = \"src\" }")); assert!(out.contains("\"contoso_winrt\" = [\"py.typed\", \"*.pyi\"]")); assert!(out.contains("\"contoso_winrt.windows\" = [\"*.pyi\"]")); assert!(out.contains("\"contoso_winrt.windows.foundation\" = [\"*.pyi\"]")); diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index b8f312ab..37c28227 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -169,6 +169,7 @@ enum Commands { lang: String, /// Dedicated codegen-owned output directory. + /// For Python, this is the installable project root; package sources are in src/. /// Existing contents may be replaced or removed; do not store handwritten files here. #[arg(long, default_value = "./generated", value_name = "DIR")] output: String, @@ -562,6 +563,9 @@ fn run() -> Result<(), String> { .map(|transaction| transaction.stage_dir().to_path_buf()) .unwrap_or_else(|| final_output_dir.to_path_buf()); let output_dir = effective_output_dir.as_path(); + if lang == "py" && !dry_run { + prepare_python_output_layout(output_dir, final_output_dir)?; + } let bootstrap = winappsdk_output::prepare( output_dir, &lang, @@ -1612,7 +1616,7 @@ fn generate_for_types( public_types .retain(|identity| !python_type_shadowed_by_class(identity, &class_identities_all)); python_output_paths::warn( - final_output_dir, + &PythonOutputLayout::new(final_output_dir, final_output_dir)?.package_root(), &python_output_paths::dry_run_source_files( context, &implementations, @@ -4135,6 +4139,10 @@ fn generate_py_files( use dynwinrt_codegen::codegen::python_stub; let previous = read_python_type_inventory(output_dir)?; + let layout = python_output_layout(output_dir)?; + let package_root = layout.package_root(); + ensure_safe_generated_parent(output_dir, &package_root.join("__init__.py"))?; + let output_dir = package_root.as_path(); let mut struct_interfaces = all_interfaces.to_vec(); struct_interfaces.extend_from_slice(shared_interfaces); let mut current = python_generated_types(all_classes, &struct_interfaces, all_enums); @@ -4307,7 +4315,7 @@ fn generate_py_files( write_file(&marker, "")?; } reconcile_python_implementation_root_exports(context, output_dir, &previous, &types, pyi)?; - write_python_type_inventory(output_dir, &types)?; + write_python_type_inventory(&layout.project_root, &types)?; Ok(()) } @@ -4426,6 +4434,9 @@ fn migrate_python_implementation_inventory( supplemental: &[meta::InterfaceMeta], ) -> Result, String> { let mut types = read_python_type_inventory(output_dir)?; + let layout = python_output_layout(output_dir)?; + let package_root = layout.package_root(); + let output_dir = package_root.as_path(); let class_names = classes .iter() .map(|class| (class.namespace.clone(), class.name.clone())) @@ -4511,7 +4522,7 @@ fn migrate_python_implementation_inventory( missing.join(", ") )); } - write_python_type_inventory(output_dir, &types)?; + write_python_type_inventory(&layout.project_root, &types)?; Ok(upgrades) } @@ -4710,6 +4721,10 @@ fn write_python_package_indexes( } else { Vec::new() }; + let layout = python_output_layout(output_dir)?; + let package_root = layout.package_root(); + ensure_safe_generated_parent(output_dir, &package_root.join("__init__.py"))?; + let output_dir = package_root.as_path(); all_types = merge_python_generated_types(all_types, current_types); let module_identities = all_types @@ -4850,7 +4865,7 @@ fn write_python_package_indexes( for (namespace, group) in groups { write_python_namespace_group(&context, output_dir, &namespace, &group, pyi, append)?; } - write_python_type_inventory(output_dir, &all_types)?; + write_python_type_inventory(&layout.project_root, &all_types)?; Ok(()) } @@ -6825,19 +6840,15 @@ fn write_python_package_manifest(output_dir: &Path, final_output_dir: &Path) -> )); } } - let leaf = final_output_dir - .file_name() - .and_then(|name| name.to_str()) - .ok_or_else(|| { - format!( - "Cannot derive Python package name from '{}'", - final_output_dir.display() - ) - })?; - let import_name = normalize_python_package_name(leaf); + let layout = PythonOutputLayout::new(output_dir, final_output_dir)?; + let import_name = &layout.import_name; let distribution_name = import_name.replace('_', "-"); let version = env!("CARGO_PKG_VERSION"); - let namespace_packages = collect_python_namespace_packages(output_dir)?; + let namespace_packages = if layout.package_root().is_dir() { + collect_python_namespace_packages(&layout.package_root())? + } else { + Vec::new() + }; let manifest = package::render_python_pyproject_with_winappsdk( &package::PythonPackageManifestInput { distribution_name: &distribution_name, @@ -6896,6 +6907,163 @@ const PYTHON_GENERATOR_METADATA: &str = ".dynwinrt-generator.json"; #[serde(deny_unknown_fields)] struct PythonGeneratorMetadata { generator_version: String, + #[serde(default)] + layout: Option, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct PythonPackageLayout { + version: u32, + import_name: String, +} + +struct PythonOutputLayout { + project_root: PathBuf, + import_name: String, +} + +impl PythonOutputLayout { + fn new(project_root: &Path, final_output: &Path) -> Result { + let leaf = final_output + .file_name() + .and_then(|name| name.to_str()) + .ok_or_else(|| { + format!( + "Cannot derive Python package name from '{}'", + final_output.display() + ) + })?; + Ok(Self { + project_root: project_root.into(), + import_name: normalize_python_package_name(leaf), + }) + } + + fn package_prefix(&self) -> PathBuf { + Path::new("src").join(&self.import_name) + } + + fn package_root(&self) -> PathBuf { + self.project_root.join(self.package_prefix()) + } +} + +fn python_output_layout(output_dir: &Path) -> Result { + let path = output_dir.join(PYTHON_GENERATOR_METADATA); + match fs::read_to_string(&path) { + Ok(content) => { + let metadata: PythonGeneratorMetadata = serde_json::from_str(&content) + .map_err(|error| format!("Invalid {}: {error}", path.display()))?; + let layout = metadata.layout.ok_or_else(|| { + python_regeneration_error( + output_dir, + "Python output predates the src package layout", + ) + })?; + if layout.version != 1 + || layout.import_name.is_empty() + || normalize_python_package_name(&layout.import_name) != layout.import_name + { + return Err(python_regeneration_error( + output_dir, + "Invalid Python src package layout", + )); + } + Ok(PythonOutputLayout { + project_root: output_dir.into(), + import_name: layout.import_name, + }) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + PythonOutputLayout::new(output_dir, output_dir) + } + Err(error) => Err(format!("Failed to read {}: {error}", path.display())), + } +} + +fn prepare_python_output_layout(output_dir: &Path, final_output: &Path) -> Result<(), String> { + let layout = PythonOutputLayout::new(output_dir, final_output)?; + if output_dir.join(PYTHON_GENERATOR_METADATA).is_file() { + let previous = python_output_layout(output_dir)?; + if previous.import_name != layout.import_name { + // Validate retained resources before relocating their ownership records. + winappsdk_output::prepare(output_dir, "py", "dynwinrt", None)?; + let inventory = output_dir.join(PYTHON_GENERATED_INVENTORY); + let content = fs::read_to_string(&inventory) + .map_err(|error| format!("Failed to read {}: {error}", inventory.display()))?; + let mut relocated = Vec::new(); + let mut moves = Vec::new(); + for line in content.lines() { + let relative = Path::new(line); + if !is_safe_relative_path(relative) { + return Err(format!("Invalid generated inventory path: {line}")); + } + if let Ok(suffix) = relative.strip_prefix(previous.package_prefix()) { + let target = layout.package_prefix().join(suffix); + if !is_generator_owned_python_source_file(output_dir, relative)? + || path_entry_exists(&output_dir.join(&target)) + { + return Err(format!( + "Cannot relocate generated Python file `{line}` to '{}': source is not owned or destination already exists", + target.display() + )); + } + ensure_safe_generated_destination(output_dir, &output_dir.join(&target))?; + moves.push((relative.to_path_buf(), target.clone())); + relocated.push(target); + } else { + relocated.push(relative.to_path_buf()); + } + } + for (source, target) in &moves { + fs::rename(output_dir.join(source), output_dir.join(target)) + .map_err(|error| format!("Failed to relocate {}: {error}", source.display()))?; + } + winappsdk_output::relocate_python_package(output_dir, &previous, &layout)?; + write_file( + &inventory, + &format!( + "{}\n", + relocated + .iter() + .map(|path| path.to_string_lossy()) + .collect::>() + .join("\n") + ), + )?; + let mut directories = moves + .iter() + .filter_map(|(source, _)| source.parent()) + .flat_map(|parent| parent.ancestors()) + .filter(|parent| parent.starts_with(previous.package_prefix())) + .map(Path::to_path_buf) + .collect::>() + .into_iter() + .collect::>(); + directories.sort_by_key(|path| std::cmp::Reverse(path.components().count())); + for relative in directories { + let path = output_dir.join(relative); + match fs::remove_dir(&path) { + Ok(()) => {} + Err(error) + if matches!( + error.kind(), + std::io::ErrorKind::NotFound | std::io::ErrorKind::DirectoryNotEmpty + ) => {} + Err(error) => { + return Err(format!( + "Failed to remove old package directory {}: {error}", + path.display() + )); + } + } + } + } + } + fs::create_dir_all(output_dir) + .map_err(|error| format!("Failed to create {}: {error}", output_dir.display()))?; + write_python_layout_metadata(&layout) } fn python_regeneration_error(output_dir: &Path, reason: &str) -> String { @@ -6959,6 +7127,7 @@ fn validate_python_generator_version_against( ), )); } + python_output_layout(output_dir)?; } Err(error) if error.kind() == std::io::ErrorKind::NotFound => { if path_entry_exists(&output_dir.join(PYTHON_GENERATED_INVENTORY)) @@ -6979,13 +7148,21 @@ fn validate_python_generator_version_against( } fn write_python_generator_metadata(output_dir: &Path) -> Result<(), String> { + write_python_layout_metadata(&python_output_layout(output_dir)?) +} + +fn write_python_layout_metadata(layout: &PythonOutputLayout) -> Result<(), String> { let metadata = PythonGeneratorMetadata { generator_version: env!("CARGO_PKG_VERSION").into(), + layout: Some(PythonPackageLayout { + version: 1, + import_name: layout.import_name.clone(), + }), }; let content = serde_json::to_string_pretty(&metadata) .map_err(|error| format!("Failed to serialize Python generator metadata: {error}"))?; write_file( - &output_dir.join(PYTHON_GENERATOR_METADATA), + &layout.project_root.join(PYTHON_GENERATOR_METADATA), &format!("{content}\n"), ) } @@ -7061,7 +7238,12 @@ fn remove_all_generated_python_stubs(output_dir: &Path) -> Result<(), String> { } Ok(()) } - visit(output_dir) + visit(output_dir)?; + let package_root = python_output_layout(output_dir)?.package_root(); + if package_root.is_dir() { + visit(&package_root)?; + } + Ok(()) } fn clean_python_generated_output(output_dir: &Path) -> Result<(), String> { @@ -7093,7 +7275,7 @@ fn clean_python_generated_output(output_dir: &Path) -> Result<(), String> { let mut parent_dirs = HashSet::new(); for (relative, owned) in files { - if !owned { + if !owned || relative == Path::new(PYTHON_GENERATOR_METADATA) { continue; } let path = output_dir.join(&relative); @@ -7160,6 +7342,7 @@ fn collect_generated_python_files( fn visit( root: &Path, current: &Path, + package_root: &Path, include_root_manifest: bool, include_root_marker: bool, files: &mut Vec, @@ -7174,10 +7357,14 @@ fn collect_generated_python_files( .file_type() .map_err(|e| format!("Failed to inspect {}: {}", path.display(), e))?; if file_type.is_dir() { - if is_generated_python_namespace(&path)? { + if path == package_root + || is_generated_python_namespace(&path)? + || (current == root && entry.file_name() == "src") + { visit( root, &path, + package_root, include_root_manifest, include_root_marker, files, @@ -7190,7 +7377,9 @@ fn collect_generated_python_files( } let generated = match entry.file_name().to_str() { - Some("py.typed") => include_root_marker && current == root, + Some("py.typed") => { + include_root_marker && (current == root || current == package_root) + } Some("pyproject.toml" | "setup.cfg") => include_root_manifest && current == root, Some(PYTHON_GENERATOR_METADATA) => include_root_manifest && current == root, Some(name) if name.ends_with(".py") || name.ends_with(".pyi") => { @@ -7211,6 +7400,7 @@ fn collect_generated_python_files( visit( output_dir, output_dir, + &python_output_layout(output_dir)?.package_root(), include_root_manifest, include_root_marker, &mut files, @@ -7252,6 +7442,10 @@ fn is_generator_owned_python_source_file( if winappsdk_output::owns(output_dir, relative)? { return Ok(true); } + let package_prefix = python_output_layout(output_dir)?.package_prefix(); + if relative == package_prefix.join("py.typed") { + return Ok(true); + } let parent = relative .parent() .filter(|parent| !parent.as_os_str().is_empty()); @@ -7283,6 +7477,9 @@ fn is_generator_owned_python_source_file( return Ok(false); }; current.push(component); + if current == output_dir.join("src") || current == output_dir.join(&package_prefix) { + continue; + } if !is_generated_python_namespace(¤t)? { return Ok(false); } @@ -9227,6 +9424,7 @@ mod tests { #[test] fn python_duplicate_short_names_use_namespace_facades() { let output = test_directory("namespace-facades"); + let package = python_output_layout(&output).unwrap().package_root(); fs::create_dir_all(&output).unwrap(); let classes = vec![ meta::ClassMeta { @@ -9246,10 +9444,10 @@ mod tests { write_python_package_indexes(&output, &classes, &[], &[], &HashSet::new(), true, false) .unwrap(); - let root = fs::read_to_string(output.join("__init__.py")).unwrap(); + let root = fs::read_to_string(package.join("__init__.py")).unwrap(); assert!(!root.contains("ResourceManager")); let contoso = fs::read_to_string( - output + package .join("contoso") .join("resources") .join("resource_manager.py"), @@ -9259,7 +9457,7 @@ mod tests { contoso.contains("from ...contoso__resources__resource_manager import ResourceManager") ); let fabrikam = fs::read_to_string( - output + package .join("fabrikam") .join("resources") .join("resource_manager.py"), @@ -9276,6 +9474,7 @@ mod tests { #[test] fn incremental_python_generation_removes_ambiguous_root_export() { let output = test_directory("incremental-root"); + let package = python_output_layout(&output).unwrap().package_root(); fs::create_dir_all(&output).unwrap(); let contoso = meta::ClassMeta { name: "ResourceManager".into(), @@ -9301,7 +9500,7 @@ mod tests { ) .unwrap(); assert!( - fs::read_to_string(output.join("__init__.py")) + fs::read_to_string(package.join("__init__.py")) .unwrap() .contains("ResourceManager") ); @@ -9317,19 +9516,19 @@ mod tests { ) .unwrap(); assert!( - !fs::read_to_string(output.join("__init__.py")) + !fs::read_to_string(package.join("__init__.py")) .unwrap() .contains("ResourceManager") ); assert!( - output + package .join("contoso") .join("resources") .join("resource_manager.py") .is_file() ); assert!( - output + package .join("fabrikam") .join("resources") .join("resource_manager.py") @@ -9342,6 +9541,7 @@ mod tests { #[test] fn incremental_python_generation_removes_disambiguated_generic_root_export() { let output = test_directory("incremental-generic-root"); + let package = python_output_layout(&output).unwrap().package_root(); fs::create_dir_all(&output).unwrap(); let interface = |namespace: &str| meta::InterfaceMeta { name: "IBox_Point".into(), @@ -9370,7 +9570,7 @@ mod tests { true, ) .unwrap(); - let first_root = fs::read_to_string(output.join("__init__.py")).unwrap(); + let first_root = fs::read_to_string(package.join("__init__.py")).unwrap(); assert!( first_root.contains("IBox_Example_Left_Point_struct"), "{first_root}" @@ -9386,7 +9586,7 @@ mod tests { true, ) .unwrap(); - let final_root = fs::read_to_string(output.join("__init__.py")).unwrap(); + let final_root = fs::read_to_string(package.join("__init__.py")).unwrap(); assert!(!final_root.contains("IBox_"), "{final_root}"); fs::remove_dir_all(output).unwrap(); @@ -9457,13 +9657,19 @@ mod tests { } let mut output = BTreeMap::new(); - visit(root, root, &mut output); + let package = python_output_layout(root).unwrap().package_root(); + visit(&package, &package, &mut output); + output.insert( + PYTHON_TYPE_INVENTORY.into(), + fs::read_to_string(root.join(PYTHON_TYPE_INVENTORY)).unwrap(), + ); output } #[test] fn same_short_interfaces_and_delegates_use_semantic_identity() { let output = test_directory("same-short-python-identities"); + let package = python_output_layout(&output).unwrap().package_root(); fs::create_dir_all(&output).unwrap(); let left_delegate = colliding_delegate("Example.Left", "11111111-1111-1111-1111-111111111111"); @@ -9544,8 +9750,8 @@ mod tests { write_python_package_indexes(&output, &classes, &interfaces, &[], &ambiguity, true, false) .unwrap(); - let left = fs::read_to_string(output.join("example__left__i_value.py")).unwrap(); - let right = fs::read_to_string(output.join("example__right__i_value.py")).unwrap(); + let left = fs::read_to_string(package.join("example__left__i_value.py")).unwrap(); + let right = fs::read_to_string(package.join("example__right__i_value.py")).unwrap(); assert!( left.contains( "_dynwinrt_symbol('example__left__changed_handler', 'IID_ChangedHandler')" @@ -9557,7 +9763,7 @@ mod tests { ) ); let cross = - fs::read_to_string(output.join("example__cross__i_cross_namespace.py")).unwrap(); + fs::read_to_string(package.join("example__cross__i_cross_namespace.py")).unwrap(); assert!( cross.contains("IValue as Example_Left_IValue_interface"), "{cross}" @@ -9580,7 +9786,7 @@ mod tests { cross.contains("44444444-4444-4444-4444-444444444444"), "{cross}" ); - let combined = fs::read_to_string(output.join("example__cross__combined.py")).unwrap(); + let combined = fs::read_to_string(package.join("example__cross__combined.py")).unwrap(); assert!( combined.contains("IID_Example_Left_IValue_interface"), "{combined}" @@ -9597,12 +9803,12 @@ mod tests { combined.contains("_Example_Right_IValue_interface = DynWinRTType.register_interface"), "{combined}" ); - let root = fs::read_to_string(output.join("__init__.py")).unwrap(); + let root = fs::read_to_string(package.join("__init__.py")).unwrap(); assert!(!root.contains("IValue"), "{root}"); assert!(!root.contains("ChangedHandler"), "{root}"); for namespace in ["left", "right"] { let facade = - fs::read_to_string(output.join("example").join(namespace).join("__init__.py")) + fs::read_to_string(package.join("example").join(namespace).join("__init__.py")) .unwrap(); assert!(facade.contains("\"IValue\""), "{facade}"); assert!(facade.contains("\"IID_ChangedHandler\""), "{facade}"); @@ -9725,6 +9931,7 @@ mod tests { #[test] fn python_implementation_pair_union_tracks_incremental_support_and_indexes() { let output = test_directory("implementation-pair-incremental"); + let package = python_output_layout(&output).unwrap().package_root(); fs::create_dir_all(&output).unwrap(); let interface = |namespace: &str, iid: &str| meta::InterfaceMeta { namespace: namespace.into(), @@ -9762,32 +9969,32 @@ mod tests { .unwrap(); }; emit(std::slice::from_ref(&left)); - let first = fs::read_to_string(output.join("_implementation_types.pyi")).unwrap(); + let first = fs::read_to_string(package.join("_implementation_types.pyi")).unwrap(); assert!(first.contains(".example__left__i_value import _ImplementationPair")); assert!(!first.contains("example__right__i_value")); fs::write( - output.join("unrelated.pyi"), + package.join("unrelated.pyi"), format!( "{GENERATED_PYTHON_HEADER}_ImplementationPair: TypeAlias = tuple[object, object]\n" ), ) .unwrap(); emit(std::slice::from_ref(&right)); - let complete = fs::read_to_string(output.join("_implementation_types.pyi")).unwrap(); + let complete = fs::read_to_string(package.join("_implementation_types.pyi")).unwrap(); assert!( !complete.contains("unrelated"), "pair membership must come from validated inventory, never stub text" ); assert!(complete.contains(".example__left__i_value import _ImplementationPair")); assert!(complete.contains(".example__right__i_value import _ImplementationPair")); - assert!(!output.join("_implementation_types.py").exists()); + assert!(!package.join("_implementation_types.py").exists()); assert!( - !fs::read_to_string(output.join("__init__.py")) + !fs::read_to_string(package.join("__init__.py")) .unwrap() .contains("_Pair") ); for namespace in ["left", "right"] { - let stub = output.join("example").join(namespace).join("__init__.pyi"); + let stub = package.join("example").join(namespace).join("__init__.pyi"); let inventory = read_python_type_inventory(&output).unwrap(); let handler = inventory .iter() @@ -9813,11 +10020,11 @@ mod tests { .diagnostics .push("Unsupported contract".into()); emit(std::slice::from_ref(&unsupported)); - let reduced = fs::read_to_string(output.join("_implementation_types.pyi")).unwrap(); + let reduced = fs::read_to_string(package.join("_implementation_types.pyi")).unwrap(); assert!(!reduced.contains("example__left__i_value")); assert!(reduced.contains("example__right__i_value")); for extension in ["py", "pyi"] { - let namespace = output.join("example").join("left"); + let namespace = package.join("example").join("left"); for module in ["__init__", "i_value"] { let text = fs::read_to_string(namespace.join(format!("{module}.{extension}"))).unwrap(); @@ -9828,16 +10035,16 @@ mod tests { emit(std::slice::from_ref(&left)); assert_eq!( complete, - fs::read_to_string(output.join("_implementation_types.pyi")).unwrap() + fs::read_to_string(package.join("_implementation_types.pyi")).unwrap() ); emit(std::slice::from_ref(&right)); assert_eq!( complete, - fs::read_to_string(output.join("_implementation_types.pyi")).unwrap() + fs::read_to_string(package.join("_implementation_types.pyi")).unwrap() ); remove_all_generated_python_stubs(&output).unwrap(); - assert!(!output.join("_implementation_types.pyi").exists()); - assert!(output.join("example__left__i_value.py").exists()); + assert!(!package.join("_implementation_types.pyi").exists()); + assert!(package.join("example__left__i_value.py").exists()); fs::remove_dir_all(output).unwrap(); } @@ -10701,21 +10908,28 @@ mod tests { #[test] fn python_generation_emits_shared_runtime_and_typing_support() { let output = test_directory("python-shared-support"); + let package = python_output_layout(&output).unwrap().package_root(); fs::create_dir_all(&output).unwrap(); let context = python::PythonProjectionContext::packaged([]).unwrap(); generate_py_files(&context, &output, &[], &[], &[], &[], &HashSet::new(), true).unwrap(); - assert!(output.join("_runtime.py").is_file()); - assert!(output.join("_runtime.pyi").is_file()); - assert!(output.join("_typing.pyi").is_file()); - assert!(output.join("py.typed").is_file()); + assert!(package.join("_runtime.py").is_file()); + assert!(package.join("_runtime.pyi").is_file()); + assert!(package.join("_typing.pyi").is_file()); + assert!(package.join("py.typed").is_file()); + let files = collect_generated_python_files(&output, false, true).unwrap(); + let prefix = python_output_layout(&output).unwrap().package_prefix(); + for file in ["_runtime.py", "_runtime.pyi", "_typing.pyi", "py.typed"] { + assert!(files.contains(&prefix.join(file)), "{file}"); + } fs::remove_dir_all(output).unwrap(); } #[test] fn python_generation_uses_one_canonical_struct_module() { let output = test_directory("python-canonical-struct"); + let package = python_output_layout(&output).unwrap().package_root(); fs::create_dir_all(&output).unwrap(); let point = TypeMeta::Struct { namespace: "Windows.Foundation".into(), @@ -10769,9 +10983,9 @@ mod tests { ) .unwrap(); - let class_py = fs::read_to_string(output.join("contoso__widget.py")).unwrap(); - let class_pyi = fs::read_to_string(output.join("contoso__widget.pyi")).unwrap(); - let struct_py = fs::read_to_string(output.join("windows__foundation__point.py")).unwrap(); + let class_py = fs::read_to_string(package.join("contoso__widget.py")).unwrap(); + let class_pyi = fs::read_to_string(package.join("contoso__widget.pyi")).unwrap(); + let struct_py = fs::read_to_string(package.join("windows__foundation__point.py")).unwrap(); assert!(class_py.contains("from .windows__foundation__point import Point")); assert!(class_pyi.contains("from .windows__foundation__point import Point")); assert!(!class_py.contains("\nclass Point:")); @@ -10788,27 +11002,27 @@ mod tests { false, ) .unwrap(); - let point_facade = fs::read_to_string(output.join("windows/foundation/point.py")).unwrap(); + let point_facade = fs::read_to_string(package.join("windows/foundation/point.py")).unwrap(); assert!(point_facade.contains("Point.__module__ = __name__")); assert!(point_facade.contains("Point_TYPE")); assert!(point_facade.contains("pack_point")); assert!(point_facade.contains("unpack_point")); - let point_stub = fs::read_to_string(output.join("windows/foundation/point.pyi")).unwrap(); + let point_stub = fs::read_to_string(package.join("windows/foundation/point.pyi")).unwrap(); assert!(point_stub.contains("Point_TYPE as Point_TYPE")); assert!(point_stub.contains("pack_point as pack_point")); assert!(point_stub.contains("unpack_point as unpack_point")); let foundation_index = - fs::read_to_string(output.join("windows/foundation/__init__.py")).unwrap(); + fs::read_to_string(package.join("windows/foundation/__init__.py")).unwrap(); assert!(foundation_index.contains("def __getattr__(name):")); assert!(!foundation_index.contains("from .point import")); assert!(foundation_index.contains("\"Point\": (\".point\", \"Point\")")); assert!(!foundation_index.contains("Point_TYPE")); - let root_index = fs::read_to_string(output.join("__init__.py")).unwrap(); + let root_index = fs::read_to_string(package.join("__init__.py")).unwrap(); assert!(root_index.contains("\"Point\": (\".windows.foundation.point\", \"Point\")")); assert!(root_index.contains("\"Widget\": (\".contoso.widget\", \"Widget\")")); assert!(!root_index.contains("windows__foundation__point")); assert!( - !fs::read_to_string(output.join("contoso/widget.py")) + !fs::read_to_string(package.join("contoso/widget.py")) .unwrap() .contains("Point") ); @@ -11000,7 +11214,7 @@ mod tests { let preview = "0.1.0-preview.21"; fs::write( output.join(PYTHON_GENERATOR_METADATA), - format!(r#"{{"generator_version":"{preview}"}}"#), + format!(r#"{{"generator_version":"{preview}","layout":{{"version":1,"import_name":"bindings"}}}}"#), ) .unwrap(); validate_python_generator_version_against(&output, preview).unwrap(); @@ -11181,6 +11395,7 @@ mod tests { #[test] fn type_facades_keep_abi_symbols_while_public_indexes_export_types_only() { let output = test_directory("stub-reexports"); + let package = python_output_layout(&output).unwrap().package_root(); fs::create_dir_all(&output).unwrap(); let interface = meta::InterfaceMeta { name: "IWidget".into(), @@ -11201,7 +11416,7 @@ mod tests { .unwrap(); let facade = fs::read_to_string( - output + package .join("contoso") .join("foundation") .join("i_widget.pyi"), @@ -11209,17 +11424,17 @@ mod tests { .unwrap(); assert!(facade.contains("IID_IWidget as IID_IWidget")); assert!(facade.contains("IWidget as IWidget")); - let root_runtime = fs::read_to_string(output.join("__init__.py")).unwrap(); + let root_runtime = fs::read_to_string(package.join("__init__.py")).unwrap(); assert!(root_runtime.contains("def __getattr__(name):")); assert!( root_runtime.contains("\"IWidget\": (\".contoso.foundation.i_widget\", \"IWidget\")") ); assert!(!root_runtime.contains("contoso__foundation__i_widget")); - let root_stub = fs::read_to_string(output.join("__init__.pyi")).unwrap(); + let root_stub = fs::read_to_string(package.join("__init__.pyi")).unwrap(); assert!(root_stub.contains("from .contoso.foundation.i_widget import IWidget as IWidget")); assert!(!root_stub.contains("IID_IWidget")); let namespace_stub = - fs::read_to_string(output.join("contoso/foundation/__init__.pyi")).unwrap(); + fs::read_to_string(package.join("contoso/foundation/__init__.pyi")).unwrap(); assert!(namespace_stub.contains("from .i_widget import IWidget as IWidget")); assert!(!namespace_stub.contains("IID_IWidget")); fs::remove_dir_all(output).unwrap(); diff --git a/tools/dynwinrt-codegen/src/winappsdk_output.rs b/tools/dynwinrt-codegen/src/winappsdk_output.rs index 8fa0a8ce..7b73b9f9 100644 --- a/tools/dynwinrt-codegen/src/winappsdk_output.rs +++ b/tools/dynwinrt-codegen/src/winappsdk_output.rs @@ -499,22 +499,22 @@ fn read_manifest(output: &Path) -> Result, String> { "Unsupported Windows App SDK bundle manifest", )); } - let allowed = allowed_files(&manifest.language, config); + let allowed = allowed_files(output, &manifest.language, config)?; + let mapped = |path: &str| resource_path(output, &manifest.language, path); if manifest .files .iter() .any(|(path, hash)| !allowed.contains(path) || !valid_hash(hash)) || ![CONFIG, NOTICE] .iter() - .all(|path| manifest.files.contains_key(*path)) - || config - .dlls - .iter() - .any(|(arch, hash)| manifest.files.get(&dll_path(arch)) != Some(hash)) + .all(|path| mapped(path).is_ok_and(|path| manifest.files.contains_key(&path))) + || config.dlls.iter().any(|(arch, hash)| { + !mapped(&dll_path(arch)).is_ok_and(|path| manifest.files.get(&path) == Some(hash)) + }) || (manifest.language == "py" && !["_winappsdk.py", WHEEL_HOOK, "MANIFEST.in"] .iter() - .all(|path| manifest.files.contains_key(*path))) + .all(|path| mapped(path).is_ok_and(|path| manifest.files.contains_key(&path)))) || (manifest.language == "js" && !manifest.files.contains_key("_winappsdk.cjs")) { return Err(regeneration_error( @@ -531,7 +531,22 @@ fn valid_hash(hash: &str) -> bool { .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) } -fn allowed_files(language: &str, config: &Configuration) -> BTreeSet { +fn resource_path(output: &Path, language: &str, relative: &str) -> Result { + if language != "py" || relative == "MANIFEST.in" { + return Ok(relative.into()); + } + if relative == WHEEL_HOOK { + return Ok(format!("src/{WHEEL_HOOK}")); + } + let layout = super::python_output_layout(output)?; + Ok(format!("src/{}/{relative}", layout.import_name)) +} + +fn allowed_files( + output: &Path, + language: &str, + config: &Configuration, +) -> Result, String> { [CONFIG, NOTICE, LICENSE] .into_iter() .map(String::from) @@ -545,9 +560,42 @@ fn allowed_files(language: &str, config: &Configuration) -> BTreeSet { .into_iter() .map(String::from), ) + .map(|path| resource_path(output, language, &path)) .collect() } +pub(super) fn relocate_python_package( + output: &Path, + previous: &super::PythonOutputLayout, + layout: &super::PythonOutputLayout, +) -> Result<(), String> { + let Some(mut manifest) = read_manifest(output)? else { + return Ok(()); + }; + let old = format!("src/{}/", previous.import_name); + let new = format!("src/{}/", layout.import_name); + manifest.files = manifest + .files + .into_iter() + .map(|(path, hash)| { + ( + path.strip_prefix(&old) + .map(|suffix| format!("{new}{suffix}")) + .unwrap_or(path), + hash, + ) + }) + .collect(); + super::write_file( + &output.join(MANIFEST), + &format!( + "{}\n", + serde_json::to_string_pretty(&manifest) + .map_err(|error| format!("Cannot serialize Bootstrap manifest: {error}"))? + ), + ) +} + fn inspect_owned_path(output: &Path, relative: &str) -> Result<(), String> { let mut current = output.to_path_buf(); for component in Path::new(relative).components() { @@ -601,6 +649,12 @@ pub(crate) fn prepare( inputs: Option, ) -> Result, String> { let existing = read_manifest(output)?; + if language == "py" + && (inputs.is_some() || existing.is_some()) + && super::python_output_layout(output)?.import_name == "_dynwinrt_build" + { + return Err("Python Bootstrap output name `_dynwinrt_build` conflicts with the build-only helper; choose a different --output leaf name".into()); + } if language == "js" && (inputs.is_some() || existing.is_some()) && !is_npm_package_name(runtime_import) @@ -622,6 +676,9 @@ pub(crate) fn prepare( "_native/winappsdk", ] .iter() + .map(|name| resource_path(output, language, name)) + .collect::, _>>()? + .iter() .any(|name| super::path_entry_exists(&output.join(name))) { return Err(regeneration_error( @@ -645,8 +702,20 @@ pub(crate) fn prepare( path.display() ))); } - if relative == LICENSE || relative.ends_with(".dll") { - retained.insert(relative.clone(), bytes); + if relative == &resource_path(output, language, LICENSE)? || relative.ends_with(".dll") + { + let logical = if language == "py" { + relative + .strip_prefix(&format!( + "src/{}/", + super::python_output_layout(output)?.import_name + )) + .ok_or("Invalid Python Bootstrap resource prefix")? + .to_string() + } else { + relative.clone() + }; + retained.insert(logical, bytes); } } } @@ -670,7 +739,7 @@ pub(crate) fn prepare( return Ok(None); }; // Keep every currently-owned helper in the reservation set, including optional stubs. - let reservations = allowed_files(language, &bundle.manifest.configuration); + let reservations = allowed_files(output, language, &bundle.manifest.configuration)?; let prior = read_manifest(output)?; for relative in reservations { inspect_owned_path(output, &relative)?; @@ -727,7 +796,11 @@ impl Bundle { .insert(WHEEL_HOOK.into(), self.python_wheel_hook().into_bytes()); self.contents.insert( "MANIFEST.in".into(), - format!("{}include {WHEEL_HOOK}\n", super::GENERATED_PYTHON_HEADER).into_bytes(), + format!( + "{}include src/{WHEEL_HOOK}\n", + super::GENERATED_PYTHON_HEADER + ) + .into_bytes(), ); if pyi { self.contents.insert( @@ -753,7 +826,21 @@ impl Bundle { .into_bytes(), ); } - for relative in allowed_files(&self.manifest.language, &self.manifest.configuration) { + self.contents = self + .contents + .into_iter() + .map(|(relative, bytes)| { + Ok(( + resource_path(output, &self.manifest.language, &relative)?, + bytes, + )) + }) + .collect::>()?; + for relative in allowed_files( + output, + &self.manifest.language, + &self.manifest.configuration, + )? { inspect_owned_path(output, &relative)?; let path = output.join(&relative); match fs::symlink_metadata(&path) { diff --git a/tools/dynwinrt-codegen/tests/common/mod.rs b/tools/dynwinrt-codegen/tests/common/mod.rs index bfb298b8..23b7a41a 100644 --- a/tools/dynwinrt-codegen/tests/common/mod.rs +++ b/tools/dynwinrt-codegen/tests/common/mod.rs @@ -9,6 +9,65 @@ use dynwinrt_codegen::meta::{ }; use dynwinrt_codegen::types::{TypeIdentity, TypeIdentityKind, TypeMeta}; +pub fn python_package_dir(project: &std::path::Path) -> std::path::PathBuf { + let metadata: serde_json::Value = + serde_json::from_slice(&std::fs::read(project.join(".dynwinrt-generator.json")).unwrap()) + .unwrap(); + assert_eq!(metadata["layout"]["version"], 1); + project + .join("src") + .join(metadata["layout"]["import_name"].as_str().unwrap()) +} + +// Renderer tests also construct standalone packages without CLI project metadata. +pub fn python_fixture_package(path: &std::path::Path) -> std::path::PathBuf { + if path.join(".dynwinrt-generator.json").is_file() { + python_package_dir(path) + } else { + path.to_path_buf() + } +} + +pub fn python_fixture_search_path(root: &std::path::Path) -> std::ffi::OsString { + let mut paths = vec![root.to_path_buf()]; + if root.join(".dynwinrt-generator.json").is_file() { + paths.push(root.join("src")); + } + for entry in std::fs::read_dir(root).unwrap() { + let path = entry.unwrap().path(); + if path.join(".dynwinrt-generator.json").is_file() { + paths.push(path.join("src")); + } + } + std::env::join_paths(paths).unwrap() +} + +pub fn python_fixture_mypy_path( + root: &std::path::Path, + source_runtime: bool, +) -> std::ffi::OsString { + let mut paths = std::env::split_paths(&python_fixture_search_path(root)).collect::>(); + if source_runtime { + paths.push( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("..") + .join("bindings") + .join("py"), + ); + } + std::env::join_paths(paths).unwrap() +} + +pub fn python_fixture_pyright_config(root: &std::path::Path) { + let paths = std::env::split_paths(&python_fixture_search_path(root)).collect::>(); + std::fs::write( + root.join("pyrightconfig.json"), + serde_json::json!({"extraPaths": paths}).to_string(), + ) + .unwrap(); +} + pub fn python_module(identity: TypeIdentity) -> String { PythonProjectionContext::packaged([identity.clone()]) .unwrap() diff --git a/tools/dynwinrt-codegen/tests/delegate_root_selection_test.rs b/tools/dynwinrt-codegen/tests/delegate_root_selection_test.rs index 8726e82e..aa15f1d7 100644 --- a/tools/dynwinrt-codegen/tests/delegate_root_selection_test.rs +++ b/tools/dynwinrt-codegen/tests/delegate_root_selection_test.rs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output, Stdio}; @@ -179,7 +181,8 @@ fn module_file(output: &Path, name: &str, language: &str, extension: &str) -> Pa .join(format!("{name}.{extension}")) } else { let module = dynwinrt_codegen::codegen::python::to_snake_case_filename(name); - output.join(format!("windows__system__threading__{module}.{extension}")) + common::python_package_dir(output) + .join(format!("windows__system__threading__{module}.{extension}")) } } @@ -212,7 +215,7 @@ fn assert_delegate(output: &Path, name: &str, language: &str, no_pyi: bool) { ); } else { assert!(!module_file(output, name, language, "pyi").exists()); - assert!(!output.join("py.typed").exists()); + assert!(!common::python_package_dir(output).join("py.typed").exists()); } } @@ -678,7 +681,7 @@ fn standalone_namespace_delegates_are_emitted_without_referencing_classes() { .join("standalone-delegate") .join("Handler.js") } else { - output.join("tests__standalone_delegate__handler.py") + common::python_package_dir(&output).join("tests__standalone_delegate__handler.py") }; let source = fs::read_to_string(module).unwrap(); assert!(source.contains("IID_Handler = "), "{source}"); @@ -1055,8 +1058,14 @@ fn explicitly_selected_delegate_callables_pass_strict_mypy_and_pyright() { ) .unwrap(); if !negative { - let legacy = - mypy_consumer(&fixture, &[incomplete_source.clone(), extra_stubs.clone()]); + let legacy = mypy_consumer( + &fixture, + &[ + incomplete_source.clone(), + extra_stubs.clone(), + output.join("src"), + ], + ); let text = diagnostics(&legacy); assert_eq!(legacy.status.code(), Some(1), "{text}"); assert!( @@ -1069,8 +1078,9 @@ fn explicitly_selected_delegate_callables_pass_strict_mypy_and_pyright() { } else { &[true][..] } { - let stub_paths = + let mut stub_paths = consumer_stub_paths(use_source.then_some(source_stubs.as_path()), &paths); + stub_paths.push(output.join("src")); assert!(stub_paths.contains(&extra_stubs)); assert!(!stub_paths.contains(&incomplete_source)); eprintln!( diff --git a/tools/dynwinrt-codegen/tests/fixtures/delegate_root_native.py b/tools/dynwinrt-codegen/tests/fixtures/delegate_root_native.py index 41d3e4ca..1df9f2fa 100644 --- a/tools/dynwinrt-codegen/tests/fixtures/delegate_root_native.py +++ b/tools/dynwinrt-codegen/tests/fixtures/delegate_root_native.py @@ -12,7 +12,7 @@ from dynwinrt import DynWinRTValue, RoApartment, projected_lifetime_scope generated = Path(sys.argv[1]).resolve() -sys.path.insert(0, str(generated.parent)) +sys.path.insert(0, str(generated / "src")) package = importlib.import_module(generated.name) callbacks = 0 failure = None diff --git a/tools/dynwinrt-codegen/tests/implementation_naming_test.rs b/tools/dynwinrt-codegen/tests/implementation_naming_test.rs index 02a888a9..89245f0c 100644 --- a/tools/dynwinrt-codegen/tests/implementation_naming_test.rs +++ b/tools/dynwinrt-codegen/tests/implementation_naming_test.rs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; @@ -294,7 +296,8 @@ IComplexImplementationSplitResult.from_value import pyviews as g for name in ('IComplexImplementationDelegate0', 'IComplexImplementationDelegate0Result', 'IComplexImplementationSplitResult'): assert hasattr(getattr(g, name), 'from_value'), name -"#]).current_dir(&fixture.0).output().unwrap()); +"#]).current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)).output().unwrap()); } } } @@ -432,10 +435,10 @@ fn typecheck_py(directory: &Path, source: &str) { "consumer.py", ]) .current_dir(directory) + .env_remove("PYTHONPATH") .env( "MYPYPATH", - std::env::join_paths([root().join("bindings").join("py"), directory.to_path_buf()]) - .unwrap(), + common::python_fixture_mypy_path(directory, true), ) .output() .unwrap(), @@ -465,15 +468,14 @@ fn typecheck_py_package(directory: &Path) { { success( Command::new(python()) - .args([ - "-m", - "mypy", - "--no-incremental", - "--follow-imports=silent", - "pyviews", - ]) + .args(["-m", "mypy", "--no-incremental", "--follow-imports=silent"]) + .arg(common::python_fixture_package(&directory.join("pyviews"))) .current_dir(directory) - .env("MYPYPATH", root().join("bindings").join("py")) + .env_remove("PYTHONPATH") + .env( + "MYPYPATH", + common::python_fixture_mypy_path(directory, true), + ) .output() .unwrap(), ); @@ -481,8 +483,16 @@ fn typecheck_py_package(directory: &Path) { } fn write_python_module(package: &Path, module: &str, source: String, stub: String) { - fs::write(package.join(format!("{module}.py")), source).unwrap(); - fs::write(package.join(format!("{module}.pyi")), stub).unwrap(); + fs::write( + common::python_fixture_package(&package).join(format!("{module}.py")), + source, + ) + .unwrap(); + fs::write( + common::python_fixture_package(&package).join(format!("{module}.pyi")), + stub, + ) + .unwrap(); } fn write_python_support(package: &Path, implementation_modules: &[String]) { @@ -657,12 +667,12 @@ fn python_handler_annotations_resolve_colliding_struct_and_interface_names() { }; let module = context.implementation_module_for_interface(&metadata); fs::write( - package.join(format!("{module}.py")), + common::python_fixture_package(&package).join(format!("{module}.py")), python::generate_interface(&context, &metadata), ) .unwrap(); fs::write( - package.join(format!("{module}.pyi")), + common::python_fixture_package(&package).join(format!("{module}.pyi")), python_stub::generate_interface_stub(&context, &metadata), ) .unwrap(); @@ -697,7 +707,11 @@ fn python_handler_annotations_resolve_colliding_struct_and_interface_names() { assert!(source.contains(" owner: IValue | None\n")); assert!(source.contains(&format!(" result: list[{namespace}_Payload_struct]\n"))); assert!(!source.contains(&format!("{namespace}_IValue_interface"))); - fs::write(package.join(format!("{module}.{extension}")), source).unwrap(); + fs::write( + common::python_fixture_package(&package).join(format!("{module}.{extension}")), + source, + ) + .unwrap(); } let peer = if namespace == "Alpha" { "Beta" @@ -726,12 +740,12 @@ fn python_handler_annotations_resolve_colliding_struct_and_interface_names() { for structure in &structs { let module = context.implementation_module_for_type(structure); fs::write( - package.join(format!("{module}.py")), + common::python_fixture_package(&package).join(format!("{module}.py")), python::generate_struct(&context, structure).unwrap(), ) .unwrap(); fs::write( - package.join(format!("{module}.pyi")), + common::python_fixture_package(&package).join(format!("{module}.pyi")), python_stub::generate_struct_stub(&context, structure).unwrap(), ) .unwrap(); @@ -779,7 +793,11 @@ fn python_handler_annotations_resolve_colliding_struct_and_interface_names() { assert!(source.contains("class Envelope:")); assert!(!source.contains("Alpha_Payload_struct")); assert!(!source.contains("Alpha_Envelope_struct")); - fs::write(package.join(format!("alpha__host.{extension}")), source).unwrap(); + fs::write( + common::python_fixture_package(&package).join(format!("alpha__host.{extension}")), + source, + ) + .unwrap(); } for (extension, source) in [ ( @@ -794,7 +812,8 @@ fn python_handler_annotations_resolve_colliding_struct_and_interface_names() { assert!(!source.contains("class Payload:")); assert!(source.contains("from .alpha__payload import Payload as Alpha_Payload_struct")); fs::write( - package.join(format!("alpha__standalone_envelope.{extension}")), + common::python_fixture_package(&package) + .join(format!("alpha__standalone_envelope.{extension}")), source, ) .unwrap(); @@ -831,7 +850,8 @@ for path in pathlib.Path('pyviews').glob('*__*.py'): assert type(module.Envelope().item).__name__ == 'Payload' if path.stem == 'alpha__host': assert type(module.Envelope().item) is module.Payload -"#]).current_dir(&fixture.0).output().unwrap()); +"#]).current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)).output().unwrap()); } for source in [ @@ -1031,6 +1051,7 @@ for name in ('contoso__host', 'contoso__i_host'): "#, ]) .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(), ); @@ -1137,7 +1158,8 @@ for method, expected in ((box.echo_self, box), (box.echo_peer, peer), (box.echo_ hints = typing.get_type_hints(method) assert hints['value'] is expected assert hints['return'] == expected | None -"#)]).current_dir(&fixture.0).output().unwrap()); +"#)]).current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)).output().unwrap()); } } } @@ -1230,7 +1252,8 @@ with dw.RoApartment(1), g.IValue.implement(Handler(), interfaces=[(IValueHandler other = IValueHandlers.from_implementation(impl) try: assert other.read_real_interface() == 2 finally: dw.release_projected(other) -"#]).current_dir(&fixture.0).output().unwrap()); +"#]).current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)).output().unwrap()); success(Command::new("node").args(["-e", r#" const assert = require('node:assert/strict'); const g = require('./js'); @@ -1242,7 +1265,8 @@ try { const other = deep.IValueHandlers.fromImplementation(impl); try { assert.equal(other.readRealInterface(), 2); } finally { g.releaseProjected(other); } } finally { impl.dispose(); } -"#]).current_dir(&fixture.0).output().unwrap()); +"#]).current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)).output().unwrap()); } } @@ -1271,11 +1295,11 @@ fn incremental_helper_aliases_match_clean_generation_and_retain_unrelated_module &[], )); let retained = if lang == "js" { - "control\\IWidget.js" + incremental.join("control\\IWidget.js") } else { - "control__i_widget.py" + common::python_package_dir(&incremental).join("control__i_widget.py") }; - let original = fs::read(incremental.join(retained)).unwrap(); + let original = fs::read(&retained).unwrap(); // New manifests retain helper identity and eligibility without old WinMD. success(generate( &extra, @@ -1284,7 +1308,7 @@ fn incremental_helper_aliases_match_clean_generation_and_retain_unrelated_module "Alpha.Beta.IWidget", &[], )); - assert_eq!(original, fs::read(incremental.join(retained)).unwrap()); + assert_eq!(original, fs::read(&retained).unwrap()); success(generate( &combined, &clean, @@ -1301,8 +1325,12 @@ fn incremental_helper_aliases_match_clean_generation_and_retain_unrelated_module typecheck_js(&clean); } else { assert_eq!( - fs::read(incremental.join("_implementation_types.pyi")).unwrap(), - fs::read(clean.join("_implementation_types.pyi")).unwrap() + fs::read( + common::python_fixture_package(&incremental).join("_implementation_types.pyi") + ) + .unwrap(), + fs::read(common::python_fixture_package(&clean).join("_implementation_types.pyi")) + .unwrap() ); let exports = |path: &Path| { python_inventory(path) @@ -1416,7 +1444,8 @@ with IValue.implement(First(), interfaces=[(IValueHandlers, Second())]) as impl: ); if runtime_available() { success(Command::new(python()).args(["-c", "import pyviews as g; from pyviews.contoso.i_value_handlers import IValueHandlers; assert g.IValueHandlers is IValueHandlers; assert hasattr(g.IValueHandlers, 'from_value')"]) - .current_dir(&fixture.0).output().unwrap()); + .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)).output().unwrap()); } } let previous = snapshot(&output); @@ -1462,7 +1491,11 @@ fn python_inventory_migration_uses_metadata_not_stub_text_and_fails_atomically() "Extra.ISecond", &["--no-pyi"], )); - assert!(!output.join("_implementation_types.pyi").exists()); + assert!( + !common::python_fixture_package(&output) + .join("_implementation_types.pyi") + .exists() + ); } else { let before = snapshot(&output); let rejected = generate(&extra, &output, "py", "Extra.ISecond", &[]); @@ -1486,10 +1519,12 @@ fn python_inventory_migration_uses_metadata_not_stub_text_and_fails_atomically() .all(|record| record["schema_version"] == 2) ); assert_eq!( - fs::read_to_string(output.join("_implementation_types.pyi")) - .unwrap() - .matches(" import _ImplementationPair") - .count(), + fs::read_to_string( + common::python_fixture_package(&output).join("_implementation_types.pyi") + ) + .unwrap() + .matches(" import _ImplementationPair") + .count(), 2 ); } @@ -1544,7 +1579,7 @@ fn check_root_owner_visibility(first: &str, unrelated: &str, pyi: bool, regenera options, )); assert!( - fs::read_to_string(output.join("__init__.py")) + fs::read_to_string(common::python_fixture_package(&output).join("__init__.py")) .unwrap() .contains("\"IWidgetHandlers\"") ); @@ -1566,7 +1601,9 @@ fn check_root_owner_visibility(first: &str, unrelated: &str, pyi: bool, regenera .unwrap()["implementation"]["module"] .as_str() .unwrap(); - let unchanged_source = fs::read(output.join(format!("{unchanged_module}.py"))).unwrap(); + let unchanged_source = + fs::read(common::python_fixture_package(&output).join(format!("{unchanged_module}.py"))) + .unwrap(); let selected = if regenerate_first { "Alpha.IWidget,Beta.IWidget".to_string() } else { @@ -1602,7 +1639,7 @@ import importlib import json from pathlib import Path import sys -sys.path.insert(0, sys.argv[1]) +sys.path[:0] = [str(Path(sys.argv[1]) / name / "src") for name in ("incremental", "clean")] import incremental import clean namespace = {} @@ -1640,21 +1677,26 @@ with RoApartment(1), views["Alpha"].implement(Alpha(), interfaces=[(views["Beta" "#]).arg(&fixture.0).arg(unrelated).output().unwrap()); } assert_eq!( - fs::read_to_string(output.join("__init__.py")).unwrap(), - fs::read_to_string(clean.join("__init__.py")).unwrap() + fs::read_to_string(common::python_fixture_package(&output).join("__init__.py")).unwrap(), + fs::read_to_string(common::python_fixture_package(&clean).join("__init__.py")).unwrap() ); assert_eq!( unchanged_source, - fs::read(output.join(format!("{unchanged_module}.py"))).unwrap() + fs::read(common::python_fixture_package(&output).join(format!("{unchanged_module}.py"))) + .unwrap() ); if pyi { assert_eq!( - fs::read_to_string(output.join("__init__.pyi")).unwrap(), - fs::read_to_string(clean.join("__init__.pyi")).unwrap() + fs::read_to_string(common::python_fixture_package(&output).join("__init__.pyi")) + .unwrap(), + fs::read_to_string(common::python_fixture_package(&clean).join("__init__.pyi")) + .unwrap() ); assert_eq!( - fs::read(output.join("_implementation_types.pyi")).unwrap(), - fs::read(clean.join("_implementation_types.pyi")).unwrap() + fs::read(common::python_fixture_package(&output).join("_implementation_types.pyi")) + .unwrap(), + fs::read(common::python_fixture_package(&clean).join("_implementation_types.pyi")) + .unwrap() ); let handler = |ns: &str| { after @@ -1690,8 +1732,16 @@ with {unrelated}.implement(Third()) as third: ), ); } else { - assert!(!output.join("__init__.pyi").exists()); - assert!(!output.join("_implementation_types.pyi").exists()); + assert!( + !common::python_fixture_package(&output) + .join("__init__.pyi") + .exists() + ); + assert!( + !common::python_fixture_package(&output) + .join("_implementation_types.pyi") + .exists() + ); } let repeated = snapshot(&output); success(generate(&extra, &output, "py", &selected, &extra_options)); @@ -1713,7 +1763,11 @@ fn typed_append_after_no_pyi_requires_regenerating_missing_declarations() { "Original.IFirst", &["--no-pyi"], )); - assert!(!output.join("original__i_first.pyi").exists()); + assert!( + !common::python_fixture_package(&output) + .join("original__i_first.pyi") + .exists() + ); let before = snapshot(&output); let rejected = generate(&second, &output, "py", "Extra.ISecond", &[]); assert!(!rejected.status.success()); @@ -1730,12 +1784,18 @@ fn typed_append_after_no_pyi_requires_regenerating_missing_declarations() { "Original.IFirst,Extra.ISecond", &["--ref", first.to_str().unwrap()], )); - assert!(output.join("original__i_first.pyi").is_file()); + assert!( + common::python_fixture_package(&output) + .join("original__i_first.pyi") + .is_file() + ); assert_eq!( - fs::read_to_string(output.join("_implementation_types.pyi")) - .unwrap() - .matches(" import _ImplementationPair") - .count(), + fs::read_to_string( + common::python_fixture_package(&output).join("_implementation_types.pyi") + ) + .unwrap() + .matches(" import _ImplementationPair") + .count(), 2 ); } @@ -1784,20 +1844,27 @@ fn legacy_interface_facade_cannot_override_a_current_runtime_class() { ); for extension in ["py", "pyi"] { assert!( - !fs::read_to_string(output.join(format!("__init__.{extension}"))) - .unwrap() - .contains("IValueHandlers") + !fs::read_to_string( + common::python_fixture_package(&output).join(format!("__init__.{extension}")) + ) + .unwrap() + .contains("IValueHandlers") ); assert!( - !fs::read_to_string(output.join(format!("contoso__i_value.{extension}"))) - .unwrap() - .contains("def implement(") + !fs::read_to_string( + common::python_fixture_package(&output) + .join(format!("contoso__i_value.{extension}")) + ) + .unwrap() + .contains("def implement(") ); } assert!( - !fs::read_to_string(output.join("_implementation_types.pyi")) - .unwrap() - .contains("contoso__i_value") + !fs::read_to_string( + common::python_fixture_package(&output).join("_implementation_types.pyi") + ) + .unwrap() + .contains("contoso__i_value") ); } @@ -1828,7 +1895,8 @@ fn legacy_migration_reuses_records_already_present_without_their_metadata() { lines.join("\n") + "\n", ) .unwrap(); - let retained = fs::read(output.join("extra__i_second.py")).unwrap(); + let retained = + fs::read(common::python_fixture_package(&output).join("extra__i_second.py")).unwrap(); success(generate( &third, &output, @@ -1838,7 +1906,7 @@ fn legacy_migration_reuses_records_already_present_without_their_metadata() { )); assert_eq!( retained, - fs::read(output.join("extra__i_second.py")).unwrap() + fs::read(common::python_fixture_package(&output).join("extra__i_second.py")).unwrap() ); assert!( python_inventory(&output) diff --git a/tools/dynwinrt-codegen/tests/observable_map_test.rs b/tools/dynwinrt-codegen/tests/observable_map_test.rs index 546d91af..d9575db2 100644 --- a/tools/dynwinrt-codegen/tests/observable_map_test.rs +++ b/tools/dynwinrt-codegen/tests/observable_map_test.rs @@ -532,7 +532,8 @@ impl Output { } fn read(&self, file: &str) -> String { - fs::read_to_string(self.0.join(file)).unwrap_or_else(|error| panic!("{file}: {error}")) + fs::read_to_string(common::python_package_dir(&self.0).join(file)) + .unwrap_or_else(|error| panic!("{file}: {error}")) } } diff --git a/tools/dynwinrt-codegen/tests/output_cleanliness_test.rs b/tools/dynwinrt-codegen/tests/output_cleanliness_test.rs index 92a944cb..17444bbe 100644 --- a/tools/dynwinrt-codegen/tests/output_cleanliness_test.rs +++ b/tools/dynwinrt-codegen/tests/output_cleanliness_test.rs @@ -5,6 +5,8 @@ //! generated type-identity inventory. No transient cache files //! (e.g. `.index.ts`), temp files, or raw `.ts` sources may leak. +mod common; + use std::fs; use std::path::Path; use std::process::Command; @@ -349,13 +351,18 @@ fn python_emits_stubs_by_default_and_supports_opt_out() { .status() .expect("spawn dynwinrt-codegen (Python defaults)"); assert!(default_status.success()); - let default_namespace = default_dir.join("windows").join("foundation"); + let default_package = common::python_package_dir(&default_dir); + let default_namespace = default_package.join("windows").join("foundation"); assert!(default_namespace.join("uri.py").exists()); assert!(default_namespace.join("uri.pyi").exists()); - assert!(default_dir.join("windows__foundation__uri.py").exists()); - assert!(default_dir.join("windows__foundation__uri.pyi").exists()); - assert!(default_dir.join("__init__.pyi").exists()); - assert!(default_dir.join("py.typed").exists()); + assert!(default_package.join("windows__foundation__uri.py").exists()); + assert!( + default_package + .join("windows__foundation__uri.pyi") + .exists() + ); + assert!(default_package.join("__init__.pyi").exists()); + assert!(default_package.join("py.typed").exists()); assert!(default_dir.join("pyproject.toml").exists()); let opt_out_status = Command::new(exe) @@ -374,13 +381,18 @@ fn python_emits_stubs_by_default_and_supports_opt_out() { .status() .expect("spawn dynwinrt-codegen (Python stub opt-out)"); assert!(opt_out_status.success()); - let opt_out_namespace = opt_out_dir.join("windows").join("foundation"); + let opt_out_package = common::python_package_dir(&opt_out_dir); + let opt_out_namespace = opt_out_package.join("windows").join("foundation"); assert!(opt_out_namespace.join("uri.py").exists()); assert!(!opt_out_namespace.join("uri.pyi").exists()); - assert!(opt_out_dir.join("windows__foundation__uri.py").exists()); - assert!(!opt_out_dir.join("windows__foundation__uri.pyi").exists()); - assert!(!opt_out_dir.join("__init__.pyi").exists()); - assert!(!opt_out_dir.join("py.typed").exists()); + assert!(opt_out_package.join("windows__foundation__uri.py").exists()); + assert!( + !opt_out_package + .join("windows__foundation__uri.pyi") + .exists() + ); + assert!(!opt_out_package.join("__init__.pyi").exists()); + assert!(!opt_out_package.join("py.typed").exists()); let _ = fs::remove_dir_all(&default_dir); let _ = fs::remove_dir_all(&opt_out_dir); diff --git a/tools/dynwinrt-codegen/tests/python_as_interface_test.rs b/tools/dynwinrt-codegen/tests/python_as_interface_test.rs index be2e8b18..6cdb8805 100644 --- a/tools/dynwinrt-codegen/tests/python_as_interface_test.rs +++ b/tools/dynwinrt-codegen/tests/python_as_interface_test.rs @@ -401,6 +401,7 @@ print("as-interface-collision-ok") let output = Command::new(python()) .args(["-B", "as_interface_probe.py"]) .current_dir(directory) + .env("PYTHONPATH", common::python_fixture_search_path(directory)) .output() .unwrap(); assert!( @@ -466,7 +467,10 @@ fn colliding_metadata_declarations_alias_the_as_interface_helper() { .output() .unwrap(), ); - let source = fs::read_to_string(packaged.join("pyviews").join("audit__widget.py")).unwrap(); + let source = fs::read_to_string( + common::python_package_dir(&packaged.join("pyviews")).join("audit__widget.py"), + ) + .unwrap(); assert_aliased_as_interface(&source, 2); if run_runtime { probe(&packaged, "audit__widget"); diff --git a/tools/dynwinrt-codegen/tests/python_collection_helper_collision_test.rs b/tools/dynwinrt-codegen/tests/python_collection_helper_collision_test.rs index 4ec1256a..e3bb7573 100644 --- a/tools/dynwinrt-codegen/tests/python_collection_helper_collision_test.rs +++ b/tools/dynwinrt-codegen/tests/python_collection_helper_collision_test.rs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; @@ -193,7 +195,11 @@ fn modules(context: &PythonProjectionContext) -> Modules { fn write_standalone(root: &Path, classes: &[ClassMeta]) -> Modules { let package = root.join("pyviews"); fs::create_dir_all(&package).unwrap(); - fs::write(package.join("__init__.py"), "").unwrap(); + fs::write( + common::python_fixture_package(&package).join("__init__.py"), + "", + ) + .unwrap(); fs::write( package.join("_runtime.py"), python::generate_runtime_support_module(), @@ -205,7 +211,11 @@ fn write_standalone(root: &Path, classes: &[ClassMeta]) -> Modules { let module = context.implementation_module(&class_identity(class)); let source = python::generate_class(&context, class, &Default::default()); assert_collision_safe(&source, &module); - fs::write(package.join(format!("{module}.py")), source).unwrap(); + fs::write( + common::python_fixture_package(&package).join(format!("{module}.py")), + source, + ) + .unwrap(); } modules(&context) } @@ -234,7 +244,10 @@ fn generate_packaged(root: &Path, custom: &Path, classes: &[ClassMeta], no_pyi: (&modules.vector_class, "vector operations"), (&modules.map_class, "map operations"), ] { - let source = fs::read_to_string(package.join(format!("{module}.py"))).unwrap(); + let source = fs::read_to_string( + common::python_fixture_package(&package).join(format!("{module}.py")), + ) + .unwrap(); assert_collision_safe(&source, operation); } modules @@ -329,6 +342,7 @@ print("collection-helper-collision-ok") let output = Command::new(python()) .args(["-B", "probe.py"]) .current_dir(root) + .env("PYTHONPATH", common::python_fixture_search_path(root)) .output() .unwrap(); assert!( @@ -342,7 +356,8 @@ print("collection-helper-collision-ok") fn old_hardcoded_binding_fails(root: &Path, modules: &Modules) { for module in [&modules.vector_class, &modules.map_class] { - let path = root.join("pyviews").join(format!("{module}.py")); + let path = + common::python_fixture_package(&root.join("pyviews")).join(format!("{module}.py")); let source = fs::read_to_string(&path).unwrap(); let old = source .replace( @@ -355,6 +370,7 @@ fn old_hardcoded_binding_fails(root: &Path, modules: &Modules) { let output = Command::new(python()) .args(["-B", "probe.py"]) .current_dir(root) + .env("PYTHONPATH", common::python_fixture_search_path(root)) .env("DYNWINRT_EXPECT_OLD_COLLECTION_HELPER", "1") .output() .unwrap(); @@ -461,14 +477,18 @@ def invalid(vector: Vector, mapping: Map, value: DynWinRTValue) -> None: "--cache-dir", "mypy-cache", ]) - .current_dir(root); + .current_dir(root) + .env_remove("PYTHONPATH"); if *source_stubs { command.env( "MYPYPATH", - std::env::join_paths([binding_stubs.clone(), root.to_path_buf()]).unwrap(), + std::env::join_paths(std::iter::once(binding_stubs.clone()).chain( + std::env::split_paths(&common::python_fixture_search_path(root)), + )) + .unwrap(), ); } else { - command.env_remove("MYPYPATH"); + command.env("MYPYPATH", common::python_fixture_mypy_path(root, false)); } success(command.arg("typing_probe.py").output().unwrap()); let output = command.arg("invalid_probe.py").output().unwrap(); @@ -504,6 +524,7 @@ def invalid(vector: Vector, mapping: Map, value: DynWinRTValue) -> None: .arg(python()) .arg("pyright_probe.py") .current_dir(root) + .env("PYTHONPATH", common::python_fixture_search_path(root)) .output() .unwrap(), ); @@ -536,7 +557,7 @@ fn assert_incremental_parity(complete: &Path, root: &Path, custom: &Path, no_pyi success(command.output().unwrap()); } let modules = |directory: &Path| { - let mut files = fs::read_dir(directory) + let mut files = fs::read_dir(common::python_package_dir(directory)) .unwrap() .map(|entry| entry.unwrap().file_name()) .filter(|name| { @@ -552,8 +573,8 @@ fn assert_incremental_parity(complete: &Path, root: &Path, custom: &Path, no_pyi assert_eq!(modules(&incremental), files); for file in files { assert_eq!( - fs::read(complete.join("pyviews").join(&file)).unwrap(), - fs::read(incremental.join(&file)).unwrap(), + fs::read(common::python_package_dir(&complete.join("pyviews")).join(&file)).unwrap(), + fs::read(common::python_package_dir(&incremental).join(&file)).unwrap(), "incremental helper surface drift: {}", file.to_string_lossy() ); @@ -595,13 +616,17 @@ fn collection_helper_aliases_execute_for_packaged_and_standalone_outputs() { &custom, true, ); - assert!(fs::read_dir(no_pyi.join("pyviews")).unwrap().all(|entry| { - entry + assert!( + fs::read_dir(common::python_package_dir(&no_pyi.join("pyviews"))) .unwrap() - .path() - .extension() - .is_none_or(|ext| ext != "pyi") - })); + .all(|entry| { + entry + .unwrap() + .path() + .extension() + .is_none_or(|ext| ext != "pyi") + }) + ); strict_typecheck(&no_pyi, &modules, true); if runtime_available() { runtime_probe(&no_pyi, &modules); diff --git a/tools/dynwinrt-codegen/tests/python_collection_member_collision_test.rs b/tools/dynwinrt-codegen/tests/python_collection_member_collision_test.rs index c1448c36..6767bb45 100644 --- a/tools/dynwinrt-codegen/tests/python_collection_member_collision_test.rs +++ b/tools/dynwinrt-codegen/tests/python_collection_member_collision_test.rs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; @@ -579,6 +581,7 @@ fn native_collection_members_keep_their_names_dispatch_and_aliases_in_both_outpu Command::new(python()) .args(["-B", "runtime.py"]) .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(), ); @@ -605,13 +608,17 @@ fn native_collection_members_keep_their_names_dispatch_and_aliases_in_both_outpu "--no-incremental", "consumer.py", ]) - .current_dir(&fixture.0); + .current_dir(&fixture.0) + .env_remove("PYTHONPATH"); if std::env::var("DYNWINRT_TEST_INSTALLED_RUNTIME").as_deref() == Ok("1") { - command.env_remove("MYPYPATH"); + command.env( + "MYPYPATH", + common::python_fixture_mypy_path(&fixture.0, false), + ); } else { command.env( "MYPYPATH", - Path::new(env!("CARGO_MANIFEST_DIR")).join(r"..\..\bindings\py"), + common::python_fixture_mypy_path(&fixture.0, true), ); } // Main already reports these exact nominal ABC overrides. diff --git a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs index 9e32ff12..ce89e58d 100644 --- a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs @@ -120,21 +120,18 @@ fn typecheck_with_imports( "--cache-dir", ".mypy_cache", ]) - .args(packages) + .args( + packages + .iter() + .map(|name| common::python_fixture_package(&fixture.0.join(name))), + ) .arg("consumer.py") - .current_dir(&fixture.0); - if *source_stubs { - command.env( - "MYPYPATH", - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("..") - .join("..") - .join("bindings") - .join("py"), - ); - } else { - command.env_remove("MYPYPATH"); - } + .current_dir(&fixture.0) + .env_remove("PYTHONPATH"); + command.env( + "MYPYPATH", + common::python_fixture_mypy_path(&fixture.0, *source_stubs), + ); let output = command.output().unwrap(); let text = diagnostics(&output); if errors.is_empty() { @@ -163,11 +160,13 @@ fn pyright_typecheck(fixture: &Fixture, consumer: &str, expected_errors: usize) format!("# pyright: strict\n{consumer}"), ) .unwrap(); + common::python_fixture_pyright_config(&fixture.0); let output = Command::new(pyright) .args(["--pythonpath"]) .arg(python()) .arg("pyright_consumer.py") .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(); let text = diagnostics(&output); @@ -737,7 +736,10 @@ fn reference_array_results_preserve_null_elements() { } let fixture = Fixture::new(); generate_fixture(&fixture, "views"); - let source = fs::read_to_string(fixture.0.join("views").join("contoso__content.py")).unwrap(); + let source = fs::read_to_string( + common::python_fixture_package(&fixture.0.join("views")).join("contoso__content.py"), + ) + .unwrap(); assert!(source.contains("def get_resources(self) -> list[Resource | None]:")); assert!(source.contains("_dynwinrt_wrap_values('contoso__resource', 'Resource'")); assert!(source.contains("def get_items(self) -> list[IItem | None]:")); @@ -811,6 +813,7 @@ print("nullable-reference-array-native-ok", flush=True) let output = Command::new(python()) .args(["-B", "reference_array_runtime.py"]) .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(); assert!(output.status.success(), "{}", diagnostics(&output)); @@ -997,6 +1000,7 @@ print("subclass-factory-native-ok", flush=True) let output = Command::new(python()) .args(["-B", "factory_runtime.py"]) .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(); assert!(output.status.success(), "{}", diagnostics(&output)); @@ -1238,9 +1242,7 @@ def invalid(resources: ResourceDictionary, other: Unrelated, mapping: IMap_Objec let output = command.output().unwrap(); assert!(output.status.success(), "{}", diagnostics(&output)); let source = fs::read_to_string( - fixture - .0 - .join("views") + common::python_fixture_package(&fixture.0.join("views")) .join("microsoft__ui__xaml__resource_dictionary.py"), ) .unwrap(); @@ -1251,8 +1253,11 @@ def invalid(resources: ResourceDictionary, other: Unrelated, mapping: IMap_Objec "contoso__grandchild_resources", "windows__ui__xaml__color_palette_resources", ] { - let derived = - fs::read_to_string(fixture.0.join("views").join(format!("{module}.py"))).unwrap(); + let derived = fs::read_to_string( + common::python_fixture_package(&fixture.0.join("views")) + .join(format!("{module}.py")), + ) + .unwrap(); assert!(derived.contains("def lookup(self, key: str |")); assert!(derived.contains( "_dynwinrt_to_winrt_object(str.__str__(key), _dynwinrt_property_type.String)" @@ -1260,17 +1265,13 @@ def invalid(resources: ResourceDictionary, other: Unrelated, mapping: IMap_Objec assert!(derived.contains(".invoke(self._collection_obj,")); } let other = fs::read_to_string( - fixture - .0 - .join("views") + common::python_fixture_package(&fixture.0.join("views")) .join("contoso__resource_dictionary.py"), ) .unwrap(); assert!(!other.contains("to_winrt_object")); let unrelated_child = fs::read_to_string( - fixture - .0 - .join("views") + common::python_fixture_package(&fixture.0.join("views")) .join("contoso__unrelated_resources.py"), ) .unwrap(); @@ -1332,7 +1333,7 @@ class DisplayKey(str): def __str__(self): return "not the stored key" -source = ast.parse((Path("views") / "microsoft__ui__xaml__resource_dictionary.py").read_text(encoding="utf-8")) +source = ast.parse((Path("views") / "src" / "views" / "microsoft__ui__xaml__resource_dictionary.py").read_text(encoding="utf-8")) owner = next(node for node in source.body if isinstance(node, ast.ClassDef) and node.name == "ResourceDictionary") assert sum(isinstance(node, ast.FunctionDef) and node.name == "lookup" for node in owner.body) == 1 for method in (ResourceDictionary.get, ResourceDictionary.pop): @@ -1458,6 +1459,7 @@ with RoApartment(1), projected_lifetime_scope(): print("resource-key-fixture-ok") "#]) .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(); assert!(output.status.success(), "{}", diagnostics(&output)); @@ -1769,6 +1771,7 @@ print("collection-subscript-native-ok", flush=True) let output = Command::new(python()) .args(["-B", "collections_runtime.py"]) .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(); assert!(output.status.success(), "{}", diagnostics(&output)); @@ -2081,6 +2084,7 @@ print("collection-comparison-native-ok", flush=True) let output = Command::new(python()) .args(["-B", "comparison_runtime.py"]) .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(); assert!(output.status.success(), "{}", diagnostics(&output)); @@ -2348,6 +2352,7 @@ print("map-changed-native-ok", changes, string_changes, flush=True) let output = Command::new(python()) .args(["-B", "map_events_runtime.py"]) .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(); assert!(output.status.success(), "{}", diagnostics(&output)); @@ -2599,41 +2604,37 @@ fn mutable_collection_mutators_accept_none() { .unwrap(); let stringable_module = stringable_context.implementation_module_for_interface(&stringable_map); fs::write( - fixture - .0 - .join("sdk") + common::python_fixture_package(&fixture.0.join("sdk")) .join(format!("{stringable_module}.py")), python::generate_interface(&stringable_context, &stringable_map), ) .unwrap(); fs::write( - fixture - .0 - .join("sdk") + common::python_fixture_package(&fixture.0.join("sdk")) .join(format!("{stringable_module}.pyi")), python_stub::generate_interface_stub(&stringable_context, &stringable_map), ) .unwrap(); let object_map_stub = fs::read_to_string( - fixture - .0 - .join("sdk") + common::python_fixture_package(&fixture.0.join("sdk")) .join("windows__foundation__collections__i_map_object_object.pyi"), ) .unwrap(); assert!(object_map_stub.contains("MutableMapping[DynWinRTValue | None, DynWinRTValue | None]")); - let pair_stub = fs::read_to_string(fixture.0.join("sdk").join(format!( - "{}.pyi", - common::python_module(TypeIdentity::closed_generic( - TypeIdentityKind::Interface, - "Windows.Foundation.Collections", - "IKeyValuePair`2", - [ - TypeMeta::Object.type_identity(), - TypeMeta::Object.type_identity() - ], - )) - ))) + let pair_stub = fs::read_to_string( + common::python_fixture_package(&fixture.0.join("sdk")).join(format!( + "{}.pyi", + common::python_module(TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + "Windows.Foundation.Collections", + "IKeyValuePair`2", + [ + TypeMeta::Object.type_identity(), + TypeMeta::Object.type_identity() + ], + )) + )), + ) .unwrap(); assert!(pair_stub.contains("def key(self) -> DynWinRTValue | None: ...")); assert!(pair_stub.contains("def value(self) -> DynWinRTValue | None: ...")); @@ -2751,7 +2752,8 @@ def string_keys(values: IMap_String_String) -> None: assert!(nested_source.contains("_dynwinrt_map(value, lambda item:")); assert!(nested_source.contains("_dynwinrt_box_reference(")); fs::write( - fixture.0.join("sdk").join(format!("{nested_module}.py")), + common::python_fixture_package(&fixture.0.join("sdk")) + .join(format!("{nested_module}.py")), nested_source, ) .unwrap(); @@ -2927,6 +2929,7 @@ print("nullable-collection-native-ok", flush=True) let output = Command::new(python()) .args(["-B", "nullable_collections.py"]) .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(); assert!(output.status.success(), "{}", diagnostics(&output)); @@ -3044,6 +3047,7 @@ with RoApartment(1), projected_lifetime_scope(): let output = Command::new(python()) .args(["-B", "runtime.py"]) .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(); assert!(output.status.success(), "{}", diagnostics(&output)); diff --git a/tools/dynwinrt-codegen/tests/python_delegate_callback_test.rs b/tools/dynwinrt-codegen/tests/python_delegate_callback_test.rs index 702dd532..ebd01e2c 100644 --- a/tools/dynwinrt-codegen/tests/python_delegate_callback_test.rs +++ b/tools/dynwinrt-codegen/tests/python_delegate_callback_test.rs @@ -62,7 +62,8 @@ impl Output { fn read(&self, module: &str, extension: &str) -> String { let file = format!("{module}.{extension}"); - fs::read_to_string(self.0.join(&file)).unwrap_or_else(|error| panic!("{file}: {error}")) + fs::read_to_string(common::python_package_dir(&self.0).join(&file)) + .unwrap_or_else(|error| panic!("{file}: {error}")) } } @@ -233,7 +234,9 @@ fn nested_delegate_callback_argument_preserves_native_null() { &metadata, &generated, ); - let stub = fs::read_to_string(generated.join("audit__i_emitter.pyi")).unwrap(); + let stub = + fs::read_to_string(common::python_package_dir(&generated).join("audit__i_emitter.pyi")) + .unwrap(); let signature = stub .lines() .rev() @@ -248,7 +251,9 @@ fn nested_delegate_callback_argument_preserves_native_null() { !stub.contains("from .audit__inner_handler import IID_InnerHandler, InnerHandler"), "{stub}" ); - let runtime = fs::read_to_string(generated.join("audit__i_emitter.py")).unwrap(); + let runtime = + fs::read_to_string(common::python_package_dir(&generated).join("audit__i_emitter.py")) + .unwrap(); let null_projection = "lambda __p0__: ((lambda value: None if value.is_null() else value)(__p0__),)"; assert!(runtime.contains(null_projection), "{runtime}"); @@ -256,14 +261,18 @@ fn nested_delegate_callback_argument_preserves_native_null() { if let Some(main_codegen) = std::env::var_os("DYNWINRT_MAIN_CODEGEN") { let baseline = fixture.0.join("main"); generate_nested_delegate_views(Path::new(&main_codegen), &metadata, &baseline); - let main_stub = fs::read_to_string(baseline.join("audit__i_emitter.pyi")).unwrap(); + let main_stub = + fs::read_to_string(common::python_package_dir(&baseline).join("audit__i_emitter.pyi")) + .unwrap(); let main_signature = main_stub .lines() .rev() .find(|line| line.contains("def set_handler(")) .expect("main IEmitter.set_handler signature"); assert_eq!(signature, main_signature); - let main_runtime = fs::read_to_string(baseline.join("audit__i_emitter.py")).unwrap(); + let main_runtime = + fs::read_to_string(common::python_package_dir(&baseline).join("audit__i_emitter.py")) + .unwrap(); assert!(main_runtime.contains(null_projection), "{main_runtime}"); eprintln!("#191 main and #190 IEmitter stubs: {signature}"); } @@ -351,11 +360,7 @@ def invalid(emitter: IEmitter) -> None: .current_dir(&fixture.0) .env( "MYPYPATH", - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("..") - .join("..") - .join("bindings") - .join("py"), + common::python_fixture_mypy_path(&fixture.0, true), ) .output() .unwrap(); @@ -379,6 +384,7 @@ def invalid(emitter: IEmitter) -> None: } } if let Some(pyright) = std::env::var_os("DYNWINRT_PYRIGHT") { + common::python_fixture_pyright_config(&fixture.0); let output = Command::new(pyright) .args(["--pythonpath"]) .arg(&python) @@ -478,6 +484,7 @@ print("delegate-typed-native-null-ok", received) let output = Command::new(&python) .args(["-B", "native.py"]) .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(); let diagnostics = format!( @@ -558,15 +565,15 @@ fn runtime_delegate_annotations_resolve_and_stubs_remain_precise() { ) else { return; }; - let property_runtime = output - .0 + let property_runtime = common::python_package_dir(&output.0) .join("windows__foundation__collections__property_set.py"); let bespoke_module = common::python_module(TypeIdentity::named( TypeIdentityKind::Class, "Windows.ApplicationModel.Background", "BackgroundTaskRegistration", )); - let bespoke_runtime = output.0.join(format!("{bespoke_module}.py")); + let bespoke_runtime = + common::python_package_dir(&output.0).join(format!("{bespoke_module}.py")); let property_stub = output.read("windows__foundation__collections__property_set", "pyi"); let bespoke_stub = output.read(&bespoke_module, "pyi"); assert!( diff --git a/tools/dynwinrt-codegen/tests/python_generator_version_test.rs b/tools/dynwinrt-codegen/tests/python_generator_version_test.rs index 132e769f..123dfca8 100644 --- a/tools/dynwinrt-codegen/tests/python_generator_version_test.rs +++ b/tools/dynwinrt-codegen/tests/python_generator_version_test.rs @@ -155,7 +155,10 @@ fn new_and_non_generated_output_stamp_the_current_producer() { let stamp: serde_json::Value = serde_json::from_slice(&fs::read(fixture.output.join(STAMP)).unwrap()).unwrap(); assert_eq!(stamp["generator_version"], env!("CARGO_PKG_VERSION")); - assert_eq!(stamp.as_object().unwrap().len(), 1); + assert_eq!( + stamp["layout"], + serde_json::json!({"version": 1, "import_name": "bindings"}) + ); let inventory = fs::read_to_string(fixture.output.join(".dynwinrt-generated-files")).unwrap(); assert!(inventory.lines().any(|line| line == STAMP)); @@ -218,6 +221,40 @@ fn legacy_output_with_or_without_inventories_requires_full_regeneration() { } } +#[test] +fn same_version_flat_layout_is_rejected_and_clean_src_regeneration_keeps_import_name() { + let fixture = Fixture::new(); + fs::create_dir(&fixture.output).unwrap(); + fs::write( + fixture.output.join(STAMP), + format!(r#"{{"generator_version":"{}"}}"#, env!("CARGO_PKG_VERSION")), + ) + .unwrap(); + fs::write( + fixture.output.join("__init__.py"), + "# Generated by dynwinrt-codegen\n", + ) + .unwrap(); + for dry_run in [false, true] { + let mut command = fixture.command(); + if dry_run { + command.arg("--dry-run"); + } + assert!( + fixture + .refused_unchanged(&mut command) + .contains("predates the src package layout") + ); + } + fs::remove_dir_all(&fixture.output).unwrap(); + fixture.generate(); + assert!(fixture.output.join("src\\bindings\\__init__.py").is_file()); + assert!(!fixture.output.join("__init__.py").exists()); + let project = fs::read_to_string(fixture.output.join("pyproject.toml")).unwrap(); + assert!(project.contains("package-dir = { \"\" = \"src\" }")); + assert!(project.contains("name = \"bindings\"")); +} + #[test] fn missing_and_corrupt_producer_metadata_preserve_all_existing_output() { let fixture = Fixture::new(); diff --git a/tools/dynwinrt-codegen/tests/python_generic_marker_test.rs b/tools/dynwinrt-codegen/tests/python_generic_marker_test.rs index 91b2e8b9..d86dda4c 100644 --- a/tools/dynwinrt-codegen/tests/python_generic_marker_test.rs +++ b/tools/dynwinrt-codegen/tests/python_generic_marker_test.rs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::HashSet; use std::fs; use std::path::{Path, PathBuf}; @@ -475,13 +477,20 @@ def ordinary_control(use: AlphaUse, payload: BetaPayload) -> AlphaPayload: "--show-error-codes", "--cache-dir", ".mypy_cache", - "alpha", - "beta", - "alpha_copy", + "alpha/src/alpha", + "beta/src/beta", + "alpha_copy/src/alpha_copy", &consumer, ]) .current_dir(&fixture.0) - .env("MYPYPATH", &runtime) + .env_remove("PYTHONPATH") + .env( + "MYPYPATH", + std::env::join_paths(std::iter::once(runtime.clone()).chain( + std::env::split_paths(&common::python_fixture_search_path(&fixture.0)), + )) + .unwrap(), + ) .output() .unwrap(); let text = diagnostics(&output); diff --git a/tools/dynwinrt-codegen/tests/python_interface_constructor_iid_test.rs b/tools/dynwinrt-codegen/tests/python_interface_constructor_iid_test.rs index 95e66f7a..f8f7d409 100644 --- a/tools/dynwinrt-codegen/tests/python_interface_constructor_iid_test.rs +++ b/tools/dynwinrt-codegen/tests/python_interface_constructor_iid_test.rs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; @@ -65,13 +67,13 @@ impl Generated { } fn module(&self, name: &str) -> String { - fs::read_to_string(self.root.join(name)).expect(name) + fs::read_to_string(common::python_package_dir(&self.root).join(name)).expect(name) } fn run(&self, script: &str) -> Output { Command::new(self.python()) .args(["-B", "-c", &script.replace("PY_PACKAGE", &self.package)]) - .env("PYTHONPATH", self.root.parent().unwrap()) + .env("PYTHONPATH", self.root.join("src")) .output() .expect("run isolated constructor consumer") } @@ -277,7 +279,7 @@ fn interface_projection_typing_keeps_raw_values_explicit() { command.arg(generated.root.join("mypy-cache")); command .args(["-c", &source]) - .current_dir(generated.root.parent().unwrap()); + .current_dir(generated.root.join("src")); command.env( "MYPYPATH", std::env::join_paths([repo.join(r"bindings\py"), repo.join("target")]) @@ -314,7 +316,7 @@ fn interface_projection_typing_keeps_raw_values_explicit() { .args(["--pythonpath"]) .arg(generated.python()) .arg(&path) - .env("PYTHONPATH", generated.root.parent().unwrap()) + .env("PYTHONPATH", generated.root.join("src")) .output() .expect("run pyright"); let diagnostics = format!( diff --git a/tools/dynwinrt-codegen/tests/python_json_native_null_test.rs b/tools/dynwinrt-codegen/tests/python_json_native_null_test.rs index 3a325a8f..f1ce8c79 100644 --- a/tools/dynwinrt-codegen/tests/python_json_native_null_test.rs +++ b/tools/dynwinrt-codegen/tests/python_json_native_null_test.rs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; @@ -82,29 +84,29 @@ impl Generated { } fn module(&self, name: &str) -> String { - fs::read_to_string(self.root.join(name)).expect(name) + fs::read_to_string(common::python_package_dir(&self.root).join(name)).expect(name) } fn python(&self, script: &str) -> Output { Command::new(python()) .args(["-B", "-c", &script.replace("JSON_PACKAGE", &self.package)]) - .env("PYTHONPATH", self.root.parent().unwrap()) + .env("PYTHONPATH", self.root.join("src")) .output() .expect("execute isolated Python consumer") } fn typing_environment(&self, command: &mut Command) { command - .current_dir(self.root.parent().unwrap()) + .current_dir(self.root.join("src")) .env( "MYPYPATH", std::env::join_paths([ repo_root().join(r"bindings\py"), - self.root.parent().unwrap().to_path_buf(), + self.root.join("src").to_path_buf(), ]) .expect("MYPYPATH"), ) - .env("PYTHONPATH", self.root.parent().unwrap()); + .env_remove("PYTHONPATH"); } } @@ -237,14 +239,12 @@ fn stock_json_no_pyi_runtime_annotations_match_the_native_input_contract() { return; } assert!( - !generated - .root + !common::python_package_dir(&generated.root) .join("windows__data__json__json_array.pyi") .exists() ); assert!( - !generated - .root + !common::python_package_dir(&generated.root) .join("windows__data__json__json_object.pyi") .exists() ); diff --git a/tools/dynwinrt-codegen/tests/python_output_path_test.rs b/tools/dynwinrt-codegen/tests/python_output_path_test.rs index 741f9f14..fe63004e 100644 --- a/tools/dynwinrt-codegen/tests/python_output_path_test.rs +++ b/tools/dynwinrt-codegen/tests/python_output_path_test.rs @@ -3,6 +3,8 @@ #![cfg(windows)] +mod common; + use std::collections::BTreeMap; use std::fs; use std::os::windows::ffi::OsStrExt; @@ -179,8 +181,8 @@ fn python_path_diagnostic_uses_actual_final_files_not_transactional_paths() { return; } let fixture = Fixture::new(); - let deep = fixture.output("deep", 201); - let shallow = fixture.output("short", 194); + let deep = fixture.output("deep", 201 - 23); + let shallow = fixture.output("short", 194 - 23); let output = device_command(&deep).output().unwrap(); successful(&output); let generated = files(&deep); @@ -220,7 +222,7 @@ fn python_path_diagnostic_uses_actual_final_files_not_transactional_paths() { "the no-warning control must exercise over-budget staging paths" ); - let unpublished = fixture.output("failure", 201); + let unpublished = fixture.output("failure", 201 - 23); let failure = device_command(&unpublished) .env("DYNWINRT_CODEGEN_TEST_FAIL_OUTPUT_COMMIT", "before_publish") .output() @@ -242,7 +244,7 @@ fn python_path_diagnostic_respects_relative_dry_run_and_no_pyi_boundary() { return; } let fixture = Fixture::new(); - let output = fixture.output("boundary-\u{1f642}", 199); + let output = fixture.output("boundary-\u{1f642}", 199 - 23); let relative = output.strip_prefix(&fixture.0).unwrap(); let dry_run = device_command(relative) .current_dir(&fixture.0) @@ -279,7 +281,11 @@ fn python_path_diagnostic_respects_relative_dry_run_and_no_pyi_boundary() { .keys() .all(|path| path.extension().is_none_or(|ext| ext != "pyi")) ); - assert!(!output.join("py.typed").exists()); + assert!( + !common::python_package_dir(&output) + .join("py.typed") + .exists() + ); for (path, content) in typed_files .iter() .filter(|(path, _)| path.extension().is_some_and(|ext| ext == "py")) @@ -354,7 +360,9 @@ fn same_version_incremental_output_matches_fresh_typed_and_untyped_union() { path.extension() .is_some_and(|extension| extension == "py" || extension == "pyi") }) - .all(|path| path_length(path) <= 60) + .all( + |path| path_length(path.strip_prefix("src/generated_bindings").unwrap()) <= 60 + ) ); let stamp: serde_json::Value = serde_json::from_slice(&expected[Path::new(".dynwinrt-generator.json")]).unwrap(); @@ -419,7 +427,7 @@ fn synthetic_long_metadata_installs_through_a_utf16_output_root() { path.extension() .is_some_and(|extension| extension == "py" || extension == "pyi") }) - .all(|path| path_length(path) <= 60) + .all(|path| path_length(path.strip_prefix("src/generated_bindings").unwrap()) <= 60) ); for name in &names { let identity = dynwinrt_codegen::types::TypeIdentity::named( @@ -428,7 +436,10 @@ fn synthetic_long_metadata_installs_through_a_utf16_output_root() { name, ); let implementation = context.implementation_module(&identity); - let source = fs::read_to_string(output.join(format!("{implementation}.py"))).unwrap(); + let source = fs::read_to_string( + common::python_package_dir(&output).join(format!("{implementation}.py")), + ) + .unwrap(); assert!(source.contains(&format!("class {name}(")), "{source}"); } diff --git a/tools/dynwinrt-codegen/tests/python_overload_legacy_compat_test.rs b/tools/dynwinrt-codegen/tests/python_overload_legacy_compat_test.rs index 40850685..029bf843 100644 --- a/tools/dynwinrt-codegen/tests/python_overload_legacy_compat_test.rs +++ b/tools/dynwinrt-codegen/tests/python_overload_legacy_compat_test.rs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; @@ -630,11 +632,13 @@ fn raw_async_interface_arguments_dispatch_to_their_native_slot() { .output() .unwrap(), ); - let source = - fs::read_to_string(package.join("tests__overload_compatibility__async_input_probe.py")) - .unwrap(); + let source = fs::read_to_string( + common::python_fixture_package(&package) + .join("tests__overload_compatibility__async_input_probe.py"), + ) + .unwrap(); assert!( - package + common::python_fixture_package(&package) .join("windows__foundation__i_async_info.py") .is_file(), "known-interface guards require their projected interface dependency" @@ -774,6 +778,7 @@ print("async-interface-input-ok") let output = Command::new(python()) .args(["-B", "async_probe.py"]) .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(); success(output.clone()); @@ -848,13 +853,14 @@ fn colliding_legacy_support_names_keep_metadata_types_and_native_targets() { for class in &classes { let identity = TypeIdentity::named(TypeIdentityKind::Class, NAMESPACE, &class.name); fs::write( - package.join(format!("{}.py", context.implementation_module(&identity))), + common::python_fixture_package(&package) + .join(format!("{}.py", context.implementation_module(&identity))), python::generate_class(&context, class, &Default::default()), ) .unwrap(); } fs::write( - package.join(format!( + common::python_fixture_package(&package).join(format!( "{}.py", context.implementation_module(&interface.type_identity()) )), @@ -884,8 +890,10 @@ fn colliding_legacy_support_names_keep_metadata_types_and_native_targets() { "_dynwinrt_can_cast", ), ] { - let source = - fs::read_to_string(package.join(format!("{}.py", module(name, kind)))).unwrap(); + let source = fs::read_to_string( + common::python_fixture_package(&package).join(format!("{}.py", module(name, kind))), + ) + .unwrap(); assert!( source.contains(&format!("\nclass {name}:")), "{flavor}: {source}" @@ -896,11 +904,12 @@ fn colliding_legacy_support_names_keep_metadata_types_and_native_targets() { "{flavor}: {source}" ); } - let interface_source = fs::read_to_string(package.join(format!( - "{}.py", - module(&interface.name, TypeIdentityKind::Interface) - ))) - .unwrap(); + let interface_source = + fs::read_to_string(common::python_fixture_package(&package).join(format!( + "{}.py", + module(&interface.name, TypeIdentityKind::Interface) + ))) + .unwrap(); assert!( interface_source.contains("_dynwinrt_legacy_int_guard as _dynwinrt_legacy_int_guard_2") && interface_source.contains("_dynwinrt_legacy_int_guard_2(") @@ -909,7 +918,8 @@ fn colliding_legacy_support_names_keep_metadata_types_and_native_targets() { ); let iid_name = "IID_ARG_Tests_OverloadCompatibility_IAliasCanonical"; let iid_source = fs::read_to_string( - package.join(format!("{}.py", module(iid_name, TypeIdentityKind::Class))), + common::python_fixture_package(&package) + .join(format!("{}.py", module(iid_name, TypeIdentityKind::Class))), ) .unwrap(); assert!( @@ -921,11 +931,12 @@ fn colliding_legacy_support_names_keep_metadata_types_and_native_targets() { && iid_source.contains(&format!("_dynwinrt_can_cast(_bound[0], {iid_name}_2)")), "{flavor}: {iid_source}" ); - let registration_source = fs::read_to_string(package.join(format!( - "{}.py", - module(class_names[4], TypeIdentityKind::Class) - ))) - .unwrap(); + let registration_source = + fs::read_to_string(common::python_fixture_package(&package).join(format!( + "{}.py", + module(class_names[4], TypeIdentityKind::Class) + ))) + .unwrap(); assert!( registration_source.contains(&format!( "{iid_name} = WinGUID.parse('51931917-6281-4900-b782-040302010910')" @@ -1101,6 +1112,7 @@ print("overload-support-collisions-ok") let output = Command::new(python()) .args(["-B", "collision_probe.py"]) .current_dir(&parent) + .env("PYTHONPATH", common::python_fixture_search_path(&parent)) .output() .unwrap(); success(output.clone()); @@ -1127,8 +1139,11 @@ fn old_dispatchers_and_guard_free_conversions_keep_their_exact_targets() { .output() .unwrap(), ); - let alias_source = - fs::read_to_string(package.join("tests__overload_compatibility__alias_probe.py")).unwrap(); + let alias_source = fs::read_to_string( + common::python_fixture_package(&package) + .join("tests__overload_compatibility__alias_probe.py"), + ) + .unwrap(); let alias_class = alias_source .split("\nclass IAliasLegacyString:") .next() @@ -1139,8 +1154,11 @@ fn old_dispatchers_and_guard_free_conversions_keep_their_exact_targets() { && !alias_class.contains(" foo_version = foo\n"), "{alias_source}" ); - let enum_source = - fs::read_to_string(package.join("tests__overload_compatibility__enum_probe.py")).unwrap(); + let enum_source = fs::read_to_string( + common::python_fixture_package(&package) + .join("tests__overload_compatibility__enum_probe.py"), + ) + .unwrap(); assert!( enum_source.contains( "not (_legacy_bound is not None and (type(_legacy_bound[0]) not in (str,) or _dynwinrt_legacy_int_guard(_legacy_bound[0], -2147483648, 2147483647)))" @@ -1149,15 +1167,21 @@ fn old_dispatchers_and_guard_free_conversions_keep_their_exact_targets() { ), "{enum_source}" ); - let pair_source = - fs::read_to_string(package.join("tests__overload_compatibility__pair_probe.py")).unwrap(); + let pair_source = fs::read_to_string( + common::python_fixture_package(&package) + .join("tests__overload_compatibility__pair_probe.py"), + ) + .unwrap(); assert!( !pair_source.contains("_dynwinrt_legacy_int_guard") && pair_source.contains("return self._bar_6_0(*_bound)"), "{pair_source}" ); - let bool_source = - fs::read_to_string(package.join("tests__overload_compatibility__bool_probe.py")).unwrap(); + let bool_source = fs::read_to_string( + common::python_fixture_package(&package) + .join("tests__overload_compatibility__bool_probe.py"), + ) + .unwrap(); assert!( bool_source.contains("not (_legacy_bound is not None) and isinstance(_bound[0], bool)") && bool_source.contains( @@ -1167,18 +1191,22 @@ fn old_dispatchers_and_guard_free_conversions_keep_their_exact_targets() { "{bool_source}" ); for name in ["bool_pair_probe", "bool_arity_probe"] { - let source = - fs::read_to_string(package.join(format!("tests__overload_compatibility__{name}.py"))) - .unwrap(); + let source = fs::read_to_string( + common::python_fixture_package(&package) + .join(format!("tests__overload_compatibility__{name}.py")), + ) + .unwrap(); assert!( !source.contains("_legacy_bound") && !source.contains("and not (_legacy_bound is not None"), "{source}" ); } - let numeric_domain_source = - fs::read_to_string(package.join("tests__overload_compatibility__numeric_domain_probe.py")) - .unwrap(); + let numeric_domain_source = fs::read_to_string( + common::python_fixture_package(&package) + .join("tests__overload_compatibility__numeric_domain_probe.py"), + ) + .unwrap(); assert!( numeric_domain_source.contains( "-2147483648 <= int.__index__(_legacy_bound[1]) <= 2147483647" @@ -1187,9 +1215,11 @@ fn old_dispatchers_and_guard_free_conversions_keep_their_exact_targets() { ), "{numeric_domain_source}" ); - let qi_source = - fs::read_to_string(package.join("tests__overload_compatibility__qi_dispatch_probe.py")) - .unwrap(); + let qi_source = fs::read_to_string( + common::python_fixture_package(&package) + .join("tests__overload_compatibility__qi_dispatch_probe.py"), + ) + .unwrap(); assert_eq!( qi_source .matches("_dynwinrt_can_cast(_legacy_bound[0], IID_ARG_Tests_OverloadCompatibility_IAliasCanonical)") @@ -1197,9 +1227,11 @@ fn old_dispatchers_and_guard_free_conversions_keep_their_exact_targets() { 2, "{qi_source}" ); - let index_string_source = - fs::read_to_string(package.join("tests__overload_compatibility__index_string_probe.py")) - .unwrap(); + let index_string_source = fs::read_to_string( + common::python_fixture_package(&package) + .join("tests__overload_compatibility__index_string_probe.py"), + ) + .unwrap(); assert!( index_string_source .contains("type(_legacy_bound[0]) not in (str,)) and isinstance(_bound[0], str)") @@ -1208,9 +1240,11 @@ fn old_dispatchers_and_guard_free_conversions_keep_their_exact_targets() { ), "{index_string_source}" ); - let enum_comparison_source = - fs::read_to_string(package.join("tests__overload_compatibility__enum_comparison_probe.py")) - .unwrap(); + let enum_comparison_source = fs::read_to_string( + common::python_fixture_package(&package) + .join("tests__overload_compatibility__enum_comparison_probe.py"), + ) + .unwrap(); assert!( enum_comparison_source.contains("-128 <= int.__index__(_legacy_bound[0]) <= 127") && !enum_comparison_source.contains("-128 <= _legacy_bound[0] <= 127"), @@ -1548,6 +1582,7 @@ print(json.dumps({"results": results, "calls": calls})) let output = Command::new(python()) .args(["-B", "probe.py"]) .current_dir(&fixture.0) + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) .output() .unwrap(); success(output.clone()); diff --git a/tools/dynwinrt-codegen/tests/python_overload_normalization_test.rs b/tools/dynwinrt-codegen/tests/python_overload_normalization_test.rs index 92fcff80..972f6354 100644 --- a/tools/dynwinrt-codegen/tests/python_overload_normalization_test.rs +++ b/tools/dynwinrt-codegen/tests/python_overload_normalization_test.rs @@ -884,18 +884,15 @@ async def streams(source: InMemoryRandomAccessStream, target: InMemoryRandomAcce "--show-error-codes", "--cache-dir", ".mypy_cache", - "sdk", + "sdk/src/sdk", "consumer.py", ]) .env( "MYPYPATH", - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("..") - .join("..") - .join("bindings") - .join("py"), + common::python_fixture_mypy_path(&fixture.0, true), ) .current_dir(&fixture.0) + .env_remove("PYTHONPATH") .output() .unwrap(); let text = format!( diff --git a/tools/dynwinrt-codegen/tests/python_raw_lifetime_test.rs b/tools/dynwinrt-codegen/tests/python_raw_lifetime_test.rs index e3c4044a..a673e1fa 100644 --- a/tools/dynwinrt-codegen/tests/python_raw_lifetime_test.rs +++ b/tools/dynwinrt-codegen/tests/python_raw_lifetime_test.rs @@ -70,7 +70,7 @@ impl Generated { fn run(&self, scenario: &str, script: &str) { let output = Command::new(self.python()) .args(["-B", "-c", &script.replace("PY_PACKAGE", &self.package)]) - .env("PYTHONPATH", self.root.parent().unwrap()) + .env("PYTHONPATH", self.root.join("src")) .output() .expect("run isolated Python lifetime regression"); let stdout = String::from_utf8_lossy(&output.stdout); diff --git a/tools/dynwinrt-codegen/tests/python_stub_nullability_test.rs b/tools/dynwinrt-codegen/tests/python_stub_nullability_test.rs index 7b772fed..2df7daa4 100644 --- a/tools/dynwinrt-codegen/tests/python_stub_nullability_test.rs +++ b/tools/dynwinrt-codegen/tests/python_stub_nullability_test.rs @@ -65,7 +65,8 @@ impl Generated { } fn module(&self, name: &str) -> String { - fs::read_to_string(self.0.join(name)).unwrap_or_else(|error| panic!("{name}: {error}")) + fs::read_to_string(common::python_package_dir(&self.0).join(name)) + .unwrap_or_else(|error| panic!("{name}: {error}")) } fn identity_module(&self, identity: TypeIdentity, extension: &str) -> String { diff --git a/tools/dynwinrt-codegen/tests/python_symbol_mapping_test.rs b/tools/dynwinrt-codegen/tests/python_symbol_mapping_test.rs index 01fbc7d6..ffe70e0a 100644 --- a/tools/dynwinrt-codegen/tests/python_symbol_mapping_test.rs +++ b/tools/dynwinrt-codegen/tests/python_symbol_mapping_test.rs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::fs; use std::path::{Path, PathBuf}; @@ -134,7 +136,11 @@ fn check_consumer(directory: &Path, consumer: &str, strict: bool) { ]) .args(strict.then_some("--strict")) .current_dir(directory) - .env("MYPYPATH", root().join("bindings").join("py")) + .env_remove("PYTHONPATH") + .env( + "MYPYPATH", + common::python_fixture_mypy_path(directory, true), + ) .output() .unwrap(), ); @@ -161,7 +167,11 @@ fn reject_consumer(directory: &Path, consumer: &str, codes: &[&str]) { "negative.py", ]) .current_dir(directory) - .env("MYPYPATH", root().join("bindings").join("py")) + .env_remove("PYTHONPATH") + .env( + "MYPYPATH", + common::python_fixture_mypy_path(directory, true), + ) .output() .unwrap(); let diagnostics = String::from_utf8_lossy(&output.stdout); @@ -190,6 +200,7 @@ fn runtime(directory: &Path, source: &str) { Command::new(python()) .args(["-B", "runtime_probe.py"]) .current_dir(directory) + .env("PYTHONPATH", common::python_fixture_search_path(directory)) .output() .unwrap(), ); @@ -197,8 +208,16 @@ fn runtime(directory: &Path, source: &str) { } fn module(package: &Path, name: &str, source: String, stub: String) { - fs::write(package.join(format!("{name}.py")), source).unwrap(); - fs::write(package.join(format!("{name}.pyi")), stub).unwrap(); + fs::write( + common::python_fixture_package(&package).join(format!("{name}.py")), + source, + ) + .unwrap(); + fs::write( + common::python_fixture_package(&package).join(format!("{name}.pyi")), + stub, + ) + .unwrap(); } fn support(package: &Path, interfaces: &[String]) { @@ -2371,7 +2390,10 @@ fn python_normalized_struct_helpers_round_trip_nested_fields_arrays_and_delegate } write_structs(&package, &context, &structures); let owner_module = context.implementation_module_for_interface(&interface); - let source = fs::read_to_string(package.join(format!("{owner_module}.py"))).unwrap(); + let source = fs::read_to_string( + common::python_fixture_package(&package).join(format!("{owner_module}.py")), + ) + .unwrap(); if packaged { for declaration in ["_pack_url_value", "_unpack_url_value"] { let alpha = imported_symbol( @@ -2783,7 +2805,8 @@ fn python_files(directory: &Path) -> BTreeMap> { } } let mut files = BTreeMap::new(); - visit(directory, directory, &mut files); + let directory = common::python_fixture_package(directory); + visit(&directory, &directory, &mut files); files } @@ -2876,11 +2899,18 @@ fn python_class_companion_aliases_preserve_cli_and_standalone_contracts() { let owner_module = context.implementation_module_for_type(&class_type("Audit", "Widget")); let peer_module = context.implementation_module_for_type(&class_type("Audit", peer)); - let owner_source = - fs::read_to_string(package.join(format!("{owner_module}.py"))).unwrap(); - let owner_stub = - fs::read_to_string(package.join(format!("{owner_module}.pyi"))).unwrap(); - let peer_stub = fs::read_to_string(package.join(format!("{peer_module}.pyi"))).unwrap(); + let owner_source = fs::read_to_string( + common::python_fixture_package(&package).join(format!("{owner_module}.py")), + ) + .unwrap(); + let owner_stub = fs::read_to_string( + common::python_fixture_package(&package).join(format!("{owner_module}.pyi")), + ) + .unwrap(); + let peer_stub = fs::read_to_string( + common::python_fixture_package(&package).join(format!("{peer_module}.pyi")), + ) + .unwrap(); let peer_alias = imported_symbol(&owner_source, &peer_module, peer); assert_eq!(peer_alias, imported_symbol(&owner_stub, &peer_module, peer)); assert_eq!(peer_alias == peer, peer == "WidgetPeer"); @@ -3198,7 +3228,10 @@ fn python_inline_struct_companions_share_declarations_defaults_and_native_conver if collision { qualified } else { leaf }, ) }; - let source = fs::read_to_string(package.join(format!("{owner}.py"))).unwrap(); + let source = fs::read_to_string( + common::python_fixture_package(&package).join(format!("{owner}.py")), + ) + .unwrap(); assert!(source.contains(&format!("DynWinRTType.struct_type('Audit.{leaf}'"))); if !packaged { assert!( @@ -3540,7 +3573,8 @@ fn python_symbol_collisions_incremental_package_matches_clean_generation() { let incremental = fixture.0.join("incremental").join("pyviews"); let clean = fixture.0.join("clean").join("pyviews"); generate(&winmd, &incremental, "Audit.IAlpha,Enums.IUse"); - let alpha_before = fs::read(incremental.join("alpha__url_value.py")).unwrap(); + let alpha_before = + fs::read(common::python_fixture_package(&incremental).join("alpha__url_value.py")).unwrap(); generate(&winmd, &incremental, "Audit.IHelpers,Consumers.IForeign"); generate( &winmd, @@ -3549,7 +3583,7 @@ fn python_symbol_collisions_incremental_package_matches_clean_generation() { ); assert_eq!( alpha_before, - fs::read(incremental.join("alpha__url_value.py")).unwrap() + fs::read(common::python_fixture_package(&incremental).join("alpha__url_value.py")).unwrap() ); let incremental_files = python_files(&incremental); let clean_files = python_files(&clean); diff --git a/tools/dynwinrt-codegen/tests/python_xml_nullability_test.rs b/tools/dynwinrt-codegen/tests/python_xml_nullability_test.rs index 2203ac6a..40a425cf 100644 --- a/tools/dynwinrt-codegen/tests/python_xml_nullability_test.rs +++ b/tools/dynwinrt-codegen/tests/python_xml_nullability_test.rs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::BTreeSet; use std::fs; use std::path::{Path, PathBuf}; @@ -33,9 +35,7 @@ fn class_and_standalone_interface_stubs_use_exact_xml_null_facts() { }; let stub = |name: &str| { fs::read_to_string( - fixture - .0 - .join("xml_generated") + common::python_package_dir(&fixture.0.join("xml_generated")) .join(format!("windows__data__xml__dom__{name}.pyi")), ) .unwrap() @@ -86,9 +86,7 @@ fn class_and_standalone_interface_stubs_use_exact_xml_null_facts() { } } let runtime = fs::read_to_string( - fixture - .0 - .join("xml_generated") + common::python_package_dir(&fixture.0.join("xml_generated")) .join("windows__data__xml__dom__xml_document.py"), ) .unwrap(); @@ -177,6 +175,7 @@ impl Fixture { .unwrap(), ); + let package = common::python_package_dir(&package); // Exclusive interfaces are not public CLI roots. Resolve their actual // declarations independently, then exercise the standalone renderer. let declarations = ["XmlDocument", "XmlElement"].map(|name| { @@ -261,7 +260,8 @@ fn guarded_xml_reads_pass_and_unguarded_reads_fail_strict_typechecking() { .join("bindings") .join("py"); assert!(source_stubs.join("dynwinrt.pyi").is_file()); - let mut stub_paths = vec![source_stubs]; + let source_path = fixture.0.join("xml_generated").join("src"); + let mut stub_paths = vec![source_stubs, source_path.clone()]; if let Some(paths) = std::env::var_os("MYPYPATH") { stub_paths.extend(std::env::split_paths(&paths)); } @@ -292,7 +292,7 @@ fn guarded_xml_reads_pass_and_unguarded_reads_fail_strict_typechecking() { ]) .arg(name) .current_dir(&fixture.0) - .env_remove("MYPYPATH"); + .env("MYPYPATH", &source_path); if *use_source_stubs { command.env("MYPYPATH", &source_stub_path); } @@ -320,6 +320,14 @@ fn guarded_xml_reads_pass_and_unguarded_reads_fail_strict_typechecking() { } if let Some(pyright) = std::env::var_os("DYNWINRT_PYRIGHT") { + fs::write( + fixture.0.join("pyrightconfig.json"), + serde_json::json!({ + "extraPaths": [source_path], + }) + .to_string(), + ) + .unwrap(); let output = Command::new(pyright) .args(["--pythonpath"]) .arg(python()) @@ -374,7 +382,9 @@ fn generated_xml_results_match_native_null_and_non_null_states() { }; let output = Command::new(python()) .args(["-B", "-c"]) - .arg(format!("import sys; sys.path.insert(0, '.')\n{NATIVE}")) + .arg(format!( + "import sys; sys.path.insert(0, 'xml_generated/src')\n{NATIVE}" + )) .current_dir(&fixture.0) .output() .unwrap(); diff --git a/tools/dynwinrt-codegen/tests/winappsdk_bundle_test.rs b/tools/dynwinrt-codegen/tests/winappsdk_bundle_test.rs index 45a76998..5c312e04 100644 --- a/tools/dynwinrt-codegen/tests/winappsdk_bundle_test.rs +++ b/tools/dynwinrt-codegen/tests/winappsdk_bundle_test.rs @@ -10,6 +10,8 @@ use std::sync::atomic::{AtomicU64, Ordering}; use sha2::{Digest, Sha256}; use windows_metadata::{FieldAttributes, Type, TypeAttributes, Value, writer}; +mod common; + static NEXT: AtomicU64 = AtomicU64::new(0); const DLL: &str = "Microsoft.WindowsAppRuntime.Bootstrap.dll"; const MANIFEST: &str = ".dynwinrt-winappsdk.json"; @@ -107,6 +109,14 @@ impl Fixture { command } + fn package(&self, language: &str) -> PathBuf { + if language == "py" { + common::python_fixture_package(&self.output) + } else { + self.output.clone() + } + } + fn input(&self, architecture: &str) -> PathBuf { self.root.join("inputs").join(architecture).join(DLL) } @@ -250,7 +260,7 @@ fn bundle_generation_is_opt_in_and_exposes_precise_capabilities() { let fixture = Fixture::new(); fixture.generate(language, false); assert!(!fixture.output.join(MANIFEST).exists()); - assert!(!fixture.output.join("_winappsdk.json").exists()); + assert!(!fixture.package(language).join("_winappsdk.json").exists()); assert!(!fixture.output.join("_dynwinrt_build").exists()); let before = files(&fixture.output); succeeded( @@ -273,7 +283,7 @@ fn original_dll_bytes_licenses_and_runtime_configuration_are_packaged() { assert_eq!( fs::read( fixture - .output + .package(language) .join("_native") .join("winappsdk") .join(arch) @@ -284,15 +294,24 @@ fn original_dll_bytes_licenses_and_runtime_configuration_are_packaged() { ); } assert_eq!( - fs::read_to_string(fixture.output.join("_native/winappsdk/LICENSE.txt")).unwrap(), + fs::read_to_string( + fixture + .package(language) + .join("_native/winappsdk/LICENSE.txt") + ) + .unwrap(), "SDK test license\n" ); assert!( - fs::read_to_string(fixture.output.join("_native/winappsdk/NOTICE.txt")) - .unwrap() - .contains("NOT licensed under dynwinrt's MIT") + fs::read_to_string( + fixture + .package(language) + .join("_native/winappsdk/NOTICE.txt") + ) + .unwrap() + .contains("NOT licensed under dynwinrt's MIT") ); - let config = fs::read_to_string(fixture.output.join("_winappsdk.json")).unwrap(); + let config = fs::read_to_string(fixture.package(language).join("_winappsdk.json")).unwrap(); assert!(!config.contains(&fixture.root.to_string_lossy().to_string())); if language == "py" { let project = fs::read_to_string(fixture.output.join("pyproject.toml")).unwrap(); @@ -300,7 +319,7 @@ fn original_dll_bytes_licenses_and_runtime_configuration_are_packaged() { assert!(project.contains("bindings._winappsdk:get_config")); assert!(project.contains("_native/winappsdk/*/*.dll")); assert!( - fs::read_to_string(fixture.output.join("_dynwinrt_build/wheel.py")) + fs::read_to_string(fixture.output.join("src/_dynwinrt_build/wheel.py")) .unwrap() .contains("win_amd64.win_arm64") ); @@ -507,7 +526,7 @@ fn same_bundle_survives_full_and_incremental_passes_with_omitted_options() { ); assert!( fixture - .output + .package(language) .join("_native/winappsdk/x64") .join(DLL) .is_file() @@ -520,14 +539,14 @@ fn same_bundle_survives_full_and_incremental_passes_with_omitted_options() { command.args(["--class-name", "Widget"]); } succeeded(command.output().unwrap()); - assert!(!fixture.output.join("_winappsdk.pyi").exists()); + assert!(!fixture.package(language).join("_winappsdk.pyi").exists()); let inventory = fs::read_to_string(fixture.output.join(".dynwinrt-generated-files")).unwrap(); assert!(inventory.contains(DLL)); assert!(fixture.output.join(MANIFEST).is_file()); } fixture.generate(language, false); - assert!(fixture.output.join("_winappsdk.pyi").is_file()); + assert!(fixture.package(language).join("_winappsdk.pyi").is_file()); } } } @@ -601,21 +620,22 @@ fn concrete_input_selects_its_pe_architecture_without_using_codegen_host_archite .output() .unwrap(), ); - let config: serde_json::Value = - serde_json::from_slice(&fs::read(fixture.output.join("_winappsdk.json")).unwrap()) - .unwrap(); + let config: serde_json::Value = serde_json::from_slice( + &fs::read(fixture.package(language).join("_winappsdk.json")).unwrap(), + ) + .unwrap(); assert_eq!(config["dlls"].as_object().unwrap().len(), 1); assert!(config["dlls"].get(architecture).is_some()); assert!( !fixture - .output + .package(language) .join("_native/winappsdk") .join(other) .exists() ); if language == "py" { - let setup = - fs::read_to_string(fixture.output.join("_dynwinrt_build/wheel.py")).unwrap(); + let setup = fs::read_to_string(fixture.output.join("src/_dynwinrt_build/wheel.py")) + .unwrap(); let expected = if architecture == "x64" { "win_amd64" } else { @@ -692,12 +712,12 @@ fn invalid_flags_manual_collisions_and_publication_failures_are_atomic() { ] { fixture.refused_unchanged(fixture.command("py", false).arg(field), "required"); } - fs::write(fixture.output.join("_winappsdk.json"), "user-owned").unwrap(); + fs::write(fixture.package("py").join("_winappsdk.json"), "user-owned").unwrap(); fixture.refused_unchanged( &mut fixture.command("py", true), "Refusing to overwrite non-generated", ); - fs::remove_file(fixture.output.join("_winappsdk.json")).unwrap(); + fs::remove_file(fixture.package("py").join("_winappsdk.json")).unwrap(); fixture.refused_unchanged( fixture .command("py", true) @@ -706,7 +726,10 @@ fn invalid_flags_manual_collisions_and_publication_failures_are_atomic() { ); fixture.generate("py", true); fs::write( - fixture.output.join("_native/winappsdk/x64").join(DLL), + fixture + .package("py") + .join("_native/winappsdk/x64") + .join(DLL), "modified", ) .unwrap(); @@ -739,13 +762,132 @@ fn projected_namespace_and_private_build_hook_remain_distinct() { .output() .unwrap(), ); - let projected = fs::read_to_string(fixture.output.join("dynwinrt_build/wheel.py")).unwrap(); - let build_hook = fs::read_to_string(fixture.output.join("_dynwinrt_build/wheel.py")).unwrap(); + let projected = + fs::read_to_string(fixture.package("py").join("dynwinrt_build/wheel.py")).unwrap(); + let build_hook = + fs::read_to_string(fixture.output.join("src/_dynwinrt_build/wheel.py")).unwrap(); assert!(projected.contains(" import Wheel")); assert!(!projected.contains("class BootstrapWheel")); assert!(build_hook.contains("class BootstrapWheel")); } +#[test] +fn python_project_rename_relocates_owned_package_and_bundle_without_changing_type_identity() { + for bundled in [false, true] { + let mut fixture = Fixture::new(); + fixture.generate("py", bundled); + let types = fs::read(fixture.output.join(".dynwinrt-generated-types")).unwrap(); + let old_source = fs::read( + fixture + .package("py") + .join("windows__bootstrap_test__widget.py"), + ) + .unwrap(); + fs::write( + fixture.package("py").join("manual.txt"), + "preserve user content", + ) + .unwrap(); + let renamed = fixture.root.join("Renamed Bindings"); + fs::rename(&fixture.output, &renamed).unwrap(); + fixture.output = renamed; + succeeded( + fixture + .command("py", false) + .args(["--class-name", "Widget"]) + .output() + .unwrap(), + ); + let package = fixture.package("py"); + assert!(package.ends_with("src/renamed_bindings")); + assert_eq!( + fs::read(package.join("windows__bootstrap_test__widget.py")).unwrap(), + old_source + ); + assert_eq!( + fs::read(fixture.output.join(".dynwinrt-generated-types")).unwrap(), + types + ); + assert_eq!( + fs::read_to_string(fixture.output.join("src/bindings/manual.txt")).unwrap(), + "preserve user content" + ); + assert!(!fixture.output.join("src/bindings/__init__.py").exists()); + let inventory = + fs::read_to_string(fixture.output.join(".dynwinrt-generated-files")).unwrap(); + assert!(!inventory.replace('\\', "/").contains("src/bindings/")); + assert!( + inventory + .replace('\\', "/") + .contains("src/renamed_bindings/py.typed") + ); + let project = fs::read_to_string(fixture.output.join("pyproject.toml")).unwrap(); + assert!(project.contains("name = \"renamed-bindings\"")); + assert!(project.contains("package-dir = { \"\" = \"src\" }")); + if bundled { + assert!(project.contains("renamed_bindings._winappsdk:get_config")); + assert_eq!( + fs::read(package.join("_native/winappsdk/x64").join(DLL)).unwrap(), + fs::read(fixture.input("x64")).unwrap() + ); + assert!( + !fs::read_to_string(fixture.output.join(MANIFEST)) + .unwrap() + .contains("src/bindings/") + ); + } + let before = files(&fixture.output); + succeeded( + fixture + .command("py", false) + .args(["--class-name", "Widget"]) + .output() + .unwrap(), + ); + assert_eq!(files(&fixture.output), before); + } +} + +#[test] +fn python_project_rename_conflicts_and_publication_failures_preserve_both_layouts() { + let mut fixture = Fixture::new(); + fixture.generate("py", true); + let renamed = fixture.root.join("renamed_bindings"); + fs::rename(&fixture.output, &renamed).unwrap(); + fixture.output = renamed; + let destination = fixture.output.join("src/renamed_bindings/__init__.py"); + fs::create_dir_all(destination.parent().unwrap()).unwrap(); + fs::write(&destination, "user-owned").unwrap(); + fixture.refused_unchanged( + &mut fixture.command("py", false), + "destination already exists", + ); + fs::remove_file(destination).unwrap(); + fixture.refused_unchanged( + fixture + .command("py", false) + .env("DYNWINRT_CODEGEN_TEST_FAIL_OUTPUT_COMMIT", "before_publish"), + "Injected output transaction failure", + ); + assert!(fixture.output.join("src/bindings/__init__.py").is_file()); + assert!( + !fixture + .output + .join("src/renamed_bindings/__init__.py") + .exists() + ); +} + +#[test] +fn python_bootstrap_rejects_build_helper_as_runtime_package_name() { + let mut fixture = Fixture::new(); + fixture.output = fixture.root.join("_dynwinrt_build"); + fixture.refused_unchanged( + &mut fixture.command("py", true), + "conflicts with the build-only helper", + ); +} + #[test] fn input_order_and_identical_duplicates_preserve_payloads_licenses_and_cache() { for language in ["py", "js"] { @@ -772,7 +914,12 @@ fn input_order_and_identical_duplicates_preserve_payloads_licenses_and_cache() { .unwrap(), ); assert_eq!( - fs::read_to_string(fixture.output.join("_native/winappsdk/LICENSE.txt")).unwrap(), + fs::read_to_string( + fixture + .package(language) + .join("_native/winappsdk/LICENSE.txt") + ) + .unwrap(), "License from a duplicate payload's source\n" ); let before = files(&fixture.output); @@ -1181,12 +1328,18 @@ fn input_paths_are_literal_without_architecture_placeholder_expansion() { .output() .unwrap(), ); - let config: serde_json::Value = - serde_json::from_slice(&fs::read(fixture.output.join("_winappsdk.json")).unwrap()) - .unwrap(); + let config: serde_json::Value = serde_json::from_slice( + &fs::read(fixture.package(language).join("_winappsdk.json")).unwrap(), + ) + .unwrap(); assert_eq!(config["dlls"].as_object().unwrap().len(), 1); assert!(config["dlls"].get("x64").is_some()); - assert!(!fixture.output.join("_native/winappsdk/arm64").exists()); + assert!( + !fixture + .package(language) + .join("_native/winappsdk/arm64") + .exists() + ); } } diff --git a/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs b/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs index 4274ed55..ef6fae4b 100644 --- a/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs +++ b/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs @@ -1135,7 +1135,7 @@ fn implementation_cli_emits_background_instance_public_views() { .join("application-model") .join("background") } else { - output + common::python_package_dir(&output) }; let stem = if language == "js" { "IBackgroundTaskInstance".to_string() @@ -1218,6 +1218,7 @@ fn implementation_public_python_views_type_check_without_internal_constructors() "{}", String::from_utf8_lossy(&generated.stderr) ); + let package = common::python_package_dir(&package); let foundation = package.join("windows").join("foundation"); let delegate_facade = std::fs::read_dir(&foundation) .unwrap() @@ -1445,8 +1446,10 @@ assert_type( .env("PYTHONUTF8", "1") .env( "MYPYPATH", - std::env::join_paths([binding_stubs.clone(), std::path::PathBuf::from(".")]) - .unwrap(), + std::env::join_paths(std::iter::once(binding_stubs.clone()).chain( + std::env::split_paths(&common::python_fixture_search_path(&scratch)), + )) + .unwrap(), ) .output() .expect("run the existing mypy checker")