def test_defaulted_init(self):
        class X(object):
            def __init__(self_, a, b=123, c='abc'):
                self_.a = a
                self_.b = b
                self_.c = c
        instrumentation.register_class(X)

        o = X('foo')
        eq_(o.a, 'foo')
        eq_(o.b, 123)
        eq_(o.c, 'abc')

        class Y(object):
            unique = object()

            class OutOfScopeForEval(object):
                def __repr__(self_):
                    # misleading repr
                    return '123'

            outofscope = OutOfScopeForEval()

            def __init__(self_, u=unique, o=outofscope):
                self_.u = u
                self_.o = o

        instrumentation.register_class(Y)

        o = Y()
        assert o.u is Y.unique
        assert o.o is Y.outofscope
    def test_inheritance(self):
        """tests that attributes are polymorphic"""

        for base in (object, MyBaseClass, MyClass):
            class Foo(base):pass
            class Bar(Foo):pass

            instrumentation.register_class(Foo)
            instrumentation.register_class(Bar)

            def func1(state, passive):
                return "this is the foo attr"
            def func2(state, passive):
                return "this is the bar attr"
            def func3(state, passive):
                return "this is the shared attr"
            attributes.register_attribute(Foo, 'element',
                    uselist=False, callable_=func1,
                    useobject=True)
            attributes.register_attribute(Foo, 'element2',
                    uselist=False, callable_=func3,
                    useobject=True)
            attributes.register_attribute(Bar, 'element',
                    uselist=False, callable_=func2,
                    useobject=True)

            x = Foo()
            y = Bar()
            assert x.element == 'this is the foo attr'
            assert y.element == 'this is the bar attr', y.element
            assert x.element2 == 'this is the shared attr'
            assert y.element2 == 'this is the shared attr'
    def test_basic(self):
        for base in (object, MyBaseClass, MyClass):
            class User(base):
                pass

            register_class(User)
            attributes.register_attribute(
                User, 'user_id', uselist=False, useobject=False)
            attributes.register_attribute(
                User, 'user_name', uselist=False, useobject=False)
            attributes.register_attribute(
                User, 'email_address', uselist=False, useobject=False)

            u = User()
            u.user_id = 7
            u.user_name = 'john'
            u.email_address = '*****@*****.**'

            eq_(u.user_id, 7)
            eq_(u.user_name, "john")
            eq_(u.email_address, "*****@*****.**")
            attributes.instance_state(u)._commit_all(
                attributes.instance_dict(u))
            eq_(u.user_id, 7)
            eq_(u.user_name, "john")
            eq_(u.email_address, "*****@*****.**")

            u.user_name = 'heythere'
            u.email_address = '*****@*****.**'
            eq_(u.user_id, 7)
            eq_(u.user_name, "heythere")
            eq_(u.email_address, "*****@*****.**")
    def test_collection_with_backref(self):
        for base in (object, MyBaseClass, MyClass):
            class Post(base):pass
            class Blog(base):pass

            instrumentation.register_class(Post)
            instrumentation.register_class(Blog)
            attributes.register_attribute(Post, 'blog', uselist=False,
                    backref='posts', trackparent=True, useobject=True)
            attributes.register_attribute(Blog, 'posts', uselist=True,
                    backref='blog', trackparent=True, useobject=True)
            b = Blog()
            (p1, p2, p3) = (Post(), Post(), Post())
            b.posts.append(p1)
            b.posts.append(p2)
            b.posts.append(p3)
            self.assert_(b.posts == [p1, p2, p3])
            self.assert_(p2.blog is b)

            p3.blog = None
            self.assert_(b.posts == [p1, p2])
            p4 = Post()
            p4.blog = b
            self.assert_(b.posts == [p1, p2, p4])

            p4.blog = b
            p4.blog = b
            self.assert_(b.posts == [p1, p2, p4])

            # assert no failure removing None
            p5 = Post()
            p5.blog = None
            del p5.blog
Beispiel #5
0
    def test_standard(self):
        class A(object):
            pass

        register_class(A)

        eq_(type(manager_of_class(A)), instrumentation.ClassManager)
    def test_nativeext_submanager(self):
        class Mine(instrumentation.ClassManager): pass
        class A(object):
            __sa_instrumentation_manager__ = Mine

        instrumentation.register_class(A)
        eq_(type(instrumentation.manager_of_class(A)), Mine)
