Coverage for audoma/mixins.py: 52%

25 statements  

« prev     ^ index     » next       coverage.py v6.4.2, created at 2022-08-08 06:12 +0000

1from drf_spectacular.drainage import set_override 

2 

3from audoma.examples import ( 

4 DEFAULT, 

5 Example, 

6 NumericExample, 

7 RegexExample, 

8) 

9 

10 

11class ExampleMixin: 

12 """ 

13 A mixin class that adds an example to the field in documentation by overriding 

14 `field` parameter in `_spectacular_annotation`. 

15 

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 """ 

21 

22 audoma_example_class = Example 

23 

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 

39 

40 set_override( 

41 self, 

42 "field", 

43 field, 

44 ) 

45 

46 

47class NumericExampleMixin(ExampleMixin): 

48 """ 

49 A mixin class that adds an example to the field in documentation for numeric fields 

50 """ 

51 

52 audoma_example_class = NumericExample 

53 

54 

55class RegexExampleMixin(ExampleMixin): 

56 """ 

57 A mixin class that adds an example to the field in documentation for regex fields 

58 """ 

59 

60 audoma_example_class = RegexExample 

61 

62 

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)