Skip to content

Commit

Permalink
Merge pull request #25 from maticardenas/24-add-possibility-of-defini…
Browse files Browse the repository at this point in the history
…ng-a-prefix-for-the-api-path

feat: introducing path prefix support for SchemaTester
  • Loading branch information
maticardenas committed Mar 14, 2024
2 parents b371571 + 99694a9 commit 9f9687f
Show file tree
Hide file tree
Showing 17 changed files with 272 additions and 6 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

# Django Contract Tester

This is a test utility to validate DRF (Django REST Framework) and Django Ninja test requests & responses against OpenAPI 2 and 3 schema.
This is a test utility to validate `DRF (Django REST Framework)` and `Django Ninja` test requests & responses against `OpenAPI` versions 2.x and 3.x schemas.

It has built-in support for:

Expand Down
1 change: 1 addition & 0 deletions openapi_tester/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
""" Django OpenAPI Schema Tester """

from .case_testers import is_camel_case, is_kebab_case, is_pascal_case, is_snake_case
from .clients import OpenAPIClient
from .loaders import BaseSchemaLoader, DrfSpectacularSchemaLoader, DrfYasgSchemaLoader, StaticSchemaLoader
Expand Down
1 change: 1 addition & 0 deletions openapi_tester/case_testers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
""" Case testers - this module includes helper functions to test key casing """

from __future__ import annotations

from typing import TYPE_CHECKING
Expand Down
1 change: 1 addition & 0 deletions openapi_tester/clients.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Subclass of ``APIClient`` using ``SchemaTester`` to validate responses."""

from __future__ import annotations

from typing import TYPE_CHECKING
Expand Down
1 change: 1 addition & 0 deletions openapi_tester/constants.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
""" Constants module """

OPENAPI_PYTHON_MAPPING = {
"boolean": bool.__name__,
"string": str.__name__,
Expand Down
1 change: 1 addition & 0 deletions openapi_tester/loaders.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
""" Loaders Module """

from __future__ import annotations

import difflib
Expand Down
1 change: 1 addition & 0 deletions openapi_tester/response_handler.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
This module contains the concrete response handlers for both DRF and Django Ninja responses.
"""

import json
from typing import TYPE_CHECKING, Optional, Union

Expand Down
17 changes: 14 additions & 3 deletions openapi_tester/schema_tester.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
""" Schema Tester """

from __future__ import annotations

import re
Expand Down Expand Up @@ -68,16 +69,19 @@ def __init__(
schema_file_path: str | None = None,
validators: list[Callable[[dict, Any], str | None]] | None = None,
field_key_map: dict[str, str] | None = None,
path_prefix: str | None = None,
) -> None:
"""
Iterates through an OpenAPI schema object and API response to check that they match at every level.
:param case_tester: An optional callable that validates schema and response keys
:param ignore_case: An optional list of keys for the case_tester to ignore
:schema_file_path: The file path to an OpenAPI yaml or json file. Only passed when using a static schema loader
:param path_prefix: An optional string to prefix the path of the schema file
:raises: openapi_tester.exceptions.DocumentationError or ImproperlyConfigured
"""
self.case_tester = case_tester
self._path_prefix = path_prefix
self.ignore_case = ignore_case or []
self.validators = validators or []

Expand Down Expand Up @@ -132,6 +136,14 @@ def get_schema_type(schema: dict[str, str]) -> str | None:
return "object"
return None

def get_paths_object(self) -> dict[str, Any]:
schema = self.loader.get_schema()
paths_object = self.get_key_value(schema, "paths")
if self._path_prefix:
paths_object = {f"{self._path_prefix}{key}": value for key, value in paths_object.items()}

return paths_object

def get_response_schema_section(self, response_handler: ResponseHandler) -> dict[str, Any]:
"""
Fetches the response section of a schema, wrt. the route, method, status code, and schema version.
Expand All @@ -146,7 +158,7 @@ def get_response_schema_section(self, response_handler: ResponseHandler) -> dict
parameterized_path, _ = self.loader.resolve_path(
response.request["PATH_INFO"], method=response_method # type: ignore
)
paths_object = self.get_key_value(schema, "paths")
paths_object = self.get_paths_object()

route_object = self.get_key_value(
paths_object,
Expand Down Expand Up @@ -212,11 +224,10 @@ def get_request_body_schema_section(self, request: dict[str, Any]) -> dict[str,
:param response: DRF Request Instance
:return dict
"""
schema = self.loader.get_schema()
request_method = request["REQUEST_METHOD"].lower()

parameterized_path, _ = self.loader.resolve_path(request["PATH_INFO"], method=request_method)
paths_object = self.get_key_value(schema, "paths")
paths_object = self.get_paths_object()

