pytest Interview Questions and Answers for Automation Testers (2026)

pytest is the backbone of almost every Python test automation framework, so interviews for Playwright, Selenium and API roles all include pytest questions. This page covers the questions that come up most, from discovery rules and assert rewriting to fixture scopes, conftest.py, parametrization, markers, hooks, plugins and CI, each with a short answer and code where it helps. A runnable example at the end shows fixture order and scopes in action, because “explain what this prints” is a favourite interview task.

Advertisement

📖 What You’ll Learn: how to answer questions on test discovery and naming, assert rewriting, fixtures, yield teardown and scopes, autouse, conftest.py, fixture overriding, parametrize, ids and pytest.param, parametrized fixtures, markers, skip and xfail, configuration files and addopts, command-line selection, hooks such as pytest_addoption and pytest_runtest_makereport, plugins, output capture, tmp_path, monkeypatch, caplog, parallel runs, and reading fixture order.


🔍 Basics and Discovery

  1. Why pytest instead of unittest?

Plain functions and assert instead of classes and self.assertEqual; powerful fixtures with dependency injection and scopes; parametrization; markers; a large plugin ecosystem (pytest-playwright, xdist, html, rerunfailures). pytest also runs existing unittest tests. (Lesson 24)

  1. How does pytest find tests?

By default it collects files named test_*.py or *_test.py, functions named test_*, and methods named test_* in classes named Test* without an __init__. testpaths, python_files, python_classes and python_functions in the config change these rules.

  1. What is assertion rewriting?

pytest rewrites assert statements in test modules (and conftest/plugins) at import time so a failure shows the compared values, for example assert 3 == 4 explains both sides and diffs for lists and dicts. That is why plain assert is enough.

  1. How do you check that code raises an exception?

with pytest.raises(ValueError, match="must be positive"):
    set_price(-1)

match is a regular expression searched in the message; excinfo.value gives the exception object.

  1. How do you compare floating point numbers?

assert total == pytest.approx(10.3) (relative tolerance 1e-6 by default), or use Decimal for money.


🧩 Fixtures

  1. What is a fixture?

A function decorated with @pytest.fixture that provides a resource or state to tests that list it as an argument. pytest resolves dependencies between fixtures automatically (dependency injection). (Lesson 25)

  1. How does teardown work in fixtures?

Code after yield runs after the test, whether it passed or failed:

@pytest.fixture
def temp_user(api):
    user = api.create_user()
    yield user
    api.delete_user(user["id"])

request.addfinalizer(fn) is the older alternative.

  1. What scopes exist, and when do you use each?

function (default, fresh per test), class, module, package, session. Use wider scopes for expensive, read-only resources (a browser, an API client, a login state), and function scope for anything a test can change (a page, a cart).

  1. Can a function-scoped fixture use a session-scoped one? And the reverse?

Yes; a fixture may depend on fixtures with the same or wider scope. The reverse raises a ScopeMismatch error, because a session fixture would outlive the function fixture it depends on.

  1. What does autouse=True do?

The fixture runs for every test in its scope without being requested. Use it sparingly, for cross-cutting concerns such as attaching logs or setting timeouts.

  1. What is conftest.py?

A file whose fixtures and hooks are available to all tests in its directory and below, without imports. Layer them: shared fixtures at tests/, UI fixtures in tests/ui/, and so on. (Lesson 26)

  1. How can you override a fixture?

Define a fixture with the same name closer to the test (a sub-folder conftest, the test module or class). It can request the original by the same name, for example def browser_context_args(browser_context_args): return {**browser_context_args, ...}.

  1. What is the factory-as-fixture pattern?

The fixture yields a function that creates objects on demand and remembers them for clean-up, so one test can create several. (Lesson 58)

  1. Which built-in fixtures do you know?

tmp_path and tmp_path_factory (temporary folders), monkeypatch (patch attributes, environment variables, sys.path), capsys/capfd (captured output), caplog (log records), request (information about the requesting test), pytestconfig, record_property.

Advertisement

  1. How do you get information about the current test inside a fixture?

Through request: request.node.name, request.node.get_closest_marker("slow"), request.param in parametrized fixtures, request.getfixturevalue("name") for dynamic fixtures, request.config for options.


🎛️ Parametrization

  1. How do you run one test with several inputs?

@pytest.mark.parametrize("a, b, total", [(1, 2, 3), (2, 2, 4)])
def test_add(a, b, total):
    assert a + b == total

Each tuple becomes its own test. (Lesson 27)

  1. How do you name parametrized cases and mark one of them?

pytest.param(..., id="negative", marks=pytest.mark.xfail(reason="bug 123")), or ids=[...] / ids=function on the decorator.

  1. What happens when you stack two parametrize decorators?

pytest runs the cross product: 3 values × 4 values = 12 tests.

  1. What is a parametrized fixture?

@pytest.fixture(params=["admin", "viewer"]): every test that uses it runs once per parameter, available as request.param. Good for running many tests under several setups. (Lesson 45)

  1. What is pytest_generate_tests?

A hook that can call metafunc.parametrize(...) at collection time, for example to build cases from a command-line option or a file.


🏷️ Markers and Selection

  1. What are markers and how do you register them?

Labels on tests (@pytest.mark.smoke). Register them under markers in the config, and use --strict-markers so typos fail. Select with -m "smoke and not slow". (Lesson 28)

  1. skip vs skipif vs xfail?

skip always skips with a reason; skipif(condition, reason=...) skips conditionally (OS, version, environment); xfail runs the test but expects failure (known bug), and strict=True turns an unexpected pass into a failure.

  1. How do you run a single test or a subset?

A node id (pytest tests/test_cart.py::test_coupon[save10]), -k "coupon and not flat200" (name expression), -m smoke (markers), --lf (last failed), --ff (failed first), -x (stop at first failure), --maxfail=3.


⚙️ Configuration, Hooks and Plugins

  1. Where can pytest configuration live?

pytest.ini, pyproject.toml ([tool.pytest.ini_options]), tox.ini or setup.cfg. Only one file is used: the first found walking up from the arguments, with pytest.ini taking precedence. (Lesson 29)

  1. What is addopts?

Options added to every run, such as --strict-markers -ra --base-url=.... PYTEST_ADDOPTS adds more from the environment, and -o addopts="" clears it for one run.

  1. How do you add a custom command-line option?

def pytest_addoption(parser):
    parser.addoption("--env", default="qa", choices=["qa", "staging"])

in the root conftest.py or a plugin, then read it with request.config.getoption("--env"). (Lesson 30)

  1. Which hooks have you used?

pytest_addoption, pytest_configure, pytest_collection_modifyitems (add markers, reorder, skip), pytest_runtest_makereport (attach screenshots, record outcomes), pytest_report_header, pytest_sessionstart/finish.

  1. How do you take a screenshot only when a UI test fails?

A wrapper hook records the call outcome on the item; a fixture or the hook itself uses the open page:

@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
    report = yield
    if report.when == "call" and report.failed and "page" in item.funcargs:
        item.funcargs["page"].screenshot(path=f"failures/{item.name}.png")
    return report

pytest-playwright also offers --screenshot only-on-failure. (Lesson 63)

  1. Name plugins you use in a Playwright project.

pytest-playwright, pytest-base-url, pytest-xdist (parallel), pytest-rerunfailures (retries), pytest-html and allure-pytest (reports), pytest-bdd (Gherkin), pytest-asyncio (async tests), pytest-dotenv or python-dotenv (configuration).

  1. How do you write your own plugin?

Put hooks and fixtures in a module and register it with -p module_name, pytest_plugins = ["module"] in the root conftest, or an entry point in pyproject.toml ([project.entry-points.pytest11]) to share it as a package.


🛠️ Running and Output

Advertisement

  1. Why don’t I see my print() output?

pytest captures stdout and shows it only for failing tests. Use -s (or --capture=no) to see it live, or -rP to show passed tests’ output in the summary.

  1. How do you see the slowest tests?

--durations=10 lists the ten slowest setup, call and teardown phases.

  1. How do you use temporary files safely?

tmp_path gives each test its own pathlib.Path folder, cleaned up automatically after a few runs. tmp_path_factory creates folders for wider-scoped fixtures.

  1. How do you set an environment variable for one test?

monkeypatch.setenv("API_URL", "http://localhost"); it is restored after the test. monkeypatch.setattr(module, "name", value) patches attributes.

  1. How do you check that something was logged?

def test_logs_warning(caplog):
    caplog.set_level("WARNING")
    process_order(-1)
    assert "invalid order" in caplog.text

  1. How do you run tests in parallel and what breaks?

pytest -n auto with pytest-xdist. Session fixtures run once per worker, shared data and accounts collide, --pdb does not work in workers, and exactly-once setup needs a file lock. (Lesson 65)

  1. How do you retry flaky tests?

pytest-rerunfailures: --reruns 2 --reruns-delay 1, or @pytest.mark.flaky(reruns=2) per test, ideally with --only-rerun for infrastructure errors. Fix root causes; retries are a safety net. (Lesson 44)

  1. What exit codes does pytest use?

0 all passed, 1 some tests failed, 2 interrupted, 3 internal error, 4 usage error, 5 no tests collected. CI relies on them; exit code 5 often means a wrong path or marker expression.

  1. How do you produce JUnit XML for CI?

--junitxml=reports/junit.xml; record_property adds per-test properties (use junit_family = xunit1 for those). (Lesson 60)

  1. Explain the order in which fixtures run.

Higher-scoped fixtures are set up first (session, then module, then function); autouse fixtures run before requested ones of the same scope; dependencies run before the fixtures that need them; teardown happens in reverse order. The demo below proves it.


🧪 “What Does This Print?”

A classic interview task: predict the output, then run it.

📄 test_order.py

import pytest

log = []


@pytest.fixture(scope="session")
def session_res():
    log.append("session setup")
    yield
    log.append("session teardown")


@pytest.fixture(scope="module")
def module_res(session_res):
    log.append("module setup")
    yield
    log.append("module teardown")


@pytest.fixture(autouse=True)
def every_test():
    log.append("  autouse setup")
    yield
    log.append("  autouse teardown")


@pytest.fixture
def item(module_res):
    log.append("  item setup")
    yield "item"
    log.append("  item teardown")


@pytest.mark.parametrize("n", [1, 2], ids=["first", "second"])
def test_uses_item(item, n):
    log.append(f"    test {n}")


def test_last():
    print("\n" + "\n".join(log))

⌨️ Terminal

pytest test_order.py -q -s

🖥️ Output

..
session setup
module setup
  autouse setup
  item setup
    test 1
  item teardown
  autouse teardown
  autouse setup
  item setup
    test 2
  item teardown
  autouse teardown
  autouse setup
.
3 passed in 0.01s

Read it top to bottom: the session and module fixtures were set up once, before the first test that needed them; the autouse fixture wrapped every test, including test_last, which requested nothing; item was set up and torn down around each parametrized case; and the module and session teardowns have not happened yet when test_last prints, because they run after the last test of their scope.


Advertisement

🏋️ 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: Write a fixture api_token (session scope) that logs in once, and a function-scoped fixture client that uses it. What happens if you make api_token function-scoped and client session-scoped?

Show answer
@pytest.fixture(scope="session")
def api_token(api):
    return api.login("admin", "admin@123")


@pytest.fixture
def client(api, api_token):
    return ApiClient(api, token=api_token)

The reverse (a session-scoped client depending on a function-scoped api_token) raises ScopeMismatch: a fixture can only depend on fixtures with the same or wider scope.

Exercise 2: Run only tests marked smoke whose names contain login but not locked, stopping at the first failure. Write the command.

Show answer
pytest -m smoke -k "login and not locked" -x

Exercise 3: A teammate’s xfail test started passing and nobody noticed. How do you make that impossible?

Show answer

Use @pytest.mark.xfail(reason="bug 123", strict=True) (or set xfail_strict = true in the config). An unexpected pass then fails the run, so the team removes the marker when the bug is fixed.

Exercise 4: Write a test that uses monkeypatch to set TEST_ENV=staging and checks that load_settings().env == "staging".

Show answer
def test_env_from_variable(monkeypatch):
    monkeypatch.setenv("TEST_ENV", "staging")
    assert load_settings().env == "staging"

monkeypatch restores the original environment after the test.


🧠 MCQ Quiz: pytest Interview Questions

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which file names does pytest collect by default?
  2. What runs the code after yield in a fixture?
  3. What error do you get when a session fixture depends on a function fixture?
  4. What does pytest.param(..., marks=pytest.mark.xfail) affect?
  5. Where must pytest_addoption be defined?
  6. What does -k "cart and not coupon" select?
  7. Which built-in fixture gives each test its own temporary folder?
  8. What does exit code 5 mean?
  9. In which order are fixtures of different scopes set up?
  10. How do you see print output from passing tests?

Want a longer, timed test? Take the Playwright Python mock interviews (13 modules, 20 MCQs each).


Advertisement

❓ Frequently Asked Questions

🤔 How deep should my pytest knowledge be for an automation role?

Be fluent with fixtures (scopes, yield, conftest, overriding), parametrization, markers and configuration, and be able to explain one or two hooks you used in a real framework. Plugin authoring is a bonus for senior roles.

🤔 What is the most common pytest mistake interviewers look for?

Tests that depend on each other or on shared mutable state, and fixtures with the wrong scope (for example a session-scoped page). Mention isolation and scope choices explicitly in your answers.

🤔 Should I know unittest as well?

Know the differences and that pytest runs unittest tests. Most modern Python test frameworks use pytest style.

🤔 How do I practise these questions?

Take the pytest module mock interview and the Python pytest MCQ test, and rebuild one fixture-heavy example from Module 3 without looking.

🤔 What about the “what does this print” questions?

Practise with the fixture-order demo above: change scopes, add autouse, and predict the output before running it.


🏁 Summary

  • Discovery rules, assertion rewriting, pytest.raises and pytest.approx are the basics.
  • Fixtures: yield teardown, scopes and the scope rule, autouse, conftest layering, overriding and factory fixtures.
  • Parametrize with ids and per-case marks; stack for cross products; parametrized fixtures for setups.
  • Markers with strict registration, skip/skipif/xfail(strict), and selection with node ids, -k, -m, --lf.
  • Configuration and hooks (addoption, collection, makereport), plugins, output, built-in fixtures, parallel runs and fixture order.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page