Skip to content

Instantly share code, notes, and snippets.

@ksamuel
Last active July 17, 2024 11:21
Show Gist options
  • Save ksamuel/f5ecac891b6d046092a424eeb365f068 to your computer and use it in GitHub Desktop.
Save ksamuel/f5ecac891b6d046092a424eeb365f068 to your computer and use it in GitHub Desktop.
Isolated tests
import json
from pathlib import Path
import pytest
from mockito import when, mock
from django.urls import reverse
from django.shortcuts import get_object_or_404
from ninja.testing import TestClient
from .views import add_to_cart
from .models import Product, User, CartSchema, CartItem, Product
from .endpoints import api
client = TestClient(api)
schema_file = Path('api_schema.json')
@pytest.fixture
def cart(db):
user = User.objects.create_user(username='testuser', password='testpass')
return Cart.objects.create(user=user)
@pytest.fixture
def product(db):
return Product.objects.create(name='Test Product', price=10.00)
def test_add_existing_item_to_cart(cart, product, cart_item):
cart_item = CartItem.objects.create(cart=cart, product=product, quantity=1)
updated_cart_item = add_item_to_cart(cart, product, 2)
cart_item.refresh_from_db()
assert cart_item.quantity == 3
assert updated_cart_item == cart_item
def test_add_new_item_to_cart(product, cart):
new_product = Product.objects.create(name='New Product', price=15.00)
new_cart_item = add_item_to_cart(cart, new_product, 1)
assert new_cart_item.cart == cart
assert new_cart_item.product == new_product
assert new_cart_item.quantity == 1
def test_add_to_cart_endpoint():
product_mock = mock()
cart_mock = mock()
cart_item_mock = mock(quantity=1)
user_mock = mock(cart=cart_mock)
request_mock = mock(user=user_mock)
when(get_object_or_404).called_with(Product, id=1).thenReturn(product_mock)
when(add_item_to_cart).called_with(cart_mock, product_mock, 1).thenReturn(cart_item_mock)
response = add_to_cart(request_mock, CartSchema(id=1, quantity=1))
assert response == {"id": 1, "quantity": 1}
def test_api_schema(get_api_schema):
if not schema_file.exists():
pytest.fail(f"API schema is missing, please run ./manage.py dump_schema.")
current_schema = client.get(reverse("api:schema")).json()
saved_schema = json.loads(schema_file.read_text())
if current_schema != saved_schema:
pytest.fail("API schema has changed. Follow the stability policy.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment