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_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) 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_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_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 __setstate__(self, state): from sqlalchemy.orm import instrumentation self.obj = weakref.ref(state['instance'], self._cleanup) self.class_ = state['instance'].__class__ self.manager = manager = instrumentation.manager_of_class(self.class_) if manager is None: raise orm_exc.UnmappedInstanceError( state['instance'], "Cannot deserialize object of type %r - no mapper() has" " been configured for this class within the current Python process!" % self.class_) elif manager.is_mapped and not manager.mapper.configured: mapperlib.configure_mappers() self.committed_state = state.get('committed_state', {}) self.pending = state.get('pending', {}) self.parents = state.get('parents', {}) self.modified = state.get('modified', False) self.expired = state.get('expired', False) self.callables = state.get('callables', {}) if self.modified: self._strong_obj = state['instance'] self.__dict__.update([ (k, state[k]) for k in ( 'key', 'load_options', 'mutable_dict' ) if k in state ]) if 'load_path' in state: self.load_path = interfaces.deserialize_path(state['load_path']) manager.dispatch.unpickle(self, state)
def test_standard(self): class A(object): pass register_class(A) eq_(type(manager_of_class(A)), instrumentation.ClassManager)
def _listen(cls, target, identifier, fn, active_history=False, raw=False, retval=False, propagate=False): if active_history: target.dispatch._active_history = True # TODO: for removal, need to package the identity # of the wrapper with the original function. if not raw or not retval: orig_fn = fn def wrap(target, value, *arg): if not raw: target = target.obj() if not retval: orig_fn(target, value, *arg) return value else: return orig_fn(target, value, *arg) fn = wrap event.Events._listen(target, identifier, fn, propagate) if propagate: from sqlalchemy.orm.instrumentation import manager_of_class manager = manager_of_class(target.class_) for mgr in manager.subclass_managers(True): event.Events._listen(mgr[target.key], identifier, fn, True)
def __setstate__(self, state): from sqlalchemy.orm import instrumentation self.obj = weakref.ref(state['instance'], self._cleanup) self.class_ = state['instance'].__class__ self.manager = manager = instrumentation.manager_of_class(self.class_) if manager is None: raise orm_exc.UnmappedInstanceError( state['instance'], "Cannot deserialize object of type %r - no mapper() has" " been configured for this class within the current Python process!" % self.class_) elif manager.is_mapped and not manager.mapper.configured: mapperlib.configure_mappers() self.committed_state = state.get('committed_state', {}) self.pending = state.get('pending', {}) self.parents = state.get('parents', {}) self.modified = state.get('modified', False) self.expired = state.get('expired', False) self.callables = state.get('callables', {}) if self.modified: self._strong_obj = state['instance'] self.__dict__.update([(k, state[k]) for k in ('key', 'load_options', 'mutable_dict') if k in state]) if 'load_path' in state: self.load_path = interfaces.deserialize_path(state['load_path']) manager.dispatch.unpickle(self, state)
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)
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_nativeext_interfaceexact(self): class A(object): __sa_instrumentation_manager__ = ( instrumentation.InstrumentationManager ) register_class(A) ne_(type(manager_of_class(A)), instrumentation.ClassManager)
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)
def __setstate__(self, state): if state["instance"] is not None: self.obj = weakref.ref(state["instance"]) self.class_ = state["class_"] self.load_options = state["load_options"] self.load_path = state["load_path"] self.manager = instrumentation.manager_of_class(self.class_) if "load_path" in state: self.load_path = interfaces.deserialize_path(state["load_path"])
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_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)
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(manager_of_class(A)), Mine)
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 __setstate__(self, state): from sqlalchemy.orm import instrumentation inst = state['instance'] if inst is not None: self.obj = weakref.ref(inst, self._cleanup) self.class_ = inst.__class__ else: # None being possible here generally new as of 0.7.4 # due to storage of state in "parents". "class_" # also new. self.obj = None self.class_ = state['class_'] self.manager = manager = instrumentation.manager_of_class(self.class_) if manager is None: raise orm_exc.UnmappedInstanceError( inst, "Cannot deserialize object of type %r - no mapper() has" " been configured for this class within the current Python process!" % self.class_) elif manager.is_mapped and not manager.mapper.configured: mapperlib.configure_mappers() self.committed_state = state.get('committed_state', {}) self.pending = state.get('pending', {}) self.parents = state.get('parents', {}) self.modified = state.get('modified', False) self.expired = state.get('expired', False) self.callables = state.get('callables', {}) if self.modified: self._strong_obj = inst self.__dict__.update([ (k, state[k]) for k in ( 'key', 'load_options', 'mutable_dict' ) if k in state ]) if 'load_path' in state: self.load_path = interfaces.deserialize_path(state['load_path']) # setup _sa_instance_state ahead of time so that # unpickle events can access the object normally. # see [ticket:2362] manager.setup_instance(inst, self) manager.dispatch.unpickle(self, state)
def _dive_for_classically_mapped_class(cls): # support issue #4321 # if we are within a base hierarchy, don't # search at all for classical mappings if hasattr(cls, "_decl_class_registry"): return None manager = instrumentation.manager_of_class(cls) if manager is not None: return cls else: for sup in cls.__bases__: mapper = _dive_for_classically_mapped_class(sup) if mapper is not None: return sup else: return None
def _accept_with(cls, target): from sqlalchemy.orm.instrumentation import ClassManager, manager_of_class from sqlalchemy.orm import Mapper, mapper if isinstance(target, ClassManager): return target elif isinstance(target, Mapper): return target.class_manager elif target is mapper: return ClassManager elif isinstance(target, type): if issubclass(target, Mapper): return ClassManager else: manager = manager_of_class(target) if manager: return manager return None
def _dive_for_classically_mapped_class(cls): # support issue #4321 # if we are within a base hierarchy, don't # search at all for classical mappings if hasattr(cls, '_decl_class_registry'): return None manager = instrumentation.manager_of_class(cls) if manager is not None: return cls else: for sup in cls.__bases__: mapper = _dive_for_classically_mapped_class(sup) if mapper is not None: return sup else: return None
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)
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 __setstate__(self, state): from sqlalchemy.orm import instrumentation inst = state["instance"] if inst is not None: self.obj = weakref.ref(inst, self._cleanup) self.class_ = inst.__class__ else: # None being possible here generally new as of 0.7.4 # due to storage of state in "parents". "class_" # also new. self.obj = None self.class_ = state["class_"] self.manager = manager = instrumentation.manager_of_class(self.class_) if manager is None: raise orm_exc.UnmappedInstanceError( inst, "Cannot deserialize object of type %r - no mapper() has" " been configured for this class within the current Python process!" % self.class_, ) elif manager.is_mapped and not manager.mapper.configured: mapperlib.configure_mappers() self.committed_state = state.get("committed_state", {}) self.pending = state.get("pending", {}) self.parents = state.get("parents", {}) self.modified = state.get("modified", False) self.expired = state.get("expired", False) self.callables = state.get("callables", {}) if self.modified: self._strong_obj = inst self.__dict__.update([(k, state[k]) for k in ("key", "load_options", "mutable_dict") if k in state]) if "load_path" in state: self.load_path = interfaces.deserialize_path(state["load_path"]) manager.dispatch.unpickle(self, state)
def set_cls_attribute(self, attrname, value): manager = instrumentation.manager_of_class(self.cls) manager.install_member(attrname, value) return value