From eea28cce1544021f3d152782c9932a20402d6240 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Barrois?= Date: Sat, 2 Apr 2016 16:11:58 +0200 Subject: Refactor: move error defs to a dedicated module. --- factory/__init__.py | 7 +++++-- factory/base.py | 31 ++++++++----------------------- factory/containers.py | 8 ++------ factory/errors.py | 42 ++++++++++++++++++++++++++++++++++++++++++ tests/test_base.py | 11 ++++++----- tests/test_containers.py | 3 ++- 6 files changed, 65 insertions(+), 37 deletions(-) create mode 100644 factory/errors.py diff --git a/factory/__init__.py b/factory/__init__.py index 1fa581b..ccd71cd 100644 --- a/factory/__init__.py +++ b/factory/__init__.py @@ -32,14 +32,17 @@ from .base import ( ListFactory, StubFactory, - FactoryError, - BUILD_STRATEGY, CREATE_STRATEGY, STUB_STRATEGY, use_strategy, ) + +from .errors import ( + FactoryError, +) + from .faker import Faker from .declarations import ( diff --git a/factory/base.py b/factory/base.py index 0f2af59..1ddb742 100644 --- a/factory/base.py +++ b/factory/base.py @@ -24,6 +24,7 @@ import logging from . import containers from . import declarations +from . import errors from . import utils logger = logging.getLogger('factory.generate') @@ -35,22 +36,6 @@ STUB_STRATEGY = 'stub' -class FactoryError(Exception): - """Any exception raised by factory_boy.""" - - -class AssociatedClassError(FactoryError): - """Exception for Factory subclasses lacking Meta.model.""" - - -class UnknownStrategy(FactoryError): - """Raised when a factory uses an unknown strategy.""" - - -class UnsupportedStrategy(FactoryError): - """Raised when trying to use a strategy on an incompatible Factory.""" - - # Factory metaclasses def get_factory_bases(bases): @@ -82,7 +67,7 @@ class FactoryMetaClass(type): elif cls._meta.strategy == STUB_STRATEGY: return cls.stub(**kwargs) else: - raise UnknownStrategy('Unknown Meta.strategy: {0}'.format( + raise errors.UnknownStrategy('Unknown Meta.strategy: {0}'.format( cls._meta.strategy)) def __new__(mcs, class_name, bases, attrs): @@ -296,12 +281,12 @@ class BaseFactory(object): """Factory base support for sequences, attributes and stubs.""" # Backwards compatibility - UnknownStrategy = UnknownStrategy - UnsupportedStrategy = UnsupportedStrategy + UnknownStrategy = errors.UnknownStrategy + UnsupportedStrategy = errors.UnsupportedStrategy def __new__(cls, *args, **kwargs): """Would be called if trying to instantiate the class.""" - raise FactoryError('You cannot instantiate BaseFactory') + raise errors.FactoryError('You cannot instantiate BaseFactory') _meta = FactoryOptions() @@ -477,7 +462,7 @@ class BaseFactory(object): attrs (dict): attributes to use for generating the object """ if cls._meta.abstract: - raise FactoryError( + raise errors.FactoryError( "Cannot generate instances of abstract factory %(f)s; " "Ensure %(f)s.Meta.model is set and %(f)s.Meta.abstract " "is either not set or False." % dict(f=cls.__name__)) @@ -680,7 +665,7 @@ Factory = FactoryMetaClass('Factory', (BaseFactory,), { # Backwards compatibility -Factory.AssociatedClassError = AssociatedClassError # pylint: disable=W0201 +Factory.AssociatedClassError = errors.AssociatedClassError # pylint: disable=W0201 class StubFactory(Factory): @@ -695,7 +680,7 @@ class StubFactory(Factory): @classmethod def create(cls, **kwargs): - raise UnsupportedStrategy() + raise errors.UnsupportedStrategy() class BaseDictFactory(Factory): diff --git a/factory/containers.py b/factory/containers.py index 0ae354b..c591988 100644 --- a/factory/containers.py +++ b/factory/containers.py @@ -25,13 +25,10 @@ import logging logger = logging.getLogger(__name__) from . import declarations +from . import errors from . import utils -class CyclicDefinitionError(Exception): - """Raised when cyclic definition were found.""" - - class LazyStub(object): """A generic container that only allows getting attributes. @@ -93,7 +90,7 @@ class LazyStub(object): attributes being computed. """ if name in self.__pending: - raise CyclicDefinitionError( + raise errors.CyclicDefinitionError( "Cyclic lazy attribute definition for %s; cycle found in %r." % (name, self.__pending)) elif name in self.__values: @@ -112,7 +109,6 @@ class LazyStub(object): "The parameter %s is unknown. Evaluated attributes are %r, " "definitions are %r." % (name, self.__values, self.__attrs)) - def __setattr__(self, name, value): """Prevent setting attributes once __init__ is done.""" if not self.__initialized: diff --git a/factory/errors.py b/factory/errors.py new file mode 100644 index 0000000..79d85f4 --- /dev/null +++ b/factory/errors.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2011-2015 Raphaƫl Barrois +# +# 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 FactoryError(Exception): + """Any exception raised by factory_boy.""" + + +class AssociatedClassError(FactoryError): + """Exception for Factory subclasses lacking Meta.model.""" + + +class UnknownStrategy(FactoryError): + """Raised when a factory uses an unknown strategy.""" + + +class UnsupportedStrategy(FactoryError): + """Raised when trying to use a strategy on an incompatible Factory.""" + + +class CyclicDefinitionError(FactoryError): + """Raised when a cyclical declaration occurs.""" + + diff --git a/tests/test_base.py b/tests/test_base.py index dd74e35..a3b3704 100644 --- a/tests/test_base.py +++ b/tests/test_base.py @@ -24,6 +24,7 @@ import warnings from factory import base from factory import declarations +from factory import errors from .compat import unittest @@ -63,7 +64,7 @@ class TestModel(FakeDjangoModel): class SafetyTestCase(unittest.TestCase): def test_base_factory(self): - self.assertRaises(base.FactoryError, base.BaseFactory) + self.assertRaises(errors.FactoryError, base.BaseFactory) class AbstractFactoryTestCase(unittest.TestCase): @@ -88,8 +89,8 @@ class AbstractFactoryTestCase(unittest.TestCase): class TestObjectFactory(base.Factory): pass - self.assertRaises(base.FactoryError, TestObjectFactory.build) - self.assertRaises(base.FactoryError, TestObjectFactory.create) + self.assertRaises(errors.FactoryError, TestObjectFactory.build) + self.assertRaises(errors.FactoryError, TestObjectFactory.create) def test_abstract_factory_not_inherited(self): """abstract=True isn't propagated to child classes.""" @@ -110,8 +111,8 @@ class AbstractFactoryTestCase(unittest.TestCase): abstract = False model = None - self.assertRaises(base.FactoryError, TestObjectFactory.build) - self.assertRaises(base.FactoryError, TestObjectFactory.create) + self.assertRaises(errors.FactoryError, TestObjectFactory.build) + self.assertRaises(errors.FactoryError, TestObjectFactory.create) class OptionsTests(unittest.TestCase): diff --git a/tests/test_containers.py b/tests/test_containers.py index 825e897..20c773a 100644 --- a/tests/test_containers.py +++ b/tests/test_containers.py @@ -23,6 +23,7 @@ from factory import base from factory import containers from factory import declarations +from factory import errors from .compat import unittest @@ -88,7 +89,7 @@ class LazyStubTestCase(unittest.TestCase): stub = containers.LazyStub({'one': LazyAttr('two'), 'two': LazyAttr('one')}) - self.assertRaises(containers.CyclicDefinitionError, getattr, stub, 'one') + self.assertRaises(errors.CyclicDefinitionError, getattr, stub, 'one') def test_representation(self): class RandomObj(object): -- cgit v1.2.3