Skip to content
This repository
Browse code

factory_boy: a test fixtures replacement based on thoughtbot's factor…

…y_girl for Ruby
  • Loading branch information...
commit 0431afa53f064529dd0d018f3c67f254352b66e7 0 parents
Mark authored August 22, 2010
1  .gitignore
... ...
@@ -0,0 +1 @@
  1
+*.pyc
19  LICENSE
... ...
@@ -0,0 +1,19 @@
  1
+Copyright (c) 2010 Mark Sandstrom
  2
+
  3
+Permission is hereby granted, free of charge, to any person obtaining a copy
  4
+of this software and associated documentation files (the "Software"), to deal
  5
+in the Software without restriction, including without limitation the rights
  6
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7
+copies of the Software, and to permit persons to whom the Software is
  8
+furnished to do so, subject to the following conditions:
  9
+
  10
+The above copyright notice and this permission notice shall be included in
  11
+all copies or substantial portions of the Software.
  12
+
  13
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19
+THE SOFTWARE.
167  README.rst
Source Rendered
... ...
@@ -0,0 +1,167 @@
  1
+factory_boy
  2
+===========
  3
+
  4
+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.
  5
+
  6
+Credits
  7
+-------
  8
+
  9
+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.
  10
+
  11
+factory_boy was written by Mark Sandstrom.
  12
+
  13
+Thank you Joe Ferris and thoughtbot for creating factory_girl.
  14
+
  15
+Download
  16
+--------
  17
+
  18
+Github: http://github.com/dnerdy/factory_boy/tree/master
  19
+
  20
+easy_install::
  21
+    
  22
+    easy_install factory_boy
  23
+    
  24
+Source::
  25
+    
  26
+    # Download the source and run
  27
+    python setup.py install
  28
+    
  29
+
  30
+Defining factories
  31
+------------------
  32
+
  33
+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::
  34
+
  35
+    import factory
  36
+    from models import User
  37
+    
  38
+    # This will guess the User class
  39
+    class UserFactory(factory.Factory):
  40
+        first_name = 'John'
  41
+        last_name = 'Doe'
  42
+        admin = False
  43
+        
  44
+    # This will use the User class (Admin would have been guessed)
  45
+    class AdminFactory(factory.Factory):
  46
+        FACTORY_FOR = User
  47
+        
  48
+        first_name = 'Admin'
  49
+        last_name = 'User'
  50
+        admin = True
  51
+
  52
+Using factories
  53
+---------------
  54
+
  55
+factory_boy supports several different build strategies: build, create, attributes and stub::
  56
+
  57
+    # Returns a User instance that's not saved
  58
+    user = UserFactory.build()
  59
+    
  60
+    # Returns a saved User instance
  61
+    user = UserFactory.create()
  62
+    
  63
+    # Returns a dict of attributes that can be used to build a User instance
  64
+    attributes = UserFactory.attributes()
  65
+    
  66
+    # Returns an object with all defined attributes stubbed out:
  67
+    stub = UserFactory.stub()
  68
+    
  69
+You can use the Factory class as a shortcut for the default build strategy::
  70
+
  71
+    # Same as UserFactory.create()
  72
+    user = UserFactory()
  73
+    
  74
+The default strategy can be overridden::
  75
+
  76
+    UserFactory.default_strategy = factory.BUILD_STRATEGY
  77
+    user = UserFactory()
  78
+    
  79
+The default strategy can also be overridden for all factories::
  80
+
  81
+    # This will set the default strategy for all factories that don't define a default build strategy
  82
+    factory.Factory.default_strategy = factory.BUILD_STRATEGY
  83
+    
  84
+No matter which strategy is used, it's possible to override the defined attributes by passing keyword arguments::
  85
+
  86
+    # Build a User instance and override first_name
  87
+    user = UserFactory.build(first_name='Joe')
  88
+    user.first_name
  89
+    # => 'Joe'
  90
+    
  91
+Lazy Attributes
  92
+---------------
  93
+
  94
+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::
  95
+
  96
+    class UserFactory(factory.Factory):
  97
+        first_name = 'Joe'
  98
+        last_name = 'Blow'
  99
+        email = factory.LazyAttribute(lambda a: '{0}.{1}@example.com'.format(a.first_name, a.last_name).lower())
  100
+        
  101
+    UserFactory().email
  102
+    # => 'joe.blow@example.com'
  103
+    
  104
+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::
  105
+
  106
+    # Stub factories don't have an associated class.
  107
+    class SumFactory(factory.StubFactory):
  108
+        lhs = 1
  109
+        rhs = 1
  110
+        
  111
+        @lazy_attribute
  112
+        def sum(a):
  113
+            result = a.lhs + a.rhs  # Or some other fancy calculation
  114
+            return result
  115
+    
  116
+Associations
  117
+------------
  118
+
  119
