Mastering pytest: A Comprehensive Guide

Table of Contents

Pytest Drill

Running Tests

How do I run all tests in the current directory?   drill python_pytest

Answer
  • pytest

How do I run all tests in a specific file?   drill python_pytest

Answer
  • pytest <filename>

How do I run a specific test function?   drill python_pytest

Answer
  • pytest <filename>::<functionname>

How do I run all tests with a specific marker?   drill python_pytest

Answer
  • pytest -m <markername>

Fixtures

What is a fixture in pytest?   drill python_pytest

Answer
  • A setup function that provides a fixed baseline so that tests execute reliably and consistently.

How do I define a fixture in pytest?   drill python_pytest

Answer
  • Using the `@pytest.fixture` decorator.

How do I use a fixture in a test function?   drill python_pytest

Answer
  • By including the fixture name as an argument in the test function.

Assertions

How do I make an assertion in pytest?   drill python_pytest

Answer
  • Using the `assert` statement.

What happens if an assertion fails in pytest?   drill python_pytest

Answer
  • The test fails and pytest displays an error message.

Markers

What is a marker in pytest?   drill python_pytest

Answer
  • A way to categorize tests based on certain characteristics.

How do I define a marker in pytest?   drill python_pytest

Answer
  • Using the `@pytest.mark` decorator.

How do I run all tests with a specific marker?   drill python_pytest

Answer
  • pytest -m <markername>

Skipping Tests

How do I skip a test in pytest?   drill python_pytest

Answer
  • Using the `@pytest.mark.skip` decorator.

How do I skip a test based on a condition?   drill python_pytest

Answer
  • Using the `@pytest.mark.skipif` decorator.

Xfail

What is xfail in pytest?   drill python_pytest

Answer
  • A way to mark a test as expected to fail.

How do I mark a test as xfail in pytest?   drill python_pytest

Answer
  • Using the `@pytest.mark.xfail` decorator.

Parametrize

What is parametrize in pytest?   drill python_pytest

Answer
  • A way to run the same test function with different inputs.

How do I parametrize a test function in pytest?   drill python_pytest

Answer
  • Using the `@pytest.mark.parametrize` decorator.

Plugins

What is a plugin in pytest?   drill python_pytest

Answer
  • A way to extend the functionality of pytest.

How do I install a pytest plugin?   drill python_pytest

Answer
  • Using pip, e.g. `pip install pytest-<pluginname>`.

Author: Jason Walsh

j@wal.sh

Last Updated: 2024-08-14 13:07:23