Skip to content

Commit

Permalink
Add support for token-based string generation (#1047)
Browse files Browse the repository at this point in the history
  • Loading branch information
malefice authored and fcurella committed Nov 12, 2019
1 parent 97b5536 commit a8dda8b
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
3 changes: 2 additions & 1 deletion faker/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import random as random_module
import re
import six

_re_token = re.compile(r'\{\{(\s?)(\w+)(\s?)\}\}')
random = random_module.Random()
Expand Down Expand Up @@ -108,5 +109,5 @@ def parse(self, text):

def __format_token(self, matches):
formatter = list(matches.groups())
formatter[1] = self.format(formatter[1])
formatter[1] = six.text_type(self.format(formatter[1]))
return ''.join(formatter)
4 changes: 4 additions & 0 deletions faker/providers/python/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import unicode_literals

from decimal import Decimal
import string
import sys

import six
Expand Down Expand Up @@ -32,6 +33,9 @@ def pystr(self, min_chars=None, max_chars=20):
),
)

def pystr_format(self, string_format='?#-###{{random_int}}{{random_letter}}', letters=string.ascii_letters):
return self.bothify(self.generator.parse(string_format), letters=letters)

def pyfloat(self, left_digits=None, right_digits=None, positive=False,
min_value=None, max_value=None):

Expand Down
20 changes: 20 additions & 0 deletions tests/providers/test_python.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# -*- coding: utf-8 -*-

import unittest
try:
from unittest.mock import patch
except ImportError:
from mock import patch

from faker import Faker

Expand Down Expand Up @@ -87,3 +91,19 @@ def test_max_value_should_be_greater_than_min_value(self):

message = str(raises.exception)
self.assertEqual(message, expected_message)


class TestPystrFormat(unittest.TestCase):

def setUp(self):
self.factory = Faker(includes=['tests.mymodule.en_US'])

def test_formatter_invocation(self):
with patch.object(self.factory, 'foo') as mock_foo:
with patch('faker.providers.BaseProvider.bothify',
wraps=self.factory.bothify) as mock_bothify:
mock_foo.return_value = 'barbar'
value = self.factory.pystr_format('{{foo}}?#?{{foo}}?#?{{foo}}', letters='abcde')
assert value.count('barbar') == 3
assert mock_foo.call_count == 3
mock_bothify.assert_called_once_with('barbar?#?barbar?#?barbar', letters='abcde')

0 comments on commit a8dda8b

Please sign in to comment.