+Associated instances can also be generated using ``LazyAttribute``::
  120
+
  121
+    from models import Post
  122
+    
  123
+    class PostFactory(factory.Factory):
  124
+        author = factory.LazyAttribute(lambda a: UserFactory())
  125
+        
  126
+The associated object's default strategy is always used::
  127
+
  128
+    # Builds and saves a User and a Post
  129
+    post = PostFactory()
  130
+    post.id == None           # => False
  131
+    post.author.id == None    # => False
  132
+
  133
+    # Builds and saves a User, and then builds but does not save a Post
  134
+    post = PostFactory.build()
  135
+    post.id == None           # => True
  136
+    post.author.id == None    # => False
  137
+  
  138
+Inheritance
  139
+-----------
  140
+
  141
+You can easily create multiple factories for the same class without repeating common attributes by using inheritance::
  142
+
  143
+    class PostFactory(factory.Factory):
  144
+        title = 'A title'
  145
+        
  146
+    class ApprovedPost(PostFactory):
  147
+        approved = True
  148
+        approver = factory.LazyAttribute(lambda a: UserFactory())
  149
+        
  150
+Sequences
  151
+---------
  152
+
  153
+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``::
  154
+
  155
+    class UserFactory(factory.Factory):
  156
+        email = factory.Sequence(lambda n: 'person{0}@example.com'.format(n))
  157
+        
  158
+    UserFactory().email  # => 'person0@example.com'
  159
+    UserFactory().email  # => 'person1@example.com'
  160
+        
  161
+Sequences can be combined with lazy attributes::
  162
+
  163
+    class UserFactory(factory.Factory):
  164
+        name = 'Mark'
  165
+        email = factory.LazyAttributeSequence(lambda a, n: '{0}+{1}@example.com'.format(a.name, n).lower())
  166
+        
  167
+    UserFactory().email  # => mark+1@example.com
40  factory/__init__.py
... ...
@@ -0,0 +1,40 @@
  1
+# Copyright (c) 2010 Mark Sandstrom
  2
+# 
  3
+# Permission is hereby granted, free of charge, to any person obtaining a copy
  4
+# of this software and associated documentation files (the "Software"), to deal
  5
+# in the Software without restriction, including without limitation the rights
  6
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7
+# copies of the Software, and to permit persons to whom the Software is
  8
+# furnished to do so, subject to the following conditions:
  9
+# 
  10
+# The above copyright notice and this permission notice shall be included in
  11
+# all copies or substantial portions of the Software.
  12
+# 
  13
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19
+# THE SOFTWARE.
  20
+
  21
+__version__ = '1.0.0'  # Remember to change in setup.py as well!
  22
+__author__ = 'Mark Sandstrom <mark@deliciouslynerdy.com>'
  23
+
  24
+from base import (
  25
+    Factory,
  26
+    StubFactory,
  27
+    BUILD_STRATEGY,
  28
+    CREATE_STRATEGY,
  29
+    STUB_STRATEGY
  30
+)
  31
+
  32
+from declarations import (
  33
+    LazyAttribute,
  34
+    Sequence,
  35
+    LazyAttributeSequence,
  36
+    lazy_attribute,
  37
+    sequence,
  38
+    lazy_attribute_sequence
  39
+)
  40
+
244  factory/base.py
... ...
@@ -0,0 +1,244 @@
  1
+# Copyright (c) 2010 Mark Sandstrom
  2
+# 
  3
+# Permission is hereby granted, free of charge, to any person obtaining a copy
  4
+# of this software and associated documentation files (the "Software"), to deal
  5
+# in the Software without restriction, including without limitation the rights
  6
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7
+# copies of the Software, and to permit persons to whom the Software is
  8
+# furnished to do so, subject to the following conditions:
  9
+# 
  10
+# The above copyright notice and this permission notice shall be included in
  11
+# all copies or substantial portions of the Software.
  12
+# 
  13
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19
+# THE SOFTWARE.
  20
+
  21
+import re
  22
+import sys
  23
+
  24
+from containers import ObjectParamsWrapper, StubObject
  25
+from declarations import OrderedDeclaration
  26
+
  27
+# Strategies
  28
+
  29
+BUILD_STRATEGY = 'build'
  30
+CREATE_STRATEGY = 'create'
  31
+STUB_STRATEGY = 'stub'
  32
+
  33
+# Creation functions. Use Factory.set_creation_function() to set a creation function appropriate for your ORM.
  34
+
  35
+DJANGO_CREATION = lambda class_to_create, **kwargs: class_to_create.objects.create(**kwargs)
  36
+        
  37
+# Special declarations
  38
+
  39
+FACTORY_CLASS_DECLARATION = 'FACTORY_FOR'
  40
+
  41
+# Factory class attributes
  42
+
  43
+CLASS_ATTRIBUTE_ORDERED_DECLARATIONS = '_ordered_declarations'
  44
