Testing

class django_orjson.test.Client[source]

A subclass of Django’s test client that uses orjson to:

  1. Encode request JSON.

  2. Parse response JSON, in the patched-on response.json() method.

Request encoding uses django_orjson.default() for extended type support. Django’s json_encoder argument is not used.

Normally, you’ll want to use it by subclassing django-orjson’s SimpleTestCase (below), which sets the client class automatically. But you can also use it directly in your own test classes by setting client_class.

If you use pytest fixtures, you can replace the the client fixture from pytest-django with a custom one that returns django-orjson’s client in your conftest.py:

# conftest.py
import pytest
from django_orjson.test import Client


@pytest.fixture
def client():
    return Client()
class django_orjson.test.AsyncClient[source]

A subclass of Django’s async test client, with the same extensions as the above sync client, Client.

class django_orjson.test.SimpleTestCase[source]

A subclass of Django’s SimpleTestCase that:

  1. Uses Client as its client_class.

  2. Uses AsyncClient as its async_client_class.

  3. Parses JSON with orjson in assertJSONEqual() and assertJSONNotEqual().

Use it like Django’s built-in test case:

from django_orjson.test import SimpleTestCase


class MyTests(SimpleTestCase):
    def test_json(self):
        self.assertJSONEqual('{"key":"value"}', {"key": "value"})

Use it as a base class for your own base test case classes like so:

# example/test.py
from django import test
from django_orjson.test import SimpleTestCase as OrJsonSimpleTestCase


class SimpleTestCase(OrJsonSimpleTestCase):
    pass


class TestCase(SimpleTestCase, test.TestCase):
    pass


class TransactionTestCase(SimpleTestCase, test.TransactionTestCase):
    pass

…then your tests can all import from your own base classes instead of Django’s built-in ones, and they’ll get the benefits of django-orjson automatically, like:

from example.test import SimpleTestCase


class IndexTests(SimpleTestCase):
    def test_index(self):
        response = self.client.get("/", headers={"accept": "application/json"})
        assert response.status_code == 200
        assert response.json() == {  # uses orjson to parse the response body
            "title": "Hello, world!"
        }