Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -91,17 +91,15 @@ jobs:
run: |
npm install --prefix target/tsc --no-save --ignore-scripts --no-package-lock typescript@5.9.3
$tsc = (Resolve-Path target/tsc/node_modules/typescript/bin/tsc).Path
$windowsWinmd = Get-ChildItem 'C:\Program Files (x86)\Windows Kits\10\UnionMetadata' `
-Filter Windows.winmd -File -Recurse |
Sort-Object FullName -Descending |
Select-Object -First 1
if (-not $windowsWinmd) {
throw 'Windows SDK metadata is required for declaration tests'
}
"DYNWINRT_TSC=$tsc" >> $env:GITHUB_ENV
"DYNWINRT_WINDOWS_WINMD=$($windowsWinmd.FullName)" >> $env:GITHUB_ENV
"DYNWINRT_REQUIRE_TSC=1" >> $env:GITHUB_ENV
- uses: NuGet/setup-nuget@v2
- name: Restore pinned Windows SDK corpus
shell: pwsh
run: |
$winmd = .\eng\ci\restore-windows-metadata.ps1 `
-OutputDirectory (Join-Path $env:RUNNER_TEMP 'windows-sdk-corpus')
"DYNWINRT_WINDOWS_WINMD=$winmd" >> $env:GITHUB_ENV
- name: Install Win32 metadata
shell: pwsh
run: |
Expand Down Expand Up @@ -579,6 +577,10 @@ jobs:
cargo test -p dynwinrt-codegen --test python_consumer_typing_test `
reference_array_results_preserve_null_elements -- --exact
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$env:DYNWINRT_TEST_INSTALLED_RUNTIME = '1'
cargo test -p dynwinrt-codegen --test python_consumer_typing_test `
resource_dictionary_keys_are_scoped_and_typed_in_stubs_and_inline_sources -- --exact
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
cargo test -p dynwinrt-codegen --test python_collection_helper_collision_test `
--test python_collection_member_collision_test -- --nocapture
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
Expand Down
8 changes: 8 additions & 0 deletions .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ on:
- 'crates/dynwinrt/**'
- 'crates/dynwinrt-com-contracts/**'
- 'eng/coverage/**'
- 'eng/ci/restore-windows-metadata.ps1'
- 'tests/e2e/**'
- 'tools/dynwinrt-codegen/**'
push:
Expand Down Expand Up @@ -57,6 +58,13 @@ jobs:

- uses: NuGet/setup-nuget@v2

- name: Restore pinned Windows SDK corpus
shell: pwsh
run: |
$winmd = .\eng\ci\restore-windows-metadata.ps1 `
-OutputDirectory (Join-Path $env:RUNNER_TEMP 'windows-sdk-corpus')
"DYNWINRT_WINDOWS_WINMD=$winmd" >> $env:GITHUB_ENV

- name: Install cargo-llvm-cov
shell: pwsh
run: cargo install cargo-llvm-cov --version 0.8.7 --locked
Expand Down
14 changes: 14 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ cargo build -p dynwinrt-codegen

### Running Tests

The codegen's exhaustive Windows SDK corpus assertions use the immutable
`Microsoft.Windows.SDK.CPP` package pinned in
`tools/dynwinrt-codegen/tests/windows_sdk_corpus.json`, not whichever SDK servicing
update is installed on the machine. Restore and verify that metadata before
running codegen library tests or the coverage pipeline (requires `nuget` on PATH):

```powershell
$env:DYNWINRT_WINDOWS_WINMD = .\eng\ci\restore-windows-metadata.ps1 `
-OutputDirectory .\target\windows-sdk-corpus
```

CI uses the same helper and SHA-256 pin. A missing or different corpus fails with
restore instructions rather than skipping the exact member/count assertions.

```bash
# Core library tests
cargo test -p dynwinrt
Expand Down
24 changes: 24 additions & 0 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,30 @@ classes with no instance surface are not projection targets.

### Explicit boxing and unboxing of `Object` values

Generated `Microsoft.UI.Xaml.ResourceDictionary` and
`Windows.UI.Xaml.ResourceDictionary` projections, and their WinMD-derived
classes such as `Windows.UI.Xaml.ColorPaletteResources`, accept string keys directly:

```python
raw_style = resources.lookup("AccentButtonStyle")
raw_style = resources["AccentButtonStyle"]
raw_style = resources.get("AccentButtonStyle")
```

Their key-taking lookup, membership, insert, update and removal operations box
`str` as a WinRT string internally. String subclasses, including `StrEnum` and
`str`/`Enum` members, use their underlying string contents rather than custom
`__str__()` formatting. Existing raw or projected-object keys remain accepted,
and results and enumerated keys remain raw `DynWinRTValue` objects
(or `None` where already supported). `lookup()` preserves native errors;
missing `[]` keys raise `KeyError`, and `get()` keeps its normal default.
The `get()` and `pop()` result annotations include the supplied default type
in both `.pyi` and inline-only (`--no-pyi`) output. WinMD-derived projections
retain the base dictionary's key contract even with an independent default interface.
This is a ResourceDictionary-specific input convenience, not automatic boxing
for generic `IMap<Object, Object>`, `IMapView<Object, Object>` or other
`Object`/`IInspectable` APIs. Continue boxing their inputs explicitly.

