Debian Codegraph @

test/jpypetest/test_leak.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # *****************************************************************************
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16 # See NOTICE file for details.
17 #
18 # *****************************************************************************
19 import jpype
20 import gc
21 import sys
22 from os import path
23 import subrun
24 import unittest
25
26 try:
27 import resource
28 except ImportError:
29 resource = None # type: ignore[assignment]
30
31
32 def haveResource():
33 return resource is not None
34
35
36 def hasRefCount():
37 try:
38 sys.getrefcount(sys)
39 return True
40 except:
41 return False
42
43
44 class LeakChecker:
45
46 def __init__(self):
47 self.runtime = jpype.java.lang.Runtime.getRuntime()
48
49 def memory_usage_resource(self):
50 # The Python docs aren't clear on what the units are exactly, but
51 # the Mac OS X man page for `getrusage(2)` describes the units as bytes.
52 # The Linux man page isn't clear, but it seems to be equivalent to
53 # the information from `/proc/self/status`, which is in kilobytes.
54 if sys.platform == 'darwin':
55 rusage_mp = 1
56 else:
57 rusage_mp = 1024
58 return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * rusage_mp
59
60 def freeResources(self):
61 self.runtime.gc() # Garbage collect Java
62 gc.collect() # Garbage collect Python?
63 rss_memory = self.memory_usage_resource()
64 jvm_total_mem = self.runtime.totalMemory()
65 jvm_free_mem = self.runtime.freeMemory()
66 num_gc_objects = len(gc.get_objects())
67 return (rss_memory, jvm_total_mem, jvm_free_mem)
68
69 def memTest(self, func, size):
70 # Returns true if there may be a leak
71
72 # Note, some growth is possible due to loading of objects and classes,
73 # Thus we will run it a few times to check the growth rate.
74
75 rss_memory = list()
76 jvm_total_mem = list()
77 jvm_free_mem = list()
78 grow0 = list()
79 grow1 = list()
80
81 (rss_memory0, jvm_total_mem0, jvm_free_mem0) = self.freeResources()
82 success = 0
83 for j in range(10):
84 for i in range(size):
85 func()
86 (rss_memory1, jvm_total_mem1, jvm_free_mem1) = self.freeResources()
87
88 rss_memory.append(rss_memory1)
89 jvm_total_mem.append(jvm_total_mem1)
90 jvm_free_mem.append(jvm_free_mem1)
91
92 growth0 = (rss_memory1 - rss_memory0) / (float(size))
93 growth1 = (jvm_total_mem1 - jvm_total_mem0) / (float(size))
94 rss_memory0 = rss_memory1
95 jvm_total_mem0 = jvm_total_mem1
96 jvm_free_mem0 = jvm_total_mem1
97
98 grow0.append(growth0)
99 grow1.append(growth1)
100
101 if (growth0 < 0) or (growth1 < 0):
102 continue
103
104 if (growth0 < 4) and (growth1 < 4):
105 success += 1
106
107 if success > 3:
108 return False
109
110 print()
111 for i in range(len(grow0)):
112 print(' Pass%d: %f %f - %d %d %d' %
113 (i, grow0[i], grow1[i], rss_memory[i], jvm_total_mem[i], jvm_free_mem[i]))
114 print()
115 return True
116
117
118 @subrun.TestCase(individual=True)
119 class LeakTestCase(unittest.TestCase):
120
121 def setUp(self):
122 root = path.dirname(path.abspath(path.dirname(__file__)))
123 jpype.addClassPath(path.join(root, 'classes'))
124 jvm_path = jpype.getDefaultJVMPath()
125 classpath_arg = "-Djava.class.path=%s"
126 classpath_arg %= jpype.getClassPath()
127 jpype.startJVM(jvm_path, "-ea",
128 # "-Xcheck:jni",
129 "-Xmx256M", "-Xms16M", classpath_arg)
130
131 def assertNotLeaky(self, function, counts=5000):
132 lc = LeakChecker()
133 assert not lc.memTest(function, counts), 'Potential leak found'
134
135 @unittest.skipUnless(haveResource(), "resource not available")
136 def testStringLeak(self):
137 def stringFunc():
138 jpype.java.lang.String('aaaaaaaaaaaaaaaaa')
139 self.assertNotLeaky(stringFunc)
140
141 @unittest.skipUnless(haveResource(), "resource not available")
142 def testStringLeak__str__(self):
143 def stringFunc():
144 # Casting to a string includes a cache stage, we want to make sure
145 # that the cache is tidying up properly.
146 s = jpype.types.JString('aaaaaaaaaaaaaaaaa')
147 str(s)
148 self.assertNotLeaky(stringFunc)
149
150 @unittest.skipUnless(haveResource(), "resource not available")
151 def testClassLeak(self):
152 def classFunc():
153 cls = jpype.JClass('java.lang.String')
154 self.assertNotLeaky(classFunc)
155
156 @unittest.skipUnless(haveResource(), "resource not available")
157 def testCtorLeak(self):
158 cls = jpype.JClass("java.lang.String")
159
160 def func():
161 cls("test")
162
163 self.assertNotLeaky(func)
164
165 @unittest.skipUnless(haveResource(), "resource not available")
166 def testInvokeLeak(self):
167 jstr = jpype.JString("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
168
169 def func():
170 jstr.getBytes()
171
172 self.assertNotLeaky(func)