+CLASS_ATTRIBUTE_UNORDERED_DECLARATIONS = '_unordered_declarations'
  45
+CLASS_ATTRIBUTE_ASSOCIATED_CLASS = '_associated_class'
  46
+
  47
+# Factory metaclasses
  48
+
  49
+def get_factory_base(bases):
  50
+    parents = [b for b in bases if isinstance(b, BaseFactoryMetaClass)]
  51
+    if not parents:
  52
+        return None
  53
+    if len(parents) > 1:
  54
+        raise RuntimeError('You can only inherit from one Factory')
  55
+    return parents[0]
  56
+
  57
+class BaseFactoryMetaClass(type):
  58
+    '''Factory metaclass for handling ordered declarations.'''
  59
+     
  60
+    def __call__(cls, **kwargs):
  61
+        '''Create an associated class instance using the default build strategy. Never create a Factory instance.'''
  62
+        
  63
+        if cls.default_strategy == BUILD_STRATEGY:
  64
+            return cls.build(**kwargs)
  65
+        elif cls.default_strategy == CREATE_STRATEGY:
  66
+            return cls.create(**kwargs)
  67
+        elif cls.default_strategy == STUB_STRATEGY:
  68
+            return cls.stub(**kwargs)
  69
+        else:
  70
+            raise BaseFactory.UnknownStrategy('Unknown default_strategy: {0}'.format(cls.default_strategy))
  71
+    
  72
+    def __new__(cls, class_name, bases, dict, extra_dict={}):
  73
+        '''Record attributes (unordered declarations) and ordered declarations for construction of
  74
+        an associated class instance at a later time.'''
  75
+        
  76
+        base = get_factory_base(bases)
  77
+        if not base:
  78
+            # If this isn't a subclass of Factory, don't do anything special.
  79
+            return super(BaseFactoryMetaClass, cls).__new__(cls, class_name, bases, dict)
  80
+        
  81
+        ordered_declarations = getattr(base, CLASS_ATTRIBUTE_ORDERED_DECLARATIONS, [])
  82
+        unordered_declarations = getattr(base, CLASS_ATTRIBUTE_UNORDERED_DECLARATIONS, [])
  83
+
  84
+        for name in list(dict):
  85
+            if isinstance(dict[name], OrderedDeclaration):
  86
+                ordered_declarations = [(_name, declaration) for (_name, declaration) in ordered_declarations if _name != name]
  87
+                ordered_declarations.append((name, dict[name]))
  88
+                del dict[name]
  89
+            elif not name.startswith('__'):
  90
+                unordered_declarations = [(_name, value) for (_name, value) in unordered_declarations if _name != name]
  91
+                unordered_declarations.append((name, dict[name]))
  92
+                del dict[name]
  93
+
  94
+        ordered_declarations.sort(key=lambda d: d[1].order)
  95
+
  96
+        dict[CLASS_ATTRIBUTE_ORDERED_DECLARATIONS] = ordered_declarations
  97
+        dict[CLASS_ATTRIBUTE_UNORDERED_DECLARATIONS] = unordered_declarations
  98
+        
  99
+        for name, value in extra_dict.iteritems():
  100
+            dict[name] = value
  101
+
  102
+        return super(BaseFactoryMetaClass, cls).__new__(cls, class_name, bases, dict)
  103
+
  104
+class FactoryMetaClass(BaseFactoryMetaClass):
  105
+    '''Factory metaclass for handling class association and ordered declarations.'''
  106
+    
  107
+    ERROR_MESSAGE = '''Could not determine what class this factory is for.
  108
+    Use the {0} attribute to specify a class.'''
  109
+    ERROR_MESSAGE_AUTODISCOVERY = ERROR_MESSAGE + '''
  110
+    Also, autodiscovery failed using the name '{1}'
  111
+    based on the Factory name '{2}' in {3}.'''
  112
+    
  113
+    def __new__(cls, class_name, bases, dict):
  114
+        '''Determine the associated class based on the factory class name. Record the associated class
  115
+        for construction of an associated class instance at a later time.'''
  116
+        
  117
+        base = get_factory_base(bases)
  118
+        if not base:
  119
+            # If this isn't a subclass of Factory, don't do anything special.
  120
+            return super(FactoryMetaClass, cls).__new__(cls, class_name, bases, dict)
  121
+        
  122
+        inherited_associated_class = getattr(base, CLASS_ATTRIBUTE_ASSOCIATED_CLASS, None)
  123
+        own_associated_class = None
  124
+        used_auto_discovery = False
  125
+            
  126
+        if FACTORY_CLASS_DECLARATION in dict:
  127
+            own_associated_class = dict[FACTORY_CLASS_DECLARATION]
  128
+            del dict[FACTORY_CLASS_DECLARATION]
  129
+        else:
  130
+            factory_module = sys.modules[dict['__module__']]
  131
