Complete worked example
python
from bootstrap_lab import django_setup
django_setup(__name__)
import io
import unittest
from django.http import JsonResponse
from django.test import SimpleTestCase
from django.urls import path
current_count, extra_field = 2, False
def summary(request):
result = {"count": current_count}
if extra_field:
result["debug"] = True
return JsonResponse(result)
urlpatterns = [path("summary/", summary)]
class ContractTests(SimpleTestCase):
def test_status(self):
self.assertEqual(self.client.get("/summary/").status_code, 200)
def test_count(self):
self.assertEqual(self.client.get("/summary/").json()["count"], 2)
def suite_result(count, extra=False):
global current_count, extra_field
current_count, extra_field = count, extra
suite = unittest.TestLoader().loadTestsFromTestCase(ContractTests)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
return {"passed": result.wasSuccessful(), "tests": result.testsRun}- Reasoning
- The suite checks status and the declared count value in separate tests. The helper supplies controlled response state, creates a fresh suite and captures the test runner’s output instead of printing it into the application response.