-
-
Notifications
You must be signed in to change notification settings - Fork 432
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
# Testing | ||
|
||
**Django Ninja** provides a test client to make it easy to test your API. | ||
|
||
To test the following API: | ||
```python | ||
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) | ||
``` | ||
|
||
You can use the Django test class: | ||
```python | ||
from django.test import TestCase | ||
from ninja.testing import TestClient | ||
|
||
class HelloTest(TestCase): | ||
def test_hello(self): | ||
client = NinjaTestClient(router) | ||
response = client.get("/hello") | ||
|
||
self.assertEqual(response.status_code, 200) | ||
self.assertEqual(response.json(), {"msg": "Hello World"}) | ||
``` | ||
|
||
Arbitrary attributes can be added to the request object by passing keyword arguments to the client request methods: | ||
```python | ||
class HelloTest(TestCase): | ||
def test_hello(self): | ||
client = NinjaTestClient(router) | ||
# request.company_id will now be set within the view | ||
response = client.get("/hello", company_id=1) | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters