Unit testing NeMo Guardrails configurations

Unit tests pin the guardrail behavior your policy depends on, so prompt edits, flow changes and library upgrades fail a build instead of quietly weakening protection. This page covers what to test, how the test doubles fit, and how to run them in CI.

On this page

Why unit testing NeMo Guardrails configurations comes before every release

Unit testing comes before every release because a NeMo Guardrails configuration is code that changes often: config.yml, Colang files and Python actions are all edited by people who may not know which blocked input the team promised to keep blocked. A unit test pins one expected behavior, such as a jailbreak attempt being refused or a restricted topic being redirected, and fails the build if a later prompt edit, flow change or library upgrade makes that behavior disappear. The question this topic answers is how to write those pins so they run quickly, produce the same result every time and need no live model.

A unit test is different from the other checks in your program. It asserts a specific input produces a specific rail outcome, using stubbed model responses, so it is fast and deterministic. An evaluation with nemoguardrails eval measures compliance across a dataset with a judge, and a garak scan probes the application with a large set of attack prompts. Those checks answer how well the configuration performs. Unit tests answer whether a known guarantee still holds after the last change. Treat unit tests as the fast, deterministic layer of a wider testing program, and expect the slower layers to run before a release rather than replace them.

Confirm the test utilities your installed version provides before you design the suite, since helpers such as the fake model and recording HTTP client are tied to the library release you run. The current release is 0.25.0, which requires Python 3.11, 3.12 or 3.13, and the library is licensed under Apache 2.0. Pin the exact version in your lock file, record which version the tests passed against, and rerun the suite as part of every upgrade, because a version bump is one of the most common ways a guardrail quietly changes behavior.

Test doubles replace the model and HTTP calls, so tests never reach external services

The test runner starts with a configuration folder holding config.yml, Colang files and actions, and loads it into the code under test. Inside that boundary, FakeLLMModel stands in for the model, so every prompt and completion is scripted. RecordingHTTPClient captures outbound calls from actions, and TestChat drives multi-turn conversations and asserts on each reply. Check that nothing crosses the dashed boundary: no live model, no network, no safety model endpoint.

Test doubles replace the model and HTTP calls around the code under test.

Which guardrail behaviors to pin in unit tests

A unit test suite for a NeMo Guardrails configuration should pin the behaviors that a silent edit could weaken without anyone noticing. The six categories below cover where a rail can fail open, where a flow can route to the wrong answer, and where a fallback can leak. Each one is checked with fixed inputs and exact expected outcomes, so a prompt edit, flow change or library upgrade fails the build instead of reaching users.

Input rail refusals

Each input rail should refuse a fixed set of prompts that must never reach the model, such as a known jailbreak string or a request for disallowed content. The test asserts that the refusal happens and that the model fake received no call. Pin one refusal per rail type you rely on, because a rewritten self-check prompt can quietly stop matching. Keep a benign prompt beside each refusal so an over-broad change also fails the build.

NeMo Guardrails docs

Output rail blocks

Output rails inspect what the model returns, so the test feeds a scripted model reply through FakeLLMModel that contains a disallowed statement and asserts the user receives the block message instead. This catches regressions where an input rail passes but the response is delivered unchecked. Include a clean reply that must pass through unchanged, which confirms the rail does not rewrite ordinary answers. Deterministic scripted replies are the reason this belongs in unit tests rather than a judged evaluation.

Dialog flow routing

Colang flows decide which canned or generated path a conversation takes, and a renamed intent or edited utterance can send a request to the wrong flow. Use TestChat to run a short multi-turn script and assert which flow fired at each step. Check that off-topic turns reach the refusal flow and that in-scope turns reach the answer flow. Routing is a discrete outcome, so an exact assertion is more reliable than a model's opinion of the transcript.

Retrieval rail filtering

Retrieval rails decide which RAG chunks may reach the prompt, for example by dropping chunks tagged for another tenant or marked restricted. The test supplies a fixed set of chunks through a stubbed retrieval step and asserts that only permitted chunks appear in the rendered prompt. Pin a case where every chunk is filtered, so the empty-context path is also tested. A changed filter condition or metadata key would otherwise expose data without any visible error.

Execution rail permissions

Execution rails control which custom actions and tools the model may call and with what arguments. Use RecordingHTTPClient to capture outbound requests and assert that an allowed action runs and a disallowed one never produces a request. Test argument validation as well, such as a refused amount or an unlisted host. Confirm the exact action names in your configuration, since a rename can leave a permission check pointing at nothing.

Fallback messages

Fallback messages are what users see when a model call fails, times out or returns nothing usable. The test forces each failure through the fake model and asserts the configured fallback text, with no internal error, stack trace or partial model output. Upgrades sometimes change default fallback behavior, so pin the exact wording you have approved. Ask your compliance reviewer which wording is required before writing the expected value.

How FakeLLMModel, RecordingHTTPClient and TestChat each work

FakeLLMModel replaces the language model that the guardrail configuration calls for self-check prompts, intent matching and generated replies. Because the model returns scripted responses, a test can state exactly what the rail sees and assert which branch the flow takes. This makes it possible to check that a self-check input prompt flags a scripted unsafe message, that a dialog flow routes to the refusal, or that an output rail blocks a scripted leak. The tests run without network access or model costs, so they can execute on every commit.

  • Scripted responses: each test queues the model output it expects, so the decision logic is tested in isolation.
  • Prompt-level assertions: a test can check that the rendered prompt contains the policy text you intended to ship.
  • Branch coverage: you can force each rail outcome, including the fallback path that a real model rarely reaches.
  • Fast regression: a prompt or flow edit that changes routing fails the test without any model call.
  • Limit: a scripted reply proves only that your flow reacts correctly to that reply. It cannot prove that a real model refuses a prompt, produces the same classification, or behaves the same after a model version change.

Before relying on it, confirm the exact class name, import path and supported versions for your installed release in the NeMo Guardrails documentation.

Test scope options and when each fits

This table compares three ways to write unit tests for a NeMo Guardrails configuration: single-rail tests, full-flow tests through the Python API, and server-level tests against the HTTP API. Read each row as a trade-off, and note that most teams combine two or more scopes so that narrow tests catch local regressions and broader tests catch broken paths between rails.

ScopeWhat it catchesSetup costWhen to choose it
Single-rail testsWrong refusal wording, a rail that stops matching its trigger phrases, or a flow edit that changes one rail's outputLow to moderate: stub the model with FakeLLMModel and load a minimal configurationEarly in development, or when a prompt or flow edit should only affect one rail
Full-flow tests through the Python APIOrdering problems between input, dialog and output rails, and blocked messages that never reach the modelModerate: load the full config folder and drive a TestChat session with scripted turnsBefore a release, to pin end-to-end behavior the user actually sees
Server-level tests against the HTTP APISerialization, configuration loading from the folder, authentication in front of the server, and differences in the deployed containerHigher: run the guardrails server or its image and send requests with RecordingHTTPClientWhen the deployed server is the product boundary, or before a library or image upgrade
Catching model-side changesBehavior drift when a real model replaces the stub, which stub-based tests cannot seeRecurring: needs a model endpoint and tolerates nondeterminismKeep these in separate evaluation runs, not in the fast unit suite
Speed and determinism in CIFast, repeatable failures on every merge when stubs return fixed outputsLow per run once the stubs are writtenGate every change with these tests, and confirm run times in your own pipeline
Coverage of external callsWhether tool calls and HTTP actions are asserted, not just the final answerModerate: record outbound calls and assert their argumentsWhen custom actions or retrieval rails call internal systems
Maintenance burdenTest churn when prompts change often and scripted turns must be updatedOngoing: every flow rename touches test scriptsChoose fewer, broader tests for stable policies and narrower ones for policies still under review

Setting up the first guardrail test suite

