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)

Using marks from fixtures

We can use the request fixture to access marks that are applied to test functions.

Suppose we have an autouse fixture that always initializes the current locale to English:

@pytest.fixture(autouse=True)
def setup_locale():
locale.setlocale(locale.LC_ALL, "en_US")
yield
locale.setlocale(locale.LC_ALL, None)

def test_currency_us():
assert locale.currency(10.5) == "$10.50"

But what if we want to use a different locale for just a few tests?

One way to do that is to use a custom mark, and access the mark object from within our fixture:

@pytest.fixture(autouse=True)
def setup_locale(request):
mark = request.node.get_closest_marker("change_locale")
loc = mark.args[0] if mark is not None else "en_US"
locale.setlocale(locale.LC_ALL, loc)
yield
locale.setlocale(locale.LC_ALL, None)

@pytest.mark.change_locale...