Exemple #1
0
def test_examples():

    api = NinjaAPI()

    with patch("builtins.api", api, create=True):
        import docs.src.tutorial.path.code010

        client = NinjaClient(api)

        response = client.get("/events/2020/1/1")
        assert response.json() == {"date": "2020-01-01"}
        schema = api.get_openapi_schema("")
        events_params = schema["paths"]["/events/{year}/{month}/{day}"]["get"][
            "parameters"]
        assert events_params == [
            {
                "in": "path",
                "name": "year",
                "required": True
            },
            {
                "in": "path",
                "name": "month",
                "required": True
            },
            {
                "in": "path",
                "name": "day",
                "required": True
            },
        ]
Exemple #2
0
def test_intro():
    from docs.src.tutorial.authentication.code001 import api

    client = NinjaClient(api)
    assert client.get("/pets").status_code == 401

    user = Mock()
    user.is_authenticated = True

    response = client.get("/pets", user=user)
    assert response.status_code == 200
def test_no_handlers():
    api = NinjaAPI()
    api._exception_handlers = {}

    @api.get("/error")
    def thrower(request):
        raise RuntimeError("test")

    client = NinjaClient(api)

    with pytest.raises(RuntimeError):
        client.get("/error")
Exemple #4
0
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,
                               },
                           }
Exemple #5
0
def test_examples():

    api = NinjaAPI()

    with patch("builtins.api", api, create=True):
        import docs.src.tutorial.path.code010
        import docs.src.tutorial.path.code02
        import docs.src.tutorial.path.code01

        client = NinjaClient(api)

        response = client.get("/items/123")
        assert response.json() == {"item_id": 123}

        response = client.get("/events/2020/1/1")
        assert response.json() == {"date": "2020-01-01"}
        schema = api.get_openapi_schema("")
        events_params = schema["paths"]["/events/{year}/{month}/{day}"]["get"][
            "parameters"]
        # print(events_params, "!!")
        assert events_params == [
            {
                "in": "path",
                "name": "year",
                "required": True,
                "schema": {
                    "title": "Year",
                    "type": "integer"
                },
            },
            {
                "in": "path",
                "name": "month",
                "required": True,
                "schema": {
                    "title": "Month",
                    "type": "integer"
                },
            },
            {
                "in": "path",
                "name": "day",
                "required": True,
                "schema": {
                    "title": "Day",
                    "type": "integer"
                },
            },
        ]
Exemple #6
0
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
Exemple #7
0
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
Exemple #8
0

router = Router()


@router.post("/book")
def booking_request(request, booking: Booking):
    return booking


@router.get("/search")
def booking_search(request, date: date, room: RoomEnum):
    return {"date": date, "room": room}


client = NinjaClient(router)


def test_enums():
    response = client.post("/book",
                           json={
                               "start": "2020-01-01",
                               "end": "2020-01-02",
                               "room": "double"
                           })
    assert response.status_code == 200, response.content
    assert response.json() == {
        "start": "2020-01-01",
        "end": "2020-01-02",
        "room": "double",
    }
Exemple #9
0

api = NinjaAPI()


@api.post("/book")
def create_booking(request, booking: Booking):
    return booking


@api.get("/search")
def booking_search(request, room: RoomEnum):
    return {"room": room}


client = NinjaClient(api)


def test_enums():
    response = client.post("/book",
                           json={
                               "start": "2020-01-01",
                               "end": "2020-01-02",
                               "room": "double"
                           })
    assert response.status_code == 200, response.content
    assert response.json() == {
        "start": "2020-01-01",
        "end": "2020-01-02",
        "room": "double",
    }
Exemple #10
0
def test_csrf_off():
    client = NinjaClient(csrf_OFF)
    assert client.post("/post", COOKIES=COOKIES).status_code == 200
