Run Playwright Python Tests Against Multiple Environments
The same test suite usually has to run against several copies of an application: a QA server, a staging server before release and, carefully, production after release. Copying tests per environment is a maintenance trap. In this lesson you will run one suite anywhere by changing a single command-line option: use --base-url and relative URLs, add a custom --env option with pytest_addoption, keep each environment’s URL, users and flags in one config file, load per-environment .env secrets, and stop destructive tests from ever touching production.
📖 What You’ll Learn: why environments need configuration not code, relative URLs with base_url, the –base-url option and pytest.ini, a custom –env option with pytest_addoption, an environments.json config file, an env_config fixture that also drives base_url, per-environment .env files, markers that skip tests by environment, a production safety guard, and printing the environment in the report header.
🌍 One Suite, Many Environments
A typical company has at least these environments:
| Environment | Purpose | What tests may do |
|---|---|---|
| local / dev | A developer’s machine | Anything |
| QA | Shared test server | Create and delete test data |
| staging | Copy of production before a release | Mostly read; limited test data |
| production | Real users | Read-only smoke tests only |
The URLs, accounts and rules differ; the tests stay the same. The goal of this lesson is a command like:
⌨️ Terminal
pytest --env qa
pytest --env staging -m smoke
pytest --env prod -m smoke
🔗 Step 1: Relative URLs and –base-url
pytest-playwright (through the pytest-base-url plugin) gives every test a base_url. When it is set, page.goto() accepts relative URLs and joins them to it:
📄 pytest.ini
[pytest]
base_url = https://sqatools.in
markers =
smoke: quick checks that are safe on every environment
destructive: creates, changes or deletes data
only_env(*names): run only on the named environments
📄 tests/test_relative.py
from playwright.sync_api import Page, expect
def test_store_home(page: Page, base_url):
page.goto("/dummy-ecommerce-website/") # becomes https://sqatools.in/dummy-ecommerce-website/
print("\nopened", page.url, "with base_url", base_url)
expect(page.get_by_test_id("logo")).to_be_visible()
⌨️ Terminal
pytest tests/test_relative.py -q -s
🖥️ Output
opened https://sqatools.in/dummy-ecommerce-website/ with base_url https://sqatools.in
.
1 passed in 2.52s
The command line beats the ini file, so pytest --base-url https://staging.example.com would run the same test on another host. Rule number one for multi-environment suites: never hard-code a host name in a test.
📌 Note: The base_url value from pytest.ini is also applied to context.new_page() and to the page fixture through browser_context_args, so every page in the test uses it.
⚙️ Step 2: A Custom –env Option
A URL alone is not enough: environments also differ in accounts, feature flags and what is allowed. Add a single --env option and keep the details in a config file.
📄 environments.json
{
"qa": {
"base_url": "https://sqatools.in",
"shop_path": "/dummy-ecommerce-website/",
"user": "testuser",
"read_only": false
},
"staging": {
"base_url": "https://sqatools.in",
"shop_path": "/dummy-ecommerce-website/",
"user": "testuser",
"read_only": false
},
"prod": {
"base_url": "https://sqatools.in",
"shop_path": "/dummy-ecommerce-website/",
"user": "testuser",
"read_only": true
}
}
📌 Note: SQA Tools has a single public practice site, so all three entries point at it and you can run every command in this lesson. In your project each entry would have its own host, for example https://qa.shop.example.com.
Since the host now comes from the config file, remove base_url from pytest.ini (otherwise pytest-base-url copies it into the --base-url option, and the option would always win):
📄 pytest.ini
[pytest]
markers =
smoke: quick checks that are safe on every environment
destructive: creates, changes or deletes data
only_env(*names): run only on the named environments
The root conftest.py registers the option, loads the matching entry once per session, and overrides the base_url fixture so the URL comes from the config:
📄 conftest.py
import json
import os
from dataclasses import dataclass
from pathlib import Path
import pytest
from dotenv import load_dotenv
ROOT = Path(__file__).parent
def pytest_addoption(parser):
parser.addoption("--env", default=os.getenv("TEST_ENV", "qa"), choices=["qa", "staging", "prod"],
help="target environment (default: qa, or $TEST_ENV)")
@dataclass(frozen=True)
class EnvConfig:
name: str
base_url: str
shop_path: str
user: str
read_only: bool
password: str
@pytest.fixture(scope="session")
def env_config(pytestconfig) -> EnvConfig:
name = pytestconfig.getoption("--env")
data = json.loads((ROOT / "environments.json").read_text(encoding="utf-8"))[name]
load_dotenv(ROOT / f".env.{name}") # per-environment secrets, if the file exists
password = os.getenv("SHOP_PASSWORD", "")
return EnvConfig(name=name, password=password, **data)
@pytest.fixture(scope="session")
def base_url(env_config, pytestconfig) -> str:
# an explicit --base-url still wins, which is handy for one-off runs
return pytestconfig.getoption("base_url") or env_config.base_url
def pytest_report_header(config):
return f"target environment: {config.getoption('--env')}"
Two details matter:
default=os.getenv("TEST_ENV", "qa")lets CI choose the environment with a variable instead of editing the command.choices=[...]makes a typo such as--env staginfail immediately with a clear argparse error.
Secrets come from .env.qa, .env.staging and .env.prod (all git-ignored, see Lesson 47):
📄 .env.qa
SHOP_PASSWORD=Test@123
📄 .env.staging
SHOP_PASSWORD=Test@123
📄 .env.prod
SHOP_PASSWORD=Test@123
🧪 Step 3: Tests That Use the Config
📄 tests/test_shop.py
import pytest
from playwright.sync_api import Page, expect
@pytest.mark.smoke
def test_store_loads(page: Page, env_config):
page.goto(env_config.shop_path)
expect(page.get_by_test_id("product-card").first).to_be_visible()
@pytest.mark.smoke
def test_user_can_log_in(page: Page, env_config):
page.goto(env_config.shop_path + "#/login")
page.get_by_test_id("login-username").fill(env_config.user)
page.get_by_test_id("login-password").fill(env_config.password)
page.get_by_test_id("login-button").click()
expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")
@pytest.mark.destructive
def test_place_order(page: Page, env_config):
page.goto(env_config.shop_path + "#/search/earbuds")
page.get_by_role("button", name="Add to cart").first.click()
expect(page.get_by_test_id("cart-count")).to_have_text("1")
@pytest.mark.only_env("qa")
def test_qa_only_feature(page: Page, env_config):
page.goto(env_config.shop_path + "#/deals")
expect(page.get_by_test_id("product-card").first).to_be_visible()
⌨️ Terminal
pytest tests/test_shop.py --env qa -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
target environment: qa
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 4 items
tests/test_shop.py::test_store_loads[chromium] PASSED [ 25%]
tests/test_shop.py::test_user_can_log_in[chromium] PASSED [ 50%]
tests/test_shop.py::test_place_order[chromium] PASSED [ 75%]
tests/test_shop.py::test_qa_only_feature[chromium] PASSED [100%]
============================= 4 passed in 10.29s ==============================
The header line target environment: qa comes from pytest_report_header. It makes every CI log and HTML report state which environment was tested.
🛡️ Step 4: Protect Production
Nobody should be able to place orders or delete data on production by running the wrong command. A collection hook skips destructive tests on read-only environments and applies only_env markers:
📄 tests/conftest.py
import json
from pathlib import Path
import pytest
ENVIRONMENTS = json.loads((Path(__file__).parent.parent / "environments.json").read_text(encoding="utf-8"))
def pytest_collection_modifyitems(config, items):
env = config.getoption("--env")
read_only = ENVIRONMENTS[env]["read_only"]
for item in items:
if read_only and item.get_closest_marker("destructive"):
item.add_marker(pytest.mark.skip(reason=f"destructive test blocked on read-only environment '{env}'"))
only = item.get_closest_marker("only_env")
if only and env not in only.args:
item.add_marker(pytest.mark.skip(reason=f"runs only on {', '.join(only.args)}"))
⌨️ Terminal
pytest tests/test_shop.py --env prod -v -rs
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
target environment: prod
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 4 items
tests/test_shop.py::test_store_loads[chromium] PASSED [ 25%]
tests/test_shop.py::test_user_can_log_in[chromium] PASSED [ 50%]
tests/test_shop.py::test_place_order[chromium] SKIPPED (destructive ...) [ 75%]
tests/test_shop.py::test_qa_only_feature[chromium] SKIPPED (runs onl...) [100%]
=========================== short test summary info ===========================
SKIPPED [1] tests\test_shop.py:20: destructive test blocked on read-only environment 'prod'
SKIPPED [1] tests\test_shop.py:27: runs only on qa
======================== 2 passed, 2 skipped in 6.59s =========================
On prod the order test and the QA-only test are skipped with clear reasons (-rs prints them), and the smoke tests still run. The guard lives in one place, so a new destructive test is protected as soon as it is marked.
⚠️ Watch out: Skipping is a safety net, not a permission system. Production test accounts should also be restricted on the server side, so a mistake in the hook cannot do real damage.
🔀 Choosing the Environment Without the Option
Because the default comes from TEST_ENV, these are equivalent:
⌨️ Terminal
pytest --env staging
$env:TEST_ENV = "staging"; pytest # PowerShell
TEST_ENV=staging pytest # macOS / Linux
⌨️ Terminal
$env:TEST_ENV = "staging"; pytest tests/test_shop.py -m smoke
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0
target environment: staging
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collected 4 items / 2 deselected / 2 selected
tests\test_shop.py .. [100%]
======================= 2 passed, 2 deselected in 4.50s =======================
The report header shows target environment: staging. A one-off override of only the host also still works, because the base_url fixture checks --base-url first:
⌨️ Terminal
pytest --env qa --base-url https://qa2.shop.example.com
🧭 What Belongs Where
| Kind of value | Where it lives |
|---|---|
| Host names, paths, feature flags, read-only flag | environments.json (committed) |
| Passwords, API keys, tokens | .env.<env> locally, CI secrets in pipelines (never committed) |
| Which environment to test | --env option or TEST_ENV variable |
| Test inputs and expected results | data files (Lesson 46) |
🏋️ Practice Exercises
Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.
Exercise 1: Add a boolean field slow_network to each environment in environments.json and a fixture that sets the default navigation timeout to 60 seconds when it is true. Write the fixture.
Show answer
import pytest
from playwright.sync_api import Page
@pytest.fixture(autouse=True)
def env_timeouts(page: Page, env_config):
if getattr(env_config, "slow_network", False):
page.set_default_navigation_timeout(60_000)
yieldAdd slow_network: bool = False to the EnvConfig dataclass so the JSON field is accepted. autouse=True applies it to every test without changing them.
Exercise 2: Write a test marker prod_only and the hook code that skips such tests on every environment except prod.
Show answer
# pytest.ini: markers = prod_only: runs only against production
def pytest_collection_modifyitems(config, items):
env = config.getoption("--env")
for item in items:
if item.get_closest_marker("prod_only") and env != "prod":
item.add_marker(pytest.mark.skip(reason="production-only check"))(This is a special case of only_env("prod"); prefer the general marker when you already have it.)
Exercise 3: A teammate runs pytest --env Staging and gets argument --env: invalid choice: 'Staging'. Change the option so the value is case-insensitive.
Show answer
parser.addoption("--env", default=os.getenv("TEST_ENV", "qa"), type=str.lower,
choices=["qa", "staging", "prod"], help="target environment")argparse applies type before checking choices, so Staging becomes staging.
Exercise 4: Why does the lesson override the base_url fixture instead of writing page.goto(env_config.base_url + "/path") in every test?
Show answer
Overriding base_url makes relative goto() calls work everywhere (the page and every new context use it), keeps host names out of tests, and still lets an explicit --base-url win. Concatenating strings in tests repeats the host logic in hundreds of places and breaks easily (double or missing slashes).
🧠 MCQ Quiz: Run Against Multiple Environments
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What does
page.goto("/login")do whenbase_urlishttps://qa.example.com?Answer: Openshttps://qa.example.com/login. With a base URL configured, relative paths are resolved against it. - Which wins:
--base-urlon the command line orbase_urlin pytest.ini?Answer: The command line. Command-line options override ini settings. - Which hook registers a custom option such as
--env?Answer:pytest_addoption.pytest_addoption(parser)adds command-line options and ini keys. - What does
choices=["qa", "staging", "prod"]on the option give you?Answer: An immediate error for an unknown value such asstagin. argparse validates the value againstchoicesbefore any test runs. - Where should production passwords used by smoke tests live?Answer: In git-ignored
.env.prodlocally and in CI secrets. Config files are committed; secrets must stay out of Git. - What is the purpose of
pytest_report_headerin this lesson?Answer: It prints the target environment at the top of every run. The header line makes logs and reports show which environment was tested. - How does the lesson stop destructive tests from running on production?Answer: A
pytest_collection_modifyitemshook adds a skip marker on read-only environments. The hook inspects each test’s markers after collection and skips the dangerous ones. - What does
item.get_closest_marker("only_env")return?Answer: The nearestonly_envmarker (from the test, class or module), orNone. It searches the test and its parents and returns the Mark object, whose.argshold the environment names. - Why give
--enva default ofos.getenv("TEST_ENV", "qa")?Answer: CI can choose the environment with a variable without changing the command. The variable sets the default; the option still overrides it when given. - Why is skipping destructive tests on prod not enough on its own?Answer: A bug or a wrong command could still reach prod; the server should also restrict test accounts. Defence in depth: the client-side guard prevents mistakes, server-side permissions prevent damage.
Want a longer, timed test? Take the Module 7 mock interview (20 MCQs in 20 minutes).
❓ Frequently Asked Questions
🤔 Should I use separate test folders per environment?
No. Separate copies drift apart. Keep one suite and let configuration (and markers such as smoke or destructive) decide what runs where.
🤔 Can I run the suite against two environments in one command?
Not with one session-scoped env_config. Run pytest twice (for example as two CI jobs in a matrix), which also keeps the reports separate. Lesson 66 shows a GitHub Actions matrix.
🤔 Where do I put environment-specific test data, such as product IDs?
Add it to the environment entry in environments.json (or a data file per environment, such as test_data/qa/products.csv) and read it through env_config.
🤔 What is the difference between base_url and env_config.base_url here?
env_config.base_url is the value from the config file. The base_url fixture is what pytest-playwright uses for relative navigation; the lesson’s override returns --base-url if given, otherwise the config value.
🤔 How do I make API tests use the same environment?
Use env_config (or base_url) when you create the API request context: playwright.request.new_context(base_url=env_config.base_url). Module 9 covers API testing.
🏁 Summary
- Never hard-code hosts: use relative
page.goto()withbase_url, which--base-urlcan override. - Add one
--envoption withpytest_addoption(default fromTEST_ENV, validated withchoices). - Keep URLs and flags in a committed
environments.json; keep secrets in git-ignored.env.<env>files or CI secrets. - Override the
base_urlfixture from the environment config and print the environment withpytest_report_header. - Guard production with
destructiveandonly_envmarkers inpytest_collection_modifyitems, plus server-side restrictions.
🎬 Watch the Playwright tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page