本文整理汇总了Python中test.test_support.gc_collect函数的典型用法代码示例。如果您正苦于以下问题:Python gc_collect函数的具体用法?Python gc_collect怎么用?Python gc_collect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了gc_collect函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test___del__
def test___del__(self):
self.assertFalse(self.info_exists("varname"))
v = Variable(self.root, "sample string", "varname")
self.assertTrue(self.info_exists("varname"))
del v
gc_collect()
self.assertFalse(self.info_exists("varname"))
示例2: test_leak_fast_process_del_killed
def test_leak_fast_process_del_killed(self):
# Issue #12650: on Unix, if Popen.__del__() was called before the
# process exited, and the process got killed by a signal, it would never
# be removed from subprocess._active, which triggered a FD and memory
# leak.
# spawn a Popen, delete its reference and kill it
p = subprocess.Popen([sys.executable, "-c",
'import time;'
'time.sleep(3)'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
ident = id(p)
pid = p.pid
del p
test_support.gc_collect()
os.kill(pid, signal.SIGKILL)
# check that p is in the active processes list
self.assertIn(ident, [id(o) for o in subprocess._active])
# let some time for the process to exit, and create a new Popen: this
# should trigger the wait() of p
time.sleep(0.2)
with self.assertRaises(EnvironmentError) as c:
with subprocess.Popen(['nonexisting_i_hope'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE) as proc:
pass
# p should have been wait()ed on, and removed from the _active list
self.assertRaises(OSError, os.waitpid, pid, 0)
self.assertNotIn(ident, [id(o) for o in subprocess._active])
示例3: test__count
def test__count(self):
# Test the _count() function.
orig = thread._count()
mut = thread.allocate_lock()
mut.acquire()
started = []
def task():
started.append(None)
mut.acquire()
mut.release()
thread.start_new_thread(task, ())
while not started:
time.sleep(0.01)
self.assertEqual(thread._count(), orig + 1)
# Allow the task to finish.
mut.release()
# The only reliable way to be sure that the thread ended from the
# interpreter's point of view is to wait for the function object to be
# destroyed.
done = []
wr = weakref.ref(task, lambda _: done.append(None))
del task
while not done:
time.sleep(0.01)
test_support.gc_collect()
self.assertEqual(thread._count(), orig)
示例4: test_callbacks_on_callback
def test_callbacks_on_callback(self):
# Set up weakref callbacks *on* weakref callbacks.
alist = []
def safe_callback(ignore):
alist.append("safe_callback called")
class C(object):
def cb(self, ignore):
alist.append("cb called")
c, d = C(), C()
c.other = d
d.other = c
callback = c.cb
c.wr = weakref.ref(d, callback) # this won't trigger
d.wr = weakref.ref(callback, d.cb) # ditto
external_wr = weakref.ref(callback, safe_callback) # but this will
self.assertTrue(external_wr() is callback)
# The weakrefs attached to c and d should get cleared, so that
# C.cb is never called. But external_wr isn't part of the cyclic
# trash, and no cyclic trash is reachable from it, so safe_callback
# should get invoked when the bound method object callback (c.cb)
# -- which is itself a callback, and also part of the cyclic trash --
# gets reclaimed at the end of gc.
del callback, c, d, C
self.assertEqual(alist, []) # del isn't enough to clean up cycles
gc_collect()
self.assertEqual(alist, ["safe_callback called"])
self.assertEqual(external_wr(), None)
del alist[:]
gc_collect()
self.assertEqual(alist, [])
示例5: test_class_to_test_weakness
def test_class_to_test_weakness(self):
# regrtest for bug 1522, adapted from test code submitted by Matt Brinkley
# We wish to demonstrate that the proxy created by a Python class and
# its PyType are GC'd when no longer in use, and therefore that the
# Jython type system does not keep a PyType alive gratuitously. We do
# this by holding weak references, then checking they're dead.
# Get to steady state by creating >1 Dog and then GC-ing homeless ones.
battersea = []
for i in range(2):
battersea.extend(run_script(DOG, ('Dog', 'dog', 'breed')))
test_support.gc_collect()
# This is the steady-state, GC number of Dog objects alive after GC:
start_size = len(survivors(battersea)) # probably = 1
# Add more Dogs and GC the homeless ones again.
for i in range(5):
battersea.extend(run_script(DOG, ('Dog', 'dog', 'breed')))
test_support.gc_collect()
#print "\nDogs home =", battersea
#print "\nDogs alive =", survivors(battersea)
# Post-GC number of Dogs should be as before
self.assertEqual(start_size, len(survivors(battersea)))
示例6: test_many
def test_many(self):
# mktemp can choose many usable file names (stochastic)
extant = range(TEST_FILES)
for i in extant:
extant[i] = self.do_create(pre="aa")
del extant
test_support.gc_collect()
示例7: test_init
def test_init(self):
# Issue 3634
# <weakref to class>.__init__() doesn't check errors correctly
r = weakref.ref(Exception)
self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
# No exception should be raised here
gc_collect()
示例8: test_weakref
def test_weakref(self):
f = self.thetype(int, base=16)
p = proxy(f)
self.assertEqual(f.func, p.func)
f = None
test_support.gc_collect()
self.assertRaises(ReferenceError, getattr, p, 'func')
示例9: _test_close_open_io
def _test_close_open_io(self, io_func, nb_workers=5):
def worker():
funcs = itertools.cycle((
lambda: io_func(),
lambda: self._close_and_reopen_file(),
))
for f in funcs:
if not self.do_continue:
break
try:
f()
except (IOError, ValueError):
pass
self._create_file()
self._run_workers(worker, nb_workers)
# make sure that all files can be closed now
del self.all_files
gc_collect()
if test_support.verbose:
# Useful verbose statistics when tuning this test to take
# less time to run but still ensuring that its still useful.
#
# the percent of close calls that raised an error
percent = 100. - 100.*self.close_success_count/self.close_count
print self.close_count, ('%.4f ' % percent),
示例10: test_weak_keys
def test_weak_keys(self):
#
# This exercises d.copy(), d.items(), d[] = v, d[], del d[],
# len(d), in d.
#
dict, objects = self.make_weak_keyed_dict()
for o in objects:
self.assertTrue(weakref.getweakrefcount(o) == 1,
"wrong number of weak references to %r!" % o)
self.assertTrue(o.arg is dict[o],
"wrong object returned by weak dict!")
items1 = dict.items()
items2 = dict.copy().items()
self.assertTrue(set(items1) == set(items2),
"cloning of weak-keyed dictionary did not work!")
del items1, items2
self.assertTrue(len(dict) == self.COUNT)
del objects[0]
gc_collect()
self.assertTrue(len(dict) == (self.COUNT - 1),
"deleting object did not cause dictionary update")
del objects, o
gc_collect()
self.assertTrue(len(dict) == 0,
"deleting the keys did not clear the dictionary")
o = Object(42)
dict[o] = "What is the meaning of the universe?"
self.assertIn(o, dict)
self.assertNotIn(34, dict)
示例11: test_weakref
def test_weakref(self):
s = array.array(self.typecode, self.example)
p = proxy(s)
self.assertEqual(p.tostring(), s.tostring())
s = None
test_support.gc_collect()
self.assertRaises(ReferenceError, len, p)
示例12: tearDown
def tearDown(self):
test_support.gc_collect()
for name in self.files:
os.unlink(name)
for i in xrange(2):
if os.path.exists(test_support.TESTFN):
os.rmdir(test_support.TESTFN)
示例13: testTruncateOnWindows
def testTruncateOnWindows(self):
def bug801631():
# SF bug <http://www.python.org/sf/801631>
# "file.truncate fault on windows"
f = _FileIO(TESTFN, 'w')
f.write(bytes(range(11)))
f.close()
f = _FileIO(TESTFN,'r+')
data = f.read(5)
if data != bytes(range(5)):
self.fail("Read on file opened for update failed %r" % data)
if f.tell() != 5:
self.fail("File pos after read wrong %d" % f.tell())
f.truncate()
if f.tell() != 5:
self.fail("File pos after ftruncate wrong %d" % f.tell())
f.close()
size = os.path.getsize(TESTFN)
if size != 5:
self.fail("File size after ftruncate wrong %d" % size)
try:
bug801631()
finally:
gc_collect()
os.unlink(TESTFN)
示例14: check_gc_during_creation
def check_gc_during_creation(self, makeref):
if test_support.check_impl_detail():
import gc
thresholds = gc.get_threshold()
gc.set_threshold(1, 1, 1)
gc_collect()
class A:
pass
def callback(*args):
pass
referenced = A()
a = A()
a.a = a
a.wr = makeref(referenced)
try:
# now make sure the object and the ref get labeled as
# cyclic trash:
a = A()
weakref.ref(referenced, callback)
finally:
if test_support.check_impl_detail():
gc.set_threshold(*thresholds)
示例15: test_weakref
def test_weakref(self):
d = deque('gallahad')
p = weakref.proxy(d)
self.assertEqual(str(p), str(d))
d = None
test_support.gc_collect()
self.assertRaises(ReferenceError, str, p)