Skip to main content

Generate pytest Tests from the Plan

Why This Matters

This is the step most people think of when they hear “AI writes tests”. By now you know it is the smallest step: the plan says what to test, the seed says how a test starts, the review made sure a person agrees. What is left for the generator is translating approved steps into code, and checking that code against the live page before it is saved.

That order is what makes generated tests trustworthy: every assertion traces back to an expect: line a person approved, and every selector was tried in the browser.

What you will learn

  • The generator’s workflow: set up, execute in the browser, write
  • What generator_setup_page returns: framework, rules, reporting
  • How one plan scenario becomes one test file
  • What generator_write_test checks before saving (guardrails 1 to 3 in action)
  • The test manifest, and running the suite

The workflow

You ask:

Use the selenium-test-generator agent to write the tests for specs/shopping-cart-and-checkout.md.

The generator agent then:

  1. Reads the plan with generator_read_spec. A draft plan is refused here already (lesson 8).
  2. Sets up with generator_setup_page: opens the application, starts recording, settles the framework and the report format.
  3. Executes each scenario in the browser: the steps of the plan, with click_element, input_text, capture_page and the verification tools. It sees whether each step works now, and which selectors find the elements.
  4. Reads the recording with generator_read_log: the actions, with the locators that worked.
  5. Writes one test file per scenario with generator_write_test, to the File: the plan names.

Step 3 is the difference with an AI that writes tests from memory: the generator does the test once, for real, before it writes it down.

generator_setup_page

The setup result tells the agent three things it must follow.

The framework. Without a framework named, the tool looks at the project’s build files and reports what it found, for example "frameworkSource": "detected: Python with pytest (pytest.ini)". A Java project with a pom.xml gets JUnit 5 or TestNG, a .NET project NUnit, xUnit or MSTest. Only in an empty project does it fall back to the default, Python with pytest, and say so. Lesson 11 does the same plan in Java and WebdriverIO.

Selenium’s rules for that language. The setup result ends with Selenium’s official rules for AI agents, for Python here: explicit waits, no sleeps, Selenium Manager, Options classes, one fresh session per test, quit() in teardown. The tool adds: generator_write_test rejects code that breaks them.

The report format. JUnit XML by default, Allure when you ask for it or the project already uses it, with what the project needs once and how the results link to the plan (lesson 14).

One scenario, one file

Scenario 2.1 of the plan:

#### 2.1. Totals for two products

**File:** `tests/checkout/test_totals_two_products.py`

**Steps:**
  1. Add the Mechanical Keyboard and the Ergonomic Chair
    - expect: The cart button shows "2 items" and "$289.98"
  2. Open the cart
    - expect: Subtotal $289.98
    - expect: Shipping FREE
    - expect: Tax (21%) $60.90
    - expect: Total $350.88

The generated test, saved to exactly that file:

"""Plan 2.1: Totals for two products (specs/shopping-cart-and-checkout.md)."""


def test_totals_two_products(shop):
    # 1. Add the Mechanical Keyboard and the Ergonomic Chair
    shop.add_to_cart(2)
    shop.wait_for_cart(1, "$89.99")
    shop.add_to_cart(10)
    # expect: The cart button shows "2 items" and "$289.98"
    shop.wait_for_cart(2, "$289.98")

    # 2. Open the cart
    shop.open_checkout()
    summary = " ".join(shop.order_summary().split())
    # expect: Subtotal $289.98
    assert "Subtotal: $289.98" in summary
    # expect: Shipping FREE
    assert "Shipping: FREE" in summary
    # expect: Tax (21%) $60.90
    assert "Tax (21%): $60.90" in summary
    # expect: Total $350.88
    assert "Total: $350.88" in summary

Check it against the plan the way a reviewer would:

  • The docstring names the plan and the scenario.
  • Every step is a comment, followed by its code.
  • Every expect: is a comment, followed by exactly the check that proves it, with the plan’s own values.
  • The test uses the seed’s shop fixture and helpers (lesson 7): no driver setup, no URL, no waits of its own.
  • One thing the plan didn’t say: shop.wait_for_cart(1, "$89.99") between the two products. The cart updates after the click returns (lesson 3), so the test waits for the first product to land before it adds the second. A detail like this shows up when you do the test once in the browser, and it makes the test reliable without changing what it checks.

Another scenario, 2.4, shows the same pattern with a form:

"""Plan 2.4: Pay with iDeal (specs/shopping-cart-and-checkout.md). Test data only."""
from selenium.webdriver.support.ui import Select

from conftest import tid

BILLING = {
    "billing-firstname": "Test",
    "billing-lastname": "Demo",
    "billing-email": "test.demo@example.com",
    "billing-phone": "+31 20 000 0000",
    "billing-address": "Teststraat 1",
    "billing-city": "Amsterdam",
    "billing-zipcode": "1011 AB",
}
CARD_FIELDS = ("card-number", "card-name", "card-expiry", "card-cvv")