This sequence takes a team from an empty repository to a working unit test suite that pins each guardrail policy to an expected response. Each step ends with a check that shows the harness is actually exercising the rails, so a later failure points to a real change in behavior.

  1. Pin the Python version

    The engineer responsible for the guardrail configuration chooses one interpreter for the project and records it in the repository, using Python 3.11, 3.12 or 3.13, which are the versions NeMo Guardrails 0.25.0 supports. Developers and the CI runner must use the same minor version so that tokenization, dependency resolution and test output do not differ between machines. The step is done when the chosen version appears in the project metadata and a local interpreter check prints that exact version.

  2. Install the pinned nemoguardrails version

    Install the library at an exact version in a fresh virtual environment, for example version 0.25.0, and commit the lock file or requirements file that records it. Pinning prevents a silent library upgrade from changing how rails are interpreted between test runs. The step closes when a clean install reproduces the same resolved version on a second machine and the test runner imports the library without errors.

  3. Lay out the configuration folder

    Create one configuration folder containing the config.yml file, any Colang files, and any Python actions, and keep the test code in a separate directory that loads that folder by path. Keeping policies, flows and tests apart makes it clear which files a prompt edit or flow change touches. The step is done when loading the configuration from the test directory succeeds and the test runner reports no missing files.

  4. Write one test per policy

    For each policy the team has written down, add one test that sends a representative input through the guardrailed application and asserts on the rail outcome, such as a refusal or a blocked output. Use FakeLLMModel so the test does not depend on a live model, and use TestChat to drive the conversation. The check is that each test names the policy it covers, so a reviewer can map every policy to at least one assertion.

  5. Add a baseline test that must fail

    Write a deliberately wrong assertion, such as expecting a blocked input to pass, and confirm the harness reports it as a failure. This proves that the test runner, the fake model and the assertion logic are wired together and not silently passing. Remove or mark the baseline as expected failure once the check is confirmed, and keep it in the repository as evidence that the harness can fail.

  6. Disable a rail to confirm detection

    Temporarily remove or disable one input or output rail in the configuration and run the suite. The policy test for that rail should fail, and the failure message should identify the missing behavior. If every test still passes, the suite is not covering that policy and the assertion needs to be tightened before the team relies on it. Restore the rail and confirm the suite passes again.

  7. Record the expected responses

    Save the expected response for each test in a version-controlled file so that a change in wording or refusal behavior shows up as a reviewable diff. Use RecordingHTTPClient where the configuration calls external services, so the recorded calls are replayed rather than sent to a live endpoint. The step is done when a rerun against the recorded files produces identical results and a deliberate change to a response text causes the expected test to fail.

Catching regressions from prompt edits, flow changes and library upgrades

A unit test suite earns its place when it fails on the change that weakens a guardrail, not weeks later in production. Three kinds of change move guardrail behavior silently: a rewrite of a prompt in config.yml or a prompt template, an edit to a Colang flow that changes which user intent triggers which rail, and an upgrade of the NeMo Guardrails library itself. Each one should run through the same pinned policy tests (the FakeLLMModel, RecordingHTTPClient and TestChat cases described above) before it reaches a shared branch. Treat a failing assertion after a prompt rewrite as a finding to review, not as test noise to adjust away. Keep the expected outcome for every blocked or allowed input in version control next to the configuration, so a reviewer can see exactly which behavior changed.

The upgrade path needs the most planning. NeMo Guardrails 0.25.0 deprecates the LLMRails class in favor of Guardrails, and the planned removal is no earlier than 0.27.0, according to the release notes for 0.25.0. Confirm the exact removal version against the NeMo Guardrails releases page before you set a deadline. Run the suite once on the current version to establish a baseline, then again after switching the entry point, so any difference in rail outcomes is visible as a test failure. Pin the library version in your lock file and make upgrades a reviewed change with its own test run, not an incidental side effect of a dependency refresh.

Colang migrations need the strictest handling. NVIDIA documents a Colang 1.0 to 2.x conversion using the nemoguardrails convert tool and states that converted configurations still need manual review. Write the test expectations before you convert, run them against the Colang 1.0 configuration, then run the converted configuration against the same expectations. Any test that changes outcome is a behavior change you must approve explicitly. Do not accept a converted file because it loads without error. Loading only shows the syntax is valid, not that the rails still block what they blocked before. Gate the migration branch in CI on the full suite passing, and keep the Colang 1.0 tests in the repository until the migration is signed off.

Running guardrail tests in CI

Which pipeline stages should run NeMo Guardrails unit tests on every merge?

Run the guardrail unit tests in a fast stage that does not depend on a model endpoint, and run it on every merge request and on the main branch. A typical stage installs pinned dependencies, runs the unit suite, and publishes the results. Place it before any container image build or deployment step so a failing policy stops the merge before anything is packaged. Keep slower checks, such as nemoguardrails eval runs or scanner jobs, in a separate scheduled or release stage, since other topics on this site cover them. Confirm with your platform team which runner types, caching rules and merge gates apply in your organization, because those settings decide how long the stage takes in practice.

Which Python and NeMo Guardrails versions should the CI build image pin?

Pin the exact Python interpreter and the exact NeMo Guardrails version in the build image, and change either only through a reviewed commit. NeMo Guardrails 0.25.0 requires Python 3.11, 3.12 or 3.13, so name one of those interpreters explicitly. The package is published on PyPI under Apache-2.0. The current release is 0.25.0, published on 19 November 2026, and the previous release was 0.24.1, published on 16 September 2026. Use a lock file or pinned requirements file instead of a version range, so a library upgrade becomes a deliberate change that triggers the suite. Store the resolved versions with each test report so reviewers can see which library produced each result.

Why should guardrail unit tests avoid live model and network calls?

Replace the model and the network with fakes so each run is deterministic and tests only the configuration. The testing helpers FakeLLMModel, RecordingHTTPClient and TestChat let a test script exactly what the model returns and record what the rails would send to an external service. Live calls make results depend on provider availability, rate limits and model output that changes between runs, so a passing build says little. Block outbound network access in the test stage so an accidental call fails loudly. Fakes show that flows, prompts and rail wiring behave as configured. They do not show how a real model responds to an attack, which is the job of the evaluation and scanning topics. Confirm the helper signatures against the version you pin, since they belong to the library and can change between releases.

Should a failing guardrail assertion block the merge?

Yes. A failing guardrail assertion should fail the job and block the merge, with no override path for policy tests. Each assertion should name the policy it protects, such as a test that an off-topic request is refused by a dialog flow, so the failure message tells the reviewer what weakened. Do not mark guardrail tests as allowed to fail or move them into a non-blocking job, because that turns the suite into a report nobody reads. If a test is flaky, fix its fake or its expected output instead of skipping it. Require security owner approval for any change that removes or loosens an assertion, and make that approval a required review on the test directory.

What test artifacts should CI store for guardrail test runs?

Store enough to reproduce each run and to show an auditor what was tested. Keep the test report, the resolved dependency list, the Git commit identifier, the build image identifier, and a copy or hash of the configuration folder that was tested. Keep logs from failed runs so a reviewer can trace which rail or flow changed behavior. Set the retention period with your compliance team, since the right length depends on your change records and audit cycle. Restrict who can read the artifacts if the logs contain sample prompts that include sensitive content, and avoid storing real customer data in test fixtures.

Can CI run the same guardrail tests against the server Docker image?

Yes, and doing so ties the test results to the artifact you deploy. NeMo Guardrails can run as a guardrails server that loads configurations from a folder and exposes an HTTP API, and the project provides a Dockerfile to build a server image. In CI, build that image from the Dockerfile, copy in the same configuration folder used by the library tests, start the container, and point the suite at its HTTP API. Confirm how your server build accepts fake model responses, because that wiring depends on the version you pin. Tag the image with the commit identifier and promote only the tested tag to later stages.

What drives the cost of running guardrail tests in CI?