Exemple #11
0
def test_examples():
    from someapp.models import Client

    api = NinjaAPI(csrf=True)
    Client.objects.create(key="12345")

    with patch("builtins.api", api, create=True):
        import docs.src.tutorial.authentication.code002
        import docs.src.tutorial.authentication.apikey01
        import docs.src.tutorial.authentication.apikey02
        import docs.src.tutorial.authentication.apikey03
        import docs.src.tutorial.authentication.basic01
        import docs.src.tutorial.authentication.bearer01
        import docs.src.tutorial.authentication.code001
        import docs.src.tutorial.authentication.schema01
        import docs.src.tutorial.authentication.multiple01

        client = NinjaClient(api)

        response = client.get("/ipwhiltelist",
                              META={"REMOTE_ADDR": "127.0.0.1"})
        assert response.status_code == 401
        response = client.get("/ipwhiltelist", META={"REMOTE_ADDR": "8.8.8.8"})
        assert response.status_code == 200

        # Api key --------------------------------

        response = client.get("/apikey")
        assert response.status_code == 401
        response = client.get("/apikey?api_key=12345")
        assert response.status_code == 200

        response = client.get("/headerkey")
        assert response.status_code == 401
        response = client.get("/headerkey",
                              headers={"X-API-Key": "supersecret"})
        assert response.status_code == 200

        response = client.get("/cookiekey")
        assert response.status_code == 401
        response = client.get("/cookiekey", COOKIES={"key": "supersecret"})
        assert response.status_code == 200

        # Basic http --------------------------------

        response = client.get("/basic")
        assert response.status_code == 401
        response = client.get(
            "/basic", headers={"Authorization": "Basic YWRtaW46c2VjcmV0"})
        assert response.status_code == 200
        assert response.json() == {"httpuser": "******"}

        # Bearer http --------------------------------

        response = client.get("/bearer")
        assert response.status_code == 401

        response = client.get("/bearer",
                              headers={"Authorization": "Bearer supersecret"})
        assert response.status_code == 200

        # Multiple ------------------------------------
        assert client.get("/multiple").status_code == 401
        assert client.get("/multiple?key=supersecret").status_code == 200
        assert (client.get("/multiple", headers={
            "key": "supersecret"
        }).status_code == 200)
Exemple #12
0
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"]}
Exemple #13
0
def test_examples():

    api = NinjaAPI()

    with patch("builtins.api", api, create=True):
        import docs.src.tutorial.query.code01
        import docs.src.tutorial.query.code02
        import docs.src.tutorial.query.code03
        import docs.src.tutorial.query.code010

        client = NinjaClient(api)

        # Defaults
        assert client.get("/weapons").json() == [
            "Ninjato",
            "Shuriken",
            "Katana",
            "Kama",
            "Kunai",
            "Naginata",
            "Yari",
        ]

        assert client.get("/weapons?offset=0&limit=3").json() == [
            "Ninjato",
            "Shuriken",
            "Katana",
        ]

        assert client.get("/weapons?offset=2&limit=2").json() == [
            "Katana",
            "Kama",
        ]

        # Required/Optional

        assert client.get("/weapons/search?offset=1&q=k").json() == [
            "Katana",
            "Kama",
            "Kunai",
        ]

        # Coversion

        # fmt: off
        assert client.get("/example?b=1").json() == [None, True, None, None]
        assert client.get("/example?b=True").json() == [None, True, None, None]
        assert client.get("/example?b=true").json() == [None, True, None, None]
        assert client.get("/example?b=on").json() == [None, True, None, None]
        assert client.get("/example?b=yes").json() == [None, True, None, None]
        assert client.get("/example?b=0").json() == [None, False, None, None]
        assert client.get("/example?b=no").json() == [None, False, None, None]
        assert client.get("/example?b=false").json() == [
            None, False, None, None
        ]
        assert client.get("/example?d=1577836800").json() == [
            None, None, "2020-01-01", None
        ]
        assert client.get("/example?d=2020-01-01").json() == [
            None, None, "2020-01-01", None
        ]
        # fmt: on

        # Schema

        assert client.get("/filter").json() == {
            "filters": {
                "limit": 100,
                "offset": None,
                "query": None
            }
        }
        assert client.get("/filter?limit=10").json() == {
            "filters": {
                "limit": 10,
                "offset": None,
                "query": None
            }
        }
        assert client.get("/filter?offset=10").json() == {
            "filters": {
                "limit": 100,
                "offset": 10,
                "query": None
            }
        }
        assert client.get("/filter?query=10").json() == {
            "filters": {
                "limit": 100,
                "offset": None,
                "query": "10"
            }
        }

        schema = api.get_openapi_schema("")
        params = schema["paths"]["/filter"]["get"]["parameters"]
        assert params == [
            {
                "in": "query",
                "name": "limit",
                "required": False,
                "schema": {
                    "title": "Limit",
                    "default": 100,
                    "type": "integer"
                },
            },
            {
                "in": "query",
                "name": "offset",
                "required": False,
                "schema": {
                    "title": "Offset",
                    "type": "integer"
                },
            },
            {
                "in": "query",
                "name": "query",
                "required": False,
                "schema": {
                    "title": "Query",
                    "type": "string"
                },
            },
        ]
def test_response_class(api, content_type, expected_content):
    client = NinjaClient(api)
    response = client.get("/test")
    assert response.status_code == 200
    assert response["Content-Type"] == content_type
    assert response.content.decode() == expected_content