Beispiel #7
0
    def test_instance_dict(self):
        class User(MyClass):
            pass

        register_class(User)
        attributes.register_attribute(
            User, "user_id", uselist=False, useobject=False
        )
        attributes.register_attribute(
            User, "user_name", uselist=False, useobject=False
        )
        attributes.register_attribute(
            User, "email_address", uselist=False, useobject=False
        )

        u = User()
        u.user_id = 7
        u.user_name = "john"
        u.email_address = "*****@*****.**"
        eq_(
            u.__dict__,
            {
                "_my_state": u._my_state,
                "_goofy_dict": {
                    "user_id": 7,
                    "user_name": "john",
                    "email_address": "*****@*****.**",
                },
            },
        )
    def test_customfinder_pass(self):
        class A(object): pass
        def find(cls):
            return None

        instrumentation.instrumentation_finders.insert(0, find)
        instrumentation.register_class(A)
        eq_(type(instrumentation.manager_of_class(A)), instrumentation.ClassManager)
 def register(self, cls, canary):
     original_init = cls.__init__
     instrumentation.register_class(cls)
     ne_(cls.__init__, original_init)
     manager = instrumentation.manager_of_class(cls)
     def init(state, args, kwargs):
         canary.append((cls, 'init', state.class_))
     event.listen(manager, 'init', init, raw=True)
Beispiel #10
0
    def test_nativeext_interfaceexact(self):
        class A(object):
            __sa_instrumentation_manager__ = (
                instrumentation.InstrumentationManager
            )

        register_class(A)
        ne_(type(manager_of_class(A)), instrumentation.ClassManager)
    def test_null_instrumentation(self):
        class Foo(MyBaseClass):
            pass
        instrumentation.register_class(Foo)
        attributes.register_attribute(Foo, "name", uselist=False, useobject=False)
        attributes.register_attribute(Foo, "bars", uselist=True, trackparent=True, useobject=True)

        assert Foo.name == attributes.manager_of_class(Foo)['name']
        assert Foo.bars == attributes.manager_of_class(Foo)['bars']
Beispiel #12
0
    def test_customfinder_greedy(self):
        class Mine(instrumentation.ClassManager): pass
        class A(object): pass
        def find(cls):
            return Mine

        instrumentation.instrumentation_finders.insert(0, find)
        register_class(A)
        eq_(type(instrumentation.manager_of_class(A)), Mine)
    def test_single_down(self):
        class A(object): pass
        instrumentation.register_class(A)

        mgr_factory = lambda cls: instrumentation.ClassManager(cls)
        class B(A):
            __sa_instrumentation_manager__ = staticmethod(mgr_factory)

        assert_raises_message(TypeError, "multiple instrumentation implementations", instrumentation.register_class, B)
    def test_diamond_b2(self):
        mgr_factory = lambda cls: instrumentation.ClassManager(cls)

        class A(object): pass
        class B1(A): pass
        class B2(A):
            __sa_instrumentation_manager__ = staticmethod(mgr_factory)
        class C(object): pass

        instrumentation.register_class(B2)
        assert_raises_message(TypeError, "multiple instrumentation implementations", instrumentation.register_class, B1)
    def test_subclassed(self):
        class MyEvents(events.InstanceEvents):
            pass
        class MyClassManager(instrumentation.ClassManager):
            dispatch = event.dispatcher(MyEvents)

        instrumentation.instrumentation_finders.insert(0, lambda cls: MyClassManager)

        class A(object): pass

        instrumentation.register_class(A)
        manager = instrumentation.manager_of_class(A)
        assert issubclass(manager.dispatch._parent_cls.__dict__['dispatch'].events, MyEvents)
