API Reference
This reference documents the methods, properties, and types that test case writers interact with. It covers the developer-facing surface — methods you call or override — not internal framework methods. It is the canonical source for signatures and configuration tables; the Test Case Guide explains how to use them. It describes nac-test 2.1 (>= 2.1.0b2) with nac-test-pyats-common >= 0.4.0b2.
NACTestBase
Section titled “NACTestBase”Base class for all pyATS test cases. Inherits from pyats.aetest.Testcase.
Properties
Section titled “Properties”| Property | Type | Description |
|---|---|---|
self.data_model | dict[str, Any] | Merged YAML data model loaded from all --data files. Available after setup(). |
self.logger | logging.Logger | Logger scoped to the test module (logging.). |
self. | str | Controller type from the controller context nac-test passes to each test process (detected from which credential env vars are set): "ACI", "SDWAN", "CC", "IOSXE", etc. |
self. | str | Controller URL from env var (e.g., ACI_URL, SDWAN_URL, CC_URL, MERAKI_URL, FMC_URL, ISE_URL). |
self. | TestResultCollector | Collects results for HTML reporting. Typically used via helper methods. |
Methods to Override
Section titled “Methods to Override”get_items_to_verify() -> list[dict[str, Any]] | dict[str, list[dict[str, Any]]]
Section titled “get_items_to_verify() -> list[dict[str, Any]] | dict[str, list[dict[str, Any]]]”Returns items to verify. Called once before verification begins.
- List return (standard): Each dict is a context for one
verify_item()call. - Dict return (grouped): Keys are group identifiers, values are lists of contexts. Triggers
verify_group()instead. - Must NOT execute device commands (SSH not established at this point).
Example:
def get_items_to_verify(self) -> list[dict[str, Any]]: tenants = jmespath.search("apic.tenants[?name]", self.data_model) or [] return [{"tenant": t["name"]} for t in tenants]async verify_item(semaphore: asyncio.Semaphore, client: Any, context: dict[str, Any]) -> dict[str, Any]
Section titled “async verify_item(semaphore: asyncio.Semaphore, client: Any, context: dict[str, Any]) -> dict[str, Any]”Verify a single item. Called once per context dict from get_items_to_verify().
semaphore: Shared by allverify_item()calls of the test (default limit 55,NAC_TEST_PYATS_API_CONCURRENCY). The framework does not acquire it — wrap the body inasync with semaphore:. Calls run concurrently, also within a single D2D device.client: HTTP client for API tests, orNonefor SSH tests.context: One dict fromget_items_to_verify(). Setcontext["display_context"]before returning.- Returns: Result dict from
format_verification_result()or similar helper.
Example:
async def verify_item(self, semaphore, client, context): async with semaphore: tenant = context["tenant"] context["display_context"] = f"Tenant {tenant}" api_context = self.build_api_context("Tenant", tenant) context["api_context"] = api_context
response = await client.get( f"/api/node/mo/uni/tn-{tenant}.json", test_context=api_context )
if response.status_code != 200: return self.format_api_error(response.status_code, str(response.url), context)
if not response.json().get("imdata"): return self.format_not_found("Tenant", tenant, context)
return self.format_verification_result(ResultStatus.PASSED, context, "Tenant exists")async verify_group(semaphore: asyncio.Semaphore, client: Any, group_key: str, contexts: list[dict[str, Any]]) -> list[dict[str, Any]]
Section titled “async verify_group(semaphore: asyncio.Semaphore, client: Any, group_key: str, contexts: list[dict[str, Any]]) -> list[dict[str, Any]]”Verify a group of related items (1:N pattern). Called when get_items_to_verify() returns a dict.
group_key: The dict key identifying this group.contexts: All context dicts for this group.- Returns: List of result dicts.
See the verify_group() pattern in the Test Case Guide for a complete example.
Methods to Call
Section titled “Methods to Call”run_async_verification_test(steps: aetest.Steps) -> None
Section titled “run_async_verification_test(steps: aetest.Steps) -> None”Entry point for async verification. Call from your @aetest.test method:
@aetest.testdef test_something(self, steps): self.run_async_verification_test(steps)Creates an event loop, creates the HTTP client (API tests), calls get_items_to_verify(), dispatches verify_item() or verify_group(), and processes results.
format_verification_result(status: ResultStatus, context: dict, reason: str, api_duration: float = 0, api_details: ApiDetails | None = None) -> BaseVerificationResultOptional
Section titled “format_verification_result(status: ResultStatus, context: dict, reason: str, api_duration: float = 0, api_details: ApiDetails | None = None) -> BaseVerificationResultOptional”Build a standardized result dict.
status: AResultStatusvalue, typically.PASSED,.FAILED,.SKIPPED,.ERRORED, or.INFO.context: The context dict (should havedisplay_contextset).reason: Markdown-formatted string explaining the result.api_duration: API call duration in seconds (float). Defaults to0.api_details: Optional dict with any of the keysurl(str),response_code(int),response_time(float) andresponse_body. Added to the result only when given.
Example:
return self.format_verification_result( ResultStatus.PASSED, context, "BGP neighbor is established", api_duration=0.234)format_mismatch(attribute: str, expected: Any, actual: Any, context: dict) -> BaseVerificationResultOptional
Section titled “format_mismatch(attribute: str, expected: Any, actual: Any, context: dict) -> BaseVerificationResultOptional”Convenience for attribute mismatches. Returns a FAILED result. Uses TEST_CONFIG["attribute_names"] for human-readable attribute names if available. Reads api_duration from context["api_duration"] if set.
Example:
if actual_scope != expected_scope: context["api_duration"] = api_duration # optional, improves report detail return self.format_mismatch("scope", expected_scope, actual_scope, context)format_not_found(resource_type: str, identifier: str, context: dict) -> BaseVerificationResultOptional
Section titled “format_not_found(resource_type: str, identifier: str, context: dict) -> BaseVerificationResultOptional”Convenience for resources not found in API response. Returns a FAILED result.
Example:
if not subnets: return self.format_not_found("Subnet", context["subnet_ip"], context)format_api_error(status_code: int, url: str, context: dict) -> BaseVerificationResultOptional
Section titled “format_api_error(status_code: int, url: str, context: dict) -> BaseVerificationResultOptional”Convenience for HTTP error responses. Returns a FAILED result. Reads api_duration from context["api_duration"] if set. url is a string — convert an httpx.URL with str(response.url).
format_mismatch(), format_not_found() and format_api_error() take no api_duration argument; set context["api_duration"] instead. Their messages currently use ACI wording (for example “Source: APIC fabric”) regardless of architecture; use format_verification_result() with your own reason if that doesn’t fit.
Example:
if response.status_code != 200: context["api_duration"] = api_duration # optional return self.format_api_error(response.status_code, str(response.url), context)build_api_context(resource_type: str, identifier: str, **kwargs) -> str
Section titled “build_api_context(resource_type: str, identifier: str, **kwargs) -> str”Build a context string for linking HTTP responses or SSH command output to result entries in the HTML report. Two steps are needed for the link to appear:
- Store the string in
context["api_context"]. - API tests: pass it to
client.get(..., test_context=api_context). D2D tests: pass it toself.test_context(api_context).
api_context = self.build_api_context("BGP Neighbors", f"Device {hostname}")context["api_context"] = api_context # required for report linkingresponse = await client.get(url, test_context=api_context)See display_context, api_context, and test_context in the Test Case Guide for how these fit together, including multiple calls per verify_item().
get_default_value(*paths: str, required: bool = True) -> Any
Section titled “get_default_value(*paths: str, required: bool = True) -> Any”Read a value from the defaults block in the data model.
- Paths are RELATIVE — the framework auto-prepends the architecture prefix (
defaults.apic.,defaults.sdwan., etc.). required=True(default): raises if path not found.required=False: returnsNoneif path not found.
Example:
# Resolves to: self.data_model["defaults"]["apic"]["tenants"]["bridge_domains"]["arp_flooding"]arp_flooding = self.get_default_value("tenants.bridge_domains.arp_flooding")
# Optional value — compare against None, so a real False or 0 is keptmtu = self.get_default_value("interfaces.mtu", required=False)if mtu is None: mtu = 1500 # fallbackbuild_identifier(context: dict) -> str
Section titled “build_identifier(context: dict) -> str”Format an identifier string using TEST_CONFIG["identifier_format"] and the context dict.
Example:
# With TEST_CONFIG["identifier_format"] = "Device {hostname} ({system_ip})"identifier = self.build_identifier({"hostname": "edge01", "system_ip": "10.1.1.1"})# Returns: "Device edge01 (10.1.1.1)"categorize_results(results: list[dict]) -> tuple[list, list, list]
Section titled “categorize_results(results: list[dict]) -> tuple[list, list, list]”Split results into (failed, skipped, passed) lists.
Example:
failed, skipped, passed = self.categorize_results(all_results)self.logger.info(f"Passed: {len(passed)}, Failed: {len(failed)}, Skipped: {len(skipped)}")test_context(api_context: str) -> ContextManager
Section titled “test_context(api_context: str) -> ContextManager”Labels a command output block in the HTML report. Use together with context["api_context"] to link the command to the result entry.
api_context = self.build_api_context("OSPF Neighbors", self.hostname)with self.test_context(api_context): output = await self.execute_command("show ip ospf neighbor")
# Set after the with block — links command output to this result in the reportcontext["api_context"] = api_contextWorks identically for both API and D2D tests. For multiple commands per verify_item, only one can be the primary:
with self.test_context(self.build_api_context("Control Connections", self.hostname)): output_a = await self.execute_command("show sdwan control connections")
with self.test_context(self.build_api_context("SD-WAN Version", self.hostname)): output_b = await self.execute_command("show sdwan version")
context["api_context"] = self.build_api_context("Control Connections", self.hostname)# output_b appears in "Commands Without Matching Results" — expectedwrap_client_for_tracking(client: Any, device_name: str) -> Any
Section titled “wrap_client_for_tracking(client: Any, device_name: str) -> Any”Wrap an HTTP client for API call tracking in reports. Called by architecture base classes — you typically don’t call this directly.
api_call_with_retry(func: Callable, *args, **kwargs) -> Any
Section titled “api_call_with_retry(func: Callable, *args, **kwargs) -> Any”Retry wrapper using SmartRetry. Handles transient API failures.
Example:
response = await self.api_call_with_retry( client.get, endpoint, test_context=api_context)SSHTestBase
Section titled “SSHTestBase”Extends NACTestBase for SSH/D2D (direct-to-device) tests.
Properties
Section titled “Properties”| Property | Type | Description |
|---|---|---|
self.hostname | str | Current device hostname (extracted from env var DEVICE_INFO JSON blob). |
self. | dict | Device metadata from the data model (from env var DEVICE_INFO). |
self. | dict | Alias for self.. |
Methods
Section titled “Methods”await self.execute_command(command: str) -> str
Section titled “await self.execute_command(command: str) -> str”Execute a CLI command on the current device.
- Checks the command cache first (1-hour TTL per device).
- If not cached, executes via the Connection Broker’s shared SSH pool.
- Returns raw CLI output as a string.
- Always
awaitthis call.
Example:
output = await self.execute_command("show ip ospf neighbor")if "FULL" in output: self.logger.info("OSPF neighbor is up")await self.parse_output(command: str, output: str | None = None) -> dict[str, Any] | None
Section titled “await self.parse_output(command: str, output: str | None = None) -> dict[str, Any] | None”Parse CLI output using Genie parsers.
- Returns structured data as a dict, or
Noneif no parser is available or parsing fails. - Asynchronous — always
awaitit. - In nac-test 2.0 this method was synchronous (called without
await). Tests written for 2.0 must addawaitwhen upgrading — see the parse_output() migration.
Example:
output = await self.execute_command("show ip ospf neighbor")parsed = await self.parse_output("show ip ospf neighbor", output=output)if parsed: neighbors = parsed.get("interfaces", {})Architecture-Specific Base Classes
Section titled “Architecture-Specific Base Classes”APICTestBase
Section titled “APICTestBase”Extends NACTestBase for ACI/APIC API tests.
- Auth: Cookie-based authentication (600s TTL), auto-cached.
- Client:
httpx.AsyncClientwith APIC base URL and auth cookies. - Import:
from nac_test_pyats_common.aci import APICTestBase
No additional methods beyond NACTestBase. The base class handles APIC authentication and client creation.
Example:
from nac_test_pyats_common.aci.test_base import APICTestBasefrom pyats import aetest
class VerifyTenants(APICTestBase): @aetest.test def test_tenants(self, steps): self.run_async_verification_test(steps)
def get_items_to_verify(self): import jmespath tenants = jmespath.search("apic.tenants[?name]", self.data_model) or [] return [{"tenant": t["name"]} for t in tenants]
async def verify_item(self, semaphore, client, context): async with semaphore: tenant = context["tenant"] response = await client.get(f"/api/node/mo/uni/tn-{tenant}.json") # ... verification logicSDWANManagerTestBase
Section titled “SDWANManagerTestBase”Extends NACTestBase for SD-WAN Manager (vManage) API tests.
- Auth: Dual-mode (JWT token + session), auto-cached.
- Client:
httpx.AsyncClientwith vManage base URL and auth headers. - Import:
from nac_test_pyats_common.sdwan import SDWANManagerTestBase
Additional Methods
Section titled “Additional Methods”get_devices_from_data_model() -> list[dict]
Section titled “get_devices_from_data_model() -> list[dict]”Convenience method to extract devices from the SD-WAN data model (available from nac-test-pyats-common 0.4.0b1). Walks sdwan.sites[].routers[], skips routers without a system_ip in their device_variables, and returns a list of dicts with these keys:
system_ipsite_id— fromdevice_variables.site_id, falling back to the site’sidhostname— fromdevice_variables.system_hostname, thenhost_name, falling back to the system IP
Example:
def get_items_to_verify(self): devices = self.get_devices_from_data_model() return [{"system_ip": d["system_ip"], "hostname": d["hostname"]} for d in devices]CatalystCenterTestBase
Section titled “CatalystCenterTestBase”Extends NACTestBase for Catalyst Center API tests.
- Auth: Basic Auth → X-Auth-Token exchange (3600s TTL), auto-cached.
- Client:
httpx.AsyncClientwith CC base URL and auth token. - Import:
from nac_test_pyats_common.catc import CatalystCenterTestBase
No additional methods beyond NACTestBase.
Example:
from nac_test_pyats_common.catc.api_test_base import CatalystCenterTestBasefrom pyats import aetest
class VerifyDeviceHealth(CatalystCenterTestBase): @aetest.test def test_device_health(self, steps): self.run_async_verification_test(steps)IOSXETestBase
Section titled “IOSXETestBase”Extends SSHTestBase. Controller-agnostic SSH base — the preferred base class for D2D tests targeting devices managed by SD-WAN or Catalyst Center. It determines the managing architecture at runtime from the controller context that nac-test passes to each test process (derived from which controller credentials are set), falling back to the data model’s root keys (sdwan, catalyst_center), and delegates device inventory resolution to the matching resolver from its plugin registry. There is no user-facing controller_type environment variable.
- Import:
from nac_test_pyats_common.iosxe import IOSXETestBase - Device resolution: Automatic — SD-WAN or Catalyst Center resolver, selected as described above.
- Credentials:
IOSXE_USERNAME/IOSXE_PASSWORD. - Inherits:
execute_command(),parse_output(),self.hostname,self.device_datafromSSHTestBase. - Note: Standalone IOS-XE (no controller) is not yet supported — device inventory must come from a controller data model.
SDWANTestBase
Section titled “SDWANTestBase”Extends SSHTestBase. Hard-wired to SD-WAN device inventory (sdwan.sites[].routers[]). Use when writing explicitly SD-WAN-specific SSH tests.
- Import:
from nac_test_pyats_common.sdwan import SDWANTestBase
CatalystCenterSSHTestBase
Section titled “CatalystCenterSSHTestBase”Extends SSHTestBase. Hard-wired to Catalyst Center device inventory (catalyst_center.inventory.devices[]). Use when writing explicitly CC-specific SSH tests.
- Import:
from nac_test_pyats_common.catc import CatalystCenterSSHTestBase - Note: nac-test’s test discovery doesn’t recognize this base class, so place these tests under a
d2d/directory to have them classified as D2D tests. Theirgroupstags are not picked up.
NXOSTestBase
Section titled “NXOSTestBase”Extends SSHTestBase. SSH base for NX-OS switches, with the device inventory taken from nxos.devices[] (devices with managed: false are skipped). Available from nac-test-pyats-common 0.4.0b1.
- Import:
from nac_test_pyats_common.nxos import NXOSTestBase - Credentials:
NXOS_USERNAME/NXOS_PASSWORD.
FTDTestBase
Section titled “FTDTestBase”Extends SSHTestBase. SSH (CLISH) base for Firepower Threat Defense devices, with the device inventory taken from the FMC data model (fmc.domains[].devices.devices[]). Available from nac-test-pyats-common 0.4.0b2.
- Import:
from nac_test_pyats_common.fmc import FTDTestBase - Credentials:
FTD_USERNAME/FTD_PASSWORD. - Note: nac-test 2.1.0b2’s test discovery doesn’t recognize this base class yet (later releases do). With 2.1.0b2, place these tests under a
d2d/directory.
Example (any SSH base):
from nac_test_pyats_common.iosxe.test_base import IOSXETestBasefrom pyats import aetest
class VerifyOSPF(IOSXETestBase): @aetest.test def test_ospf_neighbors(self, steps): self.run_async_verification_test(steps)
def get_items_to_verify(self): return [{"hostname": self.hostname}]
async def verify_item(self, semaphore, client, context): async with semaphore: output = await self.execute_command("show ip ospf neighbor") parsed = await self.parse_output("show ip ospf neighbor", output=output) # ... verification logicResultStatus Enum
Section titled “ResultStatus Enum”from nac_test.pyats_core.reporting.types import ResultStatus| Value | When to Use |
|---|---|
ResultStatus. | Verification succeeded — actual matches expected |
ResultStatus. | Verification found a mismatch or error condition |
ResultStatus. | Item not applicable (feature not configured, empty response) |
ResultStatus. | Infrastructure error (API unreachable, timeout, exception) |
ResultStatus. | Informational result with no pass/fail judgment |
ResultStatus. | pyATS “passed with exception” status; rarely needed in test code |
ResultStatus. | pyATS status for an aborted run; rarely needed in test code |
ResultStatus. | pyATS status for an item blocked by a failed dependency; rarely needed in test code |
ResultStatus is a str enum; its values are the lowercase names ("passed", "failed", …).
Example:
if not neighbors: return self.format_verification_result( ResultStatus.SKIPPED, context, "No BGP neighbors configured" )
if neighbor_state == "established": return self.format_verification_result( ResultStatus.PASSED, context, "BGP neighbor is established" )else: return self.format_verification_result( ResultStatus.FAILED, context, f"BGP neighbor state is {neighbor_state}, expected established" )TEST_CONFIG Keys
Section titled “TEST_CONFIG Keys”Every test class should define TEST_CONFIG (the framework reads it directly, e.g. when building the skip message for a test with no items). All keys are optional; these are the keys the framework reads:
| Key | Type | Default | Description |
|---|---|---|---|
resource_type | str | "Resource" | Resource name used in the HTML report, skip messages and default step names (e.g., “SD-WAN BGP Neighbors”) |
identifier_ | str | "Resource Verification" | Python format string using context dict keys (e.g., "Device {hostname} ({system_ip})"), used by build_ |
step_ | str | "{resource_ | Format string for pyATS step names |
log_fields | list[str] | [] | Context dict keys to include in log output |
attribute_names | dict[str, str] | {} | Maps API attribute keys to human-readable names for format_ |
schema_paths | dict[str, str] | {} | Maps attribute keys to data model paths. format_ shows the path for the mismatched attribute; format_ lists related paths |
schema_ | list[str] | [] | Data model paths listed in the skip message when no items are found |
managed_objects | list[str] | [] | Managed objects listed in the skip message when no items are found |
test_type_name | str | "{resource_ | Name used in the result summary log |
Keys such as api_endpoint (REST path or CLI command) or expected_values (static expected values for the NRFU pattern) are not read by the framework. The examples in these docs use them as a convention to keep that data next to the rest of the test metadata; your own code reads them from self.TEST_CONFIG.
Example:
TEST_CONFIG = { "resource_type": "SD-WAN BGP Neighbors", "api_endpoint": "/dataservice/device/bgp/neighbors", "identifier_format": "Device {hostname} - Peer {peer_ip}", "step_name_format": "Verify BGP neighbor {peer_ip} on {hostname}", "log_fields": ["hostname", "peer_ip", "state"], "attribute_names": { "state": "BGP State", "peer_ip": "Peer IP Address", "as_number": "AS Number" }, "schema_paths": { "system_ip": "sdwan.sites[].routers[].device_variables.system_ip", "hostname": "sdwan.sites[].routers[].device_variables.system_hostname" }}Module-Level Constants
Section titled “Module-Level Constants”Strongly recommended — these generate descriptive HTML reports.
| Constant | Type | Purpose |
|---|---|---|
TITLE | str | Short test title (appears in report headers) |
DESCRIPTION | str | What this test verifies and why it matters |
SETUP | str | Bullet list of prerequisites (markdown) |
PROCEDURE | str | Bullet list of verification steps (markdown) |
PASS_ | str | When the test passes, fails, or skips (markdown) |
Example:
TITLE = "SD-WAN BGP Neighbor Verification"
DESCRIPTION = """Verifies that all BGP neighbors defined in the data model are establishedand operational on SD-WAN edge devices."""
SETUP = """- SD-WAN Manager API must be reachable- Edge devices must be online and reachable- BGP must be configured per the data model"""
PROCEDURE = """1. Query SD-WAN Manager API for BGP neighbor status2. For each neighbor in the data model: - Verify neighbor exists in API response - Verify neighbor state is "established" - Verify routes received > 0"""
PASS_FAIL_CRITERIA = """- **Pass:** All BGP neighbors are established and receiving routes- **Fail:** Any neighbor is not established or not found- **Skip:** Device has no BGP neighbors configured"""Common Patterns
Section titled “Common Patterns”The Test Case Guide walks through complete examples of each pattern:
- NRFU pattern — static expected values
- Data-model-driven pattern — expected values from the data model
- D2D/SSH pattern — CLI commands on devices
- Batch API pattern —
verify_group()