Coverage for audoma/examples.py: 50%

1 import random

2 from typing import (

3 Any,

4 Type,

5)

6

7 import exrex

8

9 from django.core import validators

10

11

12 class DEFAULT:

13 pass

14

15

16 class Example:

17 """

18 Class that represents an example for a field.

19 It allows to add example to the field during initialization.

20 """

21

22 def __init__(self, field, example=DEFAULT) -> None:

23 self.field = field

24 self.example = example

25

26 def generate_value(self) -> Type[DEFAULT]:

27 return DEFAULT

28

29 def get_value(self) -> Any:

30 if self.example is not DEFAULT:

31 if callable(self.example):

32 return self.example()

33 return self.example

34 return self.generate_value()

35

36 def to_representation(self, value) -> Any:

37 return self.field.to_representation(value)

38

39

40 class NumericExample(Example):

41 def generate_value(self) -> float:

42 """

43 Extracts information from the field and generates a random value

44 based on min_value and max_value.

45

46 Returns:

47 Random value between min_value and max_value

48 """

49 min_val = getattr(self.field, "min_value", 1) or 1

50 max_val = getattr(self.field, "max_value", 1000) or 1000

51 return random.uniform(min_val, max_val)

52

53

54 class RegexExample(Example):

55 def generate_value(self) -> str:

56 """

57 Extracts information from the field and generates a random value

58 based on field's RegexValidators.

59

60 Returns:

61 Generated regex string if regex is found, otherwise returns None

62 """

63 regex_validators = [

64 validator

65 for validator in self.field.validators

66 if isinstance(validator, validators.RegexValidator)

67 ]

68 if regex_validators:

69 regex_validator = regex_validators[0]

70 return exrex.getone(regex_validator.regex.pattern)

71 return None