Coverage for audoma/mixins.py: 52%
25 statements
« prev ^ index » next coverage.py v6.4.2, created at 2022-08-08 06:12 +0000
« prev ^ index » next coverage.py v6.4.2, created at 2022-08-08 06:12 +0000
1from drf_spectacular.drainage import set_override
3from audoma.examples import (
4 DEFAULT,
5 Example,
6 NumericExample,
7 RegexExample,
8)
11class ExampleMixin:
12 """
13 A mixin class that adds an example to the field in documentation by overriding
14 `field` parameter in `_spectacular_annotation`.
16 Args:
17 audoma_example_class : Type[Example]
18 The class that will be used to create the example.
19 Depends on the type of field
20 """
22 audoma_example_class = Example
24 def __init__(self, *args, example=DEFAULT, **kwargs) -> None:
25 self.audoma_example = self.audoma_example_class(self, example)
26 super().__init__(*args, **kwargs)
27 example = self.audoma_example.get_value()
28 if example is not DEFAULT:
29 has_annotation = (
30 hasattr(self, "_spectacular_annotation")
31 and "field" in self._spectacular_annotation
32 and isinstance(self._spectacular_annotation["field"], dict)
33 )
34 example_representation = self.audoma_example.to_representation(example)
35 field = {"example": example_representation}
36 if has_annotation:
37 field = self._spectacular_annotation["field"].copy()
38 field["example"] = example_representation
40 set_override(
41 self,
42 "field",
43 field,
44 )
47class NumericExampleMixin(ExampleMixin):
48 """
49 A mixin class that adds an example to the field in documentation for numeric fields
50 """
52 audoma_example_class = NumericExample
55class RegexExampleMixin(ExampleMixin):
56 """
57 A mixin class that adds an example to the field in documentation for regex fields
58 """
60 audoma_example_class = RegexExample
63class ModelExampleMixin:
64 def __init__(self, *args, **kwargs) -> None:
65 if kwargs.get("example", None):
66 self.example = kwargs.pop("example", None)
67 super().__init__(*args, **kwargs)