Most of the cost is engineering time to design fixtures and assertions, plus the runner minutes and upkeep that follow. Building the suite is largely one-time work, while maintenance recurs whenever policies, flows or the pinned library change, since each upgrade may need new fixtures. Runner cost depends on how many jobs run per merge and how long the server image build takes, and caching dependency layers reduces rebuilds. Ask any provider for a written scope that lists the policies covered, the CI platform, the image build, artifact retention and handover to your team. DeployOpen works in fixed-scope engagements agreed in writing before work starts, and a quote follows from that scope. Confirm your policy count and CI platform before estimating effort, because no suite size or duration is set here.

Security and operational considerations for test suites

A guardrail test suite handles credentials, recorded traffic and the policy rules themselves, so it carries its own risks. The cards below cover what to keep out of fixtures, how to govern recordings, who may change policy tests, and where fakes can mislead.

Keep credentials out of fixtures

Test fixtures that call a real model endpoint often pick up an API key from a config file or an environment variable and then get committed or printed in CI logs. Build your tests so the FakeLLMModel never needs a provider key, and reserve real credentials for a separate, opt-in integration job with its own secret store. Ask whether your CI system masks secrets in logs and whether fork or pull request builds can read them. A test that needs a key to pass is also a test that fails for every contributor without one.

Treat recordings as sensitive data

A RecordingHTTPClient captures request and response bodies, which can include user prompts, retrieved documents, internal tool results or personal data copied into a test case. Store recordings under the same access and retention rules as production logs, scrub them before commit, and review new recordings for sensitive content in code review. Decide who may regenerate them, since a fresh recording silently changes what the test expects.

Control who edits policy tests

Tests that pin a rail's refusal behavior are the control that stops a weakened guardrail from merging. If the same developers who tune prompts can also edit those assertions without review, the test stops being an independent check. Protect the test directory with code owners that include the security or compliance owner, and require a named approver for any change that removes or loosens an assertion on a blocked input.

Review test deletions deliberately

A deleted or skipped test is the quietest way to weaken a guardrail, and a large diff can hide it. Configure review so that removed test cases, added skip markers and lowered expectations appear as explicit findings, not as ordinary line changes. Ask reviewers to confirm that each removal has a documented reason, such as a retired policy, and that the policy change itself was approved. Track the total count of policy tests over time so silent shrinkage is visible.

Fakes can hide production behavior

A test that passes against FakeLLMModel proves that your flow logic, routing and action wiring behave as written. It does not prove that a production model will refuse the same input, follow the same self-check prompt or format output the same way. Keep a small set of scheduled tests against the real model you deploy, pin its version where your provider allows, and rerun them after each model or library change. Ask which assertions are fake-only and which are confirmed against the live model.

NeMo Guardrails repository

What buyers ask before hiring help with guardrail unit tests

What drives the cost and effort of a guardrail unit test suite?

The main driver is how many policies and rails the suite must pin, and how many distinct conversation paths each one has. Cost also rises with the number of Colang flows, custom actions that call external services, and whether the configuration uses Colang 1.0 or 2.x. Work splits into scoping the policies, writing fake model and HTTP fixtures so tests run offline, writing the test cases, and wiring the suite into CI. Most of the cost is one-time build effort, followed by a smaller recurring effort for updates. Ask any partner for a written scope that lists the configurations covered, the number of test cases per policy, the fixtures to be built, and the CI system targeted.

Can an internal team build guardrail unit tests without outside help?

Yes, if the team already knows the configuration well and has someone comfortable with Python testing and the NeMo Guardrails Python API. The hard part is not the test runner. It is deciding what behavior counts as the policy, so that each test asserts a real guardrail outcome rather than a string that happens to appear in a reply. Teams often lack time to design fixtures that replace the model and HTTP calls deterministically, and to keep those fixtures current as the configuration changes. An outside partner is usually most useful for the first baseline and the fixture design, after which the internal team maintains the suite.

How long does it take to reach a useful test baseline?

