def test_unhashable_types(): import System class OldUserClass: def foo(): pass import _weakref from _collections import deque AssertError(TypeError, hash, slice(None)) hashcode = System.Object.GetHashCode(slice(None)) # weakproxy AssertError(TypeError, hash, _weakref.proxy(OldUserClass())) hashcode = System.Object.GetHashCode(_weakref.proxy(OldUserClass())) # weakcallableproxy AssertError(TypeError, hash, _weakref.proxy(OldUserClass().foo)) hashcode = System.Object.GetHashCode(_weakref.proxy(OldUserClass().foo)) AssertError(TypeError, hash, deque()) hashcode = System.Object.GetHashCode(deque()) AssertError(TypeError, hash, dict()) hashcode = System.Object.GetHashCode(dict()) AssertError(TypeError, hash, list()) hashcode = System.Object.GetHashCode(list()) AssertError(TypeError, hash, set()) hashcode = System.Object.GetHashCode(set())
def test_unicode(self): import _weakref class C(object): def __str__(self): return "string" def __unicode__(self): return u"unicode" instance = C() assert "__unicode__" in dir(_weakref.proxy(instance)) assert str(_weakref.proxy(instance)) == "string" assert unicode(_weakref.proxy(instance)) == u"unicode"
def test_inplace_add(self): import _weakref class A(object): def __add__(self, other): return other a1 = A() a2 = A() p1 = _weakref.proxy(a1) p2 = _weakref.proxy(a2) p1 += p2 assert p1 is a2
def test_add(self): import _weakref class A(object): def __add__(self, other): return other a1 = A() a2 = A() p1 = _weakref.proxy(a1) p2 = _weakref.proxy(a2) a3 = p1 + p2 assert a3 is a2
def helper_func(): class C: def __eq__(self, *args, **kwargs): return True a = C() Assert(C()==3) x = _weakref.proxy(a) y = _weakref.proxy(a) AreEqual(x, y) keep_alive(a) #Just to keep 'a' alive up to this point. return x, y
def test_callable_proxy(self): import _weakref, gc class A(object): def __call__(self): global_a.x = 1 global_a = A() global_a.x = 41 A_ = _weakref.proxy(A) a = A_() assert isinstance(a, A) a_ = _weakref.proxy(a) a_() assert global_a.x == 1
def test_dont_hash(self): import _weakref, gc class A(object): pass a = A() p = _weakref.proxy(a) raises(TypeError, hash, p)
def get_dead_weakref(): class C: pass a = C() x = _weakref.proxy(a) del(a) return x
def test_proxy_to_dead_object(self): import _weakref, gc class A(object): pass p = _weakref.proxy(A()) gc.collect() raises(ReferenceError, "p + 1")
def run_test(): a = cls() b = _weakref.proxy(a) self.assertEqual(dir(a), dir(b)) del(a) return b
def test_setattr(self): import _weakref class A(object): def __setitem__(self, key, value): self.setkey = key self.setvalue = value a1 = A() a2 = A() p1 = _weakref.proxy(a1) p2 = _weakref.proxy(a2) p1[p2] = 42 assert a1.setkey is p2 assert a1.setvalue == 42 # p1[42] = p2 assert a1.setkey == 42 assert a1.setvalue is p2
def test_callable_proxy_type(self): import _weakref, gc class Callable(object): def __call__(self, x): pass o = Callable() ref1 = _weakref.proxy(o) assert type(ref1) is _weakref.CallableProxyType
def handleProjectChange(self, project): self.project_tree.clear() self.segid2treenode.clear() # Create Project Tree Node projecttreeitem = QtGui.QTreeWidgetItem([project.name]) projecttreeitem._pydat = proxy(project.segmentset) self.segid2treenode[project.segmentset.id] = projecttreeitem self.project_tree.addTopLevelItem(projecttreeitem)
def run_test(): a = cls() b = _weakref.proxy(a) AreEqual(dir(a), dir(b)) del(a) return b
def __getstate__(self): attrs = self.__dict__ try: return attrs["_p_key"] except KeyError: conn = _getframe(1).f_locals["self"] attrs["_p_key"] = conn << self attrs["_p_conn"] = proxy(conn) return attrs["_p_key"]
def __getstate__(self): node = self._p_root try: return node._p_key except AttributeError: conn = _getframe(1).f_locals["self"] node._p_key = conn << node node._p_conn = proxy(conn) return node._p_key
def __init__(self, sock, addr): self.socket = sock self.address = addr self.pid = sock.fileno() self._rbuf = self._wbuf = '' self.read_channel = channel() self.write_channel = channel() self.writing = self.reading = None socket_map[self.pid] = proxy(self)
def test_simple(self): import _weakref, gc class A(object): def __init__(self, x): self.x = x a = A(1) p = _weakref.proxy(a) assert p.x == 1 assert str(p) == str(a) raises(TypeError, p)
def test_proxy_with_callback(self): import _weakref, gc class A(object): pass a2 = A() def callback(proxy): a2.seen = proxy p = _weakref.proxy(A(), callback) gc.collect() raises(ReferenceError, "p + 1") assert a2.seen is p
def test_special_methods(): for cls in [NonCallableClass, CallableClass]: # calling repr should give us weakproxy's repr, # calling __repr__ should give us the underlying objects # repr a = cls() b = _weakref.proxy(a) Assert(repr(b).startswith('<weakproxy at')) AreEqual(repr(a), b.__repr__()) keep_alive(a) # calling a special method should work class strable(object): def __str__(self): return 'abc' a = strable() b = _weakref.proxy(a) AreEqual(str(b), 'abc') keep_alive(a)
def ApplyAttributes(self, attributes): Container.ApplyAttributes(self, attributes) self.sr.maincontainer = Container(parent=self, name='maincontainer', padding=(1, 1, 1, 1), clipChildren=True) self.sr.clipper = Container(name='__clipper', align=uiconst.TOALL, parent=self.sr.maincontainer, clipChildren=True) self.sr.clipper._OnSizeChange_NoBlock = self.OnClipperResize self.sr.content = Container(name='__content', align=uiconst.RELATIVE, parent=self.sr.clipper, state=uiconst.UI_NORMAL) self.loadingWheel = None self.Release() self.multiSelect = attributes.get('multiSelect', self.default_multiSelect) self.stickToBottom = attributes.get('stickToBottom', self.default_stickToBottom) self.autoPurgeHiddenEntries = attributes.get('autoPurgeHiddenEntries', self.default_autoPurgeHiddenEntries) self.sr.selfProxy = _weakref.proxy(self) self.Prepare_() self._mouseHoverCookie = uicore.uilib.RegisterForTriuiEvents(uiconst.UI_MOUSEHOVER, self.OnGlobalMouseHover)
def ApplyAttributes(self, attributes): uicls.SE_BaseClassCore.ApplyAttributes(self, attributes) parser.ParserBase.Prepare(self) self.sr.selfProxy = _weakref.proxy(self) self.htmldebug = 0 self.xmargin = 0 self.sr.entries = [] self.sr.overlays = [] self.sr.overlays_content = uicls.Container(name='overlays', parent=self, padding=(1, 1, 1, 1)) self.sr.content = uicls.Container(name='content', parent=self) self.sr.underlays_content = uicls.Container(name='underlays_content', parent=self, padding=(1, 1, 1, 1)) self.sr.background = uicls.Container(name='background', parent=self) self.sr.backgroundColorContainer = uicls.Container(name='backgroundColorContainer', parent=self) browser = uiutil.GetBrowser(self) self.sr.browser = browser
def handleSegmentCreated(self, segment): #print '>>TREE.handleSegmentCreated:',segment self.doNotSetActiveObject = True segindex = segment.parent.getChildIndex(segment) parent_tree_node = self.segid2treenode[segment.parent.id] #parent_tree_node = self.project_tree.topLevelItem(0) segtreeitem = QtGui.QTreeWidgetItem([segment.name]) self.segid2treenode[segment.id] = segtreeitem segtreeitem._pydat = proxy(segment) parent_tree_node.insertChild(segindex, segtreeitem) #for i in self.project_tree.selectedItems(): # i.setSelected(False) #segtreeitem.setSelected(True) self.project_tree.setCurrentItem(segtreeitem) #print '<< TREE.handleSegmentCreated' self.doNotSetActiveObject = False
def Startup(self, browser, *args): self.browser = _weakref.proxy(browser) self.taken = [] self.tableloaded = 0 self.name = 'table' self.sr.cells = None attrs = self.data.attrs self.charset = attrs.Get('charset', 'cp1252') self.stack = self.browser.attrStack[-1].copy() if not self.tableloaded: self.RefreshSizes() if self.destroyed: return s = self.stack self.AddBackground(self, s) self.tableloaded = 1
def test_type_call(): def get_dead_weakref(): class C: pass a = C() x = _weakref.proxy(a) del(a) return x wr = get_dead_weakref() # Uncomment the next line after fixing merlin#243506 # type(wr).__add__.__get__(wr, None) # no exception try: type(wr).__add__.__get__(wr, None)() # object is dead, should throw except: pass else: AssertUnreachable() # kwarg call class C: def __add__(self, other): return "abc" + other a = C() x = _weakref.proxy(a) if is_cli: # cli accepts kw-args everywhere res = type(x).__add__.__get__(x, None)(other = 'xyz') AreEqual(res, "abcxyz") res = type(x).__add__.__get__(x, None)('xyz') # test success-case without keyword args AreEqual(res, "abcxyz") # calling non-existent method should raise attribute error try: type(x).__sub__.__get(x, None)('abc') except AttributeError: pass else: AssertUnreachable() if is_cli: # cli accepts kw-args everywhere # calling non-existent method should raise attribute error (kw-arg version) try: type(x).__sub__.__get(x, None)(other='abc') except AttributeError: pass else: AssertUnreachable()
def handler(httpfile): env = httpfile.environ env['wsgi.input'] = proxy(httpfile) def start_response(status, headers, exc_info=None): if exc_info: try: if httpfile.headers_sent: raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None elif httpfile.headers_sent: raise AssertionError('headers already set') httpfile._start_response(status, headers) return httpfile.sendall for data in app(env, start_response): if data: httpfile.sendall(data, 15.+(len(data)>>10)) httpfile.close(15.)
def test_equals(): global called class C: for method, op in [('__eq__', '=='), ('__gt__', '>'), ('__lt__', '<'), ('__ge__', '>='), ('__le__', '<='), ('__ne__', '!=')]: exec """ def %s(self, *args, **kwargs): global called called = '%s' return True """ % (method, op) a = C() x = _weakref.proxy(a) for op in ('==', '>', '<', '>=', '<=', '!='): AreEqual(eval('a ' + op + ' 3'), True); AreEqual(called, op); called = None if op == '==' or op == '!=': AreEqual(eval('x ' + op + ' 3'), op == '!='); AreEqual(called, None) AreEqual(eval('3 ' + op + ' x'), op == '!='); AreEqual(called, None) else: res1, res2 = eval('x ' + op + ' 3'), eval('3 ' + op + ' x') AreEqual(called, None) Assert((res1 == True and res2 == False) or (res1 == False and res2 == True))
def BindInterface(self, interface): from _weakref import proxy self.interface = proxy(interface)
def __LoadScript(self): try: pyScrLoader = ui.PythonScriptLoader() pyScrLoader.LoadScriptFile(self, "uiscript/GuildStorageAdmin.py") except: import exception exception.Abort("test.__LoadScript.LoadObject") try: self.board = self.GetChild("Board") self.titleBar = self.GetChild("TitleBar") self.AddMemberButton = self.GetChild("GS_AddMember") self.MemberInput = self.GetChild("GS_MemberInputLine") self.scrollbar = self.GetChild("scrollbar") self.scrollbar.SetScrollEvent(ui.__mem_func__(self.__OnScroll)) self.MemberPage = {} for i in range(12): event = lambda argSelf=proxy( self), argIndex=i, argAuthority=0: apply( argSelf.OnCheckAuthority, (argIndex, argAuthority)) self.MemberPage['stock' + str(i)] = (CheckBox( self.board, 130, 60 + (20 * i), event)) event = lambda argSelf=proxy( self), argIndex=i, argAuthority=1: apply( argSelf.OnCheckAuthority, (argIndex, argAuthority)) self.MemberPage['transfer' + str(i)] = (CheckBox( self.board, 190, 60 + (20 * i), event)) event = lambda argSelf=proxy( self), argIndex=i, argAuthority=2: apply( argSelf.OnCheckAuthority, (argIndex, argAuthority)) self.MemberPage['payin' + str(i)] = (CheckBox( self.board, 250, 60 + (20 * i), event)) event = lambda argSelf=proxy( self), argIndex=i, argAuthority=3: apply( argSelf.OnCheckAuthority, (argIndex, argAuthority)) self.MemberPage['payout' + str(i)] = (CheckBox( self.board, 310, 60 + (20 * i), event)) self.MemberPage['membername_slotbar' + str(i)] = ui.MakeSlotBar( self.board, 20, 61 + (20 * i), 100, 16) self.MemberPage['membername_text' + str(i)] = ui.MakeTextLine( self.MemberPage['membername_slotbar' + str(i)]) self.MemberPage['deleteBTN' + str(i)] = ui.MakeButton( self.board, 365, 61 + (20 * i), "loeschen", "d:/ymir work/ui/public/", "close_button_01.sub", "close_button_02.sub", "close_button_03.sub") self.MemberPage['deleteBTN' + str(i)].SetEvent( ui.__mem_func__(self.DeleteMember), i) except: import exception exception.Abort("test.__LoadScript.BindObject") self.AddMemberButton.SetEvent(self.AddMember) self.titleBar.SetCloseEvent(ui.__mem_func__(self.Close)) self.isLoaded = TRUE
def __init__(self, rowset, iterator): self.rowset = _weakref.proxy(rowset) self.iterator = iterator
def test_slot_repr(): class C: pass a = C() x = _weakref.proxy(a) AreEqual(repr(type(x).__add__), "<slot wrapper '__add__' of 'weakproxy' objects>")
def __setstate__(self, key): self._p_pnt = proxy(_getframe(2).f_locals['self']) self._p_root = BNode(key, proxy(_getframe(1).f_locals['self']))
from _weakref import ref, proxy from testutils import assert_raises class X: pass a = X() b = ref(a) assert callable(b) assert b() is a class G: def __init__(self, h): self.h = h g = G(5) p = proxy(g) assert p.h == 5 del g assert_raises(ReferenceError, lambda: p.h)
def __init__(self, cls, obj, func): self.cls = cls self.obj = _weakref.proxy(obj) self.func = _weakref.proxy(func)
def __init__(self, handler): self.__handler = _weakref.proxy(handler)
def SetDragonSoulRefineWindow(self, wndDragonSoulRefine): if app.ENABLE_DRAGON_SOUL_SYSTEM: from _weakref import proxy self.wndDragonSoulRefine = proxy(wndDragonSoulRefine)
def generate_nested_column(txnctx, column_name, path, schema, mode): """Generate instance ready structures for read-only checkouts Parameters ---------- txnctx : ColumnTxn transaction context object used to access commit ref info on disk column_name : str name of the column that the reader constructors are being generated for path : Path path to the repository on disk schema : ColumnDefinitionTypes schema definition of the column. mode: str read-only or write-enabled mode. one of ['a', 'r']. Returns ------- :class:`~.nested.NestedSampleReader` Top level column accessor classes fully initialized for requested state. Initailized structures defining and initializing access to the subsample data on disk. """ specs, bes = _nested_load_sample_keys_and_specs(column_name, txnctx) if not all([BACKEND_IS_LOCAL_MAP[be] for be in bes]): _warn_remote(column_name) if mode == 'a': bes.add(schema.backend) fhand = open_file_handles(backends=bes, path=path, mode=mode, schema=schema) samples = {} schema_proxy = proxy(schema) fhand['enter_count'] = 0 if mode == 'r': for samp, subspecs in specs.items(): samples[samp] = FlatSubsampleReader(columnname=column_name, samplen=samp, be_handles=fhand, specs=subspecs, mode='r') res = NestedSampleReader(columnname=column_name, samples=samples, backend_handles=fhand, repo_path=path, mode='r', schema=schema) elif mode == 'a': fhand = ObjectProxy(fhand) fhand_proxy = proxy(fhand) for samp, subspecs in specs.items(): samples[samp] = FlatSubsampleWriter(schema=schema_proxy, aset_ctx=proxy(txnctx), repo_path=path, columnname=column_name, samplen=samp, be_handles=fhand_proxy, specs=subspecs, mode='a') res = NestedSampleWriter(aset_ctx=txnctx, columnname=column_name, samples=samples, backend_handles=fhand, schema=schema, repo_path=path, mode='a') else: raise ValueError(f'mode {mode} is not valid.') return res
def test_weakref(): """weakrefs to struct objects are supported""" x = _struct.Struct('i') import _weakref AreEqual(_weakref.proxy(x).size, x.size)
def SetInven(self, wndInventory): from _weakref import proxy self.wndInventory = proxy(wndInventory)
def test_caching(self): import _weakref, gc class A(object): pass a = A() assert _weakref.proxy(a) is _weakref.proxy(a) assert _weakref.proxy(a) is _weakref.proxy(a, None)
def test(): assert (_weakref.ReferenceType is _weakref.ref) for _ in range(99): time.sleep(5) # Throttle to avoid a MemoryError try: _weakref._remove_dead_weakref(dct, 'obj') except NameError: pass obj = fclass() _weakref.getweakrefcount dct = {'obj': _weakref.ref(obj)} _weakref.getweakrefs(obj) _weakref.getweakrefs(dct['obj']) dct['prox'] = _weakref.proxy(ffunc, ffunc) dct['oprox'] = _weakref.proxy(obj, ffunc) q = _queue.SimpleQueue() lock = rnd.choice([_thread.allocate_lock, _thread.allocate])() def lock_thread(*a, **k): try: rnd.choice([lock.acquire_lock, lock.acquire])(blocking=fbool(), timeout=rnd.randint(-10, 10)) except ValueError: pass rnd.choice([lock.locked, lock.locked_lock])() ffunc(q) try: rnd.choice([lock.release_lock, lock.release])() except RuntimeError: pass try: with lock: ffunc(q) except RuntimeError: pass rnd.choice([lock.locked, lock.locked_lock])() l = _thread._set_sentinel() if fbool(): rnd.choice([_thread.exit_thread, _thread.exit])() rlock = _thread.RLock() def rlock_thread(*a, **k): rlock.acquire(fbool()) ffunc(q) rlock._is_owned() if fbool(): try: rlock._release_save() except RuntimeError: pass if fbool(): rlock._acquire_restore( (rnd.randint(-9999, 9999), rnd.randint(-9999, 9999))) try: rlock.release() except RuntimeError: pass try: with rlock: ffunc(q) except RuntimeError: pass rlock._is_owned() if fbool(): rnd.choice([_thread.exit_thread, _thread.exit])() for _ in range(99): repr(lock) repr(rlock) try: rnd.choice([_thread.start_new, _thread.start_new_thread ])(rnd.choice([lock_thread, rlock_thread]), (q, ) + ftup(), fdict()) except RuntimeError: pass try: _thread.stack_size(rnd.randint(-99999999, 99999999)) except (ValueError, OverflowError): pass ffunc(q) try: _thread.interrupt_main() except KeyboardInterrupt: pass
def test_weakref(self): """weakrefs to struct objects are supported""" x = _struct.Struct('i') import _weakref self.assertEqual(_weakref.proxy(x).size, x.size)
def __setstate__(self, key): attrs = self.__dict__ attrs['_p_key'] = key attrs['_p_conn'] = proxy(_getframe(1).f_locals['self']) del attrs['_p_data']
def AddListener(self, listener): if not self.__isclass(listener): raise RuntimeError('AddListener only accepts instances') self.__listeners[id(listener)] = _weakref.proxy(listener)
def __setstate__(self, key): self._p_key = key self._p_conn = proxy(_getframe(1).f_locals['self'])