Beispiel #16
0
    def test_single_down(self):
        class A(object):
            pass

        register_class(A)

        mgr_factory = lambda cls: instrumentation.ClassManager(cls)

        class B(A):
            __sa_instrumentation_manager__ = staticmethod(mgr_factory)

        assert_raises_message(TypeError,
                              "multiple instrumentation implementations",
                              register_class, B)
    def test_instance_dict(self):
        class User(MyClass):
            pass

        instrumentation.register_class(User)
        attributes.register_attribute(User, 'user_id', uselist = False, useobject=False)
        attributes.register_attribute(User, 'user_name', uselist = False, useobject=False)
        attributes.register_attribute(User, 'email_address', uselist = False, useobject=False)

        u = User()
        u.user_id = 7
        u.user_name = 'john'
        u.email_address = '*****@*****.**'
        self.assert_(u.__dict__ == {'_my_state':u._my_state, '_goofy_dict':{'user_id':7, 'user_name':'john', 'email_address':'*****@*****.**'}}, u.__dict__)
    def test_collection_with_backref(self):
        for base in (object, MyBaseClass, MyClass):

            class Post(base):
                pass

            class Blog(base):
                pass

            register_class(Post)
            register_class(Blog)
            attributes.register_attribute(
                Post,
                "blog",
                uselist=False,
                backref="posts",
                trackparent=True,
                useobject=True,
            )
            attributes.register_attribute(
                Blog,
                "posts",
                uselist=True,
                backref="blog",
                trackparent=True,
                useobject=True,
            )
            b = Blog()
            (p1, p2, p3) = (Post(), Post(), Post())
            b.posts.append(p1)
            b.posts.append(p2)
            b.posts.append(p3)
            self.assert_(b.posts == [p1, p2, p3])
            self.assert_(p2.blog is b)

            p3.blog = None
            self.assert_(b.posts == [p1, p2])
            p4 = Post()
            p4.blog = b
            self.assert_(b.posts == [p1, p2, p4])

            p4.blog = b
            p4.blog = b
            self.assert_(b.posts == [p1, p2, p4])

            # assert no failure removing None
            p5 = Post()
            p5.blog = None
            del p5.blog
    def test_single_up(self):

        class A(object):
            pass
        # delay registration

        def mgr_factory(cls): return instrumentation.ClassManager(cls)

        class B(A):
            __sa_instrumentation_manager__ = staticmethod(mgr_factory)
        register_class(B)

        assert_raises_message(
            TypeError, "multiple instrumentation implementations",
            register_class, A)
    def test_register_reserved_attribute(self):
        class T(object): pass

        instrumentation.register_class(T)
        manager = instrumentation.manager_of_class(T)

        sa = instrumentation.ClassManager.STATE_ATTR
        ma = instrumentation.ClassManager.MANAGER_ATTR

        fails = lambda method, attr: assert_raises(
            KeyError, getattr(manager, method), attr, property())

        fails('install_member', sa)
        fails('install_member', ma)
        fails('install_descriptor', sa)
        fails('install_descriptor', ma)
    def test_deferred(self):
        for base in (object, MyBaseClass, MyClass):

            class Foo(base):
                pass

            data = {'a': 'this is a', 'b': 12}

            def loader(state, keys):
                for k in keys:
                    state.dict[k] = data[k]
                return attributes.ATTR_WAS_SET

            manager = register_class(Foo)
            manager.deferred_scalar_loader = loader
            attributes.register_attribute(Foo,
                                          'a',
                                          uselist=False,
                                          useobject=False)
            attributes.register_attribute(Foo,
                                          'b',
                                          uselist=False,
                                          useobject=False)

            if base is object:
                assert Foo not in instrumentation._instrumentation_factory._state_finders
            else:
                assert Foo in instrumentation._instrumentation_factory._state_finders

            f = Foo()
            attributes.instance_state(f)._expire(attributes.instance_dict(f),
                                                 set())
            eq_(f.a, "this is a")
            eq_(f.b, 12)

            f.a = "this is some new a"
            attributes.instance_state(f)._expire(attributes.instance_dict(f),
                                                 set())
            eq_(f.a, "this is a")
            eq_(f.b, 12)

            attributes.instance_state(f)._expire(attributes.instance_dict(f),
                                                 set())
            f.a = "this is another new a"
            eq_(f.a, "this is another new a")
            eq_(f.b, 12)

            attributes.instance_state(f)._expire(attributes.instance_dict(f),
                                                 set())
            eq_(f.a, "this is a")
            eq_(f.b, 12)

            del f.a
            eq_(f.a, None)
            eq_(f.b, 12)

            attributes.instance_state(f)._commit_all(
                attributes.instance_dict(f))
            eq_(f.a, None)
            eq_(f.b, 12)
 def _instrument(self, cls):
     manager = instrumentation.register_class(cls)
     canary = []
     def check(target, args, kwargs):
         canary.append((args, kwargs))
     event.listen(manager, "init", check)
     return cls, canary
