Skip to content

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.

Base class for all pyATS test cases. Inherits from pyats.aetest.Testcase.

PropertyTypeDescription
self.data_modeldict[str, Any]Merged YAML data model loaded from all --data files. Available after setup().
self.loggerlogging.LoggerLogger scoped to the test module (logging.getLogger(cls.__module__)).
self.controller_typestrController 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.controller_urlstrController URL from env var (e.g., ACI_URL, SDWAN_URL, CC_URL, MERAKI_URL, FMC_URL, ISE_URL).
self.result_collectorTestResultCollectorCollects results for HTML reporting. Typically used via helper methods.

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 all verify_item() calls of the test (default limit 55, NAC_TEST_PYATS_API_CONCURRENCY). The framework does not acquire it — wrap the body in async with semaphore:. Calls run concurrently, also within a single D2D device.
  • client: HTTP client for API tests, or None for SSH tests.
  • context: One dict from get_items_to_verify(). Set context["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.

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.test
def 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: A ResultStatus value, typically .PASSED, .FAILED, .SKIPPED, .ERRORED, or .INFO.
  • context: The context dict (should have display_context set).
  • reason: Markdown-formatted string explaining the result.
  • api_duration: API call duration in seconds (float). Defaults to 0.
  • api_details: Optional dict with any of the keys url (str), response_code (int), response_time (float) and response_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:

  1. Store the string in context["api_context"].
  2. API tests: pass it to client.get(..., test_context=api_context). D2D tests: pass it to self.test_context(api_context).
api_context = self.build_api_context("BGP Neighbors", f"Device {hostname}")
context["api_context"] = api_context # required for report linking
response = 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: returns None if 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 kept
mtu = self.get_default_value("interfaces.mtu", required=False)
if mtu is None:
mtu = 1500 # fallback

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 report
context["api_context"] = api_context

Works 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" — expected

wrap_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
)

Extends NACTestBase for SSH/D2D (direct-to-device) tests.

PropertyTypeDescription
self.hostnamestrCurrent device hostname (extracted from env var DEVICE_INFO JSON blob).
self.device_infodictDevice metadata from the data model (from env var DEVICE_INFO).
self.device_datadictAlias for self.device_info.

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 await this 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 None if no parser is available or parsing fails.
  • Asynchronous — always await it.
  • In nac-test 2.0 this method was synchronous (called without await). Tests written for 2.0 must add await when 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", {})

Extends NACTestBase for ACI/APIC API tests.

  • Auth: Cookie-based authentication (600s TTL), auto-cached.
  • Client: httpx.AsyncClient with 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 APICTestBase
from 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 logic

Extends NACTestBase for SD-WAN Manager (vManage) API tests.

  • Auth: Dual-mode (JWT token + session), auto-cached.
  • Client: httpx.AsyncClient with vManage base URL and auth headers.
  • Import: from nac_test_pyats_common.sdwan import SDWANManagerTestBase
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_ip
  • site_id — from device_variables.site_id, falling back to the site’s id
  • hostname — from device_variables.system_hostname, then host_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]

Extends NACTestBase for Catalyst Center API tests.

  • Auth: Basic Auth → X-Auth-Token exchange (3600s TTL), auto-cached.
  • Client: httpx.AsyncClient with 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 CatalystCenterTestBase
from pyats import aetest
class VerifyDeviceHealth(CatalystCenterTestBase):
@aetest.test
def test_device_health(self, steps):
self.run_async_verification_test(steps)

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_data from SSHTestBase.
  • Note: Standalone IOS-XE (no controller) is not yet supported — device inventory must come from a controller data model.

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

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. Their groups tags are not picked up.

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.

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 IOSXETestBase
from 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 logic
from nac_test.pyats_core.reporting.types import ResultStatus
ValueWhen to Use
ResultStatus.PASSEDVerification succeeded — actual matches expected
ResultStatus.FAILEDVerification found a mismatch or error condition
ResultStatus.SKIPPEDItem not applicable (feature not configured, empty response)
ResultStatus.ERROREDInfrastructure error (API unreachable, timeout, exception)
ResultStatus.INFOInformational result with no pass/fail judgment
ResultStatus.PASSXpyATS “passed with exception” status; rarely needed in test code
ResultStatus.ABORTEDpyATS status for an aborted run; rarely needed in test code
ResultStatus.BLOCKEDpyATS 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"
)

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:

KeyTypeDefaultDescription
resource_typestr"Resource"Resource name used in the HTML report, skip messages and default step names (e.g., “SD-WAN BGP Neighbors”)
identifier_formatstr"Resource Verification"Python format string using context dict keys (e.g., "Device {hostname} ({system_ip})"), used by build_identifier()
step_name_formatstr"{resource_type} Verification"Format string for pyATS step names
log_fieldslist[str][]Context dict keys to include in log output
attribute_namesdict[str, str]{}Maps API attribute keys to human-readable names for format_mismatch()
schema_pathsdict[str, str]{}Maps attribute keys to data model paths. format_mismatch() shows the path for the mismatched attribute; format_not_found() lists related paths
schema_paths_listlist[str][]Data model paths listed in the skip message when no items are found
managed_objectslist[str][]Managed objects listed in the skip message when no items are found
test_type_namestr"{resource_type} Verification"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"
}
}

Strongly recommended — these generate descriptive HTML reports.

ConstantTypePurpose
TITLEstrShort test title (appears in report headers)
DESCRIPTIONstrWhat this test verifies and why it matters
SETUPstrBullet list of prerequisites (markdown)
PROCEDUREstrBullet list of verification steps (markdown)
PASS_FAIL_CRITERIAstrWhen 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 established
and 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 status
2. 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
"""

The Test Case Guide walks through complete examples of each pattern: