Skip to content

Instantly share code, notes, and snippets.

View klement97's full-sized avatar
๐ŸŒ
Open for opportunities

Klement Omeri klement97

๐ŸŒ
Open for opportunities
View GitHub Profile
@property
def total_price(self) -> Decimal:
"""
Total price is sum of pizza prices in this order.
"""
price = Decimal(0)
for pizza in self.pizzas.all():
price += pizza.total_price
return price
@property
def total_price(self) -> Decimal:
"""
Total price is sum of the following:
- Pizza total price
- Size price
- Sum of toppings
"""
price = self.pizza.total_price + self.size.price
for topping in self.extra_toppings.all():
class Pizza(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
toppings = models.ManyToManyField(Topping, related_name='pizzas')
@property
def total_price(self) -> Decimal:
"""
Total price is sum of all topping prices.
"""
import pytest
from order.models import Pizza, Topping
@pytest.mark.django_db
def test_pizza_price_with_toppings():
# Preparation phase
pizza = Pizza.objects.create(name='Margarita')
topping1 = Topping.objects.create(description='Pizza sauce', price=1.5)
[pytest]
DJANGO_SETTINGS_MODULE = pizza_app.test_settings
# -- recommended but optional:
python_files = tests.py test_*.py *_tests.py
addopts = --reuse-db --nomigrations
pizza = Pizza.objects.create(name='Margarita')
topping1 = Topping.objects.create(description='Pizza sauce', price=1.5)
topping2 = Topping.objects.create(description='Mozzarella', price=1.65)
pizza.toppings.add(topping1)
pizza.toppings.add(topping2)
pizza = baker.make('order.Pizza')
topping1 = baker.make('order.Topping')
topping2 = baker.make('order.Topping')
pizza.toppings.add(topping1)
pizza.toppings.add(topping2)
def create_pizza(number_of_toppings: int, **kwargs) -> Pizza:
pizza = baker.make('order.Pizza', **kwargs)
for _ in range(number_of_toppings):
pizza.toppings.add(baker.make('order.Topping'))
return pizza
@pytest.mark.django_db
def test_pizza_price_with_toppings():
# Preparation phase
pizza = create_pizza(number_of_toppings=2)
# Calculating results
actual_price = pizza.total_price
expected_price = sum([t.price for t in pizza.toppings.all()])
# Assertion
@pytest.mark.django_db
@pytest.mark.parametrize('number_of_toppings', list(range(0, 10)))
def test_pizza_price(number_of_toppings):
# Preparation phase
pizza = create_pizza(number_of_toppings=number_of_toppings)
# Calculating results
actual_price = pizza.total_price
expected_price = Decimal(sum([t.price for t in pizza.toppings.all()]))