Generic WinRT `Object`/`IInspectable` results and parameters remain raw
`DynWinRTValue` instances: an `Object` may be any runtime object, not only a
boxed value. Convert explicitly where the application expects a boxed
Expand Down
31 changes: 31 additions & 0 deletions eng/ci/restore-windows-metadata.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

param(
[Parameter(Mandatory = $true)][string]$OutputDirectory,
[string]$NuGet = "nuget"
)

$ErrorActionPreference = "Stop"
$root = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path
$pin = Get-Content -LiteralPath (Join-Path $root "tools\dynwinrt-codegen\tests\windows_sdk_corpus.json") -Raw |
ConvertFrom-Json
$destination = [IO.Path]::GetFullPath($OutputDirectory)
$packageRoot = Join-Path $destination "$($pin.package).$($pin.version)"
$winmd = Join-Path $packageRoot $pin.relative_path
if (-not (Test-Path -LiteralPath $winmd -PathType Leaf)) {
& $NuGet install $pin.package -Version $pin.version `
-OutputDirectory $destination -DirectDownload -NonInteractive | Out-Host
if ($LASTEXITCODE -ne 0) {
throw "Failed to restore $($pin.package) $($pin.version)"
}
}
if (-not (Test-Path -LiteralPath $winmd -PathType Leaf)) {
throw "Pinned Windows SDK package is missing $($pin.relative_path)"
}
$actual = (Get-FileHash -LiteralPath $winmd -Algorithm SHA256).Hash
if ($actual -ne $pin.sha256) {
throw "Pinned Windows SDK metadata hash mismatch: expected $($pin.sha256), got $actual at $winmd"
}
Write-Host "Verified Windows SDK corpus: $($pin.package) $($pin.version), SHA256 $actual"
(Resolve-Path -LiteralPath $winmd).Path
82 changes: 82 additions & 0 deletions eng/ci/test_ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Licensed under the MIT License.

import copy
import hashlib
import json
import os
from pathlib import Path
Expand Down Expand Up @@ -191,6 +192,87 @@ def test_missing_empty_and_invalid_readmes_fail_in_github_wrapper(self):
readme.write_bytes(original)


class WindowsCorpusTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="dynwinrt-ci-corpus-")
self.addCleanup(self.temporary.cleanup)
self.repo = Path(self.temporary.name)
self.relative_pin = Path("tools/dynwinrt-codegen/tests/windows_sdk_corpus.json")
self.pin = json.loads((ROOT / self.relative_pin).read_text(encoding="utf-8"))
self.payload = b"test metadata bytes"
self.pin["sha256"] = hashlib.sha256(self.payload).hexdigest()
destination = self.repo / self.relative_pin
destination.parent.mkdir(parents=True)
destination.write_text(json.dumps(self.pin), encoding="utf-8")
self.script = self.repo / "eng/ci/restore-windows-metadata.ps1"
self.script.parent.mkdir(parents=True)
shutil.copyfile(CI / "restore-windows-metadata.ps1", self.script)
self.output = self.repo / "packages"
self.winmd = (
self.output / f"{self.pin['package']}.{self.pin['version']}"
/ self.pin["relative_path"]
)
self.nuget = self.repo / "nuget.ps1"
self.nuget.write_text(
"param([string]$Command, [string]$Id, [string]$Version, "
"[string]$OutputDirectory, [switch]$DirectDownload, [switch]$NonInteractive)\n"
"if ($Command -ne 'install' -or -not $DirectDownload -or -not $NonInteractive) { exit 2 }\n"
f"if ($Id -ne '{self.pin['package']}' -or $Version -ne '{self.pin['version']}') {{ exit 3 }}\n"
"$package = Join-Path $OutputDirectory \"$Id.$Version\"\n"
f"$path = Join-Path $package '{self.pin['relative_path']}'\n"
"New-Item -ItemType Directory -Path (Split-Path -Parent $path) -Force | Out-Null\n"
"[IO.File]::WriteAllBytes($path, [Text.Encoding]::UTF8.GetBytes('test metadata bytes'))\n"
"exit 0\n",
encoding="utf-8",
)

def restore(self):
return powershell(
self.script, "-OutputDirectory", self.output, "-NuGet", self.nuget,
)

def test_restore_verifies_content_and_reuses_only_verified_existing_input(self):
result = self.restore()
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
returned = Path(result.stdout.strip().splitlines()[-1])
self.assertTrue(returned.is_absolute())
self.assertTrue(returned.samefile(self.winmd), f"{returned} != {self.winmd}")
self.assertEqual(self.winmd.read_bytes(), self.payload)
self.nuget.unlink()
result = self.restore()
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)

def test_modified_input_and_failed_restore_are_errors(self):
self.winmd.parent.mkdir(parents=True)
self.winmd.write_bytes(b"rolling SDK changed in-place")
result = self.restore()
self.assertNotEqual(result.returncode, 0)
self.assertIn("metadata hash mismatch", result.stdout + result.stderr)
self.assertEqual(self.winmd.read_bytes(), b"rolling SDK changed in-place")
self.winmd.unlink()
self.nuget.write_text("exit 7\n", encoding="utf-8")
result = self.restore()
self.assertNotEqual(result.returncode, 0)
self.assertIn("Failed to restore", result.stdout + result.stderr)

def test_build_and_coverage_share_the_pinned_corpus_input(self):
coverage = yaml.safe_load(
(ROOT / ".github/workflows/coverage.yml").read_text(encoding="utf-8")
)
triggers = coverage.get("on", coverage.get(True))
self.assertIn(
"eng/ci/restore-windows-metadata.ps1", triggers["pull_request"]["paths"]
)
for job in (JOBS["test-rust"], coverage["jobs"]["coverage"]):
step, = [
step for step in job["steps"]
if step.get("name") == "Restore pinned Windows SDK corpus"
]
self.assertIn(r".\eng\ci\restore-windows-metadata.ps1", step["run"])
self.assertIn("DYNWINRT_WINDOWS_WINMD=$winmd", step["run"])
self.assertNotIn("Sort-Object", step["run"])


class WorkflowTests(unittest.TestCase):
def ancestors(self, job):
needs = JOBS[job].get("needs", [])
Expand Down
77 changes: 77 additions & 0 deletions tests/e2e/runners/py_winui_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,82 @@
from pathlib import Path


def check_resource_dictionary_keys(resources):
from enum import Enum, StrEnum
from types import SimpleNamespace
from dynwinrt import DynWinRTValue, to_winrt_object, unbox_object
from dynwinrt.values import Char16

class ResourceKey(StrEnum):
ACCENT = "AccentButtonStyle"

class LegacyResourceKey(str, Enum):
ACCENT = "AccentButtonStyle"

name = "AccentButtonStyle"
boxed = to_winrt_object(name)
identity = boxed.identity_raw()
style = resources.lookup(boxed)
assert isinstance(style, DynWinRTValue) and not style.is_null()
for key in (name, boxed, SimpleNamespace(_obj=boxed), ResourceKey.ACCENT, LegacyResourceKey.ACCENT):
assert resources.lookup(key).identity_raw() == style.identity_raw()
assert resources[key].identity_raw() == style.identity_raw()
assert resources.get(key).identity_raw() == style.identity_raw()
assert resources.has_key(key) and key in resources

missing = "DynWinRT.Missing.Resource.StringKey"
errors = []
for key in (to_winrt_object(missing), missing):
try:
resources.lookup(key)
except OSError as error:
errors.append((error.winerror, str(error)))
else:
raise AssertionError("missing ResourceDictionary.lookup did not raise")
assert errors[0] == errors[1]
try:
resources[missing]
except KeyError as error:
assert error.args == (missing,)
else:
raise AssertionError("missing ResourceDictionary item did not raise")
fallback = object()
assert resources.get(missing) is None
assert resources.get(missing, fallback) is fallback
assert resources.pop(missing, fallback) is fallback

local = type(resources)()
assert local.insert("first", style) is False
assert local.insert("first", style) is True
local["second"] = style
local.update(third=style)
assert local.setdefault("first", style).identity_raw() == style.identity_raw()
assert local.setdefault("fourth", style).identity_raw() == style.identity_raw()
# Even tagged str subclasses are keys of the native String contract.
local[Char16("x")] = style
assert local["x"].identity_raw() == style.identity_raw()
keys = list(local)
assert len(local) == len(keys) == 5
assert all(isinstance(key, DynWinRTValue) for key in keys)
assert {unbox_object(key) for key in keys} == {"first", "second", "third", "fourth", "x"}
assert local != {unbox_object(key): style for key in keys}
local.remove("first")
del local["second"]
assert local.pop("third").identity_raw() == style.identity_raw()
assert len(local) == 2
assert boxed.identity_raw() == identity and not boxed.is_released()
assert resources.lookup(boxed).identity_raw() == style.identity_raw()
released = to_winrt_object(name)
released.release()
for key in (released, SimpleNamespace(_obj=released)):
try:
resources.lookup(key)
except RuntimeError as error:
assert "released" in str(error)
else:
raise AssertionError("released ResourceDictionary key was accepted")


def load_type(package: str, namespace: str, name: str):
return getattr(importlib.import_module(f"{package}.{namespace}"), name)

Expand Down Expand Up @@ -207,6 +283,7 @@ def launched() -> None:
f"{sorted(theme_names)!r}"
)
state["fluent_theme_names"] = sorted(theme_names)
check_resource_dictionary_keys(resources)
if app.requested_theme != ApplicationTheme.Dark:
raise RuntimeError(
"Application requested theme was not applied"
Expand Down
Loading
Loading