+            match = re.match(r'^(\w+)Factory$', class_name)
  132
+            if match:
  133
+                used_auto_discovery = True
  134
+                associated_class_name = match.group(1)
  135
+                try:
  136
+                    own_associated_class = getattr(factory_module, associated_class_name)
  137
+                except AttributeError:
  138
+                    pass
  139
+                    
  140
+        if own_associated_class != None and inherited_associated_class != None and own_associated_class != inherited_associated_class:
  141
+            format = 'These factories are for conflicting classes: {0} and {1}'
  142
+            raise Factory.AssociatedClassError(format.format(inherited_associated_class, own_associated_class))
  143
+        elif inherited_associated_class != None:
  144
+            own_associated_class = inherited_associated_class
  145
+            
  146
+        if not own_associated_class and used_auto_discovery:
  147
+            format_args = FACTORY_CLASS_DECLARATION, associated_class_name, class_name, factory_module
  148
+            raise Factory.AssociatedClassError(FactoryMetaClass.ERROR_MESSAGE_AUTODISCOVERY.format(*format_args))
  149
+        elif not own_associated_class:
  150
+            raise Factory.AssociatedClassError(FactoryMetaClass.ERROR_MESSAGE.format(FACTORY_CLASS_DECLARATION))
  151
+            
  152
+        extra_dict = {CLASS_ATTRIBUTE_ASSOCIATED_CLASS: own_associated_class}
  153
+        return super(FactoryMetaClass, cls).__new__(cls, class_name, bases, dict, extra_dict=extra_dict) 
  154
+
  155
+# Factory base classes
  156
+
  157
+class BaseFactory(object):
  158
+    '''Factory base support for sequences, attributes and stubs.'''
  159
+    
  160
+    class UnknownStrategy(RuntimeError): pass
  161
+    class UnsupportedStrategy(RuntimeError): pass
  162
+    
  163
+    def __new__(cls, *args, **kwargs):
  164
+        raise RuntimeError('You cannot instantiate BaseFactory')
  165
+    
  166
+    _next_sequence = 0
  167
+    
  168
+    @classmethod
  169
+    def _generate_next_sequence(cls):
  170
+        next_sequence = cls._next_sequence
  171
+        cls._next_sequence += 1
  172
+        return next_sequence
  173
+        
  174
+    @classmethod
  175
+    def attributes(cls, **kwargs):
  176
+        attributes = {}
  177
+        cls.sequence = cls._generate_next_sequence()
  178
+
  179
+        for name, value in getattr(cls, CLASS_ATTRIBUTE_UNORDERED_DECLARATIONS):
  180
+            if name in kwargs:
  181
+                attributes[name] = kwargs[name]
  182
+                del kwargs[name]
  183
+            else:
  184
+                attributes[name] = value
  185
+
  186
+        for name, ordered_declaration in getattr(cls, CLASS_ATTRIBUTE_ORDERED_DECLARATIONS):
  187
+            if name in kwargs:
  188
+                attributes[name] = kwargs[name]
  189
+                del kwargs[name]
  190
+            else:
  191
+                a = ObjectParamsWrapper(attributes)
  192
+                attributes[name] = ordered_declaration.evaluate(cls, a)
  193
+
  194
+        for name in kwargs:
  195
+            attributes[name] = kwargs[name]
  196
+
  197
+        return attributes
  198
+        
  199
+    @classmethod
  200
+    def build(cls, **kwargs):
  201
+        raise cls.UnsupportedStrategy()
  202
+    
  203
+    @classmethod
  204
+    def create(cls, **kwargs):
  205
+        raise cls.UnsupportedStrategy()
  206
+    
  207
+    @classmethod
  208
+    def stub(cls, **kwargs):
  209
+        stub_object = StubObject()
  210
+        for name, value in cls.attributes(**kwargs).iteritems():
  211
+            setattr(stub_object, name, value)
  212
+        return stub_object
  213
+
  214
+class StubFactory(BaseFactory):
  215
+    __metaclass__ = BaseFactoryMetaClass
  216
+
  217
+    default_strategy = STUB_STRATEGY
  218
+
  219
+class Factory(BaseFactory):
  220
+    '''Factory base with build and create support.
  221
+    
  222
+    This class has the ability to support multiple ORMs by using custom creation functions.'''
  223
+    
  224
+    __metaclass__ = FactoryMetaClass
  225
+    
  226
+    default_strategy = CREATE_STRATEGY
  227
+    
  228
+    class AssociatedClassError(RuntimeError): pass
  229
+    
  230
+    _creation_function = (DJANGO_CREATION,)  # Using a tuple to keep the creation function from turning into an instance method
  231
+    @classmethod
  232
+    def set_creation_function(cls, creation_function):
  233
+        cls._creation_function = (creation_function,)
  234
+    @classmethod
  235
+    def get_creation_function(cls):
  236
