Completed
Push — main ( 26039b...693ab2 )
by Juho
17s queued 16s
created

annif.openapi.validation   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 28
dl 0
loc 45
rs 10
c 0
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A CustomRequestBodyValidator.__init__() 0 2 1
B CustomRequestBodyValidator.validate_schema() 0 25 6
1
"""Custom validator for the Annif API."""
2
3
import logging
4
5
import jsonschema
6
from connexion import decorators
7
from connexion.exceptions import BadRequestProblem
8
from connexion.utils import is_null
9
10
logger = logging.getLogger("openapi.validation")
11
12
13
class CustomRequestBodyValidator(decorators.validation.RequestBodyValidator):
14
    """Custom request body validator that overrides the default error message for the
15
    'maxItems' validator for the 'documents' property."""
16
17
    def __init__(self, *args, **kwargs):
18
        super().__init__(*args, **kwargs)
19
20
    def validate_schema(self, data, url):
21
        """Validate the request body against the schema."""
22
23
        if self.is_null_value_valid and is_null(data):
24
            return None  # pragma: no cover
25
26
        try:
27
            self.validator.validate(data)
28
        except jsonschema.ValidationError as exception:
29
            if exception.validator == "maxItems" and list(exception.schema_path) == [
30
                "properties",
31
                "documents",
32
                "maxItems",
33
            ]:
34
                exception.message = "too many items"
35
36
            error_path_msg = self._error_path_message(exception=exception)
37
            logger.error(
38
                "{url} validation error: {error}{error_path_msg}".format(
39
                    url=url, error=exception.message, error_path_msg=error_path_msg
40
                ),
41
                extra={"validator": "body"},
42
            )
43
            raise BadRequestProblem(detail=f"{exception.message}{error_path_msg}")
44
        return None
45