Testing¶
- class django_orjson.test.Client[source]¶
A subclass of Django’s test client that uses orjson to:
Encode request JSON.
Parse response JSON, in the patched-on
response.json()method.
Request encoding uses
django_orjson.default()for extended type support. Django’sjson_encoderargument 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 settingclient_class.If you use pytest fixtures, you can replace the the
clientfixture from pytest-django with a custom one that returns django-orjson’s client in yourconftest.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
SimpleTestCasethat:Uses
Clientas itsclient_class.Uses
AsyncClientas itsasync_client_class.Parses JSON with orjson in
assertJSONEqual()andassertJSONNotEqual().
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!" }