+        return cls._creation_function[0]
  237
+    
  238
+    @classmethod
  239
+    def build(cls, **kwargs):
  240
+        return getattr(cls, CLASS_ATTRIBUTE_ASSOCIATED_CLASS)(**cls.attributes(**kwargs))
  241
+        
  242
+    @classmethod
  243
+    def create(cls, **kwargs):
  244
+        return cls.get_creation_function()(getattr(cls, CLASS_ATTRIBUTE_ASSOCIATED_CLASS), **cls.attributes(**kwargs))
47  factory/containers.py
... ...
@@ -0,0 +1,47 @@
  1
+# Copyright (c) 2010 Mark Sandstrom
  2
+# 
  3
+# Permission is hereby granted, free of charge, to any person obtaining a copy
  4
+# of this software and associated documentation files (the "Software"), to deal
  5
+# in the Software without restriction, including without limitation the rights
  6
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7
+# copies of the Software, and to permit persons to whom the Software is
  8
+# furnished to do so, subject to the following conditions:
  9
+# 
  10
+# The above copyright notice and this permission notice shall be included in
  11
+# all copies or substantial portions of the Software.
  12
+# 
  13
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19
+# THE SOFTWARE.
  20
+
  21
+class ObjectParamsWrapper(object):
  22
+    '''A generic container that allows for getting but not setting of attributes.
  23
+    
  24
+    Attributes are set at initialization time.'''
  25
+    
  26
+    initialized = False
  27
+    
  28
+    def __init__(self, dict):
  29
+        self.dict = dict
  30
+        self.initialized = True
  31
+        
  32
+    def __setattr__(self, name, value):
  33
+        if not self.initialized:
  34
+            return super(ObjectParamsWrapper, self).__setattr__(name, value)
  35
+        else:
  36
+            raise AttributeError('Setting of object attributes is not allowed')
  37
+    
  38
+    def __getattr__(self, name):
  39
+        try:
  40
+            return self.dict[name]
  41
+        except KeyError:
  42
+            raise AttributeError("The param '{0}' does not exist. Perhaps your declarations are out of order?".format(name))
  43
+        
  44
+class StubObject(object):
  45
+    '''A generic container.'''
  46
+    
  47
+    pass
76  factory/declarations.py
... ...
@@ -0,0 +1,76 @@
  1
+# Copyright (c) 2010 Mark Sandstrom
  2
+# 
  3
+# Permission is hereby granted, free of charge, to any person obtaining a copy
  4
+# of this software and associated documentation files (the "Software"), to deal
  5
+# in the Software without restriction, including without limitation the rights
  6
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7
+# copies of the Software, and to permit persons to whom the Software is
  8
+# furnished to do so, subject to the following conditions:
  9
+# 
  10
+# The above copyright notice and this permission notice shall be included in
  11
+# all copies or substantial portions of the Software.
  12
+# 
  13
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19
+# THE SOFTWARE.
  20
+
  21
+class OrderedDeclaration(object):
  22
+    '''A factory declaration.
  23
+    
  24
+    Ordered declarations keep track of the order in which they're defined so that later declarations
  25
+    can refer to attributes created by earlier declarations when the declarations are evaluated.'''
  26
+    _next_order = 0
  27
+    
  28
+    def __init__(self):
  29
+        self.order = self.next_order()
  30
+        
  31
+    @classmethod
  32
+    def next_order(cls):
  33
+        next_order = cls._next_order
  34
+        cls._next_order += 1
  35
+        return next_order
  36
+        
  37
+    def evaluate(self, factory, attributes):
  38
+        '''Evaluate this declaration.
  39
+        
  40
+        Args:
  41
+            factory: The factory this declaration was defined in.
  42
+            attributes: The attributes created by the unordered and ordered declarations up to this point.'''
  43
+        
  44
+        raise NotImplementedError('This is an abstract method')
  45
+
  46
+class LazyAttribute(OrderedDeclaration):
  47
+    def __init__(self, function):
  48
+        super(LazyAttribute, self).__init__()
  49
+        self.function = function
  50
+    
  51
+    def evaluate(self, factory, attributes):
  52
+        return self.function(attributes)
  53
+
  54
+class Sequence(OrderedDeclaration):
  55
+    def __init__(self, function, type=str):
  56
+        super(Sequence, self).__init__()
  57
+        self.function = function
  58
+        self.type = type
  59
+    
  60
+    def evaluate(self, factory, attributes):
  61
+        return self.function(self.type(factory.sequence))
  62
+
  63
+class LazyAttributeSequence(Sequence):
  64
+    def evaluate(self, factory, attributes):
  65
+        return self.function(attributes, self.type(factory.sequence))
  66
+
  67
+# Decorators... in case lambdas don't cut it
  68
+
  69
+def lazy_attribute(func):
  70
+    return LazyAttribute(func)
  71
+
  72
