Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Test automation · Python & pytest · Chapter 02 / 02

Test automation learning path

Python environment & project setup

Virtual environments, dependency installation, project layout, typed settings and a run configuration the whole team shares.

Virtual environments: what venv actually does

A virtual environment is a project-local Python runtime boundary. It separates this project's interpreter and installed packages from other Python projects on the same machine.

When you run python -m venv .venv, Python creates an environment directory on top of the Python installation that ran the command. The environment gets its own Python executable, its own site-packages directory for installed packages, and activation scripts. It is isolated from the base interpreter's installed packages by default. This is why project A can use one pytest or Playwright version while project B uses another without the two installations fighting each other.

The .venv directory is generated runtime state, not project source. Treat it as disposable: create it locally, delete and recreate it when necessary, and do not commit or copy it between machines. The reproducible part belongs in version control: pyproject.toml declares the project and its dependencies; CI or another developer creates a fresh environment and installs from that declaration.

Create and activate it

Windows PowerShell:

py -m venv .venv
.\.venv\Scripts\Activate.ps1

Linux/macOS:

python3 -m venv .venv
source .venv/bin/activate

Activation does not create or start a special Python process. It mainly puts the environment's Scripts directory on Windows, or bin directory on POSIX, at the front of PATH. After that, python, pip, pytest and other installed command-line tools resolve to this environment first. Activation is convenient but not required: you can invoke the environment's Python executable directly.

Verify which Python and pip you are using

python -c "import sys; print(sys.executable); print(sys.prefix); print(sys.base_prefix)"
python -m pip --version

Inside a virtual environment, sys.prefix points at .venv while sys.base_prefix points at the base Python used to create it. Using python -m pip is deliberately explicit: it runs pip through the same interpreter selected by python, which avoids the common situation where python comes from one installation and a bare pip command comes from another.

Install the automation project, not the environment directory

The reference framework declares its Python requirement and dependencies in pyproject.toml. For local development it is installed in editable mode:

python -m pip install -e .
playwright install chromium
pytest tests/services -q

-e . tells pip to install the project in editable/development mode: dependencies are installed into the current environment, while imports of the project itself resolve to the working source tree, so changing framework code does not require reinstalling it after every edit. The reference framework uses the same pyproject.toml as the single dependency declaration instead of maintaining a second hand-written requirements.txt for the same package set.

Mental model

Machine
├── Base Python
│   └── used to create environments
│
├── project-a/
│   ├── pyproject.toml   <- committed dependency/project definition
│   └── .venv/          <- generated, disposable, not committed
│       ├── Python executable
│       └── site-packages/ (pytest, Playwright, ...)
│
└── project-b/
    ├── pyproject.toml
    └── .venv/          <- independent packages and versions

The important distinction is therefore environment versus dependency definition: .venv is one concrete local installation; pyproject.toml is the version-controlled instruction from which an installation can be created. A second developer or CI runner should recreate the environment, not receive yours.

Common mistakes

  • Creating .venv and then continuing to use a globally installed python or pip; verify the executable when something looks inconsistent.
  • Assuming activation installs dependencies. It only changes command resolution; installation is a separate step.
  • Committing .venv/ to Git or copying it to another path or machine. Virtual environments contain absolute interpreter paths and are designed to be recreated.
  • Treating venv, pip and pyproject.toml as competing tools. They solve different problems: environment isolation, package installation, and project/dependency declaration.
  • Adding a second dependency file by habit when pyproject.toml already owns the project's dependencies; use an additional lock/requirements workflow only when the project deliberately needs one.

Project layout and the conftest hierarchy

Separate reusable library code from tests, and let each layer's conftest own only its own fixtures.

A maintainable suite separates two kinds of code: a framework package containing reusable machinery, and a tests tree containing only intent. The framework holds configuration, an HTTP client, page and screen objects, data factories and reporting helpers; the tests hold assertions and business flow and nothing else. Fixtures are then layered with the directory structure. A root conftest owns everything shared — application lifecycle, command-line options, reporting hooks — and each layer's own conftest owns only what that layer needs. Fixtures are inherited downwards and never sideways, which produces a concrete benefit: running only the service tests takes seconds on a machine with no browsers and no mobile tooling installed, because nothing on that path imports them. To keep that true, put imports for optional layers inside the fixture function rather than at module top level, so collection succeeds even when the dependency is absent.

