summaryrefslogtreecommitdiff
path: root/factory
diff options
context:
space:
mode:
authorRaphaël Barrois <raphael.barrois@polytechnique.org>2012-01-06 23:39:33 +0100
committerRaphaël Barrois <raphael.barrois@polytechnique.org>2012-01-06 23:39:33 +0100
commit8563a98022b8b3e855bf036a57aad4fd86319eff (patch)
tree282264bb40e9aef33f2489b018275735a943ce54 /factory
parent105f2fe021a71e1f03650e3bcdd657152fe19a20 (diff)
downloadfactory-boy-8563a98022b8b3e855bf036a57aad4fd86319eff.tar
factory-boy-8563a98022b8b3e855bf036a57aad4fd86319eff.tar.gz
Add factory.build(), factory.create(), factory.stub() methods.
Those are shortcuts for writing a full Factory class. Signed-off-by: Raphaël Barrois <raphael.barrois@polytechnique.org>
Diffstat (limited to 'factory')
-rw-r--r--factory/__init__.py4
-rw-r--r--factory/base.py42
2 files changed, 35 insertions, 11 deletions
diff --git a/factory/__init__.py b/factory/__init__.py
index efc0001..f2652f2 100644
--- a/factory/__init__.py
+++ b/factory/__init__.py
@@ -28,6 +28,10 @@ from base import (
StubFactory,
DjangoModelFactory,
+ build,
+ create,
+ stub,
+
BUILD_STRATEGY,
CREATE_STRATEGY,
STUB_STRATEGY,
diff --git a/factory/base.py b/factory/base.py
index 3f3261b..80c49ca 100644
--- a/factory/base.py
+++ b/factory/base.py
@@ -156,17 +156,18 @@ class FactoryMetaClass(BaseFactoryMetaClass):
if FACTORY_CLASS_DECLARATION in attrs:
return attrs[FACTORY_CLASS_DECLARATION]
- factory_module = sys.modules[attrs['__module__']]
- if class_name.endswith('Factory'):
- # Try a module lookup
- used_auto_discovery = True
- associated_class_name = class_name[:-len('Factory')]
- if associated_class_name:
- # Class name was longer than just 'Factory'.
- try:
- return getattr(factory_module, associated_class_name)
- except AttributeError:
- pass
+ if '__module__' in attrs:
+ factory_module = sys.modules[attrs['__module__']]
+ if class_name.endswith('Factory'):
+ # Try a module lookup
+ used_auto_discovery = True
+ associated_class_name = class_name[:-len('Factory')]
+ if associated_class_name:
+ # Class name was longer than just 'Factory'.
+ try:
+ return getattr(factory_module, associated_class_name)
+ except AttributeError:
+ pass
# Unable to guess a good option; return the inherited class.
if inherited is not None:
@@ -439,3 +440,22 @@ class DjangoModelFactory(Factory):
).order_by('-id')[0]
except IndexError:
return 1
+
+
+def _make_factory(klass, **kwargs):
+ factory_name = '%sFactory' % klass.__name__
+ kwargs[FACTORY_CLASS_DECLARATION] = klass
+ factory_class = type(Factory).__new__(type(Factory), factory_name, (Factory,), kwargs)
+ factory_class.__name__ = '%sFactory' % klass.__name__
+ factory_class.__doc__ = 'Auto-generated factory for class %s' % klass
+ return factory_class
+
+
+def build(klass, **kwargs):
+ return _make_factory(klass, **kwargs).build()
+
+def create(klass, **kwargs):
+ return _make_factory(klass, **kwargs).create()
+
+def stub(klass, **kwargs):
+ return _make_factory(klass, **kwargs).stub()