+def sequence(func):
  73
+    return Sequence(func)
  74
+
  75
+def lazy_attribute_sequence(func):
  76
+    return LazyAttributeSequence(func)
28  setup.py
... ...
@@ -0,0 +1,28 @@
  1
+#!/usr/bin/python
  2
+
  3
+from distutils.core import setup
  4
+
  5
+# Remember to change in factory/__init__.py as well!
  6
+VERSION = '1.0.0'
  7
+
  8
+setup(
  9
+    name='factory_boy',
  10
+    version=VERSION,
  11
+    description="A test fixtures replacement based on thoughtbot's factory_girl for Ruby.",
  12
+    author='Mark Sandstrom',
  13
+    author_email='mark@deliciouslynerdy.com',
  14
+    url='http://github.com/dnerdy/factory_boy',
  15
+    keywords=['factory_boy', 'factory', 'fixtures'],
  16
+    packages=['factory'],
  17
+    license='MIT',
  18
+    classifiers=[
  19
+        'Development Status :: 5 - Production/Stable',
  20
+        'Intended Audience :: Developers',
  21
+        'Framework :: Django',
  22
+        'License :: OSI Approved :: MIT License',
  23
+        'Operating System :: OS Independent',
  24
+        'Programming Language :: Python',
  25
+        'Topic :: Software Development :: Testing',
  26
+        'Topic :: Software Development :: Libraries :: Python Modules'
  27
+    ]
  28
+)
305  tests.py
... ...
@@ -0,0 +1,305 @@
  1
+import unittest
  2
+
  3
+from factory import Factory, StubFactory, LazyAttribute, Sequence, LazyAttributeSequence, lazy_attribute, sequence, lazy_attribute_sequence
  4
+from factory import CREATE_STRATEGY, BUILD_STRATEGY, STUB_STRATEGY
  5
+
  6
+class TestObject(object):
  7
+    def __init__(self, one=None, two=None, three=None, four=None):
  8
+        self.one = one
  9
+        self.two = two
  10
+        self.three = three
  11
+        self.four = four
  12
+
  13
+class FakeDjangoModel(object):
  14
+    class FakeDjangoManager(object):  
  15
+        def create(self, **kwargs):
  16
+            fake_model = FakeDjangoModel(**kwargs)
  17
+            fake_model.id = 1
  18
+            return fake_model
  19
+    
  20
+    objects = FakeDjangoManager()
  21
+    
  22
+    def __init__(self, **kwargs):
  23
+        for name, value in kwargs.iteritems():
  24
+            setattr(self, name, value)
  25
+            self.id = None
  26
+
  27
+class TestModel(FakeDjangoModel):
  28
+    pass
  29
+
  30
+class FactoryTestCase(unittest.TestCase):
  31
+    def testAttribute(self):
  32
+        class TestObjectFactory(Factory):
  33
+            one = 'one'
  34
+            
  35
+        test_object = TestObjectFactory.build()
  36
+        self.assertEqual(test_object.one, 'one')    
  37
+    
  38
+    def testSequence(self):
  39
+        class TestObjectFactory(Factory):
  40
+            one = Sequence(lambda n: 'one' + n)
  41
+            two = Sequence(lambda n: 'two' + n)
  42
+            
  43
+        test_object0 = TestObjectFactory.build()
  44
+        self.assertEqual(test_object0.one, 'one0')
  45
+        self.assertEqual(test_object0.two, 'two0')
  46
+        
  47
+        test_object1 = TestObjectFactory.build()
  48
+        self.assertEqual(test_object1.one, 'one1')
  49
+        self.assertEqual(test_object1.two, 'two1')
  50
+        
  51
+    def testLazyAttribute(self):
  52
+        class TestObjectFactory(Factory):
  53
+            one = LazyAttribute(lambda a: 'abc' )
  54
+            two = LazyAttribute(lambda a: a.one + ' xyz')
  55
+            
  56
+        test_object = TestObjectFactory.build()
  57
+        self.assertEqual(test_object.one, 'abc')
  58
+        self.assertEqual(test_object.two, 'abc xyz')
  59
+        
  60
+    def testLazyAttributeNonExistentParam(self):
  61
+        class TestObjectFactory(Factory):
  62
+            one = LazyAttribute(lambda a: a.does_not_exist )
  63
+            
  64
+        try:
  65
+            TestObjectFactory()
  66
+            self.fail()
  67
+        except AttributeError as e:
  68
+            self.assertTrue('does not exist' in str(e))
  69
+    
  70
+    def testLazyAttributeSequence(self):
  71
+        class TestObjectFactory(Factory):
  72
+            one = LazyAttributeSequence(lambda a, n: 'abc' + n)
  73
+            two = LazyAttributeSequence(lambda a, n: a.one + ' xyz' + n)
  74
+            
  75
+        test_object0 = TestObjectFactory.build()
  76
