Skip to content

Unit Testing

Execution

Install Pytest

pip install pytest

Run the tests

pytest

Run a specific file

pytest test_shopping_cart.py

Run a specific test

pytest test_shopping_cart.py::test_can_get_total_price

File Naming Convention

Files containing tests should start with test_

Imports

from unittest.mock import Mock
from item_database import ItemDatabase
from shopping_cart import ShoppingCart
import pytest

Fixture

@pytest.fixture
def cart():
    # All setup for the cart here...
    return ShoppingCart(5)

Basic Unit-Tests

def test_can_add_item_to_cart(cart):
    cart.add("apple")
    assert cart.size() == 1
def test_when_item_added_then_cart_contains_item(cart):
    cart.add("apple")
    assert "apple" in cart.get_items()
def test_when_add_more_than_max_items_should_fail(cart):
    for _ in range(5):
        cart.add("apple")

    with pytest.raises(OverflowError):
        cart.add("apple")

Mocking

def test_can_get_total_price(cart):
    cart.add("apple")
    cart.add("orange")
    item_database = ItemDatabase()

    def mock_get_item(item: str):
        if item == "apple":
            return 1.0
        if item == "orange":
            return 2.0

    item_database.get = Mock(side_effect=mock_get_item)
    assert cart.get_total_price(item_database) == 3.0
Last Updated: 2024-01-24 ; Contributors: AhmedThahir

Comments