Skip to main content

Seed Tests and Logging In

Why This Matters

Ask an AI to write eight tests and you often get eight different ways of starting a browser, eight copies of the base URL and, behind a login, a password pasted into every file. The suite works once and is a pain to maintain from then on.

Playwright’s test agents solve this with a seed test: one file that shows how every test starts. Selenium AI Agent does the same. You write (or let the agent write) the setup once: the driver, the base URL, the login, the helpers. The planner and the generator follow it, so every generated test is short and looks the same.

The same mechanism answers the other question in this lesson: how does the planner explore an application that sits behind a login, without anyone pasting a password into the chat?

What you will learn

  • What a seed test is and why every generated test should follow one
  • The seed for the practice shop, line by line
  • How planner_setup_page uses seedTest and setupSteps
  • How to handle logins without putting secrets in the chat, the plan or the code

A seed for the shop

In a pytest project the seed is usually tests/conftest.py: pytest loads it automatically, and its fixtures are available in every test. This is the seed for the shop:

"""Seed for the practice shop: a fresh Chrome per test, the shop opened, and the helpers every test uses."""
import os

import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

BASE_URL = os.environ.get("SHOP_URL", "https://practiceautomatedtesting.com/shopping")


def tid(test_id: str):
    """Locator for a data-testid, the most stable locator the shop offers."""
    return (By.CSS_SELECTOR, f'[data-testid="{test_id}"]')


class Shop:
    """What the tests do in the shop, in the words of the plan."""

    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, 10)

    def find(self, test_id):
        return self.wait.until(EC.presence_of_element_located(tid(test_id)))

    def visible(self, test_id):
        return self.wait.until(EC.visibility_of_element_located(tid(test_id)))

    def click(self, locator):
        element = self.wait.until(EC.element_to_be_clickable(locator))
        self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", element)
        element.click()

    def cart_text(self) -> str:
        return " ".join(self.find("cart-button").text.split())

    def add_to_cart(self, product_id: int):
        self.click(tid(f"add-to-cart-{product_id}"))

    def wait_for_cart(self, count: int, total: str):
        self.wait.until(lambda d: f"{count} items" in self.cart_text() and total in self.cart_text())


@pytest.fixture
def shop():
    options = webdriver.ChromeOptions()
    if os.environ.get("HEADLESS") == "1":
        options.add_argument("--headless=new")
    driver = webdriver.Chrome(options=options)  # Selenium Manager finds the driver
    driver.set_window_size(1400, 1000)
    driver.get(BASE_URL)
    try:
        yield Shop(driver)
    finally:
        driver.quit()

Look at what this file decides, so that no generated test has to:

DecisionIn the seed
One fresh browser per test@pytest.fixture without a scope: a new Chrome for every test, quit() afterwards, even when the test fails
No driver paths or driver managerswebdriver.Chrome(options=...): Selenium Manager finds the driver
Headless in CIHEADLESS=1 adds --headless=new
Base URL in one placeSHOP_URL overrides it, for a test environment
Explicit waits onlyWebDriverWait everywhere; no implicitly_wait, no sleep
Stable locatorstid() for test ids
The words of the planadd_to_cart, wait_for_cart: a step in the plan is one line in the test

Every one of these is also one of Selenium’s rules for AI agents (lesson 13). The seed makes it easy for the generator to follow them.

The seed grows with the plan. The checkout tests in lessons 10 and 15 use three more helpers, open_product, open_checkout and order_summary, which the generator adds to the seed when it writes those tests, in the same style: wait for the element, then act. Tests can also import tid (from conftest import tid) for a locator the helpers don’t cover.

With this seed, the generated test for plan scenario 1.1 is this short:

"""Plan 1.1: Add a product from the grid (specs/shopping-cart-and-checkout.md)."""
from selenium.webdriver.common.by import By


def test_add_from_grid(shop):
    # 1. Open the shop (done by the shop fixture)
    # expect: The heading shows "Search Results (10 products)"
    heading = shop.driver.find_element(By.XPATH, "//h2[contains(., 'Search Results')]").text
    assert "Search Results (10 products)" in " ".join(heading.split())
    # expect: The cart button shows "0 items" and "$0.00"
    assert "0 items" in shop.cart_text() and "$0.00" in shop.cart_text()

    # 2. Click "Add to Cart" for the Mechanical Keyboard
    shop.add_to_cart(2)
    # expect: The cart button shows "1 items"
    # expect: The cart total is "$89.99"
    shop.wait_for_cart(1, "$89.99")

How the agent uses the seed

There are two ways to give the agent a seed.

Name it when planning. planner_setup_page takes a seedTest:

