bdd_wallet.py


Overview

`bdd_wallet.py` is a behavior-driven development (BDD) test module designed to verify the functionality of a simple wallet system using the `pytest-bdd` framework. The file defines a BDD scenario for purchasing fruits and ensures that the wallet's amount is correctly adjusted after buying apples and bananas. This module uses Gherkin language feature steps mapped to Python functions to simulate and validate wallet operations such as initializing the wallet, performing purchases, and checking the remaining balance.


Contents and Functionality

Scenario Definition

@scenario("bdd_wallet.feature", "Buy fruits")
def test_publish():
    pass

Fixture: wallet

@pytest.fixture
def wallet():
    class Wallet:
        amount = 0

    return Wallet()

Step Definitions

These functions implement the Gherkin steps for the BDD scenario.

fill_wallet(wallet)

@given("A wallet with 50")
def fill_wallet(wallet):
    wallet.amount = 50

buy_apples(wallet)

@when("I buy some apples for 1")
def buy_apples(wallet):
    wallet.amount -= 1

buy_bananas(wallet)

@when("I buy some bananas for 2")
def buy_bananas(wallet):
    wallet.amount -= 2

check(wallet)

@then("I have 47 left")
def check(wallet):
    assert wallet.amount == 47

Important Implementation Details


Interaction with Other Parts of the System


Usage Example

To run the tests defined in this file, execute the following command in the terminal:

pytest bdd_wallet.py

This will:

  1. Parse the linked bdd_wallet.feature file.

  2. Execute the scenario "Buy fruits".

  3. Run the step implementations defined here.

  4. Provide a pass/fail status based on the wallet balance assertion.


Mermaid Class Diagram

classDiagram
    class Wallet {
        +int amount
    }
    class bdd_wallet {
        +test_publish()
        +fill_wallet(wallet)
        +buy_apples(wallet)
        +buy_bananas(wallet)
        +check(wallet)
        +wallet() <<fixture>>
    }
    bdd_wallet --> Wallet : uses

Summary

`bdd_wallet.py` is a minimal but clear example of applying BDD testing with `pytest-bdd` for a wallet use case. It demonstrates how to define test scenarios, use fixtures, and implement step definitions that reflect business rules. The file is primarily a test harness and relies on an external `.feature` file to describe behavior in Gherkin syntax. This modular approach allows easy extension for more complex wallet operations or other domain-specific features.