Beispiel #23
0
    def __init__(self, cls_, classname, dict_):

        self.cls = cls_

        # dict_ will be a dictproxy, which we can't write to, and we need to!
        self.dict_ = dict(dict_)
        self.classname = classname
        self.mapped_table = None
        self.properties = util.OrderedDict()
        self.declared_columns = set()
        self.column_copies = {}
        self._setup_declared_events()

        # register up front, so that @declared_attr can memoize
        # function evaluations in .info
        manager = instrumentation.register_class(self.cls)
        manager.info['declared_attr_reg'] = {}

        self._scan_attributes()

        clsregistry.add_class(self.classname, self.cls)

        self._extract_mappable_attributes()

        self._extract_declared_columns()

        self._setup_table()

        self._setup_inheritance()

        self._early_mapping()
 def _instrument(self, cls):
     manager = instrumentation.register_class(cls)
     canary = []
     def check(target, args, kwargs):
         canary.append((args, kwargs))
     event.listen(manager, "init", check)
     return cls, canary
    def test_uninstrument(self):
        class A:
            pass

        manager = instrumentation.register_class(A)
        attributes.register_attribute(
            A,
            "x",
            comparator=object(),
            parententity=object(),
            uselist=False,
            useobject=False,
        )

        assert instrumentation.manager_of_class(A) is manager
        instrumentation.unregister_class(A)
        assert instrumentation.opt_manager_of_class(A) is None
        assert not hasattr(A, "x")

        with expect_raises_message(
                sa.orm.exc.UnmappedClassError,
                r"Can't locate an instrumentation manager for class .*A",
        ):
            instrumentation.manager_of_class(A)

        assert A.__init__ == object.__init__
    def test_subclassed(self):
        class MyEvents(events.InstanceEvents):
            pass

        class MyClassManager(instrumentation.ClassManager):
            dispatch = event.dispatcher(MyEvents)

        instrumentation.instrumentation_finders.insert(
            0, lambda cls: MyClassManager)

        class A(object):
            pass

        register_class(A)
        manager = instrumentation.manager_of_class(A)
        assert issubclass(manager.dispatch._events, MyEvents)
    def test_register_reserved_attribute(self):
        class T(object): pass

        instrumentation.register_class(T)
        manager = instrumentation.manager_of_class(T)

        sa = instrumentation.ClassManager.STATE_ATTR
        ma = instrumentation.ClassManager.MANAGER_ATTR

        fails = lambda method, attr: assert_raises(
            KeyError, getattr(manager, method), attr, property())

        fails('install_member', sa)
        fails('install_member', ma)
        fails('install_descriptor', sa)
        fails('install_descriptor', ma)
Beispiel #28
0
    def __init__(self, cls_, classname, dict_):

        self.cls = cls_

        # dict_ will be a dictproxy, which we can't write to, and we need to!
        self.dict_ = dict(dict_)
        self.classname = classname
        self.mapped_table = None
        self.properties = util.OrderedDict()
        self.declared_columns = set()
        self.column_copies = {}
        self._setup_declared_events()

        # register up front, so that @declared_attr can memoize
        # function evaluations in .info
        manager = instrumentation.register_class(self.cls)
        manager.info['declared_attr_reg'] = {}

        self._scan_attributes()

        clsregistry.add_class(self.classname, self.cls)

        self._extract_mappable_attributes()

        self._extract_declared_columns()

        self._setup_table()

        self._setup_inheritance()

        self._early_mapping()
    def test_uninstrument(self):
        class A(object):pass

        manager = instrumentation.register_class(A)

        assert instrumentation.manager_of_class(A) is manager
        instrumentation.unregister_class(A)
        assert instrumentation.manager_of_class(A) is None
    def test_uninstrument(self):
        class A(object):pass

        manager = instrumentation.register_class(A)

        assert instrumentation.manager_of_class(A) is manager
        instrumentation.unregister_class(A)
        assert instrumentation.manager_of_class(A) is None
    def test_single_up(self):
        class A(object):
            pass

        # delay registration

        def mgr_factory(cls):
            return instrumentation.ClassManager(cls)

        class B(A):
            __sa_instrumentation_manager__ = staticmethod(mgr_factory)

        register_class(B)

        assert_raises_message(TypeError,
                              "multiple instrumentation implementations",
                              register_class, A)
    def test_null_instrumentation(self):
        class Foo(MyBaseClass):
            pass

        register_class(Foo)
        attributes.register_attribute(Foo,
                                      "name",
                                      uselist=False,
                                      useobject=False)
        attributes.register_attribute(Foo,
                                      "bars",
                                      uselist=True,
                                      trackparent=True,
                                      useobject=True)

        assert Foo.name == attributes.manager_of_class(Foo)["name"]
        assert Foo.bars == attributes.manager_of_class(Foo)["bars"]