+        self.assertEqual(test_object0.one, 'abc0')
  77
+        self.assertEqual(test_object0.two, 'abc0 xyz0')
  78
+        
  79
+        test_object1 = TestObjectFactory.build()
  80
+        self.assertEqual(test_object1.one, 'abc1')
  81
+        self.assertEqual(test_object1.two, 'abc1 xyz1')
  82
+        
  83
+    def testLazyAttributeDecorator(self):
  84
+        class TestObjectFactory(Factory):
  85
+            @lazy_attribute
  86
+            def one(a):
  87
+                return 'one'
  88
+                
  89
+        test_object = TestObjectFactory.build()
  90
+        self.assertEqual(test_object.one, 'one')
  91
+        
  92
+    def testSequenceDecorator(self):
  93
+        class TestObjectFactory(Factory):
  94
+            @sequence
  95
+            def one(n):
  96
+                return 'one' + n
  97
+                
  98
+        test_object = TestObjectFactory.build()
  99
+        self.assertEqual(test_object.one, 'one0')
  100
+        
  101
+    def testLazyAttributeSequenceDecorator(self):
  102
+        class TestObjectFactory(Factory):
  103
+            @lazy_attribute_sequence
  104
+            def one(a, n):
  105
+                return 'one' + n
  106
+            @lazy_attribute_sequence
  107
+            def two(a, n):
  108
+                return a.one + ' two' + n
  109
+                  
  110
+        test_object = TestObjectFactory.build()
  111
+        self.assertEqual(test_object.one, 'one0')
  112
+        self.assertEqual(test_object.two, 'one0 two0')
  113
+    
  114
+    def testBuildWithParameters(self):
  115
+        class TestObjectFactory(Factory):
  116
+            one = Sequence(lambda n: 'one' + n)
  117
+            two = Sequence(lambda n: 'two' + n)
  118
+            
  119
+        test_object0 = TestObjectFactory.build(three='three')
  120
+        self.assertEqual(test_object0.one, 'one0')
  121
+        self.assertEqual(test_object0.two, 'two0')
  122
+        self.assertEqual(test_object0.three, 'three')
  123
+        
  124
+        test_object1 = TestObjectFactory.build(one='other')
  125
+        self.assertEqual(test_object1.one, 'other')
  126
+        self.assertEqual(test_object1.two, 'two1')
  127
+        
  128
+    def testCreate(self):
  129
+        class TestModelFactory(Factory):
  130
+            one = 'one'
  131
+        
  132
+        test_model = TestModelFactory.create()
  133
+        self.assertEqual(test_model.one, 'one')
  134
+        self.assertTrue(test_model.id)
  135
+        
  136
+    def testInheritance(self):
  137
+        class TestObjectFactory(Factory):
  138
+            one = 'one'
  139
+            two = LazyAttribute(lambda a: a.one + ' two')
  140
+                    
  141
+        class TestObjectFactory2(TestObjectFactory):
  142
+            FACTORY_FOR = TestObject
  143
+            
  144
+            three = 'three'
  145
+            four = LazyAttribute(lambda a: a.three + ' four')
  146
+            
  147
+        test_object = TestObjectFactory2.build()
  148
+        self.assertEqual(test_object.one, 'one')
  149
+        self.assertEqual(test_object.two, 'one two')
  150
+        self.assertEqual(test_object.three, 'three')
  151
+        self.assertEqual(test_object.four, 'three four')
  152
+            
  153
+    def testInheritanceWithInheritedClass(self):
  154
+        class TestObjectFactory(Factory):
  155
+            one = 'one'
  156
+            two = LazyAttribute(lambda a: a.one + ' two')
  157
+                
  158
+        class TestFactory(TestObjectFactory):
  159
+            three = 'three'
  160
+            four = LazyAttribute(lambda a: a.three + ' four')
  161
+        
  162
+        test_object = TestFactory.build()
  163
+        self.assertEqual(test_object.one, 'one')
  164
+        self.assertEqual(test_object.two, 'one two')
  165
+        self.assertEqual(test_object.three, 'three')
  166
+        self.assertEqual(test_object.four, 'three four')
  167
+    
  168
+    def testSetCreationFunction(self):
  169
+        def creation_function(class_to_create, **kwargs):
  170
+            return "This doesn't even return an instance of {0}".format(class_to_create.__name__)
  171
+            
  172
+        class TestModelFactory(Factory):
  173
+            pass
  174
+            
  175
+        TestModelFactory.set_creation_function(creation_function)
  176
+        
  177
+        test_object = TestModelFactory.create()
  178
+        self.assertEqual(test_object, "This doesn't even return an instance of TestModel")
  179
+
  180
+class FactoryDefaultStrategyTestCase(unittest.TestCase):
  181
+    def setUp(self):
  182
+        self.default_strategy = Factory.default_strategy
  183
+        
  184
