pytest-describe

3.1.0 · active · verified Mon Apr 13

pytest-describe is a plugin for the pytest testing framework that enables writing tests in an RSpec/Jasmine-style format, using arbitrary nested `describe-blocks`. This approach helps organize tests by context and behavior, making test suites more readable and maintainable. The current version is 3.1.0, and it is actively maintained with regular updates to support newer Python and pytest versions.

Warnings

Install

Imports

Quickstart

This example demonstrates how to structure tests for a `Wallet` class using nested `describe_` blocks and `pytest` fixtures. Define a top-level `describe_` function, and then nest further `describe_` functions or test functions (which can also use the `it_` prefix) within them. Fixtures defined within a `describe_` block apply to all tests within that block and its nested blocks. Save this as a Python file (e.g., `test_wallet.py`) and run `pytest` from your terminal.

import pytest

class Wallet:
    def __init__(self, initial_amount=0):
        self.balance = initial_amount

    def spend_cash(self, amount):
        if self.balance < amount:
            raise ValueError(f'Not enough available to spend {amount}')
        self.balance -= amount

    def add_cash(self, amount):
        self.balance += amount

def describe_wallet():
    def describe_start_empty():
        @pytest.fixture
        def wallet():
            return Wallet()

        def initial_amount_is_zero(wallet):
            assert wallet.balance == 0

        def can_add_cash(wallet):
            wallet.add_cash(80)
            assert wallet.balance == 80

        def cannot_spend_if_empty(wallet):
            with pytest.raises(ValueError):
                wallet.spend_cash(10)

    def describe_with_starting_balance():
        @pytest.fixture
        def wallet():
            return Wallet(20)

        def initial_amount_is_twenty(wallet):
            assert wallet.balance == 20

        def describe_adding():
            def add_little_cash(wallet):
                wallet.add_cash(5)
                assert wallet.balance == 25

            def add_much_cash(wallet):
                wallet.add_cash(980)
                assert wallet.balance == 1000

        def describe_spending():
            def spend_cash(wallet):
                wallet.spend_cash(15)
                assert wallet.balance == 5

            def spend_too_much_cash(wallet):
                with pytest.raises(ValueError):
                    wallet.spend_cash(25)

view raw JSON →