The duration depends on the drivers above rather than on a fixed figure. A small configuration with one or two input rails and a handful of dialog flows needs far less work than a multi-rail assistant with retrieval rails, custom actions and several model backends. The team's familiarity with the framework and the availability of sample policies also change the timeline considerably. Ask for a timeline in the written scope that is tied to named milestones, such as fixtures in place, policy tests passing offline, and CI gating merges, so progress can be checked against each one.

What does the work need from our side to start?

The work needs a few specific inputs. Expect to provide the configuration folder with config.yml, the Colang files and any Python actions, plus the written policies the assistant must follow, even if they are informal. You also need access to a CI system where the tests will run, such as GitLab CI, GitHub Actions or Jenkins, and a named owner who can approve policy interpretations. Sample conversations that represent real traffic are very helpful for choosing test cases. Confirm in the scope which environments the tests may touch, since the suite should run without calling live model endpoints.

What does ongoing maintenance look like after a NeMo Guardrails upgrade?

Maintenance is mostly about re-running the suite after each library release and reviewing failures. NeMo Guardrails publishes new releases on PyPI, and the release notes and version migration guides list changes that can affect configuration, Python APIs and actions. Each upgrade may require updating fixtures, adjusting expected outcomes that were correct only for an older behavior, or changing imports when classes are deprecated. A failing test after an upgrade should be treated as a finding to investigate, not a reason to loosen the assertion. Ask for a written statement of how upgrades are handled, how many upgrade cycles are included in any retainer, and who approves changes to expected outcomes.

Will the tests prove that our guardrails are safe?

No. Unit tests show that specific, named policy behaviors still hold for the cases you chose to pin. They catch regressions when prompts, flows or library versions change, but they do not measure how the assistant behaves against an unknown attacker or a full range of user inputs. That work belongs to evaluation, benchmarking and red teaming. A good scope states which policies are covered and which are out of scope, so that the test results are read for what they show.

What evidence do the tests give to a security or compliance reviewer?

A passing suite gives reviewers a versioned, repeatable record that named guardrail behaviors were checked on a specific configuration and library version. Reviewers usually want the list of policies mapped to tests, the CI history showing that merges are gated on passing results, and the procedure for updating expected outcomes. The tests do not themselves constitute an audit or certification, since independent auditors and certification bodies issue those. Ask the partner to deliver the test inventory and CI configuration in a form your compliance team can retain.

How DeployOpen scopes and delivers guardrail test suites

DeployOpen treats unit tests for a NeMo Guardrails configuration as a deliverable in their own right, written against your policies and kept in your repository. We scope the tests to the rails and flows your assistant depends on, build them with the library's test helpers, and hand over a suite your own team can run in CI after the engagement ends.

How we scope

  • Inventory the rails, Colang flows and actions your configuration uses, and list the behaviors each one must hold
  • Agree which prompt, flow and library upgrade changes the suite must catch before work starts
  • Confirm the Python version, NeMo Guardrails release and CI platform used in your environment
  • Engagements are fixed-scope, with deliverables and timelines agreed in writing before work begins

How we build

  • Write deterministic tests with FakeLLMModel and RecordingHTTPClient so results do not depend on a live model
  • Pin blocked and allowed inputs for each rail, including the boundary cases your policy names
  • Add tests for flow changes and custom actions, and check that refusals are logged as your audit process expects
  • Wire the suite into your CI pipeline so failing guardrail tests block a merge

How we hand over

  • Deliver the test code, fixtures and CI configuration in your own repository under your license terms
  • Document how each test maps to a policy statement, so reviewers can trace coverage
  • Walk your engineers through adding a test for a new rail, prompt change or upgrade
  • Record any behavior we could not pin, with the reason and the owner who should decide on it

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers
  • Update the suite when the NeMo Guardrails release line you run moves forward, including the Colang migration checks
  • Review test failures after prompt or model changes and agree fixes in the same change set
  • Confirm support scope, response expectations and any SLA in the written retainer, since none is set by default

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.