def test_pay_ideal(shop):
    shop.add_to_cart(10)
    shop.wait_for_cart(1, "$199.99")
    shop.open_checkout()

    # 1. Fill in the billing fields with test data
    for test_id, value in BILLING.items():
        shop.find(test_id).send_keys(value)
    Select(shop.find("billing-country")).select_by_visible_text("Netherlands")
    # expect: All billing fields show the entered values
    for test_id, value in BILLING.items():
        assert shop.find(test_id).get_attribute("value") == value

    # 2. Choose iDeal
    shop.click(tid("payment-ideal"))
    # expect: A bank choice appears
    bank = Select(shop.visible("ideal-bank"))
    # expect: The card fields disappear
    for test_id in CARD_FIELDS:
        assert not shop.driver.find_elements(*tid(test_id))

    # 3. Choose the bank ING and click "Place Order"
    bank.select_by_visible_text("ING")
    shop.click(tid("place-order"))
    # expect: "Payment Successful!" is shown
    assert shop.visible("payment-success").text == "Payment Successful!"

The test data is obviously fake (Teststraat 1, a +31 20 000 0000 phone number), exactly as the plan specified. Generated tests should never contain data that looks real.

What generator_write_test checks

Before a file is written, generator_write_test runs the guardrails from lesson 4 in this order:

  1. The plan (specFile): approved, or the test is refused. Under guided and strict a test without a plan is refused too.
  2. Selenium’s rules: a rule error refuses the test (lesson 13).
  3. Locked locators (strict only): every locator must be in the locked set (lesson 12).
  4. Live selector check (verify): each selector in the code is tried in the browser; the ones that match nothing are reported.

Only then is the file written and recorded in the manifest. Under guided and strict the result ends with a reminder that the test is not verified yet (lesson 17).

The manifest

generator_write_test records each test in .test-manifest.json, next to everything the healer and the CI gate need later: the framework, the run command, the seed tests and the report format. A real entry:

{
  "file": ".../tests/cart/test_add_from_grid.py",
  "framework": "selenium-python-pytest",
  "createdAt": "2026-11-19T15:27:59.021Z",
  "specFile": "specs/shopping-cart-and-checkout.md"
}

Under guided and strict the entry also holds specHash (the approved plan’s hash, for the spec lock), codeHash (the file as the agent wrote it) and, after verify_test_stability, a verification. Commit the manifest with the tests.

Run the suite

Through the agent:

Run the tests with healer_run_tests.

healer_run_tests reads the run command from the manifest (for the shop: pytest -v with JUnit XML in reports/), runs the seed tests first when they are registered, and returns the results linked to the plan (lesson 14).

Or yourself, without any AI:

pytest -v

That is the point of the whole pipeline: the output is ordinary pytest code that runs anywhere, without the agent, without an LLM.

Exercise

  1. Approve your search-and-filters plan from lessons 6 and 8 if you haven’t, and ask the generator to write its tests.
  2. Pick one generated test and check it against its scenario: does every expect: have exactly one check, right after its step, with the plan’s own value?
  3. Find one thing in a generated test that the plan didn’t say (like the extra wait in 2.1). Is it a good addition?
  4. Run the tests with pytest -v in a terminal, without the agent.
Show suggested answer
  1. Typical problems to look for: an expect: without a check (the test proves less than the plan), a check without an expect: (the test checks something nobody approved), or a value that differs from the plan’s (“2 products” where the plan says “Search Results (2 products)”). Ask the generator to fix them: “Test 1.3 has no check for the second expect line.”
  2. Good additions make the test reliable: a wait for a condition the next step depends on, scrolling an element into view, waiting for a list to reload after a filter. Bad additions change what is tested: an extra assertion on something the plan doesn’t mention. Those belong in the plan first.
  3. The tests run the same with or without the agent. If they only pass when the agent runs them, something is wrong in the seed or the run command.

Exam-style questions

Quiz

1. Why does the generator execute each scenario in the browser before writing the test?

  • A. To make the AI faster
  • B. To see that each step works now and which selectors find the elements, instead of writing from memory
  • C. Because pytest requires it
  • D. To approve the plan
Show answer
B.
Quiz

2. Where does the generator save the test for a plan scenario?

  • A. Always in tests/test_generated.py
  • B. In the file the scenario’s File: line names
  • C. In specs/
  • D. Wherever the AI decides
Show answer
B. That is also how the report links each result to its scenario (lesson 14).
Quiz

3. In which order does generator_write_test check a new test?

  • A. Selectors, rules, plan
  • B. Plan, Selenium’s rules, locked locators (strict), then the live selector check
  • C. Only the rules
  • D. Only the plan
Show answer
B.