summaryrefslogtreecommitdiff
path: root/factory/base.py
blob: 1d84b0363e376323d8959869344f720ffcb4d677 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# 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, attrs, extra_attrs={}):
        '''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, attrs)

        ordered_declarations = getattr(base, CLASS_ATTRIBUTE_ORDERED_DECLARATIONS, [])
        unordered_declarations = getattr(base, CLASS_ATTRIBUTE_UNORDERED_DECLARATIONS, [])

        for name in list(attrs):
            if isinstance(attrs[name], OrderedDeclaration):
                ordered_declarations = [(_name, declaration) for (_name, declaration) in ordered_declarations if _name != name]
                ordered_declarations.append((name, attrs[name]))
                del attrs[name]
            elif not name.startswith('__'):
                unordered_declarations = [(_name, value) for (_name, value) in unordered_declarations if _name != name]
                unordered_declarations.append((name, attrs[name]))
                del attrs[name]

        ordered_declarations.sort(key=lambda d: d[1].order)

        attrs[CLASS_ATTRIBUTE_ORDERED_DECLARATIONS] = ordered_declarations
        attrs[CLASS_ATTRIBUTE_UNORDERED_DECLARATIONS] = unordered_declarations

        for name, value in extra_attrs.iteritems():
            attrs[name] = value

        return super(BaseFactoryMetaClass, cls).__new__(cls, class_name, bases, attrs)

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, attrs):
        '''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, attrs)

        inherited_associated_class = getattr(base, CLASS_ATTRIBUTE_ASSOCIATED_CLASS, None)
        own_associated_class = None
        used_auto_discovery = False

        if FACTORY_CLASS_DECLARATION in attrs:
            own_associated_class = attrs.pop(FACTORY_CLASS_DECLARATION)
        else:
            factory_module = sys.modules[attrs['__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 is None and inherited_associated_class is not 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_attrs = {CLASS_ATTRIBUTE_ASSOCIATED_CLASS: own_associated_class}
        return super(FactoryMetaClass, cls).__new__(cls, class_name, bases, attrs, extra_attrs=extra_attrs)

# 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.pop(name)
            else:
                attributes[name] = value

        for name, ordered_declaration in getattr(cls, CLASS_ATTRIBUTE_ORDERED_DECLARATIONS):
            if name in kwargs:
                attributes[name] = kwargs.pop(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))