Test Case Guide
This guide is for engineers writing Robot Framework test templates for nac-test. It assumes basic knowledge of Robot Framework and Jinja. It explains how templates are rendered and executed, and describes general techniques for verifying a deployment against its data model. The examples use ACI and are simplified to illustrate the techniques; they are not complete tests. None of the techniques are required by nac-test — adapt them to your architecture and conventions. The syntax of rendering directives, filters and the template context is in the Reference.
What you write is what to fetch and which data model values to compare it with. nac-test and Pabot take care of:
- Rendering — one template produces test cases for every matching object in the data model
- Parallel execution — rendered suites run in parallel Pabot processes; long suites can be split per test case
- Reporting — Robot’s
log.html/report.html, a mergedxunit.xmland the combined summary with PyATS results - Tag selection —
--include/--excludeselect suites and test cases by tag
1. How Robot Tests Are Executed
Section titled “1. How Robot Tests Are Executed”- All
--datafiles are merged into one data model (see Input Data). - Every
.robot,.resourceand.j2file in--templatesis rendered with Jinja and written to<output>/robot_results/, keeping the folder structure. Other files (e.g. Python keyword libraries) are copied unchanged. - Pabot runs the rendered suites in parallel, with one suite per process by default (
--processescontrols the number of processes). - Robot results are written to
robot_results/and merged into the combined summary andxunit.xml.
Rendering happens before execution. Jinja decides which test cases and assertions exist; Robot only sees the rendered result. Anything that depends on the live system (API responses, device output) is handled by Robot keywords at runtime.
| Robot Framework | PyATS | |
|---|---|---|
| Test definition | Jinja template rendered to .robot files | Python classes |
| Data model access | At render time, via Jinja | At runtime, via self.data_model |
| Logic | Mostly in Jinja (render time) and keywords | Python |
Both engines can be used side by side in the same --templates directory, so each test can use the engine that fits it better.
2. Project Layout and Naming
Section titled “2. Project Layout and Naming”nac-test renders whatever folder structure you use, for example:
tests/templates/├── common.resource # Shared keywords (login, assertions)├── lib/ # Optional Python keyword libraries (copied, not rendered)└── tenants/ ├── tenant.robot └── bridge_domain.robotSome considerations:
- Grouping templates along the data model makes it easy to find the test for a given part of the data model.
- Test case names must be unique within a suite after rendering, so include the object’s identifiers:
Verify Bridge Domain {{ bd.name }} Tenant {{ tenant.name }}. - Folders and tags make it easy to run a subset (see §8).
3. Anatomy of a Template
Section titled “3. Anatomy of a Template”*** Settings ***Documentation Verify TenantsSuite Setup Login APICDefault Tags apic tenantsResource ../common.resource
*** Test Cases ***{% for tenant in apic.tenants | default([]) %}
Verify Tenant {{ tenant.name }} ${r}= GET On Session apic /api/mo/uni/tn-{{ tenant.name }}.json Should Be Equal Json Value ${r.json()} imdata[0].fvTenant.attributes.name {{ tenant.name }} Should Be Equal Json Value ${r.json()} imdata[0].fvTenant.attributes.descr {{ tenant.description | default() }}
{% endfor %}*** Settings ***: importing libraries and keywords from a shared resource file keeps each suite small; a login keyword typically runs asSuite Setup.Resourceis a path relative to the rendered file. Templates rendered with a rendering directive end up one folder deeper and need one more../(see §7).*** Test Cases ***is generated by Jinja loops. Since values come from the data model at render time, suites rarely need their own*** Variables ***.- If the data model has no matching objects, the rendered suite has no test cases and doesn’t produce any test results.
4. The Shared Resource File
Section titled “4. The Shared Resource File”nac-test provides the libraries (see Bundled Libraries) but no controller- or device-specific keywords. A shared resource file usually provides login and session handling, and assertion keywords that compare an API response with an expected value. Resource files are rendered with Jinja too, so they can use the data model — for example to create a session per device.
4.1 Logging In Once Across Pabot Processes
Section titled “4.1 Logging In Once Across Pabot Processes”Pabot runs suites in separate processes, and each suite calls the login keyword in its Suite Setup. To avoid one login per suite, PabotLib can run the login once and share the token with all processes:
*** Settings ***Library pabot.PabotLibLibrary RequestsLibraryLibrary JMESPathLibrary
*** Keywords ***Get Token # Authenticate against the controller and extract the token from the response ${token}= ... Set Parallel Value For Key token ${token}
Login APIC Run Only Once Get Token ${token}= Get Parallel Value For Key token Create Session apic %{ACI_URL} headers={"Cookie": "APIC-cookie=${token}"}Run Only Onceexecutes the login in the first process only; the others wait and then read the token withGet Parallel Value For Key.- Each suite creates its own
RequestsLibrarysession with the shared token. - Reading credentials from environment variables keeps them out of the data model and the templates;
Set Log Levelcan keep them out oflog.html.
For long test runs, the token may need to be refreshed (protected with Acquire Lock/Release Lock), and Run On Last Process can log out at the end.
For architectures without a controller, the resource file can loop over the devices of the data model and create one session per device, using the device name as session alias.
4.2 Assertion Keywords
Section titled “4.2 Assertion Keywords”Wrapping Robot’s comparison keywords in a few assertion keywords keeps the templates short — each assertion is a query and a rendered expected value:
Should Be Equal Json Value [Arguments] ${json} ${expression} ${value}=${EMPTY} ${actual}= JSON Search String ${json} ${expression} Run Keyword If $value Should Be Equal As Strings ${actual} ${value}Normalizations that the API requires (e.g. comparing lists regardless of order) are then implemented once instead of in every template.
4.3 Python Keyword Libraries
Section titled “4.3 Python Keyword Libraries”Logic that is awkward in Robot syntax can go into a Python library next to the resource file (Library ./lib/MyLib.py). Python files are copied to the output directory unchanged, so the relative import keeps working after rendering.
5. Writing Templates with Jinja
Section titled “5. Writing Templates with Jinja”5.1 Accessing the Data Model
Section titled “5.1 Accessing the Data Model”The merged data model is the template context: its root keys (e.g. apic and defaults) are available as variables.
{% for tenant in apic.tenants | default([]) %}{% for bd in tenant.bridge_domains | default([]) %}5.2 Undefined Values and default()
Section titled “5.2 Undefined Values and default()”Templates are rendered with a strict, chainable undefined:
- Accessing a missing key anywhere in a chain is allowed:
apic.fabric_policies.bannersdoesn’t fail iffabric_policiesis missing. - Using an undefined value — printing it, looping over it, comparing it or testing its truthiness — fails the rendering.
Optional values therefore need a default:
{% for bd in tenant.bridge_domains | default([]) %} {# loop: empty list #}{{ bd.description | default() }} {# value: empty string #}{% if apic.fabric_policies is defined %} {# section present? #}is defined is the only test that is safe on an undefined value. Note that a misspelled attribute combined with | default() renders an empty value instead of failing — check attribute names against the data model schema.
5.3 Default Values
Section titled “5.3 Default Values”Many data model attributes have a default value, defined in the defaults section of the data model. Falling back to it for attributes that are not set makes the test compare against the value that was actually deployed:
{{ pool.allocation | default(defaults.apic.access_policies.vlan_pools.allocation) }}defaults must be part of the merged data model, for example by passing the architecture’s defaults file via --data.
5.4 Derived Values
Section titled “5.4 Derived Values”Use {% set %} for values used in several places:
{% set tenant_dn = 'uni/tn-' ~ tenant.name %}5.5 Conditionals
Section titled “5.5 Conditionals”Jinja conditions decide which test cases and assertions are rendered. To render the *** Test Cases *** section only when the data model section exists, wrap it in a condition:
{% if apic.tenants is defined %}
*** Test Cases ***...{% endif %}To collect matching objects across a nested structure first, use a namespace:
{% set ns = namespace(bds=[]) %}{% for tenant in apic.tenants | default([]) %}{% set ns.bds = ns.bds + (tenant.bridge_domains | default([])) %}{% endfor %}{% if ns.bds | length > 0 %} ... {% endif %}A check that doesn’t apply can simply not be rendered, which is often simpler than Robot’s Skip or Pass Execution.
5.6 Macros
Section titled “5.6 Macros”Jinja macros help with repeated blocks:
{% macro verify_object(name, dn) %}Verify Object {{ name }} ${r}= GET On Session apic /api/mo/{{ dn }}.json ...{% endmacro %}Macros don’t see variables set outside of them with {% set %}; pass everything they need as arguments.
5.7 Filters
Section titled “5.7 Filters”Built-in Jinja filters cover most needs: join, length, sort, replace, lower, selectattr, reject, map, first, format. Conversions that are specific to an architecture can be implemented as custom filters and loaded with --filters (see Custom Jinja Filters).
5.8 Whitespace
Section titled “5.8 Whitespace”Templates are rendered with trim_blocks and lstrip_blocks, so block tags ({% for %}, {% if %}) on their own line don’t leave blank lines or indentation behind, and Jinja tags can be indented inside test case bodies. Superfluous blank lines are removed after rendering, so whitespace-control markers ({%-, -%}) are rarely needed.
6. Assertions
Section titled “6. Assertions”6.1 Fetch Once, Assert Many
Section titled “6.1 Fetch Once, Assert Many”Fetching an object once and asserting several attributes against the same response keeps the number of API calls low. Child objects can be verified in separate test cases that reuse the parent’s response:
Verify Tenant {{ tenant.name }} ${r}= GET On Session apic /api/mo/uni/tn-{{ tenant.name }}.json params=rsp-subtree=children Set Suite Variable $r ${r.json()} Should Be Equal Json Value ${r} imdata[0].fvTenant.attributes.name {{ tenant.name }}
{% for vrf in tenant.vrfs | default([]) %}Verify Tenant {{ tenant.name }} VRF {{ vrf.name }} ${vrf}= Set Variable imdata[0].fvTenant.children[?fvCtx.attributes.name=='{{ vrf.name }}'] | [0] Should Be Equal Json Value ${r} ${vrf}.fvCtx.attributes.descr {{ vrf.description | default() }}{% endfor %}A JMESPath filter expression stored in a variable selects the child; assertions append the attribute path. Test cases that reuse a suite variable depend on running in order, so such suites can’t use test-level parallelization (see §9).
6.2 Optional Attributes
Section titled “6.2 Optional Attributes”Attributes that are not set in the data model need a defined behavior. One approach is to skip the check when the expected value is empty: the assertion keyword returns without comparing, and templates render optional attributes with | default() (as in the examples above). This keeps templates short, but a value that is genuinely expected to be empty can’t be verified this way. Alternatively, the assertion can always run and treat an attribute missing from the response as matching an unset value. Whichever approach you choose, using it consistently makes templates easier to review.
6.3 Booleans and Enumerations
Section titled “6.3 Booleans and Enumerations”Data model values often differ from the API representation and can be converted at render time:
{{ 'yes' if bd.arp_flooding else 'no' }}To distinguish “not set” from false, use is true/is false instead of if val. Alternatively, values can be normalized in the assertion keyword.
6.4 Lists
Section titled “6.4 Lists”Lists can be rendered as Robot list arguments and compared in the keyword, for example regardless of order:
${expected}= Create List {{ values | join(' ') }}The join separator must be a valid Robot argument separator (at least two spaces).
6.5 Missing Objects and Failure Messages
Section titled “6.5 Missing Objects and Failure Messages”If the parent object is not found, every attribute assertion fails with a message that doesn’t point to the cause. An explicit check gives a clearer result:
${count}= JSON Search String ${r.json()} totalCountRun Keyword If '${count}' == '0' Fail Tenant '{{ tenant.name }}' not foundA msg= argument on assertion keywords helps identify the attribute in the failure message when the query alone isn’t descriptive.
6.6 Special Characters
Section titled “6.6 Special Characters”Robot treats two or more spaces as an argument separator and interprets \, $, @, &, %, = and # in certain positions. Free text from the data model (descriptions, banners) can therefore break the rendered suite or change the value:
- A custom filter can escape such values for Robot; the assertion keyword should then normalize the actual value the same way.
- Literal Jinja syntax in a resource file can be wrapped in
{% raw %}...{% endraw %}. - Rendered values shouldn’t be wrapped in quotes — the quotes become part of the value.
7. Rendering Directives
Section titled “7. Rendering Directives”By default, each template renders to exactly one suite. Rendering directives render a template once per item of a data model list, producing one suite per item. This helps with:
- Parallelism: one suite per tenant lets Pabot run them in parallel and keeps each suite small.
- Very large lists:
iterate_list_chunkedadditionally splits items with many child objects into several suites.
The directive passes the item’s identifier — a string, not the object — to the template, so the template looks the object up by that identifier:
{# iterate_list apic.tenants name tenant_name #}*** Settings ***Documentation Verify Bridge DomainsSuite Setup Login APICDefault Tags apic tenantsResource ../../common.resource
*** Test Cases ***{% set tenant = apic.tenants | selectattr('name', 'equalto', tenant_name) | first %}{% for bd in tenant.bridge_domains | default([]) %}...Rendered suites are written to a subfolder named after the item (tenants/<tenant>/bridge_domain.robot), so the Resource path needs one more ../. See Rendering Directives for the full syntax.
8. Tags and Test Selection
Section titled “8. Tags and Test Selection”8.1 Default Tags
Section titled “8.1 Default Tags”Default Tags on each suite make it possible to select tests by tag, for example by architecture or data model section:
Default Tags apic tenants-i tenants then runs only these suites. See Select Test Cases By Tag for the pattern syntax.
8.2 non-critical
Section titled “8.2 non-critical”nac-test runs Robot with --skiponfailure non-critical: a failing test tagged non-critical is reported as skipped instead of failed. This is useful for checks that should be visible in the report without failing the run.
8.3 Opt-In Test Cases
Section titled “8.3 Opt-In Test Cases”The selected tags are available in templates as robot_include_tags and robot_exclude_tags. They can be used to render test cases only when explicitly requested:
{% if 'extended' in robot_include_tags %}Verify Something Extended [Tags] extended ...{% endif %}9. Parallel Execution
Section titled “9. Parallel Execution”Pabot runs suites in parallel; test cases within a suite run sequentially in one process. Smaller suites — for example through rendering directives (§7) — therefore parallelize better.
For suites with many independent, long-running test cases, the Test Concurrency metadata runs each test case in its own process:
*** Settings ***Metadata Test Concurrency TrueThis requires test cases that don’t depend on each other: test cases that reuse a suite variable from an earlier one (§6.1) don’t work with it. See Test Concurrency for details.
10. Beyond Configuration
Section titled “10. Beyond Configuration”Besides comparing the data model with the configuration on the controller or device, templates can verify other aspects of a deployment, such as fault counts, health scores or operational state (e.g. routing protocol sessions being established). They follow the same techniques, with expected values that are either fixed or taken from the data model. For checks that need more logic, such as parsing device CLI output, a PyATS test may be a better fit.
11. Development Workflow
Section titled “11. Development Workflow”# 1. Render only and inspect the generated suitesnac-test --robot --render-only -d data/ -t tests/templates/ -o tests/results/less tests/results/robot_results/tenants/tenant.robot
# 2. Validate syntax and keywords without connecting to anythingnac-test --robot --dry-run -d data/ -t tests/templates/ -o tests/results/
# 3. Run only the suite you're working onnac-test --robot -i tenants -d data/ -t tests/templates/ -o tests/results/
# 4. Review the resultsopen tests/results/robot_results/log.html- Rendering errors (undefined values, Jinja syntax) abort the Robot part of the run before any Robot test is executed, and the run is reported as errored. Run with
--loglevel INFOto see which template was being rendered. --dry-runcatches unknown keywords and wrong argument counts, including in blocks that your test data rarely renders.- A small test data set that sets every optional attribute used by a template makes sure each rendered branch is executed at least once.
- Additional Robot options, such as
--loglevel TRACEor--variable, can be appended to thenac-testcommand (see Robot Options).
12. Common Pitfalls
Section titled “12. Common Pitfalls”- Missing
default: looping over, printing or comparing an optional value without| default(...)fails the rendering when the data model doesn’t contain it. - Silently skipped checks: if empty expected values are skipped (§6.2), a misspelled attribute renders empty and the check never runs. Reviewing the rendered suites (
--render-only) shows which assertions have no expected value. - Duplicate test case names: test names that don’t include all identifiers collide after rendering.
- Wrong
Resourcepath: templates with rendering directives are written one folder deeper. - Test Concurrency with dependent test cases: suites that share state between test cases fail when their test cases run in separate processes.
- Unescaped free text: consecutive spaces or special characters in descriptions split or alter Robot arguments.