Coverage for audoma/drf/validators.py: 100%

1 from typing import (

2 List,

3 Tuple,

4 Union,

5)

6

7 from rest_framework import serializers

8 from rest_framework.validators import * # noqa: F403, F401

9

10

11 class ExclusiveFieldsValidator:

12 """

13 This is extra validator defined in audoma.

14 This validator allows to define mutually exclusvie fields.

15

16 Attributes:

17 fields - list or a tuple of mutually exclusive field names

18 message - string validation error message

19 required - boolean value, determines if fields are required

20 message_reqiured - string message if one of fields is required and none has been passed

21

22 Args:

23 fields - list or a tuple of mutually exclusive field names

24 message - string validation error message

25 required - boolean value, determines if fields are required

26 message_reqiured - string message if one of fields is required and none has been passed

27 """

28

29 message = "The fields {field_names} are mutually exclusive arguments."

30 message_required = "One of the fields {field_names} is required."

31 # requires_context = True

32

33 def __init__(

34 self,

35 fields: Union[List[str], Tuple[str]],

36 message: str = None,

37 required: bool = True,

38 message_required: str = None,

39 ) -> None:

40 self.fields = fields

41 self.required = required

42 if message:

43 self.message = message

44 if message_required:

45 self.message_required = message_required

46

47 def __call__(self, data: dict) -> None:

48 in_data = sum(f in data for f in self.fields)

49 if in_data > 1:

50 raise serializers.ValidationError(

51 self.message.format(field_names=", ".join(self.fields))

52 )

53 if in_data == 0 and self.required:

54 raise serializers.ValidationError(

55 self.message_required.format(field_names=", ".join(self.fields))

56 )