summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorIonuț Arțăriși <ionut@artarisi.eu>2015-07-18 14:30:50 +0100
committerRaphaël Barrois <raphael.barrois@polytechnique.org>2015-10-20 23:03:07 +0200
commit57be4ac78b1213928a83079d298bafcc93e69483 (patch)
treea56b33189dd5781c94001e2020a443db62fe796a
parentb9347efae7e2f04687863f54e8db7d9e10f9dc6a (diff)
downloadfactory-boy-57be4ac78b1213928a83079d298bafcc93e69483.tar
factory-boy-57be4ac78b1213928a83079d298bafcc93e69483.tar.gz
add a way to add custom providers to Faker
factory_boy wraps faker and it stores Faker generators in a 'private' _FAKER_REGISTRY class attribute dict. There needs to be a way to extend the Faker generators with additional custom providers (without having to access _FAKER_REGISTRY directly). This commit adds a (factory_boy) Faker.add_provider class method which calls Faker's own `add_provider` method on internally stored (via _FAKER_REGISTRY) Faker generators.
-rw-r--r--factory/faker.py5
-rw-r--r--tests/test_faker.py32
2 files changed, 36 insertions, 1 deletions
diff --git a/factory/faker.py b/factory/faker.py
index 10a0cba..5411985 100644
--- a/factory/faker.py
+++ b/factory/faker.py
@@ -94,3 +94,8 @@ class Faker(declarations.OrderedDeclaration):
cls._FAKER_REGISTRY[locale] = faker.Faker(locale=locale)
return cls._FAKER_REGISTRY[locale]
+
+ @classmethod
+ def add_provider(cls, provider, locale=None):
+ """Add a new Faker provider for the specified locale"""
+ cls._get_faker(locale).add_provider(provider)
diff --git a/tests/test_faker.py b/tests/test_faker.py
index 41f8e19..99e54af 100644
--- a/tests/test_faker.py
+++ b/tests/test_faker.py
@@ -21,9 +21,12 @@
# THE SOFTWARE.
-import factory
import unittest
+import faker.providers
+
+import factory
+
class MockFaker(object):
def __init__(self, expected):
@@ -103,3 +106,30 @@ class FakerTests(unittest.TestCase):
self.assertEqual("John", profile.first_name)
self.assertEqual("Valjean", profile.last_name)
+ def test_add_provider(self):
+ class Face(object):
+ def __init__(self, smiley, french_smiley):
+ self.smiley = smiley
+ self.french_smiley = french_smiley
+
+ class FaceFactory(factory.Factory):
+ class Meta:
+ model = Face
+
+ smiley = factory.Faker('smiley')
+ french_smiley = factory.Faker('smiley', locale='fr_FR')
+
+ class SmileyProvider(faker.providers.BaseProvider):
+ def smiley(self):
+ return ':)'
+
+ class FrenchSmileyProvider(faker.providers.BaseProvider):
+ def smiley(self):
+ return '(:'
+
+ factory.Faker.add_provider(SmileyProvider)
+ factory.Faker.add_provider(FrenchSmileyProvider, 'fr_FR')
+
+ face = FaceFactory()
+ self.assertEqual(":)", face.smiley)
+ self.assertEqual("(:", face.french_smiley)