72 lines
2.0 KiB
Python
72 lines
2.0 KiB
Python
from decimal import Decimal
|
|
|
|
from fake_data import fake
|
|
from starlette.testclient import TestClient
|
|
|
|
from allmende_payment_system.database import ensure_user
|
|
from allmende_payment_system.models import (
|
|
Account,
|
|
Area,
|
|
Order,
|
|
OrderItem,
|
|
Product,
|
|
Transaction,
|
|
)
|
|
|
|
|
|
def create_user_with_account(test_db, username: str, balance: float | None = None):
|
|
user_info = {"username": username, "display_name": f"Display {username}"}
|
|
user = ensure_user(user_info, test_db)
|
|
account = Account(name=f"Account for {username}")
|
|
test_db.add(account)
|
|
user.accounts.append(account)
|
|
|
|
if balance is not None:
|
|
user.accounts[0].transactions.append(
|
|
Transaction(total_amount=Decimal(balance), type="deposit")
|
|
)
|
|
test_db.flush()
|
|
return user
|
|
|
|
|
|
def test_add_item_to_cart(client: TestClient, test_db):
|
|
area = Area(**fake.area())
|
|
test_db.add(area)
|
|
product = Product(**fake.product())
|
|
product.area = area
|
|
test_db.add(product)
|
|
test_db.flush()
|
|
form_data = {"product_id": product.id, "quantity": 2, "area_id": area.id}
|
|
|
|
response = client.post(
|
|
"/shop/cart/add",
|
|
data=form_data,
|
|
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
|
follow_redirects=False,
|
|
)
|
|
assert response.status_code == 302
|
|
|
|
|
|
def test_finalize_order(client: TestClient, test_db):
|
|
area = Area(**fake.area())
|
|
test_db.add(area)
|
|
product = Product(**fake.product())
|
|
product.area = area
|
|
test_db.add(product)
|
|
test_db.flush()
|
|
|
|
user = create_user_with_account(test_db, "test", balance=100.0)
|
|
|
|
user.shopping_cart.items.append(
|
|
OrderItem(product=product, quantity=2, total_amount=product.price * 2)
|
|
)
|
|
test_db.flush()
|
|
|
|
response = client.get("/shop/finalize_order", follow_redirects=False)
|
|
assert response.status_code == 302
|
|
|
|
assert len(user.shopping_cart.items) == 0
|
|
assert len(user.orders) == 2 # shopping cart + finalized order
|
|
|
|
assert user.accounts[0].balance == Decimal(100.0) - (product.price * 2)
|