Key points

  • Framework code and test code are different things and belong in different trees
  • Root conftest owns shared lifecycle and hooks; each layer's conftest owns only its own fixtures
  • Import optional dependencies inside fixtures so collection works without browsers or devices installed

Code

# conftest.py                  root: app lifecycle, CLI options, report hooks
# tests/services/conftest.py   ApiClient, service facade, personas
# tests/web/conftest.py        browser context tuning, storage state, page objects
# tests/mobile/conftest.py     Appium driver, screen objects

# tests/mobile/conftest.py
@pytest.fixture
def driver(request):
    # Imported inside the fixture, not at module top level: a laptop without
    # Appium installed can still collect and run every other layer.
    from framework.mobile.driver_factory import create_driver

    session = create_driver()
    try:
        yield session
    finally:
        session.quit()

Layered conftests keep the fast layers fast and independent of the slow ones.

See it in the framework

  • Implementation · Root conftest: conftest.py — live · reviewed
  • Used by · Services conftest: tests/services/conftest.py — live · reviewed
  • Used by · Web conftest: tests/web/conftest.py — live · reviewed
  • Used by · Mobile conftest: tests/mobile/conftest.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • One giant conftest at the root that every layer must load, which couples unrelated layers together
  • Importing an optional driver at module level, so a developer without it cannot even collect the suite

Practice exercise

In a suite you work with, try running only the API tests on a machine or container with no browser installed. If it fails to collect, find the import that caused it and move it inside the fixture that needs it.

Typed, layered configuration

No test reads the environment directly; every setting is a typed field with one obvious place to change it.

Reading configuration straight from environment variables scatters string parsing and default values across a whole suite, and turns a mistake into a None that surfaces hours later as an unrelated failure. A typed settings object fixes all three problems at once. Values are validated when the process starts, so an invalid value on a real field is an immediate startup error with the field name in it — and, once the settings model rejects unknown keys instead of silently dropping them, a mistyped key in a config layer fails the same way. Types are real, so a timeout is a float and a flag is a boolean rather than the string "false" which is truthy; and every option is discoverable by reading one class instead of grepping for os.environ. Layer the sources so that a single variable switches environments: real environment variables win, then a local dotenv file, then a per-environment configuration file committed to the repository, then the field defaults — but don't assume your settings library gives you that order for free. Pydantic Settings, for example, ranks constructor arguments above environment variables by default, and a YAML layer is usually merged in as constructor kwargs, so without an explicit override it would silently outrank the environment variables it's supposed to lose to. Credentials never belong in the repository — commit an example file that documents the shape, and keep the real values in a secret store.

Key points

  • An invalid value for a real field, or an unknown key in a config layer, is an immediate startup error naming the field — not a None found hours later
  • Types are real: a timeout is a float, a flag is a boolean, not the truthy string "false"
  • Layered sources don't order themselves — env vars, dotenv, and a YAML/init layer must be ranked explicitly, or your settings library's own default order wins instead

Code

class ApiSettings(BaseModel):
    base_url: str = "http://127.0.0.1:8000"
    timeout: float = 10.0
    retries: int = Field(default=2, ge=0, le=5)


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_prefix="QA_", env_nested_delimiter="__", extra="forbid"
    )

    env: Env = Env.LOCAL
    api: ApiSettings = ApiSettings()

    @classmethod
    def settings_customise_sources(cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings):
        # Pydantic ranks init kwargs first by default. The YAML layer below is
        # passed in as init kwargs, so without this override it would silently
        # outrank real env vars -- the opposite of the precedence above.
        return (env_settings, dotenv_settings, init_settings, file_secret_settings)


yaml_overrides = {...}  # loaded from config/<env>.yaml
settings = Settings(**yaml_overrides)

# In a test or a page object:
#   settings.api.timeout       -> 10.0, a real float, autocompleted, validated
# Not:
#   float(os.getenv("API_TIMEOUT", "10"))   scattered in forty places

