def test_examples(): api = NinjaAPI() with patch("builtins.api", api, create=True): import docs.src.tutorial.body.code01 import docs.src.tutorial.body.code02 import docs.src.tutorial.body.code03 client = NinjaClient(api) assert client.post("/items", json={ "name": "Katana", "price": 299.00, "quantity": 10 }).json() == { "name": "Katana", "description": None, "price": 299.0, "quantity": 10, } assert client.put("/items/1", json={ "name": "Katana", "price": 299.00, "quantity": 10 }).json() == { "item_id": 1, "item": { "name": "Katana", "description": None, "price": 299.0, "quantity": 10, }, } assert client.post("/items/1?q=test", json={ "name": "Katana", "price": 299.00, "quantity": 10 }).json() == { "item_id": 1, "q": "test", "item": { "name": "Katana", "description": None, "price": 299.0, "quantity": 10, }, }
def test_csrf_on(): client = NinjaClient(csrf_ON) assert client.post("/post", COOKIES=COOKIES).status_code == 403 # check with token in formdata response = client.post("/post", {"csrfmiddlewaretoken": TOKEN}, COOKIES=COOKIES) assert response.status_code == 200 # check with headers response = client.post("/post", COOKIES=COOKIES, headers={"X-CSRFTOKEN": TOKEN}) assert response.status_code == 200 # exempt check assert client.post("/post/csrf_exempt", COOKIES=COOKIES).status_code == 200
def test_global(): from docs.src.tutorial.authentication.global01 import api @api.get("/somemethod") def mustbeauthed(request): return {"auth": request.auth} client = NinjaClient(api) assert client.get("/somemethod").status_code == 401 resp = client.post("/token", POST={ "username": "******", "password": "******" }) assert resp.status_code == 200 assert resp.json() == {"token": "supersecret"} resp = client.get("/somemethod", headers={"Authorization": "Bearer supersecret"}) assert resp.status_code == 200
def test_csrf_off(): client = NinjaClient(csrf_OFF) assert client.post("/post", COOKIES=COOKIES).status_code == 200
def test_parser(): client = NinjaClient(api) response = client.post("/test?emptyparam", body="test\nbar") assert response.status_code == 200, response.content assert response.json() == {"emptyparam": None, "body": ["test", "bar"]}