Passed
Push — testing-on-windows-and-macos ( 782857...ea99ad )
by Juho
04:06
created

annif.openapi.validation.CustomRequestBodyValidator.validate_schema()   B

Complexity

Conditions 6

Size

Total Lines 25
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 18
nop 3
dl 0
loc 25
rs 8.5666
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A annif.openapi.validation.CustomRequestBodyValidator._validate() 0 16 4
A annif.openapi.validation.CustomRequestBodyValidator.__init__() 0 2 1
1
"""Custom validator for the Annif API."""
2
3
from __future__ import annotations
4
5
import logging
6
from typing import Any
7
8
from connexion.exceptions import BadRequestProblem
9
from connexion.json_schema import format_error_with_path
10
from connexion.validators import JSONRequestBodyValidator
11
from jsonschema.exceptions import ValidationError
12
13
logger = logging.getLogger("openapi.validation")
14
15
16
class CustomRequestBodyValidator(JSONRequestBodyValidator):
17
    """Custom request body validator that overrides the default error message for the
18
    'maxItems' validator for the 'documents' property to prevent logging request body
19
    with the contents of all documents."""
20
21
    def __init__(self, *args, **kwargs) -> None:
22
        super().__init__(*args, **kwargs)
23
24
    def _validate(self, body: Any) -> dict | None:
25
        try:
26
            return self._validator.validate(body)
27
        except ValidationError as exception:
28
            if exception.validator == "maxItems" and list(exception.schema_path) == [
29
                "properties",
30
                "documents",
31
                "maxItems",
32
            ]:
33
                exception.message = "too many items"
34
            error_path_msg = format_error_with_path(exception=exception)
35
            logger.error(
36
                f"Validation error: {exception.message}{error_path_msg}",
37
                extra={"validator": "body"},
38
            )
39
            raise BadRequestProblem(detail=f"{exception.message}{error_path_msg}")
40