Precedence isn't automatic: environment variables must be ranked above the YAML layer explicitly, or Pydantic Settings' default order (constructor kwargs first) reverses it.

See it in the framework

  • Implementation · Settings implementation: framework/config.py — live · reviewed
  • Used by · Per-environment YAML: config/local.yaml — live · reviewed
  • Used by · Precedence unit tests: tests/framework/test_config.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Reading os.environ inside tests, which scatters defaults and parsing across the whole suite
  • Treating an environment variable as a boolean without converting it — the string "false" is truthy in Python
  • Assuming your documented source precedence is what the library does by default — Pydantic Settings ranks constructor kwargs above environment variables unless you override the source order explicitly

Practice exercise

Search a suite you work with for direct environment reads. Replace them with a single typed settings object, then set an invalid value on purpose and confirm the run fails immediately with a message naming the field. Then prove the precedence itself: set the same setting via an environment variable and via a lower-priority source (a config file merged in as constructor kwargs, for example) at the same time, and assert the environment variable wins — check your settings library's default source order, because it may not be what you assumed.

Making the run reproducible and strict

Put shared flags in configuration, promote warnings to errors, and keep environment-specific flags in CI.

A run should behave the same for every engineer and for the pipeline, which means the shared flags live in committed configuration rather than in a command somebody remembers. Useful defaults are a summary of all non-passing outcomes so skips are visible rather than invisible, strict marker and configuration validation, and a modern import mode. The setting with the largest long-term payoff is promoting warnings to errors: a deprecation warning today is a broken build in a year, and catching it while the fix is small is far cheaper than discovering it during an urgent upgrade. Keep the exemption list short and require a written reason beside each entry, because a blanket ignore is the same as having no policy. What should not go into shared configuration is anything environment-specific — parallel workers, rerun counts, report directories — since those differ between a laptop and a pipeline and belong in the command that runs there.

Key points

  • Shared flags belong in committed configuration so every engineer and the pipeline behave identically
  • Promoting warnings to errors turns next year's breakage into today's small fix
  • Keep environment-specific flags such as parallelism and report directories in the CI command

Code

# pyproject.toml
[tool.pytest.ini_options]
addopts = [
    "-ra",                      # summarise every non-passing outcome, including skips
    "--strict-markers",         # a marker typo is an error, not a silent no-op
    "--strict-config",
    "--import-mode=importlib",
    "--durations=10",
]
xfail_strict = true

# Warnings are bugs until proven otherwise. Each exemption names its reason.
filterwarnings = [
    "error",
    "ignore::DeprecationWarning:selenium.*",
]

# NOT here: -n auto, --reruns, --alluredir. Those differ per environment
# and belong in the CI command, where the choice is visible.

Shared and strict in configuration; environment-specific and negotiable on the command line.

See it in the framework

  • Implementation · pytest configuration: pyproject.toml — live · reviewed
  • Used by · Env var template: .env.example — live · reviewed
  • CI · CI execution: .github/workflows/ci.yml — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Adding a blanket warnings filter, which silently restores the problem the setting was meant to catch
  • Putting rerun flags in shared configuration, which quietly hides flaky tests from everyone on the team

Practice exercise

Turn on warnings-as-errors in a suite you work with and run it. Fix or explicitly exempt each warning that appears, writing the reason next to the exemption, and note how many were real future breakages.

Source registry

7 chapter references
venv — Creation of virtual environments

Virtual-environment isolation, creation, activation, disposal and interpreter behaviour

Python Software Foundation · Official documentation
Source ↗
Writing your pyproject.toml

Project metadata, dependency declaration and build-system configuration

Python Packaging Authority · Official packaging guide
Source ↗
Local project installs

Regular versus editable local project installation with pip

Python Packaging Authority · Official pip documentation
Source ↗
pytest documentation

Test discovery, assertions, configuration and the plugin model

pytest-dev · Official documentation
Source ↗
qa-automation-python reference framework

The runnable framework and demo application every lesson in this path is drawn from

sergiiiavt · Reference implementation
Source ↗
Pydantic documentation

Model validation, strict configuration and settings management

Pydantic Services · Official documentation
Source ↗
Marking test functions

Custom markers, strict marker validation and selection expressions

pytest-dev · Official how to
Source ↗