本文整理汇总了Python中test.support.gc_collect函数的典型用法代码示例。如果您正苦于以下问题:Python gc_collect函数的具体用法?Python gc_collect怎么用?Python gc_collect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了gc_collect函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_future_exception_never_retrieved
def check_future_exception_never_retrieved(self, debug):
last_ctx = None
def handler(loop, context):
nonlocal last_ctx
last_ctx = context
self.loop.set_debug(debug)
self.loop.set_exception_handler(handler)
def memory_error():
try:
raise MemoryError()
except BaseException as exc:
return exc
exc = memory_error()
future = self.create_future()
if debug:
source_traceback = future._source_traceback
future.set_exception(exc)
future = None
support.gc_collect()
test_utils.run_briefly(self.loop)
self.assertIsNotNone(last_ctx)
self.assertIs(last_ctx['exception'], exc)
self.assertEqual(last_ctx['message'],
'Future exception was never retrieved')
if debug:
tb = last_ctx['source_traceback']
self.assertEqual(tb[-2].name,
'check_future_exception_never_retrieved')
示例2: test_tb_logger_exception_unretrieved
def test_tb_logger_exception_unretrieved(self, m_log):
fut = asyncio.Future(loop=self.loop)
fut.set_exception(RuntimeError("boom"))
del fut
test_utils.run_briefly(self.loop)
support.gc_collect()
self.assertTrue(m_log.error.called)
示例3: cleanup_test_droppings
def cleanup_test_droppings(testname, verbose):
import shutil
# Try to clean up junk commonly left behind. While tests shouldn't leave
# any files or directories behind, when a test fails that can be tedious
# for it to arrange. The consequences can be especially nasty on Windows,
# since if a test leaves a file open, it cannot be deleted by name (while
# there's nothing we can do about that here either, we can display the
# name of the offending test, which is a real help).
for name in (support.TESTFN,
"db_home",
):
if not os.path.exists(name):
continue
# work around tests depending on refcounting files,
# but this doesn't work with respect to Windows
support.gc_collect()
if os.path.isdir(name):
kind, nuker = "directory", shutil.rmtree
elif os.path.isfile(name):
kind, nuker = "file", os.unlink
else:
raise SystemError("os.path says %r exists but is neither "
"directory nor file" % name)
if verbose:
print("%r left behind %s %r" % (testname, kind, name))
try:
nuker(name)
except Exception as msg:
print(("%r left behind %s %r and it couldn't be "
"removed: %s" % (testname, kind, name, msg)), file=sys.stderr)
示例4: test_widget_destroy
def test_widget_destroy(self):
# automatically created variable
x = ttk.LabeledScale()
var = x._variable._name
x.destroy()
gc_collect()
self.assertRaises(tkinter.TclError, x.tk.globalgetvar, var)
# manually created variable
myvar = tkinter.DoubleVar()
name = myvar._name
x = ttk.LabeledScale(variable=myvar)
x.destroy()
if x.tk.wantobjects():
self.assertEqual(x.tk.globalgetvar(name), myvar.get())
else:
self.assertEqual(float(x.tk.globalgetvar(name)), myvar.get())
del myvar
gc_collect()
self.assertRaises(tkinter.TclError, x.tk.globalgetvar, name)
# checking that the tracing callback is properly removed
myvar = tkinter.IntVar()
# LabeledScale will start tracing myvar
x = ttk.LabeledScale(variable=myvar)
x.destroy()
# Unless the tracing callback was removed, creating a new
# LabeledScale with the same var will cause an error now. This
# happens because the variable will be set to (possibly) a new
# value which causes the tracing callback to be called and then
# it tries calling instance attributes not yet defined.
ttk.LabeledScale(variable=myvar)
if hasattr(sys, 'last_type'):
self.assertNotEqual(sys.last_type, tkinter.TclError)
示例5: test_weakref
def test_weakref(self):
f = self.thetype(int, base=16)
p = proxy(f)
self.assertEqual(f.func, p.func)
f = None
support.gc_collect()
self.assertRaises(ReferenceError, getattr, p, "func")
示例6: 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
support.gc_collect()
self.assertFalse(self.info_exists("varname"))
示例7: test_weakref
def test_weakref(self):
m = ModuleType("foo")
wr = weakref.ref(m)
self.assertIs(wr(), m)
del m
gc_collect()
self.assertIs(wr(), None)
示例8: test_resource_warning
def test_resource_warning(self):
# Issue #11453
fd = os.open(support.TESTFN, os.O_RDONLY)
f = asyncore.file_wrapper(fd)
with support.check_warnings(('', ResourceWarning)):
f = None
support.gc_collect()
示例9: test_weakref
def test_weakref(self):
d = deque('gallahad')
p = weakref.proxy(d)
self.assertEqual(str(p), str(d))
d = None
support.gc_collect()
self.assertRaises(ReferenceError, str, p)
示例10: check_future_exception_never_retrieved
def check_future_exception_never_retrieved(self, debug, m_log):
self.loop.set_debug(debug)
def memory_error():
try:
raise MemoryError()
except BaseException as exc:
return exc
exc = memory_error()
future = self._new_future(loop=self.loop)
future.set_exception(exc)
future = None
test_utils.run_briefly(self.loop)
support.gc_collect()
if sys.version_info >= (3, 4):
regex = r'^Future exception was never retrieved\n'
exc_info = (type(exc), exc, exc.__traceback__)
m_log.error.assert_called_once_with(mock.ANY, exc_info=exc_info)
else:
regex = r'^Future/Task exception was never retrieved\n'
m_log.error.assert_called_once_with(mock.ANY, exc_info=False)
message = m_log.error.call_args[0][0]
self.assertRegex(message, re.compile(regex, re.DOTALL))
示例11: test_weakref
def test_weakref(self):
s = array.array(self.typecode, self.example)
p = weakref.proxy(s)
self.assertEqual(p.tobytes(), s.tobytes())
s = None
support.gc_collect()
self.assertRaises(ReferenceError, len, p)
示例12: 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)
support.gc_collect()
self.assertEqual(thread._count(), orig)
示例13: testOpenDel
def testOpenDel(self):
self.createTempFile()
for i in range(10000):
o = BZ2File(self.filename)
del o
if i % 100 == 0:
support.gc_collect()
示例14: test_many
def test_many(self):
# mktemp can choose many usable file names (stochastic)
extant = list(range(TEST_FILES))
for i in extant:
extant[i] = self.do_create(pre="aa")
del extant
support.gc_collect()
示例15: test_weak_keys
def test_weak_keys(self):
#
# This exercises d.copy(), d.items(), d[] = v, d[], del d[],
# len(d), k 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.assertEqual(set(items1), set(items2),
"cloning of weak-keyed dictionary did not work!")
del items1, items2
self.assertEqual(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)