route_object = self.get_key_value(
paths_object,
Expand Down
1 change: 1 addition & 0 deletions openapi_tester/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Utils Module - this file contains utility functions used in multiple places.
"""

from __future__ import annotations

from copy import deepcopy
Expand Down
1 change: 1 addition & 0 deletions openapi_tester/validators.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
""" Schema Validators """

from __future__ import annotations

import base64
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "django-contract-tester"
version = "1.2.0"
version = "1.3.0"
description = "Test utility for validating OpenAPI response documentation"
authors =["Matías Cárdenas <cardenasmatias.1990@gmail.com>", "Sondre Lillebø Gundersen <sondrelg@live.no>", "Na'aman Hirschfeld <nhirschfeld@gmail.com>"]
license = "BSD-4-Clause"
Expand All @@ -18,7 +18,6 @@ classifiers = [
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
Expand Down Expand Up @@ -98,6 +97,7 @@ disable = """
import-outside-toplevel,
fixme,
line-too-long,
too-many-arguments,
"""
enable = "useless-suppression"

Expand Down
5 changes: 5 additions & 0 deletions test_project/api/ninja/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,9 @@ def get_users(request):
]


@router.patch("/{user_id}", response={200: UserOut})
def patch_user(request, user_id: int, user: UserIn):
return {"id": 1, "name": "John Doe", "email": "john.doe@example.com"}


ninja_api.add_router("/users", router)
5 changes: 5 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ def pets_api_schema() -> Path:
return TEST_ROOT / "schemas" / "openapi_v3_reference_schema.yaml"


@pytest.fixture()
def pets_api_schema_prefix_in_server() -> Path:
return TEST_ROOT / "schemas" / "openapi_v3_prefix_in_server.yaml"


@pytest.fixture()
def pets_post_request():
request_body = MagicMock()
Expand Down
1 change: 1 addition & 0 deletions tests/schema_converter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
""" Schema to Python converter """

from __future__ import annotations

import base64
Expand Down
170 changes: 170 additions & 0 deletions tests/schemas/openapi_v3_prefix_in_server.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
description: A sample API that uses a petstore as an example to demonstrate features in the OpenAPI 3.0 specification
termsOfService: http://swagger.io/terms/
contact:
name: Swagger API Team
email: apiteam@swagger.io
url: http://swagger.io
license:
name: Apache 2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
servers:
- url: http://petstore.swagger.io/api
paths:
/pets:
get:
description: |
Returns all pets from the system that the user has access to
Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.
Sed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien.
operationId: findPets
parameters:
- name: tags
in: query
description: tags to filter by
required: false
style: form
schema:
type: array
items:
type: string
- name: limit
in: query
description: maximum number of results to return
required: false
schema:
type: integer
format: int32
responses:
'200':
description: pet response
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
post:
description: Creates a new pet in the store. Duplicates are allowed
operationId: addPet
requestBody:
description: Pet to add to the store
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/NewPet'
responses:
'201':
description: pet response
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
'400':
description: Bad Request
content:
application/json:
schema:
type: object
properties:
error:
type: string
message:
type: string
additionalProperties: true
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/pets/{id}:
get:
description: Returns a user based on a single ID, if the user does not have access to the pet
operationId: find pet by id
parameters:
- name: id
in: path
description: ID of pet to fetch
required: true
schema:
type: integer
format: int64
responses:
'200':
description: pet response
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
delete:
description: deletes a single pet based on the ID supplied
operationId: deletePet
parameters:
- name: id
in: path
description: ID of pet to delete
required: true
schema:
type: integer
format: int64
responses:
'204':
description: pet deleted
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
Pet:
allOf:
- $ref: '#/components/schemas/NewPet'
- type: object
required:
- id
properties:
id:
type: integer
format: int64

NewPet:
type: object
required:
- name
properties:
name:
type: string
tag:
type: string

Error:
type: object
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
13 changes: 13 additions & 0 deletions tests/test_django_ninja.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pytest

from openapi_tester import OpenAPIClient, SchemaTester
from openapi_tester.exceptions import UndocumentedSchemaSectionError
from tests.utils import TEST_ROOT

if TYPE_CHECKING:
Expand Down Expand Up @@ -65,3 +66,15 @@ def test_delete_user(client: OpenAPIClient):
path="/ninja_api/users/1",
)
assert response.status_code == 204


def test_patch_user_undocumented_path(client: OpenAPIClient):
payload = {
"name": "John Doe",
}
with pytest.raises(UndocumentedSchemaSectionError):
client.patch(
path="/ninja_api/users/1",
data=json.dumps(payload),
content_type="application/json",
)
Loading

0 comments on commit 9f9687f

Please sign in to comment.