Azure CLI test SDK scenario framework
Overview
Routing and coverage note: this doc owns src/azure-cli-testsdk/**, tests/agent_tools/**, and doc/authoring_tests.md. Route changes here when they affect the public azure.cli.testsdk API, replayable/live scenario execution, VCR recording processors, resource preparers, scenario-test patches, test authoring guidance, the test SDK package metadata, or the small regression tests under tests/agent_tools.
The test SDK package exposes the stable authoring surface from src/…/__init__.py: ScenarioTest, LiveScenarioTest, LocalContextScenarioTest, resource preparers, checkers, live_only/record_only, api_version_constraint, create_random_name, and MOCKED_USER_NAME. doc/authoring_tests.md tells test authors to import from this top-level namespace rather than subpackages, describes replayable VCR tests, and documents the key runtime switches: AZURE_TEST_RUN_LIVE forces live/record mode, AZURE_TEST_SKIP_ASSERT suppresses checks, AZURE_TEST_COMMAND_COVERAGE appends executed commands to az_command_coverage.txt, and preparer-specific AZURE_CLI_TEST_DEV_* variables let live tests reuse existing resources.
ScenarioTest in src/…/base.py is the normal integration-test base. It creates a dummy CLI context through reverse_dependency.get_dummy_cli, maintains self.kwargs for format-substituting commands and expected check values, and delegates command execution to ExecutionResult. ExecutionResult._in_process_execute strips a leading az, calls cli_ctx.invoke(shlex.split(command), out_file=stdout_buf), captures stdout, and turns nonzero exits or unexpected success/failure into assertions. CheckerMixin builds callable JMESPath/string checkers from src/…/checkers.py; ExecutionResult.assert_with_checks runs those callables unless AZURE_TEST_SKIP_ASSERT=True.
Replay behavior is provided by ReplayableTest in src/…/base.py. Its TestConfig reads only parsed test config and AZURE_TEST_RUN_LIVE, then configures a vcr.VCR cassette library under the test file's recordings directory or the directory passed by ScenarioTest via utilities.find_recording_dir. If a recording file is missing or live mode is enabled, the test records to <test>.temp.yaml, saves it through _save_recording_file, and replaces the real <test>.yaml only when the cassette is dirty and the unittest outcome did not fail or skip. During playback it opens the existing recording and applies replay processors and patches. ReplayableTest filters volatile request headers, lowercases and filters response headers, decodes text bodies, and registers a custom query matcher that requires the same query keys and case-insensitive values.
ScenarioTest layers Azure CLI-specific defaults onto ReplayableTest: recording processors replace subscription IDs, filter AAD auth requests, redact email addresses, drop large request/response bodies, normalize deployment names and doubled slashes, substitute random resource names with deterministic monikers, and scrub storage keys, Graph app passwords, Microsoft Graph password responses, and Microsoft Graph user profile data. Replay processors restore omitted large non-JSON bodies and repeat the deterministic name/URL normalization. Recording always patches the CLI main exception handler; playback also skips time.sleep, skips ARM polling service delay, yields briefly inside CLI foreground long-running-operation polling, loads a mocked subscription, returns a mocked MSAL user credential token, and disables progress rendering. LiveScenarioTest bypasses VCR by inheriting IntegrationTestBase directly and is decorated with live_only; it still patches the main exception handler and executes through the dummy CLI.
Recording processors are split between the vendored scenario layer and CLI-specific utilities. src/…/recording_processors.py defines the base RecordingProcessor, SubscriptionRecordingProcessor, large body processors, OAuth/token/deployment/name replacers, RequestUrlNormalizer, and ContentLengthProcessor. CLI-specific redactors in src/…/utilities.py handle storage account keys, legacy Graph password credentials, MS Graph secretText, encoded MS Graph names, @microsoft.com email addresses, signed-in MS Graph user profile fields, and AAD login traffic filtering. Stateful redactors that are reused per ScenarioTest are reset in ScenarioTest.tearDown so learned secrets and user names do not leak across test methods.
Resource setup is decorator-driven. AbstractPreparer and SingleValueReplacer in src/…/preparers.py wrap the test method, choose a real random name in live/recording or a deterministic moniker in playback, optionally append themselves as recording processors, call create_resource, merge returned parameters into the test method kwargs, trim kwargs that the final test function does not accept, and finally remove resources in reverse decorator order. The CLI preparers in src/…/preparers.py use get_dummy_cli plus execute to create resource groups, storage accounts, Key Vaults, managed HSMs, service principals, managed applications, virtual networks/NICs, and Log Analytics workspaces. Most inherit NoTrafficRecordingPreparer, which sets disable_recording=True while preparer commands run, advances the same moniker counter, and returns deterministic replacement values during playback instead of making SDK/CLI calls. Each preparer also writes short keys such as rg, sa, kv, sp, vnet, or nic into test_class_instance.kwargs for command-string formatting.
The low-level scenario utilities in src/…/utilities.py generate random names with a base32 suffix, hash files, classify VCR request/response payloads as text or JSON from content type, and detect preparer wrappers. IntegrationTestBase in src/…/base.py provides temp file/dir helpers, environment setters, and an LRO thread assertion in tearDown. LocalContextScenarioTest in src/…/base.py combines ScenarioTest with a random CLI config directory, a temporary working directory, parameter-persistence setup/cleanup commands, and the system-username patch so local-context tests do not depend on the developer machine.
Decorators and patches are small but central. src/…/decorators.py implements live_only, record_only, and AllowLargeResponse; the latter mutates the test instance's LargeResponseBodyProcessor limit before calling the wrapped test. src/…/decorators.py adds api_version_constraint, which dynamically imports azure.cli.core.profiles.supported_api_version through reverse_dependency.py, and serial_test, a pytest.mark.serial wrapper. src/…/patches.py owns generic unittest mock registration and the time.sleep skip, while src/…/patches.py owns Azure CLI-specific patches for exception handling, subscription/auth mocks, progress hooks, playback LRO delay behavior, and local-context usernames.
The package is intentionally lightweight. src/…/pyproject.toml defines the azure-cli-testsdk project, Python classifier support through 3.14, dependencies on ConfigArgParse, jmespath, vcrpy, and pytest, and includes only azure.cli.testsdk and azure.cli.testsdk.scenario_tests packages. src/azure-cli-testsdk/MANIFEST.in includes the license, RST docs, and namespace-package azure/__init__.py and azure/…/__init__.py; setup.cfg is empty after migration to PEP 621 metadata. src/azure-cli-testsdk/README.rst currently documents the playback polling behavior added to avoid busy loops while keeping live execution unchanged, and src/azure-cli-testsdk/HISTORY.rst records compatibility and packaging changes such as MSAL auth patching and removal of the old direct azure-cli dependency.
tests/…/test_aaz_source_lookup.py is covered because it is part of the scoped test tooling, but it is not part of the test SDK package. It regression-tests .x/…/aaz.py by AST-loading only find_promoted_aaz_source_pr, injecting mocked github_get and repository constants, and verifying pagination, truncated-search handling, and closed-vs-merged pull request linkage without network access.
Coupling
- If
ScenarioTestdefault processors or patches change in src/…/base.py, also check the processor and patch implementations in src/…/utilities.py, src/…/recording_processors.py, and src/…/patches.py: recording files depend on the exact order of filtering, redaction, name replacement, and content-length repair. - If resource-name generation changes in
ScenarioTest.create_random_name,AbstractPreparer.moniker, orNoTrafficRecordingPreparer.live_only_execute, verify doc/authoring_tests.md and preparer playback behavior. Both command-authored names and preparer-created resources increment the sametest_resources_count, so changing one side can desynchronize monikers from existing recordings. - If adding a preparer in src/…/preparers.py, export it from src/…/__init__.py when it is meant to be public and update doc/authoring_tests.md if authors need new
AZURE_CLI_TEST_DEV_*environment variables or decorator ordering rules. - If changing VCR request/response shape assumptions in src/…/base.py, also update processors in scenario_tests/recording_processors.py and utilities.py: some processors receive VCR request objects with
.uri,.body,.headers, and.path, while responses are dictionaries withbody.stringand header lists. - If package metadata changes in src/…/pyproject.toml, keep
src/azure-cli-testsdk/MANIFEST.inand doc/authoring_tests.md aligned. Test authoring docs currently mention pytest constraints and package-test pip behavior that must remain compatible with the package's declared dependencies. - If reverse_dependency.py changes dynamic imports for Azure CLI core objects, verify all callers in base.py, decorators.py, preparers.py, and utilities.py; the package history explicitly records removal of a direct azure-cli dependency, so direct imports would change how the test SDK can be packaged and installed.
- If changing .x/…/aaz.py behavior for promoted source PR lookup, update or rerun tests/…/test_aaz_source_lookup.py; the tests intentionally compile only the function body and provide its globals, so new module-level dependencies inside that function must be injectable.
Risks
- src/…/patches.py and
src/azure-cli-testsdk/README.rst: playback LRO delay is fragile becausepatch_time_sleep_apiremovestime.sleepglobally whilepatch_long_run_operation_delaymust still yield to background poller threads throughthreading.Event.wait(0.001). Recent scoped history includes{Test SDK} Fix foreground busy loop during playback polling (#34300), and scenario_tests/…/test_patches.py verifies hook order, cleanup, and propagation of poller results/errors; if this patch regresses, playback can spin CPU or starve pollers. - src/…/utilities.py: redactors that learn values from prior request/response pairs (
StorageAccountKeyReplacer,GraphClientPasswordReplacer,MSGraphClientPasswordReplacer,MSGraphUserProfileReplacer) must reset after eachScenarioTest. If reset is skipped or state is shared unexpectedly, later tests can redact the wrong values or leak private profile fields into recordings; scenario_tests/…/test_msgraph_user_profile_replacer.py specifically covers exact-value replacement and reset behavior. - src/…/base.py:
_save_recording_filerelies on unittest internals to decide whether to replace the final cassette and has a Python 3.11 compatibility branch for missing_Outcome.errors. If failure/skip detection changes again, failed recordings may replace good cassettes or temp cassettes may be left behind; scoped history includes{testsdk} Fix live test on Python 3.11 (#27649). - src/…/preparers.py:
NoTrafficRecordingPreparer.live_only_executeintentionally advancesself.monikerbefore live preparer commands so playback counters match command-levelScenarioTest.create_random_name. If a preparer bypasses this helper or changes decorator order, existing recordings can reference different deterministic resource names; scenario_tests/…/test_preparer_order.py only verifies create/remove nesting, not moniker synchronization. - src/…/utilities.py:
EmailAddressReplacerhas recent fix history ({Test} Add email replacer,Update the response processing, andSkip email replacer if the request body is not string). If future changes assume all bodies decode as text, binary uploads or non-text responses can fail during recording instead of being left untouched.