Book Image

pytest Quick Start Guide

By : Bruno Oliveira
Book Image

pytest Quick Start Guide

By: Bruno Oliveira

Overview of this book

Python's standard unittest module is based on the xUnit family of frameworks, which has its origins in Smalltalk and Java, and tends to be verbose to use and not easily extensible.The pytest framework on the other hand is very simple to get started, but powerful enough to cover complex testing integration scenarios, being considered by many the true Pythonic approach to testing in Python. In this book, you will learn how to get started right away and get the most out of pytest in your daily work?ow, exploring powerful mechanisms and plugins to facilitate many common testing tasks. You will also see how to use pytest in existing unittest-based test suites and will learn some tricks to make the jump to a pytest-style test suite quickly and easily.
Table of Contents (9 chapters)

Autouse

It is possible to apply a fixture to all of the tests in a hierarchy, even if the tests don't explicitly request a fixture, by passing autouse=True to the @pytest.fixture decorator. This is useful when we need to apply a side-effect before and/or after each test unconditionally.

@pytest.fixture(autouse=True)
def setup_dev_environment():
previous = os.environ.get('APP_ENV', '')
os.environ['APP_ENV'] = 'TESTING'
yield
os.environ['APP_ENV'] = previous

An autouse fixture is applied to all tests which the fixture is available for use with:

  • Same module as the fixture
  • Same class as the fixture, in the case of a fixture defined by a method
  • Tests in the same directory or below, if the fixture is defined in a conftest.py file

In other words, if a test can access an autouse fixture by declaring it in the parameter...