Skip to content

Instantly share code, notes, and snippets.

@ksamuel
Last active July 18, 2024 20:36
Show Gist options
  • Save ksamuel/1029322482b7b88559ff42899c45c3a5 to your computer and use it in GitHub Desktop.
Save ksamuel/1029322482b7b88559ff42899c45c3a5 to your computer and use it in GitHub Desktop.
Integrated tests
import pytest
from django.contrib.auth.models import User
from ninja.testing import TestClient
from .models import Product, CartItem, Cart
from .endpoints import api
@pytest.fixture
def user(db): # db fixture assumed from pytest-django
user = User.objects.create_user(username='testuser', password='testpass')
Cart.objects.create(user=user)
return user
@pytest.fixture
def client(user):
return TestClient(api)
@pytest.fixture
def authenticated_client(client, user):
client.authenticate(user)
return client
@pytest.fixture
def product(db):
return Product.objects.create(name='Test Product', price=10.0)
@pytest.fixture
def cart_item(db, user, product):
return CartItem.objects.create(cart=user.cart, product=product, quantity=1)
def test_user_not_authenticated(product, client):
response = client.post('/cart', json={'product_id': product.id, 'quantity': 1})
assert response.status_code == 401
def test_non_existing_product_raises_404(authenticated_client):
payload = {'product_id': 9999, 'quantity': 1}
response = authenticated_client.post('/cart', json=payload)
assert response.status_code == 404
def test_cart_item_quantity_incremented(authenticated_client, product, cart_item):
payload = {'product_id': product.id, 'quantity': 1}
response = authenticated_client.post('/cart', json=payload)
assert response.status_code == 200
cart_item.refresh_from_db()
assert cart_item.quantity == 2
def test_cart_item_created_if_not_exist(authenticated_client, product):
payload = {'product_id': product.id, 'quantity': 1}
response = authenticated_client.post('/cart', json=payload)
cart_item = CartItem.objects.get(cart=user.cart, product=product)
assert response.status_code == 200
assert cart_item.quantity == 1
assert response.json() == {"id": product.id, "quantity": 1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment