Python test.support.gc_collect() Examples

The following are 30 code examples of test.support.gc_collect(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module test.support , or try the search function .
Example #1
Source File: test_io.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_IOBase_finalize(self):
        # Issue #12149: segmentation fault on _PyIOBase_finalize when both a
        # class which inherits IOBase and an object of this class are caught
        # in a reference cycle and close() is already in the method cache.
        class MyIO(self.IOBase):
            def close(self):
                pass

        # create an instance to populate the method cache
        MyIO()
        obj = MyIO()
        obj.obj = obj
        wr = weakref.ref(obj)
        del MyIO
        del obj
        support.gc_collect()
        self.assertIsNone(wr(), wr) 
Example #2
Source File: test_generators.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_frame_resurrect(self):
        # A generator frame can be resurrected by a generator's finalization.
        def gen():
            nonlocal frame
            try:
                yield
            finally:
                frame = sys._getframe()

        g = gen()
        wr = weakref.ref(g)
        next(g)
        del g
        support.gc_collect()
        self.assertIs(wr(), None)
        self.assertTrue(frame)
        del frame
        support.gc_collect() 
Example #3
Source File: test_generators.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_refcycle(self):
        # A generator caught in a refcycle gets finalized anyway.
        old_garbage = gc.garbage[:]
        finalized = False
        def gen():
            nonlocal finalized
            try:
                g = yield
                yield 1
            finally:
                finalized = True

        g = gen()
        next(g)
        g.send(g)
        self.assertGreater(sys.getrefcount(g), 2)
        self.assertFalse(finalized)
        del g
        support.gc_collect()
        self.assertTrue(finalized)
        self.assertEqual(gc.garbage, old_garbage) 
Example #4
Source File: test_io.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_override_destructor(self):
        record = []
        class MyTextIO(self.TextIOWrapper):
            def __del__(self):
                record.append(1)
                try:
                    f = super().__del__
                except AttributeError:
                    pass
                else:
                    f()
            def close(self):
                record.append(2)
                super().close()
            def flush(self):
                record.append(3)
                super().flush()
        b = self.BytesIO()
        t = MyTextIO(b, encoding="ascii")
        del t
        support.gc_collect()
        self.assertEqual(record, [1, 2, 3]) 
Example #5
Source File: test_io.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_garbage_collection(self):
        # C TextIOWrapper objects are collected, and collecting them flushes
        # all data to disk.
        # The Python version has __del__, so it ends in gc.garbage instead.
        with support.check_warnings(('', ResourceWarning)):
            rawio = io.FileIO(support.TESTFN, "wb")
            b = self.BufferedWriter(rawio)
            t = self.TextIOWrapper(b, encoding="ascii")
            t.write("456def")
            t.x = t
            wr = weakref.ref(t)
            del t
            support.gc_collect()
        self.assertIsNone(wr(), wr)
        with self.open(support.TESTFN, "rb") as f:
            self.assertEqual(f.read(), b"456def") 
Example #6
Source File: test_memoryio.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_getbuffer(self):
        memio = self.ioclass(b"1234567890")
        buf = memio.getbuffer()
        self.assertEqual(bytes(buf), b"1234567890")
        memio.seek(5)
        buf = memio.getbuffer()
        self.assertEqual(bytes(buf), b"1234567890")
        # Trying to change the size of the BytesIO while a buffer is exported
        # raises a BufferError.
        self.assertRaises(BufferError, memio.write, b'x' * 100)
        self.assertRaises(BufferError, memio.truncate)
        self.assertRaises(BufferError, memio.close)
        self.assertFalse(memio.closed)
        # Mutating the buffer updates the BytesIO
        buf[3:6] = b"abc"
        self.assertEqual(bytes(buf), b"123abc7890")
        self.assertEqual(memio.getvalue(), b"123abc7890")
        # After the buffer gets released, we can resize and close the BytesIO
        # again
        del buf
        support.gc_collect()
        memio.truncate()
        memio.close()
        self.assertRaises(ValueError, memio.getbuffer) 
Example #7
Source File: test_io.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_destructor(self):
        record = []
        class MyFileIO(self.FileIO):
            def __del__(self):
                record.append(1)
                try:
                    f = super().__del__
                except AttributeError:
                    pass
                else:
                    f()
            def close(self):
                record.append(2)
                super().close()
            def flush(self):
                record.append(3)
                super().flush()
        with support.check_warnings(('', ResourceWarning)):
            f = MyFileIO(support.TESTFN, "wb")
            f.write(b"xxx")
            del f
            support.gc_collect()
            self.assertEqual(record, [1, 2, 3])
            with self.open(support.TESTFN, "rb") as f:
                self.assertEqual(f.read(), b"xxx") 
Example #8
Source File: test_socket.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_dealloc_warn(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        r = repr(sock)
        with self.assertWarns(ResourceWarning) as cm:
            sock = None
            support.gc_collect()
        self.assertIn(r, str(cm.warning.args[0]))
        # An open socket file object gets dereferenced after the socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        f = sock.makefile('rb')
        r = repr(sock)
        sock = None
        support.gc_collect()
        with self.assertWarns(ResourceWarning):
            f = None
            support.gc_collect() 
Example #9
Source File: test_io.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_IOBase_finalize(self):
        # Issue #12149: segmentation fault on _PyIOBase_finalize when both a
        # class which inherits IOBase and an object of this class are caught
        # in a reference cycle and close() is already in the method cache.
        class MyIO(self.IOBase):
            def close(self):
                pass

        # create an instance to populate the method cache
        MyIO()
        obj = MyIO()
        obj.obj = obj
        wr = weakref.ref(obj)
        del MyIO
        del obj
        support.gc_collect()
        self.assertIsNone(wr(), wr) 
Example #10
Source File: test_base_events.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_run_forever_keyboard_interrupt(self):
        # Python issue #22601: ensure that the temporary task created by
        # run_forever() consumes the KeyboardInterrupt and so don't log
        # a warning
        @asyncio.coroutine
        def raise_keyboard_interrupt():
            raise KeyboardInterrupt

        self.loop._process_events = mock.Mock()
        self.loop.call_exception_handler = mock.Mock()

        try:
            self.loop.run_until_complete(raise_keyboard_interrupt())
        except KeyboardInterrupt:
            pass
        self.loop.close()
        support.gc_collect()

        self.assertFalse(self.loop.call_exception_handler.called) 
Example #11
Source File: test_windows_utils.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_pipe_handle(self):
        h, _ = windows_utils.pipe(overlapped=(True, True))
        _winapi.CloseHandle(_)
        p = windows_utils.PipeHandle(h)
        self.assertEqual(p.fileno(), h)
        self.assertEqual(p.handle, h)

        # check garbage collection of p closes handle
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", "",  ResourceWarning)
            del p
            support.gc_collect()
        try:
            _winapi.CloseHandle(h)
        except OSError as e:
            self.assertEqual(e.winerror, 6)     # ERROR_INVALID_HANDLE
        else:
            raise RuntimeError('expected ERROR_INVALID_HANDLE') 
Example #12
Source File: test_descr.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_subtype_resurrection(self):
        # Testing resurrection of new-style instance...

        class C(object):
            container = []

            def __del__(self):
                # resurrect the instance
                C.container.append(self)

        c = C()
        c.attr = 42

        # The most interesting thing here is whether this blows up, due to
        # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
        # bug).
        del c

        support.gc_collect()
        self.assertEqual(len(C.container), 1)

        # Make c mortal again, so that the test framework with -l doesn't report
        # it as a leak.
        del C.__del__ 
Example #13
Source File: test_descr.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_subtype_resurrection(self):
        # Testing resurrection of new-style instance...

        class C(object):
            container = []

            def __del__(self):
                # resurrect the instance
                C.container.append(self)

        c = C()
        c.attr = 42

        # The most interesting thing here is whether this blows up, due to
        # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
        # bug).
        del c

        support.gc_collect()
        self.assertEqual(len(C.container), 1)

        # Make c mortal again, so that the test framework with -l doesn't report
        # it as a leak.
        del C.__del__ 
Example #14
Source File: test_windows_utils.py    From annotated-py-projects with MIT License 6 votes vote down vote up
def test_pipe_handle(self):
        h, _ = windows_utils.pipe(overlapped=(True, True))
        _winapi.CloseHandle(_)
        p = windows_utils.PipeHandle(h)
        self.assertEqual(p.fileno(), h)
        self.assertEqual(p.handle, h)

        # check garbage collection of p closes handle
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", "",  ResourceWarning)
            del p
            support.gc_collect()
        try:
            _winapi.CloseHandle(h)
        except OSError as e:
            self.assertEqual(e.winerror, 6)     # ERROR_INVALID_HANDLE
        else:
            raise RuntimeError('expected ERROR_INVALID_HANDLE') 
Example #15
Source File: test_io.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_destructor(self):
        record = []
        class MyFileIO(self.FileIO):
            def __del__(self):
                record.append(1)
                try:
                    f = super().__del__
                except AttributeError:
                    pass
                else:
                    f()
            def close(self):
                record.append(2)
                super().close()
            def flush(self):
                record.append(3)
                super().flush()
        with support.check_warnings(('', ResourceWarning)):
            f = MyFileIO(support.TESTFN, "wb")
            f.write(b"xxx")
            del f
            support.gc_collect()
            self.assertEqual(record, [1, 2, 3])
            with self.open(support.TESTFN, "rb") as f:
                self.assertEqual(f.read(), b"xxx") 
Example #16
Source File: test_socket.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_dealloc_warn(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        r = repr(sock)
        with self.assertWarns(ResourceWarning) as cm:
            sock = None
            support.gc_collect()
        self.assertIn(r, str(cm.warning.args[0]))
        # An open socket file object gets dereferenced after the socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        f = sock.makefile('rb')
        r = repr(sock)
        sock = None
        support.gc_collect()
        with self.assertWarns(ResourceWarning):
            f = None
            support.gc_collect() 
Example #17
Source File: test_memoryio.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_getbuffer(self):
        memio = self.ioclass(b"1234567890")
        buf = memio.getbuffer()
        self.assertEqual(bytes(buf), b"1234567890")
        memio.seek(5)
        buf = memio.getbuffer()
        self.assertEqual(bytes(buf), b"1234567890")
        # Trying to change the size of the BytesIO while a buffer is exported
        # raises a BufferError.
        self.assertRaises(BufferError, memio.write, b'x' * 100)
        self.assertRaises(BufferError, memio.truncate)
        self.assertRaises(BufferError, memio.close)
        self.assertFalse(memio.closed)
        # Mutating the buffer updates the BytesIO
        buf[3:6] = b"abc"
        self.assertEqual(bytes(buf), b"123abc7890")
        self.assertEqual(memio.getvalue(), b"123abc7890")
        # After the buffer gets released, we can resize and close the BytesIO
        # again
        del buf
        support.gc_collect()
        memio.truncate()
        memio.close()
        self.assertRaises(ValueError, memio.getbuffer) 
Example #18
Source File: test_generators.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_refcycle(self):
        # A generator caught in a refcycle gets finalized anyway.
        old_garbage = gc.garbage[:]
        finalized = False
        def gen():
            nonlocal finalized
            try:
                g = yield
                yield 1
            finally:
                finalized = True

        g = gen()
        next(g)
        g.send(g)
        self.assertGreater(sys.getrefcount(g), 2)
        self.assertFalse(finalized)
        del g
        support.gc_collect()
        self.assertTrue(finalized)
        self.assertEqual(gc.garbage, old_garbage) 
Example #19
Source File: test_io.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_override_destructor(self):
        record = []
        class MyTextIO(self.TextIOWrapper):
            def __del__(self):
                record.append(1)
                try:
                    f = super().__del__
                except AttributeError:
                    pass
                else:
                    f()
            def close(self):
                record.append(2)
                super().close()
            def flush(self):
                record.append(3)
                super().flush()
        b = self.BytesIO()
        t = MyTextIO(b, encoding="ascii")
        del t
        support.gc_collect()
        self.assertEqual(record, [1, 2, 3]) 
Example #20
Source File: test_io.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_garbage_collection(self):
        # C TextIOWrapper objects are collected, and collecting them flushes
        # all data to disk.
        # The Python version has __del__, so it ends in gc.garbage instead.
        with support.check_warnings(('', ResourceWarning)):
            rawio = io.FileIO(support.TESTFN, "wb")
            b = self.BufferedWriter(rawio)
            t = self.TextIOWrapper(b, encoding="ascii")
            t.write("456def")
            t.x = t
            wr = weakref.ref(t)
            del t
            support.gc_collect()
        self.assertIsNone(wr(), wr)
        with self.open(support.TESTFN, "rb") as f:
            self.assertEqual(f.read(), b"456def") 
Example #21
Source File: test_base_events.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_run_forever_keyboard_interrupt(self):
        # Python issue #22601: ensure that the temporary task created by
        # run_forever() consumes the KeyboardInterrupt and so don't log
        # a warning
        @asyncio.coroutine
        def raise_keyboard_interrupt():
            raise KeyboardInterrupt

        self.loop._process_events = mock.Mock()
        self.loop.call_exception_handler = mock.Mock()

        try:
            self.loop.run_until_complete(raise_keyboard_interrupt())
        except KeyboardInterrupt:
            pass
        self.loop.close()
        support.gc_collect()

        self.assertFalse(self.loop.call_exception_handler.called) 
Example #22
Source File: test_windows_utils.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_pipe_handle(self):
        h, _ = windows_utils.pipe(overlapped=(True, True))
        _winapi.CloseHandle(_)
        p = windows_utils.PipeHandle(h)
        self.assertEqual(p.fileno(), h)
        self.assertEqual(p.handle, h)

        # check garbage collection of p closes handle
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", "",  ResourceWarning)
            del p
            support.gc_collect()
        try:
            _winapi.CloseHandle(h)
        except OSError as e:
            self.assertEqual(e.winerror, 6)     # ERROR_INVALID_HANDLE
        else:
            raise RuntimeError('expected ERROR_INVALID_HANDLE') 
Example #23
Source File: test_descr.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_delete_hook(self):
        # Testing __del__ hook...
        log = []
        class C(object):
            def __del__(self):
                log.append(1)
        c = C()
        self.assertEqual(log, [])
        del c
        support.gc_collect()
        self.assertEqual(log, [1])

        class D(object): pass
        d = D()
        try: del d[0]
        except TypeError: pass
        else: self.fail("invalid del() didn't raise TypeError") 
Example #24
Source File: test_descr.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_delete_hook(self):
        # Testing __del__ hook...
        log = []
        class C(object):
            def __del__(self):
                log.append(1)
        c = C()
        self.assertEqual(log, [])
        del c
        support.gc_collect()
        self.assertEqual(log, [1])

        class D(object): pass
        d = D()
        try: del d[0]
        except TypeError: pass
        else: self.fail("invalid del() didn't raise TypeError") 
Example #25
Source File: test_io.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_rwpair_cleared_before_textio(self):
        # Issue 13070: TextIOWrapper's finalization would crash when called
        # after the reference to the underlying BufferedRWPair's writer got
        # cleared by the GC.
        for i in range(1000):
            b1 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO())
            t1 = self.TextIOWrapper(b1, encoding="ascii")
            b2 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO())
            t2 = self.TextIOWrapper(b2, encoding="ascii")
            # circular references
            t1.buddy = t2
            t2.buddy = t1
        support.gc_collect() 
Example #26
Source File: test_locks.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_lock_lifetime(self):
        name = "xyzzy"
        self.assertNotIn(name, self.bootstrap._module_locks)
        lock = self.bootstrap._get_module_lock(name)
        self.assertIn(name, self.bootstrap._module_locks)
        wr = weakref.ref(lock)
        del lock
        support.gc_collect()
        self.assertNotIn(name, self.bootstrap._module_locks)
        self.assertIsNone(wr()) 
Example #27
Source File: test_io.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_destructor(self):
        writer = self.MockRawIO()
        bufio = self.tp(writer, 8)
        bufio.write(b"abc")
        del bufio
        support.gc_collect()
        self.assertEqual(b"abc", writer._write_stack[0]) 
Example #28
Source File: test_ast.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_AST_garbage_collection(self):
        class X:
            pass
        a = ast.AST()
        a.x = X()
        a.x.a = a
        ref = weakref.ref(a.x)
        del a
        support.gc_collect()
        self.assertIsNone(ref()) 
Example #29
Source File: test_io.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_override_destructor(self):
        tp = self.tp
        record = []
        class MyBufferedIO(tp):
            def __del__(self):
                record.append(1)
                try:
                    f = super().__del__
                except AttributeError:
                    pass
                else:
                    f()
            def close(self):
                record.append(2)
                super().close()
            def flush(self):
                record.append(3)
                super().flush()
        rawio = self.MockRawIO()
        bufio = MyBufferedIO(rawio)
        writable = bufio.writable()
        del bufio
        support.gc_collect()
        if writable:
            self.assertEqual(record, [1, 2, 3])
        else:
            self.assertEqual(record, [1, 2]) 
Example #30
Source File: test_io.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_nonbuffered_textio(self):
        with warnings.catch_warnings(record=True) as recorded:
            with self.assertRaises(ValueError):
                self.open(support.TESTFN, 'w', buffering=0)
            support.gc_collect()
        self.assertEqual(recorded, [])