File: common.py

package info (click to toggle)
mayavi2 4.8.3-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 21,892 kB
  • sloc: python: 49,447; javascript: 32,885; makefile: 129; fortran: 60
file content (62 lines) | stat: -rw-r--r-- 1,831 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
""" Test utilities
"""
# Authors: Deepak Surti, Ioannis Tziakos
# Copyright (c) 2015, Enthought, Inc.
# License: BSD Style.

import contextlib
import gc
import unittest
import weakref

@contextlib.contextmanager
def restore_gc_state():
    """Ensure that gc state is restored on exit of the with statement."""
    originally_enabled = gc.isenabled()
    try:
        yield
    finally:
        if originally_enabled:
            gc.enable()
        else:
            gc.disable()

class TestGarbageCollection(unittest.TestCase):
    """ This is a base class to use when testing garbage collection.
        See: tvtk.tests.test_garbage_collection
             mayavi.tests.test_garbage_collection
    """

    def check_object_garbage_collected(self, obj_create_fn, obj_close_fn=None):
        """ Call this from a test function to test for garbage collection
            passing the following parameters:

            obj_create_fn: function
                A function with no parameters that creates the object

            obj_close_fn: function
                A function of 1 parameter which is the object created by
                obj_create_fn, to handling the object closing, if any.
        """
        # given
        object_collected = []
        object_weakref = None

        def object_collected_callback(weakref):
            object_collected.append(True)

        def do():
            obj = obj_create_fn()
            reference = weakref.ref(obj, object_collected_callback)
            if obj_close_fn:
                obj_close_fn(obj)
            return reference

        # when
        with restore_gc_state():
            gc.disable()
            object_weakref = do()

        # The object should have been collected.
        self.assertTrue(object_collected[0])
        self.assertIsNone(object_weakref())