Testing a DRF endpoint with pytest, factory_boy and a mocked external API

Backend Live Coding November 13, 2026 python

Write a test for an endpoint using pytest, factory_boy and a mock of an external API.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# ======================================================================
# Q: Write a test for an endpoint using pytest, factory_boy and a mock of an
# external API.
# ======================================================================

class ProductFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Product
    sku = factory.Sequence(lambda n: f'SKU-{n}')
    price = Decimal('10.00')
    stock = 5

@pytest.mark.django_db
def test_place_order_reduces_stock(api_client, customer_user, mocker):
    product = ProductFactory(stock=5)
    charge = mocker.patch('orders.services.psp.charge', return_value='ch_123')
    api_client.force_authenticate(customer_user)

    r = api_client.post('/api/v1/orders/',
                        {'items': [{'product': product.pk, 'quantity': 2}]}, format='json')

    assert r.status_code == 201
    product.refresh_from_db()
    assert product.stock == 3
    charge.assert_called_once()

@pytest.mark.django_db
def test_cannot_order_more_than_stock(api_client, customer_user):
    product = ProductFactory(stock=1)
    api_client.force_authenticate(customer_user)
    r = api_client.post('/api/v1/orders/',
                        {'items': [{'product': product.pk, 'quantity': 2}]}, format='json')
    assert r.status_code == 409