Pytest Interview Questions and Answers for Python Testing
Advanced & Scenario-Based Pytest Interview Questions
1. How Pytest Fits into CI/CD Pipelines
You'll often hear Pytest mentioned alongside CI/CD tools such as Jenkins, GitHub Actions, or GitLab CI. That's because in most projects, tests aren't executed manually, but they're triggered automatically whenever code is pushed to a repository or a pull request is raised.
A typical pipeline might:
- Build the application
- Install dependencies
- Execute the Pytest suite
- Generate test and coverage reports
- Publish the results
- Decide whether deployment can proceed
Pytest acts as a release checkpoint. A failed smoke test, API test, or critical regression test can stop the pipeline entirely, forcing the issue to be addressed before the code moves any further.
When you talk about this in an interview, you will feel like mentioning the common procedure, but try to talk from your experience instead. Think about the challenges you have faced or could have faced. For example, if a project contains thousands of automated tests, would you run all of them on every commit? Probably not. And here concepts such as smoke suites, regression suites, test markers, and parallel execution can be used. Teams use these strategies to keep feedback fast while still maintaining confidence in the quality of a release.
2. Measuring Code Coverage with pytest-cov
Pytest itself does not calculate coverage, but the pytest-cov plugin integrates with Coverage.py to measure which parts of the application were executed during testing.
Example:
pytest --cov=appA coverage report can help identify functions, modules, or code paths that have not been exercised by the test suite.
Coverage percentages should be interpreted carefully. High coverage does not automatically mean high-quality tests. A test suite with 95% coverage can still miss important business scenarios, while a lower coverage percentage may still provide strong validation if the critical workflows are thoroughly tested.
3. Useful Pytest Plugins
The plugin ecosystem in pytest helps quite a lot, and it's always best to have an idea about it.
Some commonly used plugins include:
| Plugin | Purpose |
|---|---|
| pytest-cov | Code coverage reporting |
| pytest-html | HTML report generation |
| pytest-xdist | Parallel test execution |
| pytest-rerunfailures | Retry failed tests |
| pytest-mock | Mocking utilities |
| pytest-timeout | Prevent tests from hanging indefinitely |
4. Optimizing Large Test Suites
As automation suites grow, execution time often becomes a challenge.
Several approaches can be used to improve performance:
- Categorize tests using markers such as smoke, regression, and integration.
- Execute tests in parallel using pytest-xdist.
- Reduce unnecessary browser interactions.
- Remove duplicated setup steps through fixtures.
- Mock slow external dependencies where appropriate.
- Run only impacted test groups during development.
One interview scenario you may come across involves balancing execution speed with test confidence. Imagine you're working on a large project where running the entire test suite after every code change takes a significant amount of time. While executing fewer tests can speed up development, cutting back too much increases the risk of bugs slipping into production. In such situations, interviewers often want to understand how you would strike the right balance between development efficiency and software quality.
5. Unit Tests vs Integration Tests
Experienced-level interviews frequently explore how different test types should be used.
A unit test validates a small piece of functionality in isolation. Dependencies such as databases, APIs, and external services are often mocked.
An integration test validates how multiple components work together. These tests may involve real databases, APIs, message queues, or other services.
For example:
- Verifying that a function calculates a discount correctly is typically a unit test.
- Verifying that an order is stored in a database and triggers a confirmation email is typically an integration test.
Neither approach replaces the other. Most automation strategies use a combination of both. Unit tests provide fast feedback and isolate failures, while integration tests help validate that system components work correctly when combined.
Learn via our Video Courses
6. What Interviewers Often Evaluate at Senior Levels
If you're interviewing for an entry-level role, you'll usually be asked questions about Pytest fundamentals, syntax, fixtures, assertions, and basic test execution.
As you move into mid-level and senior positions, the conversation becomes less about individual commands and more about the decisions behind your testing strategy.
You might encounter questions like:
- How would you structure a test automation framework for a growing application?
- What challenges have you faced while integrating tests into a CI/CD pipeline?
- How do you deal with flaky tests that pass sometimes and fail at other times?
- What approach do you follow for managing test data across environments?
- How do you decide whether your current test coverage is actually meaningful?
- What would you change if a test suite became too slow to scale?
In these discussions, there isn't always a single correct answer. Interviewers are usually trying to understand how you evaluate trade-offs, justify technical decisions, and balance factors such as execution speed, reliability, coverage, and long-term maintenance.
A candidate who can clearly explain “why” a particular approach was chosen will generally leave a strong impression, while of course taking into account your whole interview.
Mocking, Monkeypatching & Test Data Questions
1. What is mocking, and why is it used in unit testing?
Mocking replaces an object, function, or service with a test-controlled version during execution.
Suppose an application sends a payment request through an external API. If a unit test calls the real API, the test result now depends on internet connectivity, API availability, authentication credentials, and the response returned by that service. Any issue with those factors can cause the test to fail even when the application logic is correct.
A mock removes that dependency by returning a predefined response instead of making the actual API call. This allows the test to focus only on the code being validated.
You can mention these as examples:
- API requests
- Database queries
- File reads and writes
- Email services
- Third-party SDKs
A payment API may return a successful transaction, a declined payment, or a timeout error. Using mocks, each of these scenarios can be tested without sending real requests or waiting for the external system to respond.
You can also check out: Dictionary in Python (With Examples)
2. How do you mock a function or API call in Pytest?
I usually mock a function by replacing it with a mock object and controlling the value it returns during the test.
from unittest.mock import patch
@patch("app.get_user")
def test_user(mock_get_user):
mock_get_user.return_value = {
"id": 1,
"name": "John"
}
result = mock_get_user()
assert result["name"] == "John"The @patch("app.get_user") line tells Python to replace get_user() with a mock object before the test starts. The mock object is then passed to the test as mock_get_user.
The statement:
mock_get_user.return_value = {
"id": 1,
"name": "John"
}defines what should be returned whenever get_user() is called during the test. No real function execution takes place.
The same technique is often used when testing API integrations. Instead of waiting for a real HTTP response, the test can return a predefined status code and response body:
mock_response.status_code = 200
mock_response.json.return_value = {"success": True}This makes it possible to verify how the application handles successful responses, failed requests, invalid data, or timeout scenarios without depending on the actual API.
3. What is monkeypatch in Pytest?
monkeypatch is a built-in Pytest fixture used to temporarily modify objects, attributes, environment variables, dictionaries, or functions during a test.
Example:
def get_api_url():
return "https://prod-api.com"
def test_url(monkeypatch):
monkeypatch.setattr(
"__main__.get_api_url",
lambda: "https://test-api.com"
)
assert get_api_url() == "https://test-api.com"Unlike traditional mocking, monkeypatch automatically restores the original value after the test completes.
4. How do you test code that depends on environment variables?
Applications often read configuration values such as API keys, database credentials, or feature flags from environment variables. During testing, those values can be supplied using Pytest's monkeypatch fixture.
Suppose the application reads an API key from the environment:
import os
def get_api_key():
return os.getenv("API_KEY")The test can provide its own environment variable value:
def test_api_key(monkeypatch):
monkeypatch.setenv(
"API_KEY",
"test_key"
)
assert get_api_key() == "test_key"In this example, monkeypatch.setenv() creates the API_KEY environment variable before the test executes. When get_api_key() calls os.getenv(), it receives "test_key" instead of reading a value from the actual system environment.
The monkeypatch fixture provides several helper methods:
| Method | Purpose |
|---|---|
| setenv() | Create or modify environment variables |
| delenv() | Remove environment variables |
| setattr() | Replace attributes or functions |
| setitem() | Modify dictionary values |
Any changes made through monkeypatch are automatically reversed when the test finishes, preventing one test from affecting another.
5. How do you use tmp_path or tmpdir in Pytest?
tmp_path and tmpdir provide temporary directories that can be used to create files and folders during a test. They are useful when testing functionality that reads from or writes to the file system.
Example using tmp_path:
def test_file_creation(tmp_path):
file = tmp_path / "data.txt"
file.write_text("Hello")
assert file.read_text() == "Hello"In this example, tmp_path provides a temporary directory before the test begins. The test creates a file named data.txt, writes content to it, and then verifies that the content can be read back successfully.
Common use cases include:
- File upload testing
- Log file validation
- CSV or JSON generation tests
- Temporary configuration files
- Export and report generation tests
Both fixtures create temporary storage that is removed automatically after the test completes, so no manual cleanup is required.
The main difference is that tmp_path returns a pathlib.Path object, while tmpdir returns a legacy py.path object. For new projects, tmp_path is generally preferred because it uses Python's standard path library.
Learn more: OOPs Concepts in Python
Parametrization, Markers & Test Selection Questions
1. What is parametrization in Pytest?
Parametrization generates multiple test cases from a single test definition. Instead of creating separate test functions for every scenario, Pytest executes the same test repeatedly using the data supplied through @pytest.mark.parametrize.
So you don’t have to always write something like this:
def test_add_1():
assert 1 + 1 == 2
def test_add_2():
assert 2 + 2 == 4Pytest can execute both scenarios using a single test:
@pytest.mark.parametrize("a, b, expected", [
(1, 1, 2),
(2, 2, 4)
])
def test_add(a, b, expected):
assert a + b == expectedPytest treats each parameter set as an individual test case during execution. If one combination fails, the remaining combinations are still executed and reported separately.
2. How do you use @pytest.mark.parametrize?
I use @pytest.mark.parametrize by specifying the parameter names and the values that should be passed to the test during each execution.
If you're new to decorators, you may want to read about Python decorators before continuing, as @pytest.mark.parametrize itself is implemented as a decorator.
import pytest
@pytest.mark.parametrize(
"a,b,expected",
[
(1, 2, 3),
(2, 3, 5),
(10, 5, 15)
]
)
def test_addition(a, b, expected):
assert a + b == expectedIf you would see the example above, "a,b,expected" defines the parameters, while each tuple provides a different set of values. For the first execution, Pytest assigns a=1, b=2, and expected=3. The same test is then executed again using the remaining datasets.
Pytest treats each tuple as an independent test case:
test_addition[1-2-3]
test_addition[2-3-5]
test_addition[10-5-15]If one dataset fails, Pytest reports that specific test case separately while continuing to execute the remaining parameter sets.
3. What are Pytest markers and why are they used?
Markers are labels attached to tests that help categorize and control test execution.
Common examples include:
@pytest.mark.smoke
@pytest.mark.regression
@pytest.mark.api
@pytest.mark.slowA marker does not change how a test behaves. Its purpose is to make test selection easier.
For example, a team may run only smoke tests after every deployment while reserving the full regression suite for nightly execution.
Also check out: List in Python.
4. What is the difference between skip and xfail in Pytest?
Both markers affect test execution, but they communicate different intentions.
| Feature | skip | xfail |
|---|---|---|
| Test execution | Not executed | Executed |
| Expected result | Ignored | Expected to fail |
| Common use case | Missing dependency or unsupported environment | Known bug that has not been fixed |
| Appears in report | Skipped | Expected failure |
Examples:
@pytest.mark.skip(reason="Feature not available")
def test_payment():
pass@pytest.mark.xfail(reason="Known issue #123")
def test_payment():
assert process_payment()Use skip when a test should not run at all. Use xfail when the test should run, but failure is currently expected.
5. How do you run only a selected group of tests in Pytest?
Pytest provides multiple ways to execute a subset of tests depending on what needs to be validated.
1. Run tests with a specific marker
pytest -m smokeThis command filters tests based on markers. If a test is decorated with @pytest.mark.smoke, Pytest includes it in the execution. Tests without that marker are skipped.
2. Run tests that match a keyword
pytest -k loginThis command filters tests based on names. Pytest searches for the keyword in test function names, test class names, and file names, then executes only the matching tests.
3. Run all tests in a specific file
pytest test_login.pyThis command executes every test collected from test_login.py. It is useful when changes are limited to a single feature or module, and there is no need to run the rest of the test suite.
4. Run a specific test function
pytest test_login.py::test_valid_loginThis command targets a single test function. Pytest loads the file, locates test_valid_login(), and executes only that test.
Each approach narrows test execution differently. Markers filter by category, keywords filter by names, files filter by location, and the double-colon syntax targets an individual test.
6. What is pytest.ini and what kind of configuration can it store?
pytest.ini is a configuration file that stores project-level Pytest settings.
Example:
[pytest]
addopts = -v
testpaths = tests
markers =
smoke: Smoke tests
regression: Regression testsCommon configurations include:
| Configuration | Purpose |
|---|---|
| addopts | Default command-line options |
| testpaths | Test discovery locations |
| markers | Custom marker registration |
| python_files | Test file naming patterns |
| python_functions | Test function naming patterns |
Using pytest.ini helps keep test configuration centralized rather than repeating options every time Pytest is executed.
Pytest Basics Interview Questions
1. How is Pytest different from Python unittest?
Here, you can mention the core differences, try to remember the differentiating aspects, like in the table here -
| Aspect | Pytest | unittest |
|---|---|---|
| Availability | Third-party framework | Included with Python |
| Test structure | Functions or classes | Primarily class-based |
| Assertions | Uses assert statements | Uses methods such as assertEqual() |
| Setup and teardown | Fixtures | setUp() and tearDown() |
| Parametrization | Built-in support | Requires additional code |
| Boilerplate | Less | More |
You can keep the following differences in mind as well, if there are any follow-up questions to this -
- Pytest uses assertion introspection. If assert total == 100 fails because the actual value is 97, both values are displayed in the test output automatically.
- A fixture can run once per test, class, module, or session. For example, a database connection can be created once and reused instead of reconnecting before every test.
- Parameterization allows a single test to be executed against multiple inputs. A login validation test can be run against 20 username-password combinations without creating 20 separate test functions.
- Pytest can run existing unittest test cases, which allows teams to introduce Pytest into an existing codebase without rewriting the entire test suite.
2. What are the advantages of using Pytest for automation testing?
You can mention how Pytest is advantageous to you based on your experience with it first (it opens an opportunity to talk more). One advantage I would mention first is that Pytest doesn't require much setup for basic test cases. It has features such as fixtures and parameterization that come in handy when the number of test cases starts to increase. Also, for me, the best part is that I don't have to repeat the setup over and over for every test or create multiple versions of the same test. Pytest provides built-in ways to handle those situations.
You can name these advantages, and when you are asked Python testing interview questions:
- Minimal boilerplate code.
- Detailed assertion failure messages.
- Reusable fixtures for test setup and cleanup.
- Parameterization for testing multiple input combinations.
- Plugins for reporting, coverage, parallel execution, and more.
- Easy integration with CI/CD pipelines.
- Support for unit, integration, API, and UI automation testing.
3. How does Pytest discover test files and test functions?
Pytest discovers tests during its collection phase by scanning the project for files, functions, and classes that match its default naming patterns.
By default, Pytest looks for:
- Files named test_*.py or *_test.py
- Functions whose names begin with test_
- Classes whose names begin with Test
- Methods inside those classes that begin with test_
For example, the following function would be collected and executed automatically:
def test_login():
assert login("user", "password") is TrueIf a file or function does not follow these naming conventions, Pytest may skip it during test discovery unless custom collection rules are configured.
4. What is the default naming convention for Pytest test files and test methods?
Pytest relies on naming conventions during test discovery.
| Component | Default Convention |
|---|---|
| Test files | test_*.py or *_test.py |
| Test functions | test_* |
| Test classes | Test* |
| Test methods | test_* |
Example:
class TestLogin:
def test_valid_user(self):
assert True
def test_invalid_user(self):
assert TrueIn this example, Pytest will collect both test methods because their names begin with test_ and they belong to a class whose name begins with Test.
Also, remember that usually tests are skipped during collection if the file, class, or method name does not match Pytest's default naming patterns.
Want to learn Python but don’t know where to start? Check out this free Python Tutorial and get started with your learning journey!
5. How do assertions work in Pytest?
Pytest uses Python's built-in assert statement to verify whether a condition evaluates to True. If the condition is true, the test passes. If it evaluates to False, the test fails, simple!
Look at this example:
def test_total():
total = 8 + 2
assert total == 10Before executing a test, Pytest rewrites assert statements and captures the values involved in the expression. If the assertion fails, the test output includes the failed condition and the values that caused the failure.
assert total == 10
E assert 8 == 10The output shows that total evaluated to 8 when the assertion expected 10. Without assertion rewriting, the test would typically fail with a generic AssertionError, requiring additional debugging to determine what caused the mismatch.
Also, I have seen a lot of people make this mistake, but make sure to remember that you should avoid replacing assert statements with print statements during debugging. Pytest already captures the failed expression and values involved in the comparison, which is often enough to identify the issue.
6. What is the Arrange-Act-Assert pattern in test writing?
Arrange-Act-Assert (AAA) is a test design pattern that separates a test into three stages: preparing the test data, executing the functionality being tested, and verifying the result.
Like here -
user = {"username": "admin", "password": "password123"}
is_authenticated = login(user)
assert is_authenticated is TrueIn this example:
| Stage | Code |
|---|---|
| Arrange | Create the user object |
| Act | Call the login() function |
| Assert | Verify that authentication succeeds |
So basically, AAA is to keep setup, execution, and validation clearly separated. When these stages become difficult to identify, the test often contains multiple responsibilities and becomes harder to understand or maintain.
7. What is Pytest and why is it used in Python testing?
For this question, keep it simple with what Pytest is and try to describe well how it helps in Python testing, since it will help the person interviewing you understand whether you understand the framework to begin with.
For definition - Pytest is a Python testing framework used to write, organize, and execute automated tests. It supports different testing approaches, including unit, integration, API, and end-to-end testing, making it suitable for projects of all sizes.
For its Use - And Developers use it often because it simplifies test development. Features such as fixtures reduce repetitive setup code, parameterization allows the same test to run against multiple inputs, and detailed assertion messages make failures easier to diagnose. All these features can really help anyone in the team build test suites that are easier to maintain and scale.
Refer to these Python Interview Questions if you want to practice further.
Pytest CLI, Reports & Debugging Questions
1. How do you run a specific test file or test function in Pytest?
For this question, you must understand that Pytest supports test execution at multiple levels, depending on how narrowly you want to target a test run.
1. Run all tests from a specific file
pytest test_login.pyUse this when you want to execute every test available in a single file without running the rest of the test suite.
2. Run a specific test function
pytest test_login.py::test_valid_loginAppending the test function name after :: instructs Pytest to execute only that function.
3. Run all tests from a specific test class
pytest test_login.py::TestLoginIf the file contains multiple test classes, Pytest can target a single class and execute all test methods within it.
4. Run a specific test method from a class
pytest test_login.py::TestLogin::test_valid_loginAdding both the class name and method name creates the most specific level of test selection, allowing Pytest to execute a single test method.
The :: operator acts as a path separator for test objects. Each additional segment narrows the scope of execution from the file level to the class level and finally to an individual test.
Check out: File Handling in Python
2. How do you stop test execution after the first failure?
Use the -x option.
pytest -xWhen Pytest encounters the first failed test, it immediately stops executing the remaining tests and exits the test run.
For situations where more than one failure should be allowed, Pytest provides the --maxfail option.
pytest --maxfail=3This command continues execution until three test failures occur. Once the third failure is encountered, Pytest stops running the remaining tests.
The difference is that -x is equivalent to --maxfail=1. Both options control how many failures Pytest will tolerate before terminating the test run.
These options are useful when multiple test failures are likely to originate from the same issue, such as a failed application startup, database outage, configuration error, or broken dependency.
3. How do you generate test reports in Pytest?
Pytest supports multiple reporting formats depending on how the test results need to be viewed or shared.
1. View detailed results in the terminal
pytest -vThe -v (verbose) option displays the name and status of each test during execution. While this is not a report file, it provides a detailed summary directly in the terminal.
2. Generate a JUnit XML report
pytest --junitxml=report.xmlThis command creates an XML report named report.xml containing the test results. Many CI/CD tools can read this format and display test outcomes as part of the build pipeline.
3. Generate an HTML report
pytest --html=report.htmlThis command requires the pytest-html plugin and creates a browser-friendly report.
A typical HTML report includes:
- Passed tests
- Failed tests
- Skipped tests
- Execution time
- Error messages and tracebacks
Each format serves a different purpose. Terminal output is useful while developing and debugging tests, XML reports are commonly processed by automation tools, and HTML reports provide a detailed summary that can be reviewed and shared more easily.
4. How do you debug a failing Pytest test?
Debugging usually starts with the failure output generated by Pytest.
A typical workflow looks like this:
- Read the assertion failure message.
- Review the traceback to locate the failing line.
- Re-run the specific failing test instead of the entire suite.
- Use -s to display print statements if required.
- Use the built-in debugger for interactive inspection.
Example:
pytest -s test_login.py::test_valid_loginPytest also integrates with Python's debugger.
pytest --pdbWhen a failure occurs, execution pauses and opens an interactive debugging session, allowing variables, function calls, and program state to be inspected before the test exits.
5. What are commonly used Pytest command-line options?
Pytest provides a large number of CLI options, but a few appear frequently in day-to-day testing.
| Command | Purpose |
|---|---|
| pytest | Run all discovered tests |
| pytest -v | Show detailed test output |
| pytest -q | Display minimal output |
| pytest -s | Show print statements in the console |
| pytest -k login | Run tests matching a keyword |
| pytest -m smoke | Run tests with a specific marker |
| pytest --collect-only | Show collected tests without executing them |
| pytest -x | Stop after the first failure |
| pytest --lf | Run only previously failed tests |
| pytest --maxfail=3 | Stop after a specified number of failures |
The commands above generally fall into three categories:
- Output options: such as -v, -q, and -s control how test results are displayed.
- Test selection options: such as -k, -m, and --collect-only determine which tests Pytest should run.
- Failure handling options: such as -x, --lf, and --maxfail control what happens when tests fail.
Learn more: Python Exception Handling
Pytest Fixtures Interview Questions
1. What is conftest.py and why is it used?
conftest.py is a special Pytest file used to share fixtures and framework configuration across multiple test files. Pytest automatically discovers this file, so fixtures defined inside it can be used without importing them into individual test modules.
Without conftest.py, the same fixture may need to be duplicated across multiple test files or imported repeatedly. Placing shared fixtures in conftest.py makes them available throughout the test directory structure.
Example:
# conftest.py
import pytest
@pytest.fixture
def api_url():
return "https://api.example.com"Any test located in the same directory or a child directory can request api_url as a fixture argument without importing it explicitly.
In addition to fixtures, conftest.py can contain Pytest hooks that customize framework behavior, such as test collection, execution, reporting, and command-line options.
If you had to give examples of code stored in conftest.py, you could mention database connections, authenticated users, API clients, test configuration values, and other fixtures that are shared across multiple test files.
2. What are fixtures in Pytest?
I had mentioned fixtures previously in the answers, and now it is time to dedicate some of your time to this answer. Here, I have provided an overview, in the sense of what you should know primarily.
Fixtures are reusable functions that provide setup data or resources to test cases. Their primary purpose is to eliminate repeated setup code and ensure that the same test data or configuration can be reused across multiple tests.
import pytestThe pytest module is imported because fixtures are created using the @pytest.fixture decorator.
@pytest.fixture
def user_data():
return {"name": "John", "role": "Admin"}Here, user_data() is defined as a fixture. Instead of creating this dictionary inside every test function, the data is created once in a reusable location.
def test_user_role(user_data):
assert user_data["role"] == "Admin"Notice that user_data is passed as an argument to the test function. Pytest recognizes that the test depends on a fixture with the same name, executes the fixture, and injects its return value before running the test.
def test_user_name(user_data):
assert user_data["name"] == "John"The same fixture can be reused by multiple tests without duplicating the setup code. If the user data changes in the future, the update only needs to be made inside the fixture rather than in every test that uses it.
Also, Fixtures are mostly used for database connections, authenticated users, API clients, configuration objects, and temporary files that need to be shared across multiple tests. So, you can give your examples accordingly.
3. How are Pytest fixtures different from setup and teardown methods?
There are key differences mentioned here in the table; you can refer to this for a quick review.
| Feature | Fixtures | setup/teardown |
|---|---|---|
| Reusability | Can be shared across tests and files | Usually tied to a test class |
| Dependency Injection | Yes | No |
| Scope Control | Function, class, module, package, session | Limited |
| Explicit Usage | Requested by test functions | Runs automatically within the class lifecycle |
| Composition | Fixtures can use other fixtures | Not supported directly |
Now, to understand how it works -
A setup method runs before every test in a class, whereas fixtures are requested explicitly by test functions.
def test_login(authenticated_user):
...def test_fetch_orders(api_client):
...Here, each test receives only the dependency it requests.
Fixtures can also depend on other fixtures. For example, an authenticated_user fixture may use a db_connection fixture to create and store user data before the test runs.
As you might have known, setup methods don’t support multiples scopes, but fixtures do, and that allows expensive resources such as database connections or browser instances to be created once and reused across multiple tests.
4. What are fixture scopes in Pytest?
Fixture scope determines how often a fixture is created during a test run.
| Scope | Created |
|---|---|
| function | Once per test function |
| class | Once per test class |
| module | Once per module |
| package | Once per package |
| session | Once per test session |
Example:
@pytest.fixture(scope="module")
def db_connection():
return connect_database()A module-scoped fixture creates a single database connection for all tests in the module instead of opening a new connection before every test function.
The choice of scope depends on whether a resource should be shared between tests. Database connections, browser instances, and API clients are often reused through broader scopes, while test data that must remain isolated is commonly created with a function scope.
6. What is autouse=True in a Pytest fixture?
Normally, a fixture runs only when a test requests it.
When autouse=True is specified, Pytest executes the fixture automatically without requiring it to be listed as a test argument.
import pytest
@pytest.fixture(autouse=True)
def setup_environment():
print("Preparing test environment")This is usually used for actions that every test requires, such as configuring environment variables, creating temporary directories, or initializing logging.
7. How do you use yield in a fixture for setup and cleanup?
A fixture that uses return can provide data to a test, but it cannot execute cleanup code after the test finishes. The yield statement solves this by splitting the fixture into two phases:
- Code before yield runs during setup.
- Code after yield runs after the test completes.
import pytest
@pytest.fixture
def database_connection():
conn = connect_database()
yield conn
conn.close()Here, the database connection is created before the test starts and passed to the test through yield. Once the test finishes, Pytest resumes execution after the yield statement and closes the connection.
The same pattern is used whenever a resource must be cleaned up after a test. Examples include closing database connections, quitting browser sessions, removing temporary files, or terminating network connections.
Pytest for Automation Testing, Selenium & APIs
1. How would you design a Pytest-based automation framework?
You have to be a bit step-wise for this one. Here, mention everything you remember while demonstrating the framework. You can say something like -
When designing a Pytest automation framework, I would keep test cases, page logic, test data, configuration, and reusable utilities separate rather than placing everything inside the test files.
For example:
- Test cases should contain only the test steps and assertions.
- Page Object classes should contain locators and page-specific actions.
- Fixtures should manage browser setup, teardown, and shared test resources.
- Test data should be stored separately so that datasets can be updated without modifying the tests.
- Utility modules should contain reusable functions such as logging, file handling, API helpers, or configuration readers.
- Reports should be generated separately from the framework code to keep execution results organized.
- conftest.py should store shared fixtures that can be used across multiple test files.
- pytest.ini should contain framework configuration such as markers, test paths, and default execution settings.
Suppose the login page receives a UI update and several locators change. In a well-structured framework, those changes are usually limited to the Page Object class rather than every test that uses the page. Similarly, if a dataset changes, the update is made in the test data source instead of modifying the test logic itself.
The main objective is to make the framework easier to maintain, extend, and debug as the number of automated tests increases.
2. How is Pytest used in Selenium automation testing?
In Selenium automation projects, Pytest is usually responsible for organizing and executing the tests, while Selenium handles browser interactions.
A typical Selenium framework consists of several layers:
- Pytest manages test execution, assertions, fixtures, and reporting.
- Test cases contain the validation logic for each scenario.
- Page Objects store web element locators and reusable page actions.
- Selenium WebDriver communicates with the browser and performs actions such as clicking buttons, entering text, and navigating between pages.
For example:
def test_login(driver):
driver.get("https://example.com")
assert "Login" in driver.titleIn this test, Selenium opens the browser and loads the page, while Pytest executes the test and evaluates the assertion.
Fixtures are often used to initialize and close browser sessions, parametrization helps execute the same test against multiple datasets, and reporting plugins provide execution summaries for automation runs.
The combination is usually used because Selenium focuses on browser automation, whereas Pytest provides the framework features needed to organize, execute, and maintain large test suites.
You can also check out: Automation Testing Interview Questions and Answers
3. How do you manage test data in a Pytest automation framework?
The approach depends on the size of the project and the type of data being tested.
Common options include:
| Method | Example |
|---|---|
| JSON files | API payloads |
| CSV files | Large datasets |
| Python dictionaries | Small test data sets |
| Fixtures | Reusable test objects |
| Databases | Integration testing |
| Parametrization | Multiple input combinations |
Example:
test_users = [
{"username": "user1"},
{"username": "user2"}
]If they ask what mistake people commonly make here, then you can say that: it would be hardcoding test data directly inside test cases. Separating test data from test logic makes updates easier and reduces duplication.
4. How do you write Pytest tests for API testing?
API tests involve sending requests to an endpoint and validating the response returned by the server.
Example using the requests library:
import requests
def test_get_user():
response = requests.get(
"https://api.example.com/users/1"
)
assert response.status_code == 200This test sends a GET request and verifies that the server responds with a successful status code.
Depending on the endpoint being tested, additional validations may include:
- Status codes
- Response body content
- Response schema
- Response headers
- Authentication and authorization
- Error responses
For example, after verifying the status code, a test may validate that the expected user data is returned:
data = response.json()
assert data["id"] == 1
assert "name" in dataAs the number of API tests increases, request setup, authentication tokens, and common validation logic are often moved into fixtures or helper classes so they can be reused across multiple tests.
5. How do you handle flaky tests in a Pytest automation suite?
This one can be a bit tricky but you’ll have to articulate your answer for it since the methods keep branching to handle this.
Here’s how you can answer it -
A flaky test produces inconsistent results without any changes to the application or test code. The same test may pass in one execution and fail in the next.
Common causes include:
- Timing issues
- Hardcoded waits
- Shared test data
- Environment instability
- External service dependencies
- Order-dependent tests
When investigating a flaky test, I usually start by reviewing the test logs, reports, screenshots, and error messages to identify where the failure occurs. If the test interacts with a UI, I check for timing-related issues such as fixed sleep statements, slow page loads, or elements that are not fully loaded before interaction.
Next, I verify whether the test depends on shared data, external services, or the execution of another test. Tests should be able to run independently and produce the same result regardless of execution order.
Some common ways to reduce flaky behaviour include:
- Replacing fixed sleeps with explicit waits
- Isolating test data between executions
- Mocking unreliable external services
- Removing dependencies between tests
- Ensuring each test starts with a known state
Retries can sometimes help identify intermittent failures, but they should not be treated as a permanent solution. If a test passes only after being retried, the underlying cause still needs to be investigated and fixed.
You can check out more such practice questions at Selenium Interview Questions and Answers and learn more with Selenium Tutorial