Skip to content

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 merged xunit.xml and the combined summary with PyATS results
  • Tag selection — --include/--exclude select suites and test cases by tag
  1. All --data files are merged into one data model (see Input Data).
  2. Every .robot, .resource and .j2 file in --templates is rendered with Jinja and written to <output>/robot_results/, keeping the folder structure. Other files (e.g. Python keyword libraries) are copied unchanged.
  3. Pabot runs the rendered suites in parallel, with one suite per process by default (--processes controls the number of processes).
  4. Robot results are written to robot_results/ and merged into the combined summary and xunit.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 FrameworkPyATS
Test definitionJinja template rendered to .robot filesPython classes
Data model accessAt render time, via JinjaAt runtime, via self.data_model
LogicMostly in Jinja (render time) and keywordsPython

Both engines can be used side by side in the same --templates directory, so each test can use the engine that fits it better.

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.robot

Some 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).
*** Settings ***
Documentation Verify Tenants
Suite Setup Login APIC
Default Tags apic tenants
Resource ../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 as Suite Setup.
  • Resource is 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.

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.PabotLib
Library RequestsLibrary
Library 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 Once executes the login in the first process only; the others wait and then read the token with Get Parallel Value For Key.
  • Each suite creates its own RequestsLibrary session with the shared token.
  • Reading credentials from environment variables keeps them out of the data model and the templates; Set Log Level can keep them out of log.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.

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.

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.

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([]) %}

Templates are rendered with a strict, chainable undefined:

  • Accessing a missing key anywhere in a chain is allowed: apic.fabric_policies.banners doesn’t fail if fabric_policies is 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.

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.

Use {% set %} for values used in several places:

{% set tenant_dn = 'uni/tn-' ~ tenant.name %}

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.

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.

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

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.

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

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.

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.

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

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()} totalCount
Run Keyword If '${count}' == '0' Fail Tenant '{{ tenant.name }}' not found

A msg= argument on assertion keywords helps identify the attribute in the failure message when the query alone isn’t descriptive.

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.

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_chunked additionally 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 Domains
Suite Setup Login APIC
Default Tags apic tenants
Resource ../../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.

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.

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.

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 %}

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 True

This 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.

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.

Terminal window
# 1. Render only and inspect the generated suites
nac-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 anything
nac-test --robot --dry-run -d data/ -t tests/templates/ -o tests/results/
# 3. Run only the suite you're working on
nac-test --robot -i tenants -d data/ -t tests/templates/ -o tests/results/
# 4. Review the results
open 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 INFO to see which template was being rendered.
  • --dry-run catches 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 TRACE or --variable, can be appended to the nac-test command (see Robot Options).
  • 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 Resource path: 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.