Test Case Guide
This guide is for engineers/developers writing pyATS test cases for the nac-test framework. It assumes you understand networking concepts but are new to this test framework. We’ll cover pyATS basics as needed. It targets nac-test 2.1 (>= 2.1.0b2) with nac-test-pyats-common >= 0.4.0b2. Method signatures and configuration tables live in the API Reference; this guide explains how to use them.
A pyATS test in this framework is typically 50–100 lines of Python. You write the verification logic — what to query, what to compare. The framework handles everything else:
- Automatic test discovery — inherit from the right base class and your file is found; no registration needed
- Authentication and connection management — login tokens are cached across all parallel tests; you never call an auth API yourself
- Parallel execution — API tests verify multiple items concurrently; D2D tests run across devices in parallel, with a shared SSH connection pool so each device gets one connection regardless of how many tests run against it
- Command caching —
show versionruns once per device per hour even if 10 tests need it - Structured HTML reports — pass/fail per item, expandable command output, timing data; generated from streaming JSONL so partial results are preserved if a test crashes mid-run
- CI/CD exit codes — exit code reflects the number of failed tests; zero means everything passed
1. Architecture Overview
Section titled “1. Architecture Overview”1.1 How pyATS Tests Differ from Robot Framework
Section titled “1.1 How pyATS Tests Differ from Robot Framework”The nac-test framework supports two test execution approaches:
Robot Framework (see Robot Framework Tests):
- Test cases are
.robotfiles rendered from Jinja2 templates - Data model values are injected at template render time (before execution)
- Tests execute via Pabot for parallel execution
- Template-driven approach separates test logic from test data
pyATS:
- Test cases are pure Python classes
- No template rendering — tests are discovered and executed directly
- Data model is loaded at runtime from merged YAML files
- Executed via
pyats run jobsubprocesses - Code-driven approach with full Python expressiveness
In production runs, pyATS tests execute first, followed by Robot Framework tests sequentially. During development, use --pyats or --robot flags to run only one type for faster iteration cycles.
1.2 Test Discovery
Section titled “1.2 Test Discovery”The nac-test framework discovers pyATS tests using a two-phase process: discovery and classification.
Discovery: The framework scans the --templates directory for Python files without executing them. A file is picked up when it imports from nac_test or nac_test_pyats_common and contains at least one @aetest.test (or @aetest.setup/@aetest.cleanup) decorated method. Files whose names start with _ and __pycache__ directories are skipped. A test class without an @aetest.test method is not discovered at all.
Classification (for discovered files) uses Python’s ast module and a three-tier strategy:
- AST-based (primary): The base class names written in the file are checked against an internal mapping (e.g.,
APICTestBase→ “api”,IOSXETestBase→ “d2d”). - Directory fallback: If no base class matches, the framework checks if the file path contains
/d2d/or/api/. - Default: Falls back to
"api"with a warning logged.
Practical implication: inherit directly from one of the documented base classes and your test file is classified correctly, with no manual registration. Two caveats:
- Tag filtering (
groups, see §12) is only read from a class whose base is recognized by the AST mapping. Files classified by the directory fallback or the default have no tags. CatalystCenterSSHTestBaseis not in the mapping, andFTDTestBaseis only added after nac-test 2.1.0b2. Place tests using these bases under ad2d/directory so they are classified as D2D (they still won’t pick upgroups).
1.3 Execution Model
Section titled “1.3 Execution Model”API tests (ACI, SD-WAN Manager, Catalyst Center):
- All collected tests run in a single PyATS job file
- Execute in one subprocess with a shared HTTP client session
- Concurrent verification controlled by semaphores
- Efficient for controller-based architectures
D2D/SSH tests (IOS-XE, SD-WAN edge devices, NX-OS, FTD):
- One PyATS job per device
- Device inventory discovered from the data model via the architecture’s device resolver
- Each device gets its own subprocess with environment variables (
DEVICE_INFO, a JSON blob with the device data, andHOSTNAME) - Parallel device execution with concurrency control
1.4 Concurrency
Section titled “1.4 Concurrency”Within a test (API and D2D):
- All
verify_item()(orverify_group()) calls are started together withasyncio.gather()and share oneasyncio.Semaphore(default limit 55, configurable withNAC_TEST_PYATS_API_CONCURRENCY) - This applies to D2D tests too: on a single device,
verify_item()calls run concurrently. Only uncached CLI commands are serialized, by the Connection Broker’s per-device lock
Across devices (D2D):
- Each device runs in its own subprocess, and devices run in parallel
- The default number of parallel devices is calculated from available CPU and memory, capped at 50 (
NAC_TEST_PYATS_PROCESSESoverrides it) --max-parallel-devicescan lower this limit, but not raise it
Always use async with semaphore: at the top of verify_item() — the framework passes the semaphore in but does not acquire it for you. Because calls run concurrently, verify_item() must be safe to run in parallel: don’t share mutable state between calls (for example on self) without care.
2. Class Hierarchy
Section titled “2. Class Hierarchy”The nac-test framework uses a three-tier class hierarchy:
Layer 1: nac-test (core framework)├── NACTestBase(aetest.Testcase) — base for ALL tests└── SSHTestBase(NACTestBase) — base for SSH/D2D tests
Layer 2: nac-test-pyats-common (architecture adapters)├── APICTestBase(NACTestBase) — ACI API tests├── SDWANManagerTestBase(NACTestBase) — SD-WAN Manager API tests├── CatalystCenterTestBase(NACTestBase) — Catalyst Center API tests├── IOSXETestBase(SSHTestBase) — SSH tests, controller-agnostic (auto-detects architecture)├── SDWANTestBase(SSHTestBase) — SD-WAN edge device SSH tests (SD-WAN-specific inventory)├── CatalystCenterSSHTestBase(SSHTestBase) — CC-managed device SSH tests (CC-specific inventory)├── NXOSTestBase(SSHTestBase) — NX-OS switch SSH tests (nxos.devices[] inventory)└── FTDTestBase(SSHTestBase) — FTD device SSH tests (FMC data model inventory)
Layer 3: Your test files (architecture repos)└── verify_*.py files inheriting from Layer 2 basesKey principle: You always inherit from a Layer 2 class. The Layer 2 class handles authentication, client creation, and device resolution. You focus on verification logic.
Note: D2D/SSH tests discover the device inventory from the data model, which is the source of truth for which devices to test and how to reach them. For IOS-XE, the inventory comes from the managing controller’s data model: SD-WAN (SDWANTestBase) and Catalyst Center (CatalystCenterSSHTestBase) managed devices are supported. Standalone IOS-XE (no SD-WAN, no Catalyst Center) is not yet supported as a D2D target. NX-OS switches (NXOSTestBase, from nxos.devices[]) and FTD devices (FTDTestBase, from the FMC data model) have their own resolvers.
2.1 Choosing the Right SSH Base Class
Section titled “2.1 Choosing the Right SSH Base Class”For IOS-XE D2D/SSH tests there are three options — the right choice depends on how you want device inventory resolved. NX-OS and FTD tests use NXOSTestBase and FTDTestBase respectively.
| Base Class | Device Inventory Source | When to Use |
|---|---|---|
IOSXETestBase | Auto-detected from the controller context nac-test passes to each test process (derived from which controller credentials are set), falling back to the data model’s root keys | Preferred — works across SD-WAN and Catalyst Center managed devices. The same test file runs regardless of which controller is managing the devices. |
SDWANTestBase | Hard-wired to SD-WAN data model (sdwan.) | When your test is explicitly SD-WAN-specific and you want direct control over SD-WAN schema navigation |
CatalystCenterSSHTestBase | Hard-wired to CC data model (catalyst_) | When your test is explicitly CC-specific |
IOSXETestBase delegates to the same SDWANDeviceResolver or CatalystCenterDeviceResolver at runtime — it is not a simpler class, just a more portable entry point.
2.2 Import Table
Section titled “2.2 Import Table”| Platform | Import Statement |
|---|---|
| ACI | from nac_ |
| SD-WAN Manager | from nac_ |
| Catalyst Center | from nac_ |
| IOS-XE SSH (generic) | from nac_ |
| SD-WAN SSH (explicit) | from nac_ |
| Catalyst Center SSH (explicit) | from nac_ |
| NX-OS SSH | from nac_ |
| FTD SSH | from nac_ |
3. The Three-Method Contract
Section titled “3. The Three-Method Contract”Every test class implements exactly three things. In exchange, the framework provides parallel execution, caching, authentication, retry logic, and a structured HTML report — without any additional code from you.
3.1 The Entry Point (@aetest.test method)
Section titled “3.1 The Entry Point (@aetest.test method)”This is the method decorated with @aetest.test that PyATS discovers and executes. The body is always the same:
@aetest.testdef test_bgp_neighbors(self, steps): """Verify BGP neighbor states.""" self.run_async_verification_test(steps)- Decorated with
@aetest.test— required for PyATS discovery steps— a pyATSStepsobject injected automatically by the framework. It is used internally byrun_async_verification_test()to create one named sub-step per verified item, each with its own pass/fail status in the pyATS report. You pass it through and do not call it directly.- Body is always just:
self.run_async_verification_test(steps) - Name should be descriptive:
test_bgp_neighbors,test_control_connections,test_ospf_neighbors - The docstring appears in PyATS logs and reports
3.2 get_items_to_verify()
Section titled “3.2 get_items_to_verify()”This method returns a list of items to verify. Each item is a dictionary (called a “context”) that describes one verification task.
def get_items_to_verify(self) -> list[dict[str, Any]]: """Return list of items to verify.""" # SDWANManagerTestBase helper: walks sdwan.sites[].routers[] devices = self.get_devices_from_data_model() return [ { "hostname": device["hostname"], "system_ip": device["system_ip"], } for device in devices ]Key points:
- Returns
list[dict[str, Any]]— each dict is a context describing one item to verify - Called once before verification begins
- For SSH/D2D tests: MUST NOT execute device commands here (SSH connection not yet established)
- Common patterns:
- Data-model iteration: Extract from
self.data_modelvia JMESPath - Device enumeration: Use
self.get_devices_from_data_model()for SD-WAN Manager tests (returnssystem_ip,site_idandhostnameper router) - Single trigger: Return
[{"trigger": True}]for tests that discover items from the live system
- Data-model iteration: Extract from
3.3 async verify_item(semaphore, client, context)
Section titled “3.3 async verify_item(semaphore, client, context)”This is where the actual verification happens. It’s called once for each item returned by get_items_to_verify().
async def verify_item( self, semaphore: asyncio.Semaphore, client: Any, context: dict[str, Any],) -> dict[str, Any]: """Verify one item.""" async with semaphore: # Set display context for HTML report context["display_context"] = f"BGP -> {context['hostname']} ({context['system_ip']})"
# Build API context for tracking api_context = self.build_api_context( "BGP Neighbors", context["hostname"], system_ip=context["system_ip"], ) context["api_context"] = api_context # links the API call to this result
# Execute API call start_time = time.time() response = await client.get( f"{self.TEST_CONFIG['api_endpoint']}?deviceId={context['system_ip']}", test_context=api_context, ) api_duration = time.time() - start_time
if response.status_code != 200: context["api_duration"] = api_duration return self.format_api_error(response.status_code, str(response.url), context)
neighbors = response.json().get("data", [])
# Verify all neighbors are established failed_neighbors = [n for n in neighbors if n.get("state") != "established"]
if failed_neighbors: reason = f"Found {len(failed_neighbors)} BGP neighbors not in established state" return self.format_verification_result( ResultStatus.FAILED, context, reason, api_duration, )
return self.format_verification_result( ResultStatus.PASSED, context, f"All {len(neighbors)} BGP neighbors are established", api_duration, )Parameters:
semaphore:asyncio.Semaphore— always wrap body inasync with semaphore:client: HTTP client (API tests) orNone(SSH tests useself.execute_command())context: one dict fromget_items_to_verify()
Must return: A result dict from self.format_verification_result()
Must set: context["display_context"] for HTML report display, and context["api_context"] to link the API call or command output to the result (see §7.3)
4. Two Test Patterns
Section titled “4. Two Test Patterns”4.1 NRFU Pattern (Static Expected Values)
Section titled “4.1 NRFU Pattern (Static Expected Values)”Network Ready For Use (NRFU) tests verify universal healthy states. Expected values are hardcoded because they represent operational health, not configuration intent.
Characteristics:
- Tests verify universal healthy states: “up”, “established”, “green”
- Expected values are hardcoded in the test or in
TEST_CONFIG["expected_values"] get_items_to_verify()might or might not use the data model to discover which items to check but NOT what values to expect- Example: verify all BGP neighbors are “established”, all control connections are “up”
Example:
class VerifyControlConnections(SDWANManagerTestBase): TEST_CONFIG = { "resource_type": "SD-WAN Control Connections", "api_endpoint": "/dataservice/device/control/connections", "expected_values": { "state": "up", }, }
def get_items_to_verify(self) -> list[dict[str, Any]]: """Get all edge devices from data model.""" devices = self.get_devices_from_data_model() return [{"hostname": d["hostname"], "system_ip": d["system_ip"]} for d in devices]
async def verify_item(self, semaphore, client, context): async with semaphore: context["display_context"] = f"Control -> {context['hostname']}"
# Query live system response = await client.get( f"{self.TEST_CONFIG['api_endpoint']}?deviceId={context['system_ip']}" ) connections = response.json().get("data", [])
# Compare against hardcoded expected state down_connections = [c for c in connections if c.get("state") != "up"]
if down_connections: return self.format_verification_result( ResultStatus.FAILED, context, f"Found {len(down_connections)} control connections not up", 0.0, )
return self.format_verification_result( ResultStatus.PASSED, context, f"All {len(connections)} control connections are up", 0.0, )4.2 Data-Model-Driven Pattern (Expected Values from YAML)
Section titled “4.2 Data-Model-Driven Pattern (Expected Values from YAML)”These tests extract both items AND expected attribute values from the data model. The data model defines what the network should look like; the test verifies reality matches intent.
Characteristics:
- Tests extract BOTH items AND expected attribute values from
self.data_model - The data model defines what the network should look like
get_items_to_verify()iterates the data model and builds context dicts with expected valuesverify_item()queries the live system and compares against those expected values- Example: verify tenant BD subnet configuration matches data model, verify L3Out attributes match intent
Example:
class VerifyBridgeDomainSubnets(APICTestBase): TEST_CONFIG = { "resource_type": "ACI Bridge Domain Subnets", "api_endpoint": "/api/node/class/fvSubnet.json", "attribute_names": { "ip": "Subnet IP", "scope": "Subnet Scope", "preferred": "Primary IP", }, }
def get_items_to_verify(self) -> list[dict[str, Any]]: """Extract expected subnet configuration from data model.""" items = [] tenants = jmespath.search("apic.tenants[?name]", self.data_model) or [] default_public = self.get_default_value("tenants.bridge_domains.subnets.public") default_shared = self.get_default_value("tenants.bridge_domains.subnets.shared") default_primary = self.get_default_value("tenants.bridge_domains.subnets.primary_ip")
for tenant in tenants: bds = tenant.get("bridge_domains", []) for bd in bds: subnets = bd.get("subnets", []) for subnet in subnets: public = subnet.get("public", default_public) shared = subnet.get("shared", default_shared) primary_ip = subnet.get("primary_ip", default_primary) items.append({ "tenant": tenant["name"], "bd": bd["name"], "subnet_ip": subnet["ip"], # Expected values from data model, in APIC's format # (fvSubnet scope is e.g. "private" or "public,shared") "expected_scope": ",".join( ["public" if public else "private"] + (["shared"] if shared else []) ), "expected_preferred": "yes" if primary_ip else "no", })
return items
async def verify_item(self, semaphore, client, context): async with semaphore: context["display_context"] = ( f"{context['tenant']} -> {context['bd']} -> {context['subnet_ip']}" )
# Query live system response = await client.get( f"{self.TEST_CONFIG['api_endpoint']}?" f"query-target-filter=eq(fvSubnet.ip,\"{context['subnet_ip']}\")" )
subnets = response.json().get("imdata", []) if not subnets: return self.format_not_found("Subnet", context["subnet_ip"], context)
actual = subnets[0]["fvSubnet"]["attributes"]
# Compare actual against expected from data model if actual.get("scope") != context["expected_scope"]: return self.format_mismatch( "scope", context["expected_scope"], actual.get("scope"), context, )
if actual.get("preferred") != context["expected_preferred"]: return self.format_mismatch( "preferred", context["expected_preferred"], actual.get("preferred"), context, )
return self.format_verification_result( ResultStatus.PASSED, context, "Subnet configuration matches data model", 0.0, )4.3 D2D/SSH Pattern (Direct-to-Device Tests)
Section titled “4.3 D2D/SSH Pattern (Direct-to-Device Tests)”For tests that execute CLI commands directly on devices via SSH, the flow is similar but uses execute_command() and parse_output() instead of an HTTP client. The SD-WAN edge device example below uses SDWANTestBase, which provides device inventory from the data model and routes SSH through the Connection Broker.
import asyncioimport loggingfrom typing import Any
from pyats import aetestfrom nac_test_pyats_common.sdwan.ssh_test_base import SDWANTestBasefrom nac_test.pyats_core.reporting.types import ResultStatus
logger = logging.getLogger(__name__)
TITLE = "Verify SD-WAN Control Connections (D2D)"DESCRIPTION = """Verifies SD-WAN control connections are up by executing'show sdwan control connections' directly on each edge device via SSH."""SETUP = "* SSH access to SD-WAN edge devices.\n* Valid IOS-XE credentials configured.\n"PROCEDURE = "* Execute 'show sdwan control connections' on each device.\n* Parse output and verify all connections are 'up'.\n"PASS_FAIL_CRITERIA = "* PASS: All connections up.\n* FAIL: Any connection not up.\n* SKIP: No connections returned.\n"
class VerifySDWANControlConnectionsD2D(SDWANTestBase): """Verify SD-WAN control connections directly on edge devices."""
groups = ["sdwan", "d2d", "control-plane"]
TEST_CONFIG = { "resource_type": "SD-WAN Control Connections", "api_endpoint": "show sdwan control connections", "identifier_format": "Device {hostname}", "log_fields": ["hostname"], }
@aetest.test def test_control_connections(self, steps): """Entry point — delegates to async verification.""" self.run_async_verification_test(steps)
def get_items_to_verify(self) -> list[dict[str, Any]]: """One item per test run — verify_item() runs on the current device only.""" # self.hostname is set automatically by the framework to the current device return [{"hostname": self.hostname}]
async def verify_item( self, semaphore: asyncio.Semaphore, client: Any, # None for SSH tests context: dict[str, Any], ) -> dict[str, Any]: """Verify control connections on the current device.""" async with semaphore: command = self.TEST_CONFIG["api_endpoint"] context["display_context"] = f"Control Connections -> {self.hostname}"
api_context = self.build_api_context( self.TEST_CONFIG["resource_type"], self.hostname ) with self.test_context(api_context): output = await self.execute_command(command)
# Store api_context so the command output is linked to this result # in the HTML report — same pattern as API tests context["api_context"] = api_context
if not output: return self.format_verification_result( status=ResultStatus.ERRORED, context=context, reason=f"No output returned from '{command}' on {self.hostname}", api_duration=0.0, )
parsed = await self.parse_output(command, output=output)
if parsed is None: # No Genie parser — fall back to string check if "up" not in output.lower(): return self.format_verification_result( status=ResultStatus.FAILED, context=context, reason=f"No 'up' connections found in output on {self.hostname}", api_duration=0.0, ) return self.format_verification_result( status=ResultStatus.PASSED, context=context, reason=f"Control connections appear up on {self.hostname}", api_duration=0.0, )
# With parsed output, check each connection state connections = parsed.get("local_color", {}) or {} if not connections: return self.format_verification_result( status=ResultStatus.SKIPPED, context=context, reason=f"No control connections found on {self.hostname}", api_duration=0.0, )
down = [ f"{color}/{state['state']}" for color, state in connections.items() if state.get("state") != "up" ] if down: return self.format_verification_result( status=ResultStatus.FAILED, context=context, reason=f"Down connections on {self.hostname}: {', '.join(down)}", api_duration=0.0, )
return self.format_verification_result( status=ResultStatus.PASSED, context=context, reason=f"All {len(connections)} control connections up on {self.hostname}", api_duration=0.0, )Key differences from API tests:
clientparameter isNone— useself.execute_command()andself.parse_output()insteadself.hostnameis auto-set by the framework —get_items_to_verify()typically returns a single-element list- Each device runs in its own subprocess — you don’t iterate over devices; the framework does that
- Wrap
execute_command()inself.test_context()to link output to the HTML report
Spectrum of approaches:
Tests range from “data model for device discovery only” (pure NRFU) to “full data-model-driven attribute comparison” (configuration validation). There’s no rigid boundary — choose the approach that fits your verification goals.
5. The verify_group() Pattern
Section titled “5. The verify_group() Pattern”For 1:N parent-child relationships (e.g., one Bridge Domain with many subnets), the verify_group() pattern allows you to make one API call per parent and verify multiple children from the same response.
How it works:
get_items_to_verify()returnsdict[str, list[dict]]instead oflist[dict]- When
run_async_verification_test()sees a dict return, it dispatchesverify_group()instead ofverify_item()for each group key - Your test class implements
verify_group()instead ofverify_item()— you choose which by the return type ofget_items_to_verify() - If
get_items_to_verify()returns a list →verify_item()is called per entry; if it returns a dict →verify_group()is called per key
Signature:
async def verify_group( self, semaphore: asyncio.Semaphore, client: Any, group_key: str, contexts: list[dict[str, Any]],) -> list[dict[str, Any]]: """Verify a group of related items with one API call.""" passExample:
class VerifyBridgeDomainSubnets(APICTestBase): TEST_CONFIG = { "resource_type": "ACI Bridge Domain Subnets", "api_endpoint": "/api/node/mo/uni/tn-{tenant}/BD-{bd}.json", }
def get_items_to_verify(self) -> dict[str, list[dict[str, Any]]]: """Group subnets by bridge domain.""" groups = {} tenants = jmespath.search("apic.tenants[?name]", self.data_model) or [] default_public = self.get_default_value("tenants.bridge_domains.subnets.public") default_shared = self.get_default_value("tenants.bridge_domains.subnets.shared")
for tenant in tenants: bds = tenant.get("bridge_domains", []) for bd in bds: group_key = f"{tenant['name']}:{bd['name']}" groups[group_key] = []
for subnet in bd.get("subnets", []): public = subnet.get("public", default_public) shared = subnet.get("shared", default_shared) groups[group_key].append({ "tenant": tenant["name"], "bd": bd["name"], "subnet_ip": subnet["ip"], "expected_scope": ",".join( ["public" if public else "private"] + (["shared"] if shared else []) ), })
return groups
async def verify_group( self, semaphore: asyncio.Semaphore, client: Any, group_key: str, contexts: list[dict[str, Any]], ) -> list[dict[str, Any]]: """Verify all subnets in a bridge domain with one API call.""" async with semaphore: results = []
# All contexts in the group share tenant and BD tenant = contexts[0]["tenant"] bd = contexts[0]["bd"]
# One API call for the entire bridge domain url = self.TEST_CONFIG["api_endpoint"].format(tenant=tenant, bd=bd) response = await client.get(f"{url}?query-target=children")
bd_data = response.json().get("imdata", []) actual_subnets = { s["fvSubnet"]["attributes"]["ip"]: s["fvSubnet"]["attributes"] for item in bd_data for s in [item] if "fvSubnet" in item }
# Verify each subnet context against the single response for context in contexts: context["display_context"] = f"{tenant} -> {bd} -> {context['subnet_ip']}"
actual = actual_subnets.get(context["subnet_ip"]) if not actual: results.append( self.format_not_found("Subnet", context["subnet_ip"], context) ) continue
if actual.get("scope") != context["expected_scope"]: results.append( self.format_mismatch( "scope", context["expected_scope"], actual.get("scope"), context, ) ) else: results.append( self.format_verification_result( ResultStatus.PASSED, context, "Subnet configuration matches data model", 0.0, ) )
return resultsBenefit: One API call per bridge domain instead of one per subnet. For a BD with 10 subnets, this reduces API calls from 10 to 1.
6. Data Model Access
Section titled “6. Data Model Access”6.1 How —data Works
Section titled “6.1 How —data Works”- All
--dataYAML files are deep-merged byDataMerger, the same way as for Robot test cases. Values are loaded as-is: there is no Jinja2 templating and no${VAR}substitution (a${HOME}value stays a literal string). To read environment variables or encrypted values, use the!envand!vaultYAML tags. - The merged result is written to the output directory as
merged_data_model_test_variables.yaml(nac-test 2.1.0b2; later releases writemerged_data_model_test_variables.jsoninstead). The file is removed after execution, as it could contain sensitive values. - Its path is passed to test subprocesses via env var
MERGED_DATA_MODEL_TEST_VARIABLES_FILEPATH NACTestBase.setup()loads it intoself.data_model
In releases that write the JSON file, setting NAC_TEST_DUMP_YAML_DATA_MODEL=true also writes a YAML copy for debugging. That copy is not deleted automatically, so remove it yourself if your data contains secrets.
6.2 Accessing the Data Model
Section titled “6.2 Accessing the Data Model”The merged data model is available as self.data_model — a Python dict containing the entire merged YAML structure.
Use JMESPath for extraction:
import jmespath
# Extract all tenantstenants = jmespath.search("apic.tenants[?name]", self.data_model) or []
# Extract all SD-WAN routers across sitesrouters = jmespath.search("sdwan.sites[].routers[]", self.data_model) or []
# Extract a single valuemgmt_ip_variable = jmespath.search("sdwan.management_ip_variable", self.data_model)Always append or [] for list queries:
# Good - handles None gracefullytenants = jmespath.search("apic.tenants[?name]", self.data_model) or []
# Bad - will fail if path doesn't existtenants = jmespath.search("apic.tenants[?name]", self.data_model)for tenant in tenants: # TypeError if tenants is None ...Check None explicitly for single values:
mgmt_ip_variable = jmespath.search("sdwan.management_ip_variable", self.data_model)if mgmt_ip_variable is None: self.logger.warning("management_ip_variable not found in data model") return []6.3 Defaults Resolution
Section titled “6.3 Defaults Resolution”The framework provides a helper for reading default values from the defaults block in the data model:
self.get_default_value(*paths, required=True)Key points:
- The framework auto-prepends the architecture prefix (
defaults.apic.,defaults.sdwan., etc.) - Pass RELATIVE paths only
- Set
required=Falsefor optional defaults
Examples:
# Good - relative patharp_flooding = self.get_default_value("tenants.bridge_domains.arp_flooding")
# Bad - absolute path (will fail)arp_flooding = self.get_default_value("defaults.apic.tenants.bridge_domains.arp_flooding")
# Optional default with fallback (check for None: `or True` would turn a real False into True)unicast_routing = self.get_default_value( "tenants.bridge_domains.unicast_routing", required=False,)if unicast_routing is None: unicast_routing = True6.4 SSH/D2D Device Context
Section titled “6.4 SSH/D2D Device Context”For SSH/D2D tests, the framework automatically sets device-specific attributes:
self.hostname— current device hostname (set automatically)self.device_info— device dict built by the device resolver from the data model and passed to the test process in theDEVICE_INFOenv var (includeshostname,host,device_id,os,platform, etc.)self.device_data— alias forself.device_info
Example:
class VerifyOSPFNeighbors(IOSXETestBase): async def verify_item(self, semaphore, client, context): async with semaphore: # self.hostname is automatically set to the current device context["display_context"] = f"OSPF Neighbors -> {self.hostname}"
# self.device_data contains device metadata from data model self.logger.info(f"Verifying device {self.device_data.get('device_id')}")
output = await self.execute_command("show ip ospf neighbor") # ... verification logic7. Reporting Pass/Fail and Logging
Section titled “7. Reporting Pass/Fail and Logging”7.1 ResultStatus Enum
Section titled “7.1 ResultStatus Enum”All verification results use the ResultStatus enum from nac_test.pyats_core.reporting.types. In practice, test code uses five of its values:
ResultStatus.PASSED— verification succeededResultStatus.FAILED— verification found a mismatchResultStatus.SKIPPED— item not applicable (e.g., feature not configured)ResultStatus.ERRORED— infrastructure error (API unreachable, etc.)ResultStatus.INFO— informational result (no pass/fail judgment)
The enum also contains the pyATS statuses PASSX, ABORTED and BLOCKED; see the API Reference for the full list.
7.2 Returning Results
Section titled “7.2 Returning Results”Every verify_item() must return a result dict, built with one of these helpers (full signatures in the API Reference):
| Helper | Use for | Result |
|---|---|---|
format_ | Any outcome; the primary builder | The given status |
format_ | An attribute that differs from the expected value; uses TEST_ for readable names | FAILED |
format_ | A resource missing from the response | FAILED |
format_ | An HTTP error response; pass the URL as a string (str(response.) | FAILED |
The three convenience helpers don’t take an api_duration argument. To include the API call duration in the report, set context["api_duration"] before calling them:
if response.status_code != 200: context["api_duration"] = api_duration # optional — improves report detail return self.format_api_error(response.status_code, str(response.url), context)
if actual_scope != expected_scope: context["api_duration"] = api_duration return self.format_mismatch("scope", expected_scope, actual_scope, context)7.3 display_context, api_context, and test_context
Section titled “7.3 display_context, api_context, and test_context”The HTML report needs three pieces of information from each verify_item() call. They have similar names but serve distinct purposes:
| What the report needs | How you provide it | Effect if omitted |
|---|---|---|
| What item this result is about | context["display_ | Item label appears blank |
| Which HTTP call / CLI command produced the evidence | context["api_ | Call output appears in a separate “Commands Without Matching Results” section instead of nested under the result |
| What to name the output block | test_ (to client.get()) or with self. (D2D — see §10.3) | Output block has no label |
In practice, api_context is the same string used for both the last two — you build it once with build_api_context() and use it in both places.
7.4 display_context
Section titled “7.4 display_context”Set context["display_context"] before returning any result. This string appears in the HTML report as the item label.
Examples:
# Simple hostnamecontext["display_context"] = f"BGP -> {hostname}"
# Hierarchical pathcontext["display_context"] = f"{tenant} -> {bd} -> {subnet_ip}"
# With additional identifierscontext["display_context"] = f"BGP -> {hostname} ({system_ip})"7.5 api_context
Section titled “7.5 api_context”Use self.build_api_context() to create context strings that link HTTP responses to result entries in the HTML report. The context string must be stored in context["api_context"] and passed to client.get() — both are required for the link to appear:
api_context = self.build_api_context( "BGP Neighbors", f"Device {hostname} ({system_ip})", hostname=hostname, system_ip=system_ip,)context["api_context"] = api_context # ← links result to HTTP call in reportresponse = await client.get( f"{self.TEST_CONFIG['api_endpoint']}?deviceId={system_ip}", test_context=api_context, # ← tags the HTTP call)When both are set, the HTTP response appears nested and expandable directly under the result entry in the report. Without context["api_context"], the HTTP call still appears in the report but in a separate “Commands Without Matching Results” section.
Multiple API calls per verify_item: only one call can be the primary (linked to the result). Set context["api_context"] to the context of the most important call. Other calls will appear in “Commands Without Matching Results” — they are still visible and labelled.
D2D tests: the same context["api_context"] pattern works for SSH tests too. Set it after the command executes (after the with self.test_context() block exits) to link the command output to the result entry:
api_context = self.build_api_context(self.TEST_CONFIG["resource_type"], self.hostname)with self.test_context(api_context): output = await self.execute_command("show ip ospf neighbor")
context["api_context"] = api_context # links command to result — works for D2D tooFor multiple commands per verify_item, set context["api_context"] to the primary command’s context. Secondary commands will still appear in “Commands Without Matching Results”.
7.6 Logging
Section titled “7.6 Logging”Use self.logger for progress and diagnostic logging:
# Info - normal progressself.logger.info(f"Found {len(items)} items to verify")
# Warning - unexpected but non-fatalself.logger.warning(f"No subnets configured for BD {bd_name}")
# Error - infrastructure errors only (not test failures)self.logger.error(f"Failed to parse command output: {e}")Important: Use self.logger.error() for infrastructure errors only, not for test failures. Test failures go through format_verification_result() with ResultStatus.FAILED.
8. TEST_CONFIG and Module Constants
Section titled “8. TEST_CONFIG and Module Constants”8.1 TEST_CONFIG
Section titled “8.1 TEST_CONFIG”Class-level dict that configures framework behavior. Every test class should define it — the framework reads it, for example, to build the skip message when get_items_to_verify() returns nothing. The most important key is resource_type, which names the resource in the HTML report and in skip messages:
TEST_CONFIG = { "resource_type": "SD-WAN BGP Neighbors",}8.2 Optional TEST_CONFIG Keys
Section titled “8.2 Optional TEST_CONFIG Keys”The full list of keys the framework reads is in the API Reference. The most common are identifier_format, step_name_format, log_fields, attribute_names and schema_paths.
The examples in this guide also store the REST path or CLI command as api_endpoint (and NRFU tests sometimes store expected_values). The framework never reads these keys; they are a convention for keeping that information next to the rest of the test’s metadata, and your own code reads them via self.TEST_CONFIG[...].
Complete example:
TEST_CONFIG = { "resource_type": "ACI Bridge Domain Subnets", "api_endpoint": "/api/node/class/fvSubnet.json", "identifier_format": "{tenant}:{bd}:{subnet_ip}", "step_name_format": "Verify subnet {subnet_ip} in {bd}", "log_fields": ["tenant", "bd", "subnet_ip"], "attribute_names": { "ip": "Subnet IP", "scope": "Subnet Scope", "preferred": "Preferred", "ctrl": "Control", }, "schema_paths": { "ip": "apic.tenants[].bridge_domains[].subnets[].ip", "scope": "apic.tenants[].bridge_domains[].subnets[].public and .shared", "preferred": "apic.tenants[].bridge_domains[].subnets[].primary_ip", },}8.3 Module-Level Constants (Strongly Recommended)
Section titled “8.3 Module-Level Constants (Strongly Recommended)”These constants feed into HTML report generation. Without them, reports work but lack descriptive metadata.
TITLE = "Verify SD-WAN BGP Neighbor State"
DESCRIPTION = """Verifies that all BGP neighbors on SD-WAN edge devices are in the established state.This test queries the SD-WAN Manager API for BGP neighbor status on each device andconfirms operational readiness of BGP routing."""
SETUP = """* SD-WAN Manager API must be reachable* Edge devices must be online and reachable by the manager* BGP must be configured on the devices"""
PROCEDURE = """* Query SD-WAN Manager API for BGP neighbors on each device* Parse the response to extract neighbor state* Verify all neighbors are in "established" state* Report any neighbors in other states as failures"""
PASS_FAIL_CRITERIA = """* PASS: All BGP neighbors are in "established" state* FAIL: One or more BGP neighbors are not in "established" state* SKIP: No BGP neighbors configured on the device* ERROR: API unreachable or returned an error response"""See the API Reference for what each constant is used for.
9. API Caching
Section titled “9. API Caching”The framework provides two caching layers automatically:
9.1 Authentication Token Caching
Section titled “9.1 Authentication Token Caching”- File-based, cross-process safe (file locking)
- Stored in
nac-test-auth-cachein the system temp directory, one file per controller keyed by an MD5 hash of the controller URL - First test authenticates; subsequent tests reuse the cached token until shortly before it expires (ACI 600s, SD-WAN Manager 1800s, Catalyst Center 3600s)
- Automatic — you don’t interact with this directly
How it works:
- First test process authenticates and writes token to cache file
- Subsequent test processes read from cache file (with file locking)
- If token is expired, the process re-authenticates and updates the cache
- All processes share the same cache, reducing authentication overhead
9.2 HTTP Connection Pooling
Section titled “9.2 HTTP Connection Pooling”self.poolprovides sharedhttpx.AsyncClientinstances- Architecture base classes create the client in
run_async_verification_test()(deferred from setup for macOS fork safety) - You receive the client as the second argument to
verify_item()— just use it
Example:
async def verify_item(self, semaphore, client, context): async with semaphore: # client is a shared httpx.AsyncClient with connection pooling response = await client.get(f"{self.TEST_CONFIG['api_endpoint']}") # ... verification logicBenefits:
- Connection reuse across multiple API calls
- Automatic retry logic for transient failures
- Request/response logging for debugging
10. SSH/CLI via the Connection Broker
Section titled “10. SSH/CLI via the Connection Broker”For SSH/D2D tests (all SSHTestBase subclasses), the framework provides CLI execution through a Connection Broker — a daemon process that manages shared SSH connections so all tests executed against a given device can share the same SSH session, commands are being multiplexed through it.
10.1 execute_command()
Section titled “10.1 execute_command()”Execute a CLI command on the current device:
output = await self.execute_command("show ip ospf neighbor")Key points:
- Async function (always
awaitit) - Checks the command cache first (1-hour TTL per device)
- If not cached, executes via the broker’s shared connection pool
- Returns raw CLI output as a string
Example:
async def verify_item(self, semaphore, client, context): async with semaphore: context["display_context"] = f"OSPF Neighbors -> {self.hostname}"
# Execute command output = await self.execute_command("show ip ospf neighbor")
if not output: return self.format_verification_result( ResultStatus.ERRORED, context, "Failed to execute command", 0.0, )
# Parse and verify output # ...10.2 parse_output()
Section titled “10.2 parse_output()”Convert CLI output to structured data using Genie parsers:
parsed = await self.parse_output("show ip ospf neighbor", output=output)Key points:
- Uses Genie parsers to convert CLI output into structured data (dict)
- Returns
Noneif no parser is available for the command or parsing fails - Async (always
awaitit). It became async in nac-test 2.1 so that Genie parsers which execute additional commands can run them through the Connection Broker. In nac-test 2.0 it was synchronous — see §13.5 when upgrading older tests.
Example:
output = await self.execute_command("show ip ospf neighbor")parsed = await self.parse_output("show ip ospf neighbor", output=output)
if parsed is None: # No parser available - fall back to regex or string parsing self.logger.warning("No Genie parser available for command") # ... manual parsingelse: # Use structured data neighbors = parsed.get("interfaces", {}) # ... verification logic10.3 test_context()
Section titled “10.3 test_context()”Labels a command output block in the HTML report, and — together with context["api_context"] (explained in §7) — links it to the result entry. Use the same string for both:
api_context = self.build_api_context("OSPF Neighbors", self.hostname)with self.test_context(api_context): # ← labels the output block output = await self.execute_command("show ip ospf neighbor")
context["api_context"] = api_context # ← links block to result entryMultiple sequential test_context blocks per verify_item() are supported — each labels its own command output independently:
ctx_a = self.build_api_context("Control Connections", self.hostname)with self.test_context(ctx_a): output_a = await self.execute_command("show sdwan control connections")
ctx_b = self.build_api_context("SD-WAN Version", self.hostname)with self.test_context(ctx_b): output_b = await self.execute_command("show sdwan version")
# Link the primary command to the result; ctx_b will appear unlinkedcontext["api_context"] = ctx_aNote: test_context() labels the command output block. context["api_context"] links it to the result entry. Both are needed. For a single command, use the same string for both. For multiple commands, only one can be linked to the result — set context["api_context"] to whichever command is the primary evidence for the pass/fail decision.
10.4 Command Caching
Section titled “10.4 Command Caching”The Connection Broker provides automatic command caching:
- Per-device: Each device has its own cache
- Keyed by command string: Exact command match required
- 1-hour TTL: Cache entries expire after 1 hour
- Shared across ALL test subprocesses: Not per-process
Benefits:
- 10 tests each running
show versionon 50 devices = 50 SSH commands instead of 500 - Faster test execution
- Reduced load on network devices
Cache behavior:
- First test to execute a command on a device populates the cache
- Subsequent tests (even in different subprocesses) read from cache
- Cache is transparent — you don’t need to manage it
10.5 Broker Architecture (for understanding, not interaction)
Section titled “10.5 Broker Architecture (for understanding, not interaction)”The Connection Broker is a daemon process that:
- Listens on a Unix domain socket
- Manages a shared SSH connection pool with per-device locks (uncached commands to one device run one at a time)
- On a transport failure, reconnects and retries the command once; command errors reported by the device are returned without reconnecting
- Provides command caching across all test processes
- Writes a CLI session log per device to
<output>/pyats_results/<hostname>-cli-<timestamp>.log
You interact via execute_command() only — no direct broker interaction needed.
11. Concurrency
Section titled “11. Concurrency”Section 1 introduced concurrency at a high level. This section details what you must do in your test code.
11.1 API Tests
Section titled “11.1 API Tests”- All run in a single process with a shared event loop
verify_item()calls run concurrently, controlled by the semaphore- Always start
verify_item()withasync with semaphore: - The semaphore limit is set by the framework: 55 by default, configurable with the
NAC_TEST_PYATS_API_CONCURRENCYenvironment variable
Example:
async def verify_item(self, semaphore, client, context): async with semaphore: # Acquire semaphore slot # This code runs concurrently with other verify_item() calls # up to the semaphore limit response = await client.get(...) # ... verification logic # Semaphore released automatically when exiting the block11.2 D2D Tests
Section titled “11.2 D2D Tests”- Each device runs in its own subprocess
- Multiple devices run in parallel. The default limit is calculated from available CPU and memory (capped at 50);
--max-parallel-devicescan only lower it - Within a device,
verify_item()calls run concurrently under the same semaphore as API tests. They share the device’s single SSH session: the broker serializes uncached commands with a per-device lock, while cached results are returned immediately
Example:
# Device 1 subprocessasync def verify_item(self, semaphore, client, context): async with semaphore: # Runs concurrently with the other verify_item() calls for this device # and in parallel with other devices' subprocesses output = await self.execute_command("show version") # ... verification logic11.3 What You Must Do
Section titled “11.3 What You Must Do”Always wrap the body of verify_item() in async with semaphore::
async def verify_item(self, semaphore, client, context): async with semaphore: # REQUIRED # Your verification logic here ...Why this matters:
- The framework starts all
verify_item()calls at once and does not acquire the semaphore itself — yourasync with semaphore:is what limits concurrency - Without it, you’ll overwhelm the controller/devices with concurrent requests
- Because calls run concurrently, keep
verify_item()free of shared mutable state: keep per-item data incontextand local variables rather than onself
12. Tag Filtering
Section titled “12. Tag Filtering”Add a groups class attribute to enable --include/--exclude tag filtering. Tag selection works the same for Robot and PyATS tests (see Select Test Cases By Tag); this section covers the PyATS specifics.
class VerifyBGPRoutes(APICTestBase): groups = ["bgp", "routing"]
TEST_CONFIG = { "resource_type": "BGP Routes", "api_endpoint": "/api/node/class/bgpRoute.json", }
# ... rest of test implementationUsage:
# Run only tests with "bgp" in groupsnac-test --pyats --include bgp ...
# Skip tests with "routing" in groupsnac-test --pyats --exclude routing ...
# Run tests tagged "bgp" or "ospf", except those tagged "slow"nac-test --pyats -i bgp -i ospf --exclude slow ...
# The same selection as a single patternnac-test --pyats --include bgpORospf --exclude slow ...Key points:
- Matching uses Robot Framework’s tag patterns, the same as for Robot tests: wildcards (
bgp*,?est) and the boolean operatorsAND,ORandNOT(e.g.bgpANDrouting,bgpNOTnrfu) are supported - Matching is case-insensitive and ignores underscores (
BGP_Peersmatchesbgppeers) - To include several tags, repeat the option (
-i bgp -i ospf) or useOR. A comma-separated value like--include bgp,ospfis treated as one literal pattern and matches neither tag - Tests without
groupsrun when no--includeis given, but are excluded as soon as an--includepattern is set --excludeis checked first: a test matching an exclude pattern never runsgroupsmust be a plain list of string literals on the test class, and is only read when the class inherits from a recognized base class (see §1.2)- Use tags to organize tests by feature, protocol, or execution time
Next Steps
Section titled “Next Steps”Now that you understand the framework architecture and patterns, you’re ready to write your first test:
- Choose your base class from the Layer 2 architecture adapters (Section 2)
- Implement the three-method contract (Section 3)
- Choose your test pattern — NRFU or data-model-driven (Section 4)
- Add TEST_CONFIG and module constants (Section 8)
- Test locally with
nac-test --pyats --include your-tag
Additional resources:
- See the API Reference for complete method signatures
- See the Quickstart for a copy-paste minimal example
Common development workflow:
# 1. Create your test filevim verify_my_feature.py
# 2. Add tag filtering to your test class so you can run just this test:# class VerifyMyFeature(SDWANManagerTestBase):# groups = ["my-feature"]# ...
# 3. Run just your test during developmentnac-test --pyats --include my-feature \ --data data/my-test-data.yaml \ --templates path/to/tests/ \ --output /tmp/nac-test-output
# 4. Check the HTML reportopen /tmp/nac-test-output/combined_summary.html
# 5. Iterate until passing# ... edit test ...nac-test --pyats --include my-feature \ --data data/my-test-data.yaml \ --templates path/to/tests/ \ --output /tmp/nac-test-output
# 6. Run full test suitenac-test --pyats \ --data data/full-data.yaml \ --templates path/to/tests/ \ --output /tmp/nac-test-outputDebugging tips:
- Use
self.logger.info()liberally during development - Use
--loglevel DEBUGto see detailed execution logs - Start from
combined_summary.htmlin the output directory; the detailed pyATS reports are atpyats_results/api/html_reports/summary_report.htmlandpyats_results/d2d/html_reports/summary_report.html(robot_results/report.htmlis the Robot Framework report) - For SSH tests, check the per-device CLI session logs at
pyats_results/<hostname>-cli-<timestamp>.log - HTML report shows API call timing and response codes for performance analysis
13. Static Analysis and Type Checking
Section titled “13. Static Analysis and Type Checking”Test files live outside the nac-test core repo, so they don’t benefit from the project’s own pre-commit hooks. Setting up static analysis in your own test repo catches common mistakes — including async/await errors — before you even run nac-test.
13.1 What Static Analysis Catches
Section titled “13.1 What Static Analysis Catches”The most common mistakes for test writers:
| Mistake | Example | Detected by |
|---|---|---|
Missing await on async call | output = self. or parsed = self. | mypy — Coroutine[...] assigned to str / dict |
| Awaiting a sync function | parsed = await self. in nac-test 2.0 | mypy — Incompatible types in await |
Wrong return type from verify_item | Returning None instead of a result dict | mypy |
| Unused imports, undefined variables | — | ruff (flake8/ |
| Style inconsistencies | Line length, import order | ruff (format) |
mypy detection requires type annotations on local variables. Without them, mypy infers Any and silently passes. The key annotation is on the output of async calls:
# mypy catches this because output is annotated str but execute_command returns Coroutineoutput: str = self.execute_command("show version") # Error: Maybe you forgot await?
# mypy catches this too — parse_output is async in nac-test 2.1parsed: dict | None = self.parse_output("show version", output=output) # Error: Maybe you forgot await?13.2 Recommended Pre-commit Setup
Section titled “13.2 Recommended Pre-commit Setup”Install pre-commit in your test repo:
pip install pre-commit ruff mypyCreate .pre-commit-config.yaml in your repo root:
repos: - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.8.0 hooks: - id: ruff args: [--fix] - id: ruff-format
- repo: https://github.com/pre-commit/mirrors-mypy rev: v1.13.0 hooks: - id: mypy additional_dependencies: - nac-test - nac-test-pyats-common - pyatspre-commit install # runs on every git commitpre-commit run --all-files # run manually against all files13.3 Recommended mypy Configuration
Section titled “13.3 Recommended mypy Configuration”Create pyproject.toml (or mypy.ini) in your test repo matching the nac-test project’s own settings:
[tool.mypy]python_version = "3.10"check_untyped_defs = truedisallow_incomplete_defs = truedisallow_untyped_defs = trueignore_missing_imports = truestrict_optional = truewarn_return_any = truewarn_unreachable = trueshow_error_context = true13.4 Recommended ruff Configuration
Section titled “13.4 Recommended ruff Configuration”[tool.ruff]target-version = "py310"line-length = 88
[tool.ruff.lint]select = [ "E", # pycodestyle errors "W", # pycodestyle warnings "F", # pyflakes (undefined names, unused imports) "I", # isort "B", # flake8-bugbear (likely bugs) "UP", # pyupgrade (modern Python syntax)]13.5 The parse_output() Migration (nac-test 2.0 → 2.1)
Section titled “13.5 The parse_output() Migration (nac-test 2.0 → 2.1)”parse_output() changed from synchronous to asynchronous in nac-test 2.1 (listed as a breaking change in the 2.1.0b1 changelog). Tests written for nac-test 2.0 must add await to every parse_output() call. mypy catches code written for the wrong version:
# nac-test 2.1+ — async. Forgetting await is caught by mypy:parsed = await self.parse_output(command, output=output) # correctparsed = self.parse_output(command, output=output) # mypy error: Coroutine assigned
# nac-test 2.0 — sync (legacy). Adding await is caught by mypy:parsed = self.parse_output(command, output=output) # correct in 2.0 onlyparsed = await self.parse_output(command, output=output) # mypy error in 2.0: not AwaitableRun mypy against your test files after upgrading nac-test to catch any parse_output calls that need updating:
mypy verify_my_test.py