xref: /petsc/src/binding/petsc4py/test/test_gc.py (revision 2d240a76ffdefda4afcdc14c5a261325b30d32dc) !
1from petsc4py import PETSc
2import unittest
3import gc
4import weakref
5
6# --------------------------------------------------------------------
7
8## gc.set_debug((gc.DEBUG_STATS |
9##               gc.DEBUG_LEAK) &
10##              ~gc.DEBUG_SAVEALL)
11
12# --------------------------------------------------------------------
13
14
15class BaseTestGC:
16    def setUp(self):
17        self.obj = self.CLASS().create(comm=PETSc.COMM_SELF)
18
19    def tearDown(self):
20        wref = self.make_weakref()
21        self.assertTrue(wref() is self.obj)
22        self.obj = None
23        gc.collect()
24        self.assertTrue(wref() is None)
25        PETSc.garbage_cleanup()
26
27    def make_weakref(self):
28        return weakref.ref(self.obj)
29
30    def testCycleInSelf(self):
31        self.obj.setAttr('myself', self.obj)
32
33    def testCycleInMethod(self):
34        self.obj.setAttr('mymeth', self.obj.view)
35
36    def testCycleInInstance(self):
37        class A:
38            pass
39
40        a = A()
41        a.obj = self.obj
42        self.obj.setAttr('myinst', a)
43
44    def testCycleInAllWays(self):
45        self.testCycleInSelf()
46        self.testCycleInMethod()
47        self.testCycleInInstance()
48
49
50# --------------------------------------------------------------------
51
52
53class TestGCVec(BaseTestGC, unittest.TestCase):
54    CLASS = PETSc.Vec
55
56
57class TestGCVecSubType(TestGCVec):
58    CLASS = type('_Vec', (PETSc.Vec,), {})
59
60
61class TestGCMat(BaseTestGC, unittest.TestCase):
62    CLASS = PETSc.Mat
63
64
65class TestGCMatSubType(TestGCMat):
66    CLASS = type('_Mat', (PETSc.Mat,), {})
67
68
69class TestGCPC(BaseTestGC, unittest.TestCase):
70    CLASS = PETSc.PC
71
72
73class TestGCPCSubType(TestGCPC):
74    CLASS = type('_PC', (PETSc.PC,), {})
75
76
77class TestGCKSP(BaseTestGC, unittest.TestCase):
78    CLASS = PETSc.KSP
79
80
81class TestGCKSPSubType(TestGCKSP):
82    CLASS = type('_KSP', (PETSc.KSP,), {})
83
84
85class TestGCSNES(BaseTestGC, unittest.TestCase):
86    CLASS = PETSc.SNES
87
88    def testCycleInAppCtx(self):
89        self.obj.setAppCtx(self.obj)
90
91
92class TestGCSNESSubType(TestGCSNES):
93    CLASS = type('_SNES', (PETSc.SNES,), {})
94
95
96class TestGCTS(BaseTestGC, unittest.TestCase):
97    CLASS = PETSc.TS
98
99    def testCycleInAppCtx(self):
100        self.obj.setAppCtx(self.obj)
101
102
103class TestGCTSSubType(TestGCTS):
104    CLASS = type('_TS', (PETSc.TS,), {})
105
106    def testCycleInAppCtx(self):
107        self.obj.setAppCtx(self.obj)
108
109
110# --------------------------------------------------------------------
111
112if __name__ == '__main__':
113    unittest.main()
114