Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/factory/faker.py: 83%

35 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2023-07-17 14:22 -0600

1# Copyright: See the LICENSE file. 

2 

3 

4"""Additional declarations for "faker" attributes. 

5 

6Usage: 

7 

8 class MyFactory(factory.Factory): 

9 class Meta: 

10 model = MyProfile 

11 

12 first_name = factory.Faker('name') 

13""" 

14 

15 

16import contextlib 

17 

18import faker 

19import faker.config 

20 

21from . import declarations 

22 

23 

24class Faker(declarations.BaseDeclaration): 

25 """Wrapper for 'faker' values. 

26 

27 Args: 

28 provider (str): the name of the Faker field 

29 locale (str): the locale to use for the faker 

30 

31 All other kwargs will be passed to the underlying provider 

32 (e.g ``factory.Faker('ean', length=10)`` 

33 calls ``faker.Faker.ean(length=10)``) 

34 

35 Usage: 

36 >>> foo = factory.Faker('name') 

37 """ 

38 def __init__(self, provider, **kwargs): 

39 locale = kwargs.pop('locale', None) 

40 self.provider = provider 

41 super().__init__( 

42 locale=locale, 

43 **kwargs) 

44 

45 def evaluate(self, instance, step, extra): 

46 locale = extra.pop('locale') 

47 subfaker = self._get_faker(locale) 

48 return subfaker.format(self.provider, **extra) 

49 

50 _FAKER_REGISTRY = {} 

51 _DEFAULT_LOCALE = faker.config.DEFAULT_LOCALE 

52 

53 @classmethod 

54 @contextlib.contextmanager 

55 def override_default_locale(cls, locale): 

56 old_locale = cls._DEFAULT_LOCALE 

57 cls._DEFAULT_LOCALE = locale 

58 try: 

59 yield 

60 finally: 

61 cls._DEFAULT_LOCALE = old_locale 

62 

63 @classmethod 

64 def _get_faker(cls, locale=None): 

65 if locale is None: 65 ↛ 68line 65 didn't jump to line 68, because the condition on line 65 was never false

66 locale = cls._DEFAULT_LOCALE 

67 

68 if locale not in cls._FAKER_REGISTRY: 

69 subfaker = faker.Faker(locale=locale) 

70 cls._FAKER_REGISTRY[locale] = subfaker 

71 

72 return cls._FAKER_REGISTRY[locale] 

73 

74 @classmethod 

75 def add_provider(cls, provider, locale=None): 

76 """Add a new Faker provider for the specified locale""" 

77 cls._get_faker(locale).add_provider(provider)