{
  "url": "https://practiceautomatedtesting.com/shopping",
  "feature": "Shopping cart and checkout",
  "explorationDepth": "single_page",
  "seedTest": "tests/conftest.py"
}

The tool returns the seed’s content, and the planner records it in the plan as the Seed: of the suite. The generator reads that line and writes every test of the suite in the seed’s style.

Register it once. generator_write_seed saves a seed file and registers it in .test-manifest.json under seedTests, with a description. From then on planner_setup_page uses it by default, and healer_run_tests runs seed tests first. You can ask the generator to write the seed for you: “Write a pytest seed for the shop: a fresh Chrome per test, the base URL from SHOP_URL, and helpers for adding to the cart.”

Applications behind a login

The shop needs no login. Most real applications do. The planner can’t explore what it can’t reach, so planner_setup_page takes setup steps: actions it runs in the browser before exploring.

{
  "url": "https://the-internet.herokuapp.com/login",
  "feature": "Secure area",
  "explorationDepth": "section",
  "setupSteps": [
    { "action": "fill",  "selector": "#username", "value": "tomsmith" },
    { "action": "fill",  "selector": "#password", "value": "SuperSecretPassword!" },
    { "action": "click", "selector": "button[type='submit']" },
    { "action": "wait",  "selector": "#flash.success" }
  ]
}

The actions are navigate, fill, click, select, press and wait. This example uses the public demo account of the-internet, which is printed on the page itself. That is the only kind of password that belongs in a chat.

Logging in without sharing secrets

For a real application the password is a secret, and secrets don’t belong in a chat, a plan or a test file. Three approaches work, from simplest to most robust:

  1. A test account from the environment. The seed reads TEST_USER and TEST_PASSWORD from environment variables (or a .env file that git ignores) and logs in in a fixture. The AI writes os.environ["TEST_PASSWORD"] and never sees the value.
  2. A logged-in browser profile. Log in once by hand in a separate Chrome profile; the seed starts Chrome with --user-data-dir pointing at it. Useful when the login has multi-factor authentication. Keep the profile folder out of git.
  3. A token flow. Some platforms (Salesforce, Azure AD) offer a login with a certificate or token for automated tests. The seed does the token exchange; the secret lives in the CI’s secret store.

The planner agent’s own instructions say the same: ask the user for test credentials; never invent real ones. And guardrail 8 from lesson 4 applies: the files the agent writes stay in your project folder, so a secret in a seed file is exactly as safe as your git ignore rules make it.

Warning: never paste a production password into the chat “just to explore”. The chat may be logged, the plan may be committed, and a generated test may contain it. Use a test account on a test environment.

Exercise

The-internet’s login page (https://the-internet.herokuapp.com/login) has a public demo account.

  1. Write a pytest seed conftest.py with a fixture logged_in that opens the login page, logs in with credentials from the environment variables INTERNET_USER and INTERNET_PASSWORD, waits for the success message and yields the driver.
  2. Which line in your seed would a generated test for “log out” use, and which would it never repeat?
Show suggested answer
import os

import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

LOGIN_URL = "https://the-internet.herokuapp.com/login"


@pytest.fixture
def logged_in():
    driver = webdriver.Chrome()
    try:
        driver.get(LOGIN_URL)
        driver.find_element(By.ID, "username").send_keys(os.environ["INTERNET_USER"])
        driver.find_element(By.ID, "password").send_keys(os.environ["INTERNET_PASSWORD"])
        driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
        WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#flash.success")))
        yield driver
    finally:
        driver.quit()

Run it with INTERNET_USER=tomsmith INTERNET_PASSWORD='SuperSecretPassword!' pytest. A generated “log out” test takes logged_in as its parameter and starts at the secure area; it never repeats the login lines, the URL or the credentials.

Exam-style questions

Quiz

1. What is the main purpose of a seed test?

  • A. To run before every CI build to warm up the browser
  • B. To show once how every test starts (driver, base URL, login, helpers), so generated tests follow it
  • C. To store the test data
  • D. To replace the test plan
Show answer
B.
Quiz

2. The planner must explore pages behind a login. What is the right way?

  • A. Paste the production password into the chat
  • B. Put the password in the plan’s Overview
  • C. Use setupSteps with a test account, or a seed that reads credentials from the environment
  • D. Turn off the login in production
Show answer
C.
Quiz

3. Why does the shop’s seed create a new browser for every test instead of one per session?

  • A. It is faster
  • B. Each test starts from a known, clean state, and one failing test cannot break the next
  • C. Selenium cannot reuse a browser
  • D. pytest requires it
Show answer
B. It is slower, but independent. Selenium’s rules for AI agents ask for one fresh session per test for the same reason.