Beispiel #33
0
def get_class_bound_dispatcher(target_cls):
    """Python class-bound FSM dispatcher class."""
    try:
        out_val = FSM_EVENT_DISPATCHER_CACHE[target_cls]
    except KeyError:
        out_val = register_class(target_cls).dispatch
        FSM_EVENT_DISPATCHER_CACHE[target_cls] = out_val
    return out_val
    def test_inheritance(self):
        """tests that attributes are polymorphic"""

        for base in (object, MyBaseClass, MyClass):

            class Foo(base):
                pass

            class Bar(Foo):
                pass

            register_class(Foo)
            register_class(Bar)

            def func1(state, passive):
                return "this is the foo attr"

            def func2(state, passive):
                return "this is the bar attr"

            def func3(state, passive):
                return "this is the shared attr"

            attributes.register_attribute(Foo,
                                          "element",
                                          uselist=False,
                                          callable_=func1,
                                          useobject=True)
            attributes.register_attribute(Foo,
                                          "element2",
                                          uselist=False,
                                          callable_=func3,
                                          useobject=True)
            attributes.register_attribute(Bar,
                                          "element",
                                          uselist=False,
                                          callable_=func2,
                                          useobject=True)

            x = Foo()
            y = Bar()
            assert x.element == "this is the foo attr"
            assert y.element == "this is the bar attr", y.element
            assert x.element2 == "this is the shared attr"
            assert y.element2 == "this is the shared attr"
    def test_deferred(self):
        for base in (object, MyBaseClass, MyClass):
            class Foo(base):
                pass

            data = {'a': 'this is a', 'b': 12}

            def loader(state, keys):
                for k in keys:
                    state.dict[k] = data[k]
                return attributes.ATTR_WAS_SET

            manager = register_class(Foo)
            manager.deferred_scalar_loader = loader
            attributes.register_attribute(
                Foo, 'a', uselist=False, useobject=False)
            attributes.register_attribute(
                Foo, 'b', uselist=False, useobject=False)

            if base is object:
                assert Foo not in \
                    instrumentation._instrumentation_factory._state_finders
            else:
                assert Foo in \
                    instrumentation._instrumentation_factory._state_finders

            f = Foo()
            attributes.instance_state(f)._expire(
                attributes.instance_dict(f), set())
            eq_(f.a, "this is a")
            eq_(f.b, 12)

            f.a = "this is some new a"
            attributes.instance_state(f)._expire(
                attributes.instance_dict(f), set())
            eq_(f.a, "this is a")
            eq_(f.b, 12)

            attributes.instance_state(f)._expire(
                attributes.instance_dict(f), set())
            f.a = "this is another new a"
            eq_(f.a, "this is another new a")
            eq_(f.b, 12)

            attributes.instance_state(f)._expire(
                attributes.instance_dict(f), set())
            eq_(f.a, "this is a")
            eq_(f.b, 12)

            del f.a
            eq_(f.a, None)
            eq_(f.b, 12)

            attributes.instance_state(f)._commit_all(
                attributes.instance_dict(f))
            eq_(f.a, None)
            eq_(f.b, 12)
Beispiel #36
0
    def test_register_reserved_attribute(self):
        class T:
            pass

        instrumentation.register_class(T)
        manager = instrumentation.manager_of_class(T)

        sa = instrumentation.ClassManager.STATE_ATTR
        ma = instrumentation.ClassManager.MANAGER_ATTR

        def fails(method, attr):
            return assert_raises(KeyError, getattr(manager, method), attr,
                                 property())

        fails("install_member", sa)
        fails("install_member", ma)
        fails("install_descriptor", sa)
        fails("install_descriptor", ma)
Beispiel #37
0
    def test_single_down(self):
        class A:
            pass

        register_class(A)

        def mgr_factory(cls):
            return instrumentation.ClassManager(cls)

        class B(A):
            __sa_instrumentation_manager__ = staticmethod(mgr_factory)

        assert_raises_message(
            TypeError,
            "multiple instrumentation implementations",
            register_class,
            B,
        )
    def test_alternate_finders(self):
        """Ensure the generic finder front-end deals with edge cases."""

        class Unknown(object): pass
        class Known(MyBaseClass): pass

        instrumentation.register_class(Known)
        k, u = Known(), Unknown()

        assert instrumentation.manager_of_class(Unknown) is None
        assert instrumentation.manager_of_class(Known) is not None
        assert instrumentation.manager_of_class(None) is None

        assert attributes.instance_state(k) is not None
        assert_raises((AttributeError, KeyError),
                          attributes.instance_state, u)
        assert_raises((AttributeError, KeyError),
                          attributes.instance_state, None)
    def test_basic(self):
        import pickle

        global A
        class A(object):
            pass

        def canary(instance): assert False

        try:
            instrumentation.register_class(A)
            manager = instrumentation.manager_of_class(A)
            event.listen(manager, 'load', canary)

            a = A()
            p_a = pickle.dumps(a)
            re_a = pickle.loads(p_a)
        finally:
            del A
    def test_basic(self):
        import pickle

        global A
        class A(object):
            pass

        def canary(instance): assert False

        try:
            instrumentation.register_class(A)
            manager = instrumentation.manager_of_class(A)
            event.listen(manager, 'load', canary)

            a = A()
            p_a = pickle.dumps(a)
            re_a = pickle.loads(p_a)
        finally:
            del A
    def test_alternate_finders(self):
        """Ensure the generic finder front-end deals with edge cases."""
        class Unknown(object):
            pass

        class Known(MyBaseClass):
            pass

        register_class(Known)
        k, u = Known(), Unknown()

        assert instrumentation.manager_of_class(Unknown) is None
        assert instrumentation.manager_of_class(Known) is not None
        assert instrumentation.manager_of_class(None) is None

        assert attributes.instance_state(k) is not None
        assert_raises((AttributeError, KeyError), attributes.instance_state, u)
        assert_raises((AttributeError, KeyError), attributes.instance_state,
                      None)
