diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 40859f60..45cc7aca 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -13,6 +13,13 @@ "commands": [ "reportgenerator" ] + }, + "dotnet-coverage": { + "version": "18.12.0", + "commands": [ + "dotnet-coverage" + ], + "rollForward": false } } } \ No newline at end of file diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml index 532a9534..d1babb9d 100644 --- a/.github/workflows/integration-tests.yml +++ b/.github/workflows/integration-tests.yml @@ -14,6 +14,67 @@ permissions: contents: read jobs: + cli-contracts: + name: Portable CLI Contracts (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + + - uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0 + with: + global-json-file: global.json + + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: '3.13' + cache: pip + cache-dependency-path: tests/cli-contracts/requirements*.txt + + - name: Build C# reference + shell: pwsh + run: | + Copy-Item tests/cli-contracts/fixtures/locale.de-DE.ftl CosmosDBShell/lang/de-DE.ftl + dotnet build CosmosDBShell/CosmosDBShell.csproj + + - name: Install contract runner + run: python -m pip install -r tests/cli-contracts/requirements.txt + + - name: Validate migration inventory + run: python tests/cli-contracts/inventory.py --output artifacts/cli-contract-inventory.json + + - name: Run runner self-tests and offline contracts + shell: pwsh + env: + COSMOSDB_SHELL_UI_LANGUAGE: de-DE + run: | + $assembly = & ./tests/cli-contracts/resolve-shell-assembly.ps1 + $localizedHelp = dotnet $assembly --help + if ($LASTEXITCODE -ne 0 -or ($localizedHelp -join "`n") -notmatch 'Testkatalog: Ausgabeformat') { + throw 'The reference did not load the non-English fixture catalog.' + } + python -m pytest tests/cli-contracts --profile offline ` + --shell-executable dotnet --shell-prefix-arg $assembly ` + --contract-artifacts artifacts/cli-contract-failures ` + --junitxml artifacts/cli-contracts.xml -q + + - name: Upload contract report and synthetic failure data + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: cli-contracts-${{ matrix.os }} + path: | + artifacts/cli-contract-inventory.json + artifacts/cli-contracts.xml + artifacts/cli-contract-failures/ + retention-days: 7 + offline-tests: name: Offline Integration Tests runs-on: ubuntu-latest @@ -105,6 +166,32 @@ jobs: # The Windows emulator job below exercises those collisions. run: dotnet test CosmosDBShell.Tests/CosmosDBShell.Tests.csproj --filter "Category=Emulator&Feature!=PartitionKeyCollisions" --no-restore -p:CosmosRequireEmulator=true + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: '3.13' + + - name: Install independent emulator fixtures + run: python -m pip install -r tests/cli-contracts/requirements-emulator.txt + + - name: Run portable Linux emulator contracts + shell: pwsh + run: >- + python -m pytest tests/cli-contracts/test_contracts.py --profile emulator-linux + --shell-executable dotnet + --shell-prefix-arg (& ./tests/cli-contracts/resolve-shell-assembly.ps1) + --contract-artifacts artifacts/cli-contract-failures + --junitxml artifacts/cli-contracts-linux-emulator.xml -q + + - name: Upload emulator contract report + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: cli-contracts-linux-emulator + path: | + artifacts/cli-contracts-linux-emulator.xml + artifacts/cli-contract-failures/ + retention-days: 7 + windows-partition-key-tests: name: Windows Partition-Key Integration Tests runs-on: windows-latest @@ -155,3 +242,28 @@ jobs: - name: Run partition-key integration tests run: dotnet test .\CosmosDBShell.Tests\CosmosDBShell.Tests.csproj --filter "Category=Emulator&FullyQualifiedName~PrintPartitionKeyTests" --no-restore -p:CosmosRequireEmulator=true + + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: '3.13' + + - name: Install independent emulator fixtures + run: python -m pip install -r tests\cli-contracts\requirements-emulator.txt + + - name: Run portable Windows emulator contracts + run: >- + python -m pytest tests\cli-contracts\test_contracts.py --profile emulator-windows + --shell-executable dotnet + --shell-prefix-arg (& ./tests/cli-contracts/resolve-shell-assembly.ps1) + --contract-artifacts artifacts\cli-contract-failures + --junitxml artifacts\cli-contracts-windows-emulator.xml -q + + - name: Upload emulator contract report + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: cli-contracts-windows-emulator + path: | + artifacts/cli-contracts-windows-emulator.xml + artifacts/cli-contract-failures/ + retention-days: 7 diff --git a/.github/workflows/validate-and-package.yml b/.github/workflows/validate-and-package.yml index 3297457c..d11ec4eb 100644 --- a/.github/workflows/validate-and-package.yml +++ b/.github/workflows/validate-and-package.yml @@ -107,7 +107,7 @@ jobs: $ErrorActionPreference = 'Stop' dotnet tool restore if ($LASTEXITCODE -ne 0) { - throw "Failed to restore .NET local tools (nbgv)." + throw "Failed to restore .NET local tools." } - name: Compute version properties @@ -200,29 +200,84 @@ jobs: } - name: Test solution - run: >- - dotnet test CosmosDBShell.sln - --configuration $env:BUILD_CONFIGURATION - --no-build - --no-restore - --logger "trx;LogFileName=test-results.trx" - --results-directory TestResults - --collect "XPlat Code Coverage" + id: xunit-coverage shell: pwsh + run: | + dotnet tool run dotnet-coverage collect ` + --settings tests/cli-contracts/coverage.config ` + --output TestResults/xunit/coverage.cobertura.xml ` + --output-format cobertura ` + dotnet test CosmosDBShell.sln ` + --configuration $env:BUILD_CONFIGURATION ` + --no-build ` + --no-restore ` + --logger "trx;LogFileName=test-results.trx" ` + --results-directory TestResults + if ($LASTEXITCODE -ne 0) { + throw "Solution tests or coverage collection failed." + } - - name: Generate code coverage report - if: always() + [xml]$coverage = Get-Content -Raw TestResults/xunit/coverage.cobertura.xml + $coveredProductLines = $coverage.SelectNodes('//class[contains(@filename, "Azure.Data.Cosmos.Shell.")]/lines/line[@hits > 0]') + if ($coveredProductLines.Count -eq 0) { + throw "Solution tests collected no C# shell product coverage." + } + + - name: Setup Python for portable coverage + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: '3.13' + cache: pip + cache-dependency-path: tests/cli-contracts/requirements.txt + + - name: Install portable contract dependencies + run: python -m pip install -r tests/cli-contracts/requirements.txt + + - name: Collect C# coverage from portable CLI contracts + id: cli-coverage shell: pwsh run: | $ErrorActionPreference = 'Stop' + $assembly = & ./tests/cli-contracts/resolve-shell-assembly.ps1 -Configuration $env:BUILD_CONFIGURATION + dotnet tool run dotnet-coverage collect ` + --settings tests/cli-contracts/coverage.config ` + --output TestResults/cli-contracts/coverage.cobertura.xml ` + --output-format cobertura ` + python -m pytest tests/cli-contracts --profile offline ` + --shell-executable dotnet ` + --shell-prefix-arg $assembly ` + --contract-artifacts TestResults/cli-contract-failures ` + --junitxml TestResults/cli-contracts.xml -q + if ($LASTEXITCODE -ne 0) { + throw "Portable CLI contracts or coverage collection failed." + } - $coverageFiles = Get-ChildItem -Path TestResults -Recurse -Filter 'coverage.cobertura.xml' -ErrorAction SilentlyContinue - if (-not $coverageFiles) { - Write-Host '::warning::No coverage files found; skipping coverage report.' - return + [xml]$coverage = Get-Content -Raw TestResults/cli-contracts/coverage.cobertura.xml + $coveredProductLines = $coverage.SelectNodes('//class[contains(@filename, "Azure.Data.Cosmos.Shell.")]/lines/line[@hits > 0]') + if ($coveredProductLines.Count -eq 0) { + throw "Portable CLI contracts collected no C# shell product coverage." } - $reports = ($coverageFiles.FullName -join ';') + - name: Upload raw coverage and portable contract results + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: cli-contract-coverage-results + path: | + TestResults/cli-contracts.xml + TestResults/cli-contracts/coverage.cobertura.xml + TestResults/xunit/coverage.cobertura.xml + TestResults/cli-contract-failures/ + retention-days: 7 + + - name: Generate code coverage report + id: combined-coverage + if: steps.xunit-coverage.outcome == 'success' && steps.cli-coverage.outcome == 'success' + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + + $reports = 'TestResults/xunit/coverage.cobertura.xml;TestResults/cli-contracts/coverage.cobertura.xml' dotnet tool run reportgenerator ` "-reports:$reports" ` "-targetdir:TestResults/coverage" ` @@ -239,13 +294,13 @@ jobs: # Publish coverage to GitHub Code Quality so the aggregate percentage and # per-file breakdown appear directly on the PR (public preview feature). - # ReportGenerator merges the per-project XPlat reports into a single + # ReportGenerator merges xUnit and portable CLI reports into a single # Cobertura.xml that this action uploads. Skipped for fork PRs, which # cannot write to the base repo; `fail-on-error: false` keeps CI green if # Code Quality is not yet enabled on the repository. - name: Upload coverage to GitHub Code Quality if: >- - always() && + steps.combined-coverage.outcome == 'success' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && hashFiles('TestResults/coverage/Cobertura.xml') != '' diff --git a/.gitignore b/.gitignore index c81c327a..e655144c 100644 --- a/.gitignore +++ b/.gitignore @@ -318,6 +318,8 @@ paket-files/ # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc +.pytest_cache/ +.venv/ # Cake - Uncomment if you are using it # tools/** diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index baff521f..d4a8bef3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -120,6 +120,20 @@ Run the offline regression suite without a database: dotnet test CosmosDBShell.Tests/CosmosDBShell.Tests.csproj --filter "Category!=Emulator" ``` +### Portable CLI Contracts + +The [language-neutral CLI suite](docs/cli-contract-tests.md) runs reviewed +scripts against an executable and compares only declared result files, process +exit codes, and independently verified emulator side effects. Add cases there +for externally observable command/script behavior so the same contracts can +validate the future Rust implementation without a .NET test host. + +Keep the existing xUnit tests for the official build, which does not yet run the +portable suite, and for internal assertions. The suite's migration inventory reports links +and remaining coverage; a linked case does not imply a whole theory was migrated. +See the guide for Python setup, launcher selection, output capture, emulator +profiles, and strict comparison rules. + ### Updating Localized Text Edit `CosmosDBShell/lang/en.ftl`, then build normally: @@ -170,7 +184,8 @@ Repository administrators should keep that check required, or require ### Running Against the Emulator CI pins the Linux preview emulator image by digest to avoid rolling-tag regressions. -Update the pin only after the full Linux emulator suite passes with the replacement. +Update the pin only after both the .NET tests and portable Linux emulator contracts +pass with the replacement. You can develop and test without an Azure subscription by using the [Azure Cosmos DB Emulator](https://learn.microsoft.com/azure/cosmos-db/emulator): diff --git a/CosmosDBShell.Tests/Integration/ShellProcessTests.cs b/CosmosDBShell.Tests/Integration/ShellProcessTests.cs index 67332c7a..0a9df086 100644 --- a/CosmosDBShell.Tests/Integration/ShellProcessTests.cs +++ b/CosmosDBShell.Tests/Integration/ShellProcessTests.cs @@ -934,6 +934,7 @@ public async Task InvariantGlobalization_ExecuteCommand_LoadsEnglishCatalog() environment: new Dictionary { ["DOTNET_SYSTEM_GLOBALIZATION_INVARIANT"] = "1", + ["COSMOSDB_SHELL_UI_LANGUAGE"] = "en", }); Assert.Equal(2, result.ExitCode); @@ -941,6 +942,22 @@ public async Task InvariantGlobalization_ExecuteCommand_LoadsEnglishCatalog() Assert.DoesNotContain("1 arguments", result.StdErr); } + [Fact] + public async Task HelpOption_UsesEnglishWithExplicitApplicationUiLanguage() + { + var result = await RunShellAsync( + stdinScript: null, + extraArgs: ["--help"], + cancellationToken: TestContext.Current.CancellationToken, + environment: new Dictionary + { + ["COSMOSDB_SHELL_UI_LANGUAGE"] = "en", + }); + + Assert.Equal(0, result.ExitCode); + Assert.Contains("The output format to use", result.StdOut); + } + [Fact] public async Task StdinPipedScript_MultipleCommands_AllRunAndLastOutputVisible() { diff --git a/CosmosDBShell/Program.cs b/CosmosDBShell/Program.cs index 411699ac..53d88892 100644 --- a/CosmosDBShell/Program.cs +++ b/CosmosDBShell/Program.cs @@ -4,6 +4,7 @@ using System.CommandLine; using System.CommandLine.Parsing; +using System.Globalization; using System.Reflection; using Azure.Data.Cosmos.Shell.Commands; using Azure.Data.Cosmos.Shell.Core; @@ -72,6 +73,16 @@ public static async Task Main(string[] args) TracingBootstrap? tracing = null; try { + if (Environment.GetEnvironmentVariable("COSMOSDB_SHELL_UI_LANGUAGE") is { Length: > 0 } language) + { + // MessageService uses the English catalog for the invariant UI culture. + var culture = language.Equals("en", StringComparison.OrdinalIgnoreCase) + ? CultureInfo.InvariantCulture + : CultureInfo.GetCultureInfo(language); + CultureInfo.DefaultThreadCurrentUICulture = culture; + CultureInfo.CurrentUICulture = culture; + } + // --help / --version handled manually so we can render our own // localized usage and version heading. Only inspect the prefix // before -c / -k so that a command tail of literally "--help" or diff --git a/docs/cli-contract-tests.md b/docs/cli-contract-tests.md new file mode 100644 index 00000000..b3ce035e --- /dev/null +++ b/docs/cli-contract-tests.md @@ -0,0 +1,259 @@ +# Portable CLI contract tests + +The [shared suite](../tests/cli-contracts) exercises an executable, not C# objects. +It is the compatibility contract for a future Rust shell. The same case IDs, +scripts, fixtures, exit codes, and expectations apply to every implementation. +No implementation switches, reduced expectations, automatic baseline updates, +`xfail`, or fallback to the C# binary are supported. + +The Rust port itself is not included. Passing the C# reference does not establish +Rust compatibility. A Rust implementation must pass every offline case and both +emulator profiles before it is considered compatible. + +## Run locally + +Use Python 3.11 or newer. The runner itself does not require .NET; building the +C# reference does. From the repository root, in PowerShell: + +```powershell +python -m venv .venv +.\.venv\Scripts\Activate.ps1 +python -m pip install -r tests\cli-contracts\requirements.txt +dotnet build CosmosDBShell\CosmosDBShell.csproj +$assembly = & .\tests\cli-contracts\resolve-shell-assembly.ps1 +python -m pytest tests\cli-contracts --profile offline --shell-executable dotnet --shell-prefix-arg $assembly -q +``` + +On Linux/macOS, activate `.venv/bin/activate` and use `/` in paths. +For a published or Rust executable, substitute only the launcher: + +```powershell +python -m pytest tests\cli-contracts --profile offline --shell-executable C:\path\to\cosmos-shell.exe -q +``` + +`--shell-prefix-arg` is repeatable (use `--shell-prefix-arg=-flag` for a prefix +argument beginning with `-`). Launchers are never evaluated by an OS shell. +Relative executable/assembly paths are resolved before changing directories. +The runner requests English application messages with +`COSMOSDB_SHELL_UI_LANGUAGE=en`, independently of the parent process's language. +The English catalog is also available with .NET invariant globalization enabled. + +Run just the runner/comparator self-tests without building a shell: + +```powershell +python -m pytest tests\cli-contracts\test_runner.py tests\cli-contracts\test_comparisons.py -q +``` + +For emulator contracts, install the independent fixture dependencies and start +the appropriate local emulator: + +```powershell +python -m pip install -r tests\cli-contracts\requirements-emulator.txt +python -m pytest tests\cli-contracts\test_contracts.py --profile emulator-windows --shell-executable C:\path\to\cosmos-shell.exe -q +``` + +Use `--profile emulator-linux` for the Linux preview emulator. These are server +profiles, not implementation capabilities. The Windows profile also checks +partition-key collisions, Windows emulator policy defaults and offer metadata, +bounded change feed results, and stored procedure, trigger, and UDF registration +lifecycles (not script execution). Missing executables, +an unavailable selected emulator, malformed cases, and missing output files +**fail**; they are not skipped. `--emulator-endpoint` defaults to +`https://localhost:8081` and permits only `localhost` and `127.0.0.1`. + +The command smoke cases exercise real invocations, not just option parsing. +`edit` is covered by its noninteractive diagnostic and must not create a file; +opening an editor interactively requires a terminal harness. `jq` is outside +the current compatibility contract. + +The Python Azure Cosmos SDK creates fresh, uniquely named, owned databases, +seeds data independently of the shell, verifies mutations, and cleans up on +success or failure. Never point this suite at a real account or add real +credentials or production data to a case. + +## Capturing only command output + +Every case runs a fresh process in an isolated working/config directory with +a timeout. The runner sends optional UTF-8 input to the child's stdin pipe and +then closes it; cases without input get immediate EOF. Related commands share +a script/session. The runner captures subprocess stdout and stderr into +`stdout.txt` and `stderr.txt`. + +Structured contracts normally redirect each command's result inside the shell: + +```text +echo {"id":"one","count":9007199254740993} > 'result.json' +``` + +The runner compares only declared files and never removes prompts, ANSI escapes, +or duplicate JSON from them. If redirection must leave stdout silent, declare +`stdout.txt` with `"mode": "empty"`. If stdout intentionally carries machine-readable +data, assert its content rather than leaving the stream unchecked. + +Internal redirection bypasses the human renderer. Human/table cases therefore +use `--output user`/`--output table` without internal result redirection and +assert the captured subprocess files instead. The `-c` invocation exits without +entering the interactive editor. Startup/argument errors also use subprocess +files and assert the process exit code. + +## Case format + +[schema.json](../tests/cli-contracts/schema.json) validates every manifest before +selection. Files contain `schemaVersion: 1` and a `cases` array. IDs are unique +across the entire corpus. Source links reference existing xUnit method names or +explicitly reviewed removed methods in the migration map. + +```json +{ + "schemaVersion": 1, + "cases": [{ + "id": "example.structured-result", + "profiles": ["offline"], + "sources": ["CosmosDBShell.Tests/Integration/OutputRedirectionTests.cs::Redirect_StdoutToFile_WritesOutput"], + "script": "echo {\"id\":\"one\"} > 'result.json'", + "exitCode": 0, + "files": { + "result.json": {"mode": "json", "expected": {"id": "one"}}, + "stdout.txt": {"mode": "empty"}, + "stderr.txt": {"mode": "empty"} + } + }] +} +``` + +The example illustrates the format; use the actual method name from the source +test when adding a case. Use either `script` or raw CLI `args`; scripts get +`--output -c