1from petsc4py import PETSc 2import unittest 3import gc, weakref 4import warnings 5 6# -------------------------------------------------------------------- 7 8## gc.set_debug((gc.DEBUG_STATS | 9## gc.DEBUG_LEAK) & 10## ~gc.DEBUG_SAVEALL) 11 12# -------------------------------------------------------------------- 13 14class BaseTestGC(object): 15 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 wref = weakref.ref(self.obj) 29 return wref 30 31 def testCycleInSelf(self): 32 self.obj.setAttr('myself', self.obj) 33 34 def testCycleInMethod(self): 35 self.obj.setAttr('mymeth', self.obj.view) 36 37 def testCycleInInstance(self): 38 class A: pass 39 a = A() 40 a.obj = self.obj 41 self.obj.setAttr('myinst', a) 42 43 def testCycleInAllWays(self): 44 self.testCycleInSelf() 45 self.testCycleInMethod() 46 self.testCycleInInstance() 47 48# -------------------------------------------------------------------- 49 50class TestGCVec(BaseTestGC, unittest.TestCase): 51 CLASS = PETSc.Vec 52 53class TestGCVecSubType(TestGCVec): 54 CLASS = type('_Vec', (PETSc.Vec,), {}) 55 56class TestGCMat(BaseTestGC, unittest.TestCase): 57 CLASS = PETSc.Mat 58 59class TestGCMatSubType(TestGCMat): 60 CLASS = type('_Mat', (PETSc.Mat,), {}) 61 62class TestGCPC(BaseTestGC, unittest.TestCase): 63 CLASS = PETSc.PC 64 65class TestGCPCSubType(TestGCPC): 66 CLASS = type('_PC', (PETSc.PC,), {}) 67 68class TestGCKSP(BaseTestGC, unittest.TestCase): 69 CLASS = PETSc.KSP 70 71class TestGCKSPSubType(TestGCKSP): 72 CLASS = type('_KSP', (PETSc.KSP,), {}) 73 74class TestGCSNES(BaseTestGC, unittest.TestCase): 75 CLASS = PETSc.SNES 76 def testCycleInAppCtx(self): 77 self.obj.setAppCtx(self.obj) 78 79class TestGCSNESSubType(TestGCSNES): 80 CLASS = type('_SNES', (PETSc.SNES,), {}) 81 82class TestGCTS(BaseTestGC, unittest.TestCase): 83 CLASS = PETSc.TS 84 def testCycleInAppCtx(self): 85 self.obj.setAppCtx(self.obj) 86 87class TestGCTSSubType(TestGCTS): 88 CLASS = type('_TS', (PETSc.TS,), {}) 89 def testCycleInAppCtx(self): 90 self.obj.setAppCtx(self.obj) 91 92# -------------------------------------------------------------------- 93 94if __name__ == '__main__': 95 unittest.main() 96