+    def tearDown(self):
  185
+        Factory.default_strategy = self.default_strategy
  186
+           
  187
+    def testBuildStrategy(self):
  188
+        Factory.default_strategy = BUILD_STRATEGY
  189
+        
  190
+        class TestModelFactory(Factory):
  191
+            one = 'one'
  192
+            
  193
+        test_model = TestModelFactory()
  194
+        self.assertEqual(test_model.one, 'one')
  195
+        self.assertFalse(test_model.id)
  196
+        
  197
+    def testCreateStrategy(self):
  198
+        # Default default_strategy
  199
+        
  200
+        class TestModelFactory(Factory):
  201
+            one = 'one'
  202
+
  203
+        test_model = TestModelFactory()
  204
+        self.assertEqual(test_model.one, 'one')
  205
+        self.assertTrue(test_model.id)
  206
+        
  207
+    def testStubStrategy(self):
  208
+        Factory.default_strategy = STUB_STRATEGY
  209
+        
  210
+        class TestModelFactory(Factory):
  211
+            one = 'one'
  212
+
  213
+        test_model = TestModelFactory()
  214
+        self.assertEqual(test_model.one, 'one')
  215
+        self.assertFalse(hasattr(test_model, 'id'))  # We should have a plain old object
  216
+        
  217
+    def testUnknownStrategy(self):
  218
+        Factory.default_strategy = 'unknown'
  219
+        
  220
+        class TestModelFactory(Factory):
  221
+            one = 'one'
  222
+
  223
+        self.assertRaises(Factory.UnknownStrategy, TestModelFactory)
  224
+        
  225
+    def testStubWithNonStubStrategy(self):        
  226
+        class TestModelFactory(StubFactory):
  227
+            one = 'one'
  228
+            
  229
+        TestModelFactory.default_strategy = CREATE_STRATEGY
  230
+
  231
+        self.assertRaises(StubFactory.UnsupportedStrategy, TestModelFactory)
  232
+
  233
+class FactoryCreationTestCase(unittest.TestCase):
  234
+    def testFactoryFor(self):
  235
+        class TestFactory(Factory):
  236
+            FACTORY_FOR = TestObject
  237
+               
  238
+        self.assertTrue(isinstance(TestFactory.build(), TestObject))
  239
+        
  240
+    def testAutomaticAssociatedClassDiscovery(self):
  241
+        class TestObjectFactory(Factory):
  242
+            pass
  243
+            
  244
+        self.assertTrue(isinstance(TestObjectFactory.build(), TestObject))
  245
+    
  246
+    def testStub(self):
  247
+        class TestFactory(StubFactory):
  248
+            pass
  249
+            
  250
+        self.assertEqual(TestFactory.default_strategy, STUB_STRATEGY)
  251
+    
  252
+    def testInheritanceWithStub(self):
  253
+        class TestObjectFactory(StubFactory):
  254
+            pass
  255
+
  256
+        class TestFactory(TestObjectFactory):
  257
+            pass
  258
+
  259
+        self.assertEqual(TestFactory.default_strategy, STUB_STRATEGY)
  260
+    
  261
+    # Errors
  262
+    
  263
+    def testNoAssociatedClassWithAutodiscovery(self):
  264
+        try:
  265
+            class TestFactory(Factory):
  266
+                pass
  267
+            self.fail()
  268
+        except Factory.AssociatedClassError as e:
  269
+            self.assertTrue('autodiscovery' in str(e))
  270
+            
  271
+    def testNoAssociatedClassWithoutAutodiscovery(self):
  272
+        try:
  273
+            class Test(Factory):
  274
+                pass
  275
+            self.fail()
  276
+        except Factory.AssociatedClassError as e:
  277
+            self.assertTrue('autodiscovery' not in str(e))
  278
+            
  279
+    def testInheritanceWithConflictingClassesError(self):
  280
+        class TestObjectFactory(Factory):
  281
+            pass
  282
+
  283
+        try:
  284
+            class TestModelFactory(TestObjectFactory):
  285
+                pass
  286
+            self.fail()
  287
+        except Factory.AssociatedClassError as e:
  288
+            self.assertTrue('conflicting' in str(e))
  289
+            
  290
+    def testInheritanceFromMoreThanOneFactory(self):
  291
+        class TestObjectFactory(StubFactory):
  292
+            pass
  293
+
  294
+        class TestModelFactory(TestObjectFactory):
  295
+            pass
  296
+
  297
+        try:
  298
+            class TestFactory(TestObjectFactory, TestModelFactory):
  299
+                pass
  300
+            self.fail()
  301
+        except RuntimeError as e:
  302
+            self.assertTrue('one Factory' in str(e))
  303
+
  304
+if __name__ == '__main__':
  305
+    unittest.main()

0 notes on commit 0431afa

Please sign in to comment.
Something went wrong with that request. Please try again.