aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore1
-rw-r--r--LICENSE19
-rw-r--r--README.rst167
-rw-r--r--factory/__init__.py40
-rw-r--r--factory/base.py244
-rw-r--r--factory/containers.py47
-rw-r--r--factory/declarations.py76
-rw-r--r--setup.py28
-rw-r--r--tests.py305
9 files changed, 927 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0d20b64
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+*.pyc
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..919f659
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,19 @@
+Copyright (c) 2010 Mark Sandstrom
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE. \ No newline at end of file
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..92816a4
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,167 @@
+factory_boy
+===========
+
+factory_boy is a fixtures replacement based on thoughtbot's `factory_girl <http://github.com/thoughtbot/factory_girl>`_ . Like factory_girl it has a straightforward definition syntax, support for multiple build strategies (saved instances, unsaved instances, attribute dicts, and stubbed objects), and support for multiple factories for the same class, including factory inheritance. Django support is included, and support for other ORMs can be easily added.
+
+Credits
+-------
+
+This README parallels the factory_girl README as much as possible; text and examples are reproduced for comparison purposes. Ruby users of factory_girl should feel right at home with factory_boy in Python.
+
+factory_boy was written by Mark Sandstrom.
+
+Thank you Joe Ferris and thoughtbot for creating factory_girl.
+
+Download
+--------
+
+Github: http://github.com/dnerdy/factory_boy/tree/master
+
+easy_install::
+
+ easy_install factory_boy
+
+Source::
+
+ # Download the source and run
+ python setup.py install
+
+
+Defining factories
+------------------
+
+Factories declare a set of attributes used to instantiate an object. The name of the factory is used to guess the class of the object by default, but it's possible to explicitly specify it::
+
+ import factory
+ from models import User
+
+ # This will guess the User class
+ class UserFactory(factory.Factory):
+ first_name = 'John'
+ last_name = 'Doe'
+ admin = False
+
+ # This will use the User class (Admin would have been guessed)
+ class AdminFactory(factory.Factory):
+ FACTORY_FOR = User
+
+ first_name = 'Admin'
+ last_name = 'User'
+ admin = True
+
+Using factories
+---------------
+
+factory_boy supports several different build strategies: build, create, attributes and stub::
+
+ # Returns a User instance that's not saved
+ user = UserFactory.build()
+
+ # Returns a saved User instance
+ user = UserFactory.create()
+
+ # Returns a dict of attributes that can be used to build a User instance
+ attributes = UserFactory.attributes()
+
+ # Returns an object with all defined attributes stubbed out:
+ stub = UserFactory.stub()
+
+You can use the Factory class as a shortcut for the default build strategy::
+
+ # Same as UserFactory.create()
+ user = UserFactory()
+
+The default strategy can be overridden::
+
+ UserFactory.default_strategy = factory.BUILD_STRATEGY
+ user = UserFactory()
+
+The default strategy can also be overridden for all factories::
+
+ # This will set the default strategy for all factories that don't define a default build strategy
+ factory.Factory.default_strategy = factory.BUILD_STRATEGY
+
+No matter which strategy is used, it's possible to override the defined attributes by passing keyword arguments::
+
+ # Build a User instance and override first_name
+ user = UserFactory.build(first_name='Joe')
+ user.first_name
+ # => 'Joe'
+
+Lazy Attributes
+---------------
+
+Most factory attributes can be added using static values that are evaluated when the factory is defined, but some attributes (such as associations and other attributes that must be dynamically generated) will need values assigned each time an instance is generated. These "lazy" attributes can be added as follows::
+
+ class UserFactory(factory.Factory):
+ first_name = 'Joe'
+ last_name = 'Blow'
+ email = factory.LazyAttribute(lambda a: '{0}.{1}@example.com'.format(a.first_name, a.last_name).lower())
+
+ UserFactory().email
+ # => 'joe.blow@example.com'
+
+The function passed to ``LazyAttribute`` is given the attributes defined for the factory up to the point of the LazyAttribute declaration. If a lambda won't cut it, the ``lazy_attribute`` decorator can be used to wrap a function::
+
+ # Stub factories don't have an associated class.
+ class SumFactory(factory.StubFactory):
+ lhs = 1
+ rhs = 1
+
+ @lazy_attribute
+ def sum(a):
+ result = a.lhs + a.rhs # Or some other fancy calculation
+ return result
+
+Associations
+------------
+
+Associated instances can also be generated using ``LazyAttribute``::
+
+ from models import Post
+
+ class PostFactory(factory.Factory):
+ author = factory.LazyAttribute(lambda a: UserFactory())
+
+The associated object's default strategy is always used::
+
+ # Builds and saves a User and a Post
+ post = PostFactory()
+ post.id == None # => False
+ post.author.id == None # => False
+
+ # Builds and saves a User, and then builds but does not save a Post
+ post = PostFactory.build()
+ post.id == None # => True
+ post.author.id == None # => False
+
+Inheritance
+-----------
+
+You can easily create multiple factories for the same class without repeating common attributes by using inheritance::
+
+ class PostFactory(factory.Factory):
+ title = 'A title'
+
+ class ApprovedPost(PostFactory):
+ approved = True
+ approver = factory.LazyAttribute(lambda a: UserFactory())
+
+Sequences
+---------
+
+Unique values in a specific format (for example, e-mail addresses) can be generated using sequences. Sequences are defined by using ``Sequence`` or the decorator ``sequence``::
+
+ class UserFactory(factory.Factory):
+ email = factory.Sequence(lambda n: 'person{0}@example.com'.format(n))
+
+ UserFactory().email # => 'person0@example.com'
+ UserFactory().email # => 'person1@example.com'
+
+Sequences can be combined with lazy attributes::
+
+ class UserFactory(factory.Factory):
+ name = 'Mark'
+ email = factory.LazyAttributeSequence(lambda a, n: '{0}+{1}@example.com'.format(a.name, n).lower())
+
+ UserFactory().email # => mark+1@example.com
diff --git a/factory/__init__.py b/factory/__init__.py
new file mode 100644
index 0000000..650f572
--- /dev/null
+++ b/factory/__init__.py
@@ -0,0 +1,40 @@
+# Copyright (c) 2010 Mark Sandstrom
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+__version__ = '1.0.0' # Remember to change in setup.py as well!
+__author__ = 'Mark Sandstrom <mark@deliciouslynerdy.com>'
+
+from base import (
+ Factory,
+ StubFactory,
+ BUILD_STRATEGY,
+ CREATE_STRATEGY,
+ STUB_STRATEGY
+)
+
+from declarations import (
+ LazyAttribute,
+ Sequence,
+ LazyAttributeSequence,
+ lazy_attribute,
+ sequence,
+ lazy_attribute_sequence
+)
+
diff --git a/factory/base.py b/factory/base.py
new file mode 100644
index 0000000..5f712a2
--- /dev/null
+++ b/factory/base.py
@@ -0,0 +1,244 @@
+# Copyright (c) 2010 Mark Sandstrom
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+import re
+import sys
+
+from containers import ObjectParamsWrapper, StubObject
+from declarations import OrderedDeclaration
+
+# Strategies
+
+BUILD_STRATEGY = 'build'
+CREATE_STRATEGY = 'create'
+STUB_STRATEGY = 'stub'
+
+# Creation functions. Use Factory.set_creation_function() to set a creation function appropriate for your ORM.
+
+DJANGO_CREATION = lambda class_to_create, **kwargs: class_to_create.objects.create(**kwargs)
+
+# Special declarations
+
+FACTORY_CLASS_DECLARATION = 'FACTORY_FOR'
+
+# Factory class attributes
+
+CLASS_ATTRIBUTE_ORDERED_DECLARATIONS = '_ordered_declarations'
+CLASS_ATTRIBUTE_UNORDERED_DECLARATIONS = '_unordered_declarations'
+CLASS_ATTRIBUTE_ASSOCIATED_CLASS = '_associated_class'
+
+# Factory metaclasses
+
+def get_factory_base(bases):
+ parents = [b for b in bases if isinstance(b, BaseFactoryMetaClass)]
+ if not parents:
+ return None
+ if len(parents) > 1:
+ raise RuntimeError('You can only inherit from one Factory')
+ return parents[0]
+
+class BaseFactoryMetaClass(type):
+ '''Factory metaclass for handling ordered declarations.'''
+
+ def __call__(cls, **kwargs):
+ '''Create an associated class instance using the default build strategy. Never create a Factory instance.'''
+
+ if cls.default_strategy == BUILD_STRATEGY:
+ return cls.build(**kwargs)
+ elif cls.default_strategy == CREATE_STRATEGY:
+ return cls.create(**kwargs)
+ elif cls.default_strategy == STUB_STRATEGY:
+ return cls.stub(**kwargs)
+ else:
+ raise BaseFactory.UnknownStrategy('Unknown default_strategy: {0}'.format(cls.default_strategy))
+
+ def __new__(cls, class_name, bases, dict, extra_dict={}):
+ '''Record attributes (unordered declarations) and ordered declarations for construction of
+ an associated class instance at a later time.'''
+
+ base = get_factory_base(bases)
+ if not base:
+ # If this isn't a subclass of Factory, don't do anything special.
+ return super(BaseFactoryMetaClass, cls).__new__(cls, class_name, bases, dict)
+
+ ordered_declarations = getattr(base, CLASS_ATTRIBUTE_ORDERED_DECLARATIONS, [])
+ unordered_declarations = getattr(base, CLASS_ATTRIBUTE_UNORDERED_DECLARATIONS, [])
+
+ for name in list(dict):
+ if isinstance(dict[name], OrderedDeclaration):
+ ordered_declarations = [(_name, declaration) for (_name, declaration) in ordered_declarations if _name != name]
+ ordered_declarations.append((name, dict[name]))
+ del dict[name]
+ elif not name.startswith('__'):
+ unordered_declarations = [(_name, value) for (_name, value) in unordered_declarations if _name != name]
+ unordered_declarations.append((name, dict[name]))
+ del dict[name]
+
+ ordered_declarations.sort(key=lambda d: d[1].order)
+
+ dict[CLASS_ATTRIBUTE_ORDERED_DECLARATIONS] = ordered_declarations
+ dict[CLASS_ATTRIBUTE_UNORDERED_DECLARATIONS] = unordered_declarations
+
+ for name, value in extra_dict.iteritems():
+ dict[name] = value
+
+ return super(BaseFactoryMetaClass, cls).__new__(cls, class_name, bases, dict)
+
+class FactoryMetaClass(BaseFactoryMetaClass):
+ '''Factory metaclass for handling class association and ordered declarations.'''
+
+ ERROR_MESSAGE = '''Could not determine what class this factory is for.
+ Use the {0} attribute to specify a class.'''
+ ERROR_MESSAGE_AUTODISCOVERY = ERROR_MESSAGE + '''
+ Also, autodiscovery failed using the name '{1}'
+ based on the Factory name '{2}' in {3}.'''
+
+ def __new__(cls, class_name, bases, dict):
+ '''Determine the associated class based on the factory class name. Record the associated class
+ for construction of an associated class instance at a later time.'''
+
+ base = get_factory_base(bases)
+ if not base:
+ # If this isn't a subclass of Factory, don't do anything special.
+ return super(FactoryMetaClass, cls).__new__(cls, class_name, bases, dict)
+
+ inherited_associated_class = getattr(base, CLASS_ATTRIBUTE_ASSOCIATED_CLASS, None)
+ own_associated_class = None
+ used_auto_discovery = False
+
+ if FACTORY_CLASS_DECLARATION in dict:
+ own_associated_class = dict[FACTORY_CLASS_DECLARATION]
+ del dict[FACTORY_CLASS_DECLARATION]
+ else:
+ factory_module = sys.modules[dict['__module__']]
+ match = re.match(r'^(\w+)Factory$', class_name)
+ if match:
+ used_auto_discovery = True
+ associated_class_name = match.group(1)
+ try:
+ own_associated_class = getattr(factory_module, associated_class_name)
+ except AttributeError:
+ pass
+
+ if own_associated_class != None and inherited_associated_class != None and own_associated_class != inherited_associated_class:
+ format = 'These factories are for conflicting classes: {0} and {1}'
+ raise Factory.AssociatedClassError(format.format(inherited_associated_class, own_associated_class))
+ elif inherited_associated_class != None:
+ own_associated_class = inherited_associated_class
+
+ if not own_associated_class and used_auto_discovery:
+ format_args = FACTORY_CLASS_DECLARATION, associated_class_name, class_name, factory_module
+ raise Factory.AssociatedClassError(FactoryMetaClass.ERROR_MESSAGE_AUTODISCOVERY.format(*format_args))
+ elif not own_associated_class:
+ raise Factory.AssociatedClassError(FactoryMetaClass.ERROR_MESSAGE.format(FACTORY_CLASS_DECLARATION))
+
+ extra_dict = {CLASS_ATTRIBUTE_ASSOCIATED_CLASS: own_associated_class}
+ return super(FactoryMetaClass, cls).__new__(cls, class_name, bases, dict, extra_dict=extra_dict)
+
+# Factory base classes
+
+class BaseFactory(object):
+ '''Factory base support for sequences, attributes and stubs.'''
+
+ class UnknownStrategy(RuntimeError): pass
+ class UnsupportedStrategy(RuntimeError): pass
+
+ def __new__(cls, *args, **kwargs):
+ raise RuntimeError('You cannot instantiate BaseFactory')
+
+ _next_sequence = 0
+
+ @classmethod
+ def _generate_next_sequence(cls):
+ next_sequence = cls._next_sequence
+ cls._next_sequence += 1
+ return next_sequence
+
+ @classmethod
+ def attributes(cls, **kwargs):
+ attributes = {}
+ cls.sequence = cls._generate_next_sequence()
+
+ for name, value in getattr(cls, CLASS_ATTRIBUTE_UNORDERED_DECLARATIONS):
+ if name in kwargs:
+ attributes[name] = kwargs[name]
+ del kwargs[name]
+ else:
+ attributes[name] = value
+
+ for name, ordered_declaration in getattr(cls, CLASS_ATTRIBUTE_ORDERED_DECLARATIONS):
+ if name in kwargs:
+ attributes[name] = kwargs[name]
+ del kwargs[name]
+ else:
+ a = ObjectParamsWrapper(attributes)
+ attributes[name] = ordered_declaration.evaluate(cls, a)
+
+ for name in kwargs:
+ attributes[name] = kwargs[name]
+
+ return attributes
+
+ @classmethod
+ def build(cls, **kwargs):
+ raise cls.UnsupportedStrategy()
+
+ @classmethod
+ def create(cls, **kwargs):
+ raise cls.UnsupportedStrategy()
+
+ @classmethod
+ def stub(cls, **kwargs):
+ stub_object = StubObject()
+ for name, value in cls.attributes(**kwargs).iteritems():
+ setattr(stub_object, name, value)
+ return stub_object
+
+class StubFactory(BaseFactory):
+ __metaclass__ = BaseFactoryMetaClass
+
+ default_strategy = STUB_STRATEGY
+
+class Factory(BaseFactory):
+ '''Factory base with build and create support.
+
+ This class has the ability to support multiple ORMs by using custom creation functions.'''
+
+ __metaclass__ = FactoryMetaClass
+
+ default_strategy = CREATE_STRATEGY
+
+ class AssociatedClassError(RuntimeError): pass
+
+ _creation_function = (DJANGO_CREATION,) # Using a tuple to keep the creation function from turning into an instance method
+ @classmethod
+ def set_creation_function(cls, creation_function):
+ cls._creation_function = (creation_function,)
+ @classmethod
+ def get_creation_function(cls):
+ return cls._creation_function[0]
+
+ @classmethod
+ def build(cls, **kwargs):
+ return getattr(cls, CLASS_ATTRIBUTE_ASSOCIATED_CLASS)(**cls.attributes(**kwargs))
+
+ @classmethod
+ def create(cls, **kwargs):
+ return cls.get_creation_function()(getattr(cls, CLASS_ATTRIBUTE_ASSOCIATED_CLASS), **cls.attributes(**kwargs))
diff --git a/factory/containers.py b/factory/containers.py
new file mode 100644
index 0000000..08f0450
--- /dev/null
+++ b/factory/containers.py
@@ -0,0 +1,47 @@
+# Copyright (c) 2010 Mark Sandstrom
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+class ObjectParamsWrapper(object):
+ '''A generic container that allows for getting but not setting of attributes.
+
+ Attributes are set at initialization time.'''
+
+ initialized = False
+
+ def __init__(self, dict):
+ self.dict = dict
+ self.initialized = True
+
+ def __setattr__(self, name, value):
+ if not self.initialized:
+ return super(ObjectParamsWrapper, self).__setattr__(name, value)
+ else:
+ raise AttributeError('Setting of object attributes is not allowed')
+
+ def __getattr__(self, name):
+ try:
+ return self.dict[name]
+ except KeyError:
+ raise AttributeError("The param '{0}' does not exist. Perhaps your declarations are out of order?".format(name))
+
+class StubObject(object):
+ '''A generic container.'''
+
+ pass \ No newline at end of file
diff --git a/factory/declarations.py b/factory/declarations.py
new file mode 100644
index 0000000..37c8cbd
--- /dev/null
+++ b/factory/declarations.py
@@ -0,0 +1,76 @@
+# Copyright (c) 2010 Mark Sandstrom
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+class OrderedDeclaration(object):
+ '''A factory declaration.
+
+ Ordered declarations keep track of the order in which they're defined so that later declarations
+ can refer to attributes created by earlier declarations when the declarations are evaluated.'''
+ _next_order = 0
+
+ def __init__(self):
+ self.order = self.next_order()
+
+ @classmethod
+ def next_order(cls):
+ next_order = cls._next_order
+ cls._next_order += 1
+ return next_order
+
+ def evaluate(self, factory, attributes):
+ '''Evaluate this declaration.
+
+ Args:
+ factory: The factory this declaration was defined in.
+ attributes: The attributes created by the unordered and ordered declarations up to this point.'''
+
+ raise NotImplementedError('This is an abstract method')
+
+class LazyAttribute(OrderedDeclaration):
+ def __init__(self, function):
+ super(LazyAttribute, self).__init__()
+ self.function = function
+
+ def evaluate(self, factory, attributes):
+ return self.function(attributes)
+
+class Sequence(OrderedDeclaration):
+ def __init__(self, function, type=str):
+ super(Sequence, self).__init__()
+ self.function = function
+ self.type = type
+
+ def evaluate(self, factory, attributes):
+ return self.function(self.type(factory.sequence))
+
+class LazyAttributeSequence(Sequence):
+ def evaluate(self, factory, attributes):
+ return self.function(attributes, self.type(factory.sequence))
+
+# Decorators... in case lambdas don't cut it
+
+def lazy_attribute(func):
+ return LazyAttribute(func)
+
+def sequence(func):
+ return Sequence(func)
+
+def lazy_attribute_sequence(func):
+ return LazyAttributeSequence(func) \ No newline at end of file
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..ee80d4b
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,28 @@
+#!/usr/bin/python
+
+from distutils.core import setup
+
+# Remember to change in factory/__init__.py as well!
+VERSION = '1.0.0'
+
+setup(
+ name='factory_boy',
+ version=VERSION,
+ description="A test fixtures replacement based on thoughtbot's factory_girl for Ruby.",
+ author='Mark Sandstrom',
+ author_email='mark@deliciouslynerdy.com',
+ url='http://github.com/dnerdy/factory_boy',
+ keywords=['factory_boy', 'factory', 'fixtures'],
+ packages=['factory'],
+ license='MIT',
+ classifiers=[
+ 'Development Status :: 5 - Production/Stable',
+ 'Intended Audience :: Developers',
+ 'Framework :: Django',
+ 'License :: OSI Approved :: MIT License',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python',
+ 'Topic :: Software Development :: Testing',
+ 'Topic :: Software Development :: Libraries :: Python Modules'
+ ]
+) \ No newline at end of file
diff --git a/tests.py b/tests.py
new file mode 100644
index 0000000..6d57e7f
--- /dev/null
+++ b/tests.py
@@ -0,0 +1,305 @@
+import unittest
+
+from factory import Factory, StubFactory, LazyAttribute, Sequence, LazyAttributeSequence, lazy_attribute, sequence, lazy_attribute_sequence
+from factory import CREATE_STRATEGY, BUILD_STRATEGY, STUB_STRATEGY
+
+class TestObject(object):
+ def __init__(self, one=None, two=None, three=None, four=None):
+ self.one = one
+ self.two = two
+ self.three = three
+ self.four = four
+
+class FakeDjangoModel(object):
+ class FakeDjangoManager(object):
+ def create(self, **kwargs):
+ fake_model = FakeDjangoModel(**kwargs)
+ fake_model.id = 1
+ return fake_model
+
+ objects = FakeDjangoManager()
+
+ def __init__(self, **kwargs):
+ for name, value in kwargs.iteritems():
+ setattr(self, name, value)
+ self.id = None
+
+class TestModel(FakeDjangoModel):
+ pass
+
+class FactoryTestCase(unittest.TestCase):
+ def testAttribute(self):
+ class TestObjectFactory(Factory):
+ one = 'one'
+
+ test_object = TestObjectFactory.build()
+ self.assertEqual(test_object.one, 'one')
+
+ def testSequence(self):
+ class TestObjectFactory(Factory):
+ one = Sequence(lambda n: 'one' + n)
+ two = Sequence(lambda n: 'two' + n)
+
+ test_object0 = TestObjectFactory.build()
+ self.assertEqual(test_object0.one, 'one0')
+ self.assertEqual(test_object0.two, 'two0')
+
+ test_object1 = TestObjectFactory.build()
+ self.assertEqual(test_object1.one, 'one1')
+ self.assertEqual(test_object1.two, 'two1')
+
+ def testLazyAttribute(self):
+ class TestObjectFactory(Factory):
+ one = LazyAttribute(lambda a: 'abc' )
+ two = LazyAttribute(lambda a: a.one + ' xyz')
+
+ test_object = TestObjectFactory.build()
+ self.assertEqual(test_object.one, 'abc')
+ self.assertEqual(test_object.two, 'abc xyz')
+
+ def testLazyAttributeNonExistentParam(self):
+ class TestObjectFactory(Factory):
+ one = LazyAttribute(lambda a: a.does_not_exist )
+
+ try:
+ TestObjectFactory()
+ self.fail()
+ except AttributeError as e:
+ self.assertTrue('does not exist' in str(e))
+
+ def testLazyAttributeSequence(self):
+ class TestObjectFactory(Factory):
+ one = LazyAttributeSequence(lambda a, n: 'abc' + n)
+ two = LazyAttributeSequence(lambda a, n: a.one + ' xyz' + n)
+
+ test_object0 = TestObjectFactory.build()
+ self.assertEqual(test_object0.one, 'abc0')
+ self.assertEqual(test_object0.two, 'abc0 xyz0')
+
+ test_object1 = TestObjectFactory.build()
+ self.assertEqual(test_object1.one, 'abc1')
+ self.assertEqual(test_object1.two, 'abc1 xyz1')
+
+ def testLazyAttributeDecorator(self):
+ class TestObjectFactory(Factory):
+ @lazy_attribute
+ def one(a):
+ return 'one'
+
+ test_object = TestObjectFactory.build()
+ self.assertEqual(test_object.one, 'one')
+
+ def testSequenceDecorator(self):
+ class TestObjectFactory(Factory):
+ @sequence
+ def one(n):
+ return 'one' + n
+
+ test_object = TestObjectFactory.build()
+ self.assertEqual(test_object.one, 'one0')
+
+ def testLazyAttributeSequenceDecorator(self):
+ class TestObjectFactory(Factory):
+ @lazy_attribute_sequence
+ def one(a, n):
+ return 'one' + n
+ @lazy_attribute_sequence
+ def two(a, n):
+ return a.one + ' two' + n
+
+ test_object = TestObjectFactory.build()
+ self.assertEqual(test_object.one, 'one0')
+ self.assertEqual(test_object.two, 'one0 two0')
+
+ def testBuildWithParameters(self):
+ class TestObjectFactory(Factory):
+ one = Sequence(lambda n: 'one' + n)
+ two = Sequence(lambda n: 'two' + n)
+
+ test_object0 = TestObjectFactory.build(three='three')
+ self.assertEqual(test_object0.one, 'one0')
+ self.assertEqual(test_object0.two, 'two0')
+ self.assertEqual(test_object0.three, 'three')
+
+ test_object1 = TestObjectFactory.build(one='other')
+ self.assertEqual(test_object1.one, 'other')
+ self.assertEqual(test_object1.two, 'two1')
+
+ def testCreate(self):
+ class TestModelFactory(Factory):
+ one = 'one'
+
+ test_model = TestModelFactory.create()
+ self.assertEqual(test_model.one, 'one')
+ self.assertTrue(test_model.id)
+
+ def testInheritance(self):
+ class TestObjectFactory(Factory):
+ one = 'one'
+ two = LazyAttribute(lambda a: a.one + ' two')
+
+ class TestObjectFactory2(TestObjectFactory):
+ FACTORY_FOR = TestObject
+
+ three = 'three'
+ four = LazyAttribute(lambda a: a.three + ' four')
+
+ test_object = TestObjectFactory2.build()
+ self.assertEqual(test_object.one, 'one')
+ self.assertEqual(test_object.two, 'one two')
+ self.assertEqual(test_object.three, 'three')
+ self.assertEqual(test_object.four, 'three four')
+
+ def testInheritanceWithInheritedClass(self):
+ class TestObjectFactory(Factory):
+ one = 'one'
+ two = LazyAttribute(lambda a: a.one + ' two')
+
+ class TestFactory(TestObjectFactory):
+ three = 'three'
+ four = LazyAttribute(lambda a: a.three + ' four')
+
+ test_object = TestFactory.build()
+ self.assertEqual(test_object.one, 'one')
+ self.assertEqual(test_object.two, 'one two')
+ self.assertEqual(test_object.three, 'three')
+ self.assertEqual(test_object.four, 'three four')
+
+ def testSetCreationFunction(self):
+ def creation_function(class_to_create, **kwargs):
+ return "This doesn't even return an instance of {0}".format(class_to_create.__name__)
+
+ class TestModelFactory(Factory):
+ pass
+
+ TestModelFactory.set_creation_function(creation_function)
+
+ test_object = TestModelFactory.create()
+ self.assertEqual(test_object, "This doesn't even return an instance of TestModel")
+
+class FactoryDefaultStrategyTestCase(unittest.TestCase):
+ def setUp(self):
+ self.default_strategy = Factory.default_strategy
+
+ def tearDown(self):
+ Factory.default_strategy = self.default_strategy
+
+ def testBuildStrategy(self):
+ Factory.default_strategy = BUILD_STRATEGY
+
+ class TestModelFactory(Factory):
+ one = 'one'
+
+ test_model = TestModelFactory()
+ self.assertEqual(test_model.one, 'one')
+ self.assertFalse(test_model.id)
+
+ def testCreateStrategy(self):
+ # Default default_strategy
+
+ class TestModelFactory(Factory):
+ one = 'one'
+
+ test_model = TestModelFactory()
+ self.assertEqual(test_model.one, 'one')
+ self.assertTrue(test_model.id)
+
+ def testStubStrategy(self):
+ Factory.default_strategy = STUB_STRATEGY
+
+ class TestModelFactory(Factory):
+ one = 'one'
+
+ test_model = TestModelFactory()
+ self.assertEqual(test_model.one, 'one')
+ self.assertFalse(hasattr(test_model, 'id')) # We should have a plain old object
+
+ def testUnknownStrategy(self):
+ Factory.default_strategy = 'unknown'
+
+ class TestModelFactory(Factory):
+ one = 'one'
+
+ self.assertRaises(Factory.UnknownStrategy, TestModelFactory)
+
+ def testStubWithNonStubStrategy(self):
+ class TestModelFactory(StubFactory):
+ one = 'one'
+
+ TestModelFactory.default_strategy = CREATE_STRATEGY
+
+ self.assertRaises(StubFactory.UnsupportedStrategy, TestModelFactory)
+
+class FactoryCreationTestCase(unittest.TestCase):
+ def testFactoryFor(self):
+ class TestFactory(Factory):
+ FACTORY_FOR = TestObject
+
+ self.assertTrue(isinstance(TestFactory.build(), TestObject))
+
+ def testAutomaticAssociatedClassDiscovery(self):
+ class TestObjectFactory(Factory):
+ pass
+
+ self.assertTrue(isinstance(TestObjectFactory.build(), TestObject))
+
+ def testStub(self):
+ class TestFactory(StubFactory):
+ pass
+
+ self.assertEqual(TestFactory.default_strategy, STUB_STRATEGY)
+
+ def testInheritanceWithStub(self):
+ class TestObjectFactory(StubFactory):
+ pass
+
+ class TestFactory(TestObjectFactory):
+ pass
+
+ self.assertEqual(TestFactory.default_strategy, STUB_STRATEGY)
+
+ # Errors
+
+ def testNoAssociatedClassWithAutodiscovery(self):
+ try:
+ class TestFactory(Factory):
+ pass
+ self.fail()
+ except Factory.AssociatedClassError as e:
+ self.assertTrue('autodiscovery' in str(e))
+
+ def testNoAssociatedClassWithoutAutodiscovery(self):
+ try:
+ class Test(Factory):
+ pass
+ self.fail()
+ except Factory.AssociatedClassError as e:
+ self.assertTrue('autodiscovery' not in str(e))
+
+ def testInheritanceWithConflictingClassesError(self):
+ class TestObjectFactory(Factory):
+ pass
+
+ try:
+ class TestModelFactory(TestObjectFactory):
+ pass
+ self.fail()
+ except Factory.AssociatedClassError as e:
+ self.assertTrue('conflicting' in str(e))
+
+ def testInheritanceFromMoreThanOneFactory(self):
+ class TestObjectFactory(StubFactory):
+ pass
+
+ class TestModelFactory(TestObjectFactory):
+ pass
+
+ try:
+ class TestFactory(TestObjectFactory, TestModelFactory):
+ pass
+ self.fail()
+ except RuntimeError as e:
+ self.assertTrue('one Factory' in str(e))
+
+if __name__ == '__main__':
+ unittest.main() \ No newline at end of file