Back to Repositories

Testing Strategy Pattern Discount Calculations in python-patterns

This test suite validates the Strategy pattern implementation for order discount calculations in Python. It verifies different discount strategies and their application to order totals, ensuring correct calculation and validation of discount functions.

Test Coverage Overview

The test suite provides comprehensive coverage of the Order class and discount strategy implementations.

Key areas tested include:
  • Discount function return values
  • Order strategy validation
  • Discount application calculations
  • Edge case handling for invalid discount strategies

Implementation Analysis

The testing approach uses pytest’s parameterization to efficiently test multiple discount strategies. The implementation verifies both ten_percent_discount and on_sale_discount functions, validating their integration with the Order class using the Strategy pattern.

Technical patterns include:
  • Fixture usage for Order instantiation
  • Parameterized test cases
  • Strategy pattern validation

Technical Details

Testing infrastructure includes:
  • pytest framework
  • pytest.fixture for test setup
  • pytest.mark.parametrize for test case variations
  • Assert statements for validation

Best Practices Demonstrated

The test suite demonstrates excellent testing practices through modular test organization and comprehensive validation. Notable practices include:
  • Separation of test cases by functionality
  • Reusable test fixtures
  • Parameterized testing for multiple scenarios
  • Clear test naming conventions
  • Proper error case validation

faif/python-patterns

tests/behavioral/test_strategy.py

            
import pytest

from patterns.behavioral.strategy import Order, on_sale_discount, ten_percent_discount


@pytest.fixture
def order():
    return Order(100)


@pytest.mark.parametrize(
    "func, discount", [(ten_percent_discount, 10.0), (on_sale_discount, 45.0)]
)
def test_discount_function_return(func, order, discount):
    assert func(order) == discount


@pytest.mark.parametrize(
    "func, price", [(ten_percent_discount, 100), (on_sale_discount, 100)]
)
def test_order_discount_strategy_validate_success(func, price):
    order = Order(price, func)

    assert order.price == price
    assert order.discount_strategy == func


def test_order_discount_strategy_validate_error():
    order = Order(10, discount_strategy=on_sale_discount)

    assert order.discount_strategy is None


@pytest.mark.parametrize(
    "func, price, discount",
    [(ten_percent_discount, 100, 90.0), (on_sale_discount, 100, 55.0)],
)
def test_discount_apply_success(func, price, discount):
    order = Order(price, func)

    assert order.apply_discount() == discount