Beispiel #42
0
    def test_diamond_b2(self):
        mgr_factory = lambda cls: instrumentation.ClassManager(cls)

        class A(object):
            pass

        class B1(A):
            pass

        class B2(A):
            __sa_instrumentation_manager__ = staticmethod(mgr_factory)

        class C(object):
            pass

        register_class(B2)
        assert_raises_message(TypeError,
                              "multiple instrumentation implementations",
                              register_class, B1)
Beispiel #43
0
    def __init__(self, registry, cls_):
        self.cls = cls_
        self.classname = cls_.__name__
        self.properties = util.OrderedDict()
        self.declared_attr_reg = {}

        instrumentation.register_class(
            self.cls,
            finalize=False,
            registry=registry,
            declarative_scan=self,
            init_method=registry.constructor,
        )

        event.listen(
            cls_,
            "class_uninstrument",
            registry._dispose_declarative_artifacts,
        )
    def test_diamond_c_b(self):
        def mgr_factory(cls): return instrumentation.ClassManager(cls)

        class A(object):
            pass

        class B1(A):
            pass

        class B2(A):
            __sa_instrumentation_manager__ = staticmethod(mgr_factory)

        class C(object):
            pass

        register_class(C)

        assert_raises_message(
            TypeError, "multiple instrumentation implementations",
            register_class, B1)
