测试
Django Ninja 与标准的 django 测试客户端完全兼容,但也提供了一个测试客户端,以便于仅测试 API,而无需中间件/URL 解析层,从而使测试运行得更快。
要测试以下 API:
from ninja import NinjaAPI, Schema
api = NinjaAPI()
router = Router()
class HelloResponse(Schema):
msg: str
@router.get("/hello", response=HelloResponse)
def hello(request):
return {"msg": "Hello World"}
api.add_router("", router)
你可以使用 Django 测试类:
from django.test import TestCase
from ninja.testing import TestClient
class HelloTest(TestCase):
def test_hello(self):
client = TestClient(router)
response = client.get("/hello")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {"msg": "Hello World"})
class HelloTest(TestCase):
def test_hello(self):
client = TestClient(router)
# request.company_id will now be set within the view
response = client.get("/hello", company_id=1)
大功告成
继续下一小节 API 文档
评论
本文总阅读量次