Beispiel #45
0
    def __init__(self, registry, cls_, mapper_kw):
        self.cls = util.assert_arg_type(cls_, type, "cls_")
        self.classname = cls_.__name__
        self.properties = util.OrderedDict()
        self.declared_attr_reg = {}

        if not mapper_kw.get("non_primary", False):
            instrumentation.register_class(
                self.cls,
                finalize=False,
                registry=registry,
                declarative_scan=self,
                init_method=registry.constructor,
            )
        else:
            manager = attributes.manager_of_class(self.cls)
            if not manager or not manager.is_mapped:
                raise exc.InvalidRequestError(
                    "Class %s has no primary mapper configured.  Configure "
                    "a primary mapper first before setting up a non primary "
                    "Mapper." % self.cls)
    def test_basic(self):
        for base in (object, MyBaseClass, MyClass):

            class User(base):
                pass

            register_class(User)
            attributes.register_attribute(User,
                                          "user_id",
                                          uselist=False,
                                          useobject=False)
            attributes.register_attribute(User,
                                          "user_name",
                                          uselist=False,
                                          useobject=False)
            attributes.register_attribute(User,
                                          "email_address",
                                          uselist=False,
                                          useobject=False)

            u = User()
            u.user_id = 7
            u.user_name = "john"
            u.email_address = "*****@*****.**"

            eq_(u.user_id, 7)
            eq_(u.user_name, "john")
            eq_(u.email_address, "*****@*****.**")
            attributes.instance_state(u)._commit_all(
                attributes.instance_dict(u))
            eq_(u.user_id, 7)
            eq_(u.user_name, "john")
            eq_(u.email_address, "*****@*****.**")

            u.user_name = "heythere"
            u.email_address = "*****@*****.**"
            eq_(u.user_id, 7)
            eq_(u.user_name, "heythere")
            eq_(u.email_address, "*****@*****.**")
    def test_uninstrument(self):
        class A(object):
            pass

        manager = instrumentation.register_class(A)
        attributes.register_attribute(A, "x", uselist=False, useobject=False)

        assert instrumentation.manager_of_class(A) is manager
        instrumentation.unregister_class(A)
        assert instrumentation.manager_of_class(A) is None
        assert not hasattr(A, "x")

        assert A.__init__ == object.__init__
    def test_basic(self):
        for base in (object, MyBaseClass, MyClass):
            class User(base):
                pass

            instrumentation.register_class(User)
            attributes.register_attribute(User, 'user_id', uselist = False, useobject=False)
            attributes.register_attribute(User, 'user_name', uselist = False, useobject=False)
            attributes.register_attribute(User, 'email_address', uselist = False, useobject=False)

            u = User()
            u.user_id = 7
            u.user_name = 'john'
            u.email_address = '*****@*****.**'

            self.assert_(u.user_id == 7 and u.user_name == 'john' and u.email_address == '*****@*****.**')
            attributes.instance_state(u).commit_all(attributes.instance_dict(u))
            self.assert_(u.user_id == 7 and u.user_name == 'john' and u.email_address == '*****@*****.**')

            u.user_name = 'heythere'
            u.email_address = '*****@*****.**'
            self.assert_(u.user_id == 7 and u.user_name == 'heythere' and u.email_address == '*****@*****.**')
    def test_history(self):
        for base in (object, MyBaseClass, MyClass):
            class Foo(base):
                pass
            class Bar(base):
                pass

            instrumentation.register_class(Foo)
            instrumentation.register_class(Bar)
            attributes.register_attribute(Foo, "name", uselist=False, useobject=False)
            attributes.register_attribute(Foo, "bars", uselist=True, trackparent=True, useobject=True)
            attributes.register_attribute(Bar, "name", uselist=False, useobject=False)


            f1 = Foo()
            f1.name = 'f1'

            eq_(attributes.get_state_history(attributes.instance_state(f1), 'name'), (['f1'], (), ()))

            b1 = Bar()
            b1.name = 'b1'
            f1.bars.append(b1)
            eq_(attributes.get_state_history(attributes.instance_state(f1), 'bars'), ([b1], [], []))

            attributes.instance_state(f1).commit_all(attributes.instance_dict(f1))
            attributes.instance_state(b1).commit_all(attributes.instance_dict(b1))

            eq_(attributes.get_state_history(attributes.instance_state(f1), 'name'), ((), ['f1'], ()))
            eq_(attributes.get_state_history(attributes.instance_state(f1), 'bars'), ((), [b1], ()))

            f1.name = 'f1mod'
            b2 = Bar()
            b2.name = 'b2'
            f1.bars.append(b2)
            eq_(attributes.get_state_history(attributes.instance_state(f1), 'name'), (['f1mod'], (), ['f1']))
            eq_(attributes.get_state_history(attributes.instance_state(f1), 'bars'), ([b2], [b1], []))
            f1.bars.remove(b1)
            eq_(attributes.get_state_history(attributes.instance_state(f1), 'bars'), ([b2], [], [b1]))
Beispiel #50
0
    def test_diamond_b2(self):
        def mgr_factory(cls):
            return instrumentation.ClassManager(cls)

        class A:
            pass

        class B1(A):
            pass

        class B2(A):
            __sa_instrumentation_manager__ = staticmethod(mgr_factory)

        class C:
            pass

        register_class(B2)
        assert_raises_message(
            TypeError,
            "multiple instrumentation implementations",
            register_class,
            B1,
        )
Beispiel #51
0
    def test_uninstrument(self):
        class A(object):pass

        manager = instrumentation.register_class(A)
        attributes.register_attribute(A, 'x', uselist=False, useobject=False)

        assert instrumentation.manager_of_class(A) is manager
        instrumentation.unregister_class(A)
        assert instrumentation.manager_of_class(A) is None
        assert not hasattr(A, 'x')

        # I prefer 'is' here but on pypy
        # it seems only == works
        assert A.__init__ == object.__init__
    def test_basic(self):
        for base in (object, MyBaseClass, MyClass):

            class User(base):
                pass

            register_class(User)
            attributes.register_attribute(User,
                                          'user_id',
                                          uselist=False,
                                          useobject=False)
            attributes.register_attribute(User,
                                          'user_name',
                                          uselist=False,
                                          useobject=False)
            attributes.register_attribute(User,
                                          'email_address',
                                          uselist=False,
                                          useobject=False)

            u = User()
            u.user_id = 7
            u.user_name = 'john'
            u.email_address = '*****@*****.**'

            self.assert_(u.user_id == 7 and u.user_name == 'john'
                         and u.email_address == '*****@*****.**')
            attributes.instance_state(u)._commit_all(
                attributes.instance_dict(u))
            self.assert_(u.user_id == 7 and u.user_name == 'john'
                         and u.email_address == '*****@*****.**')

            u.user_name = 'heythere'
            u.email_address = '*****@*****.**'
            self.assert_(u.user_id == 7 and u.user_name == 'heythere'
                         and u.email_address == '*****@*****.**')
Beispiel #53
0
    def test_uninstrument(self):
        class A(object):
            pass

        manager = instrumentation.register_class(A)
        attributes.register_attribute(A, 'x', uselist=False, useobject=False)

        assert instrumentation.manager_of_class(A) is manager
        instrumentation.unregister_class(A)
        assert instrumentation.manager_of_class(A) is None
        assert not hasattr(A, 'x')

        # I prefer 'is' here but on pypy
        # it seems only == works
        assert A.__init__ == object.__init__
    def test_none(self):
        class A(object): pass
        instrumentation.register_class(A)

        mgr_factory = lambda cls: instrumentation.ClassManager(cls)
        class B(object):
            __sa_instrumentation_manager__ = staticmethod(mgr_factory)
        instrumentation.register_class(B)

        class C(object):
            __sa_instrumentation_manager__ = instrumentation.ClassManager
        instrumentation.register_class(C)
    def test_none(self):
        class A(object): pass
        instrumentation.register_class(A)

        mgr_factory = lambda cls: instrumentation.ClassManager(cls)
        class B(object):
            __sa_instrumentation_manager__ = staticmethod(mgr_factory)
        instrumentation.register_class(B)

        class C(object):
            __sa_instrumentation_manager__ = instrumentation.ClassManager
        instrumentation.register_class(C)
    def test_none(self):
        class A(object):
            pass
        register_class(A)

        def mgr_factory(cls): return instrumentation.ClassManager(cls)

        class B(object):
            __sa_instrumentation_manager__ = staticmethod(mgr_factory)
        register_class(B)

        class C(object):
            __sa_instrumentation_manager__ = instrumentation.ClassManager
        register_class(C)
    def test_none(self):
        class A(object):
            pass

        register_class(A)

        def mgr_factory(cls):
            return instrumentation.ClassManager(cls)

        class B(object):
            __sa_instrumentation_manager__ = staticmethod(mgr_factory)

        register_class(B)

        class C(object):
            __sa_instrumentation_manager__ = instrumentation.ClassManager

        register_class(C)
    def test_history(self):
        for base in (object, MyBaseClass, MyClass):

            class Foo(base):
                pass

            class Bar(base):
                pass

            register_class(Foo)
            register_class(Bar)
            attributes.register_attribute(Foo,
                                          "name",
                                          uselist=False,
                                          useobject=False)
            attributes.register_attribute(Foo,
                                          "bars",
                                          uselist=True,
                                          trackparent=True,
                                          useobject=True)
            attributes.register_attribute(Bar,
                                          "name",
                                          uselist=False,
                                          useobject=False)

            f1 = Foo()
            f1.name = "f1"

            eq_(
                attributes.get_state_history(attributes.instance_state(f1),
                                             "name"),
                (["f1"], (), ()),
            )

            b1 = Bar()
            b1.name = "b1"
            f1.bars.append(b1)
            eq_(
                attributes.get_state_history(attributes.instance_state(f1),
                                             "bars"),
                ([b1], [], []),
            )

            attributes.instance_state(f1)._commit_all(
                attributes.instance_dict(f1))
            attributes.instance_state(b1)._commit_all(
                attributes.instance_dict(b1))

            eq_(
                attributes.get_state_history(attributes.instance_state(f1),
                                             "name"),
                ((), ["f1"], ()),
            )
            eq_(
                attributes.get_state_history(attributes.instance_state(f1),
                                             "bars"),
                ((), [b1], ()),
            )

            f1.name = "f1mod"
            b2 = Bar()
            b2.name = "b2"
            f1.bars.append(b2)
            eq_(
                attributes.get_state_history(attributes.instance_state(f1),
                                             "name"),
                (["f1mod"], (), ["f1"]),
            )
            eq_(
                attributes.get_state_history(attributes.instance_state(f1),
                                             "bars"),
                ([b2], [b1], []),
            )
            f1.bars.remove(b1)
            eq_(
                attributes.get_state_history(attributes.instance_state(f1),
                                             "bars"),
                ([b2], [], [b1]),
            )
    def test_nativeext_interfaceexact(self):
        class A(object):
            __sa_instrumentation_manager__ = sa.orm.interfaces.InstrumentationManager

        instrumentation.register_class(A)
        ne_(type(instrumentation.manager_of_class(A)), instrumentation.ClassManager)
    def test_standard(self):
        class A(object): pass

        instrumentation.register_class(A)

        eq_(type(instrumentation.manager_of_class(A)), instrumentation.ClassManager)