1 """Tests for refleaks."""
4 from cherrypy
._cpcompat
import HTTPConnection
, HTTPSConnection
, ntob
8 from cherrypy
import _cprequest
13 def get_instances(cls
):
14 return [x
for x
in gc
.get_objects() if isinstance(x
, cls
)]
17 from cherrypy
.test
import helper
20 class ReferenceTests(helper
.CPWebCase
):
25 def index(self
, *args
, **kwargs
):
26 cherrypy
.request
.thing
= data
31 output
= ["Statistics:"]
33 # Uncollectable garbage
35 # gc_collect isn't perfectly synchronous, because it may
36 # break reference cycles that then take time to fully
37 # finalize. Call it twice and hope for the best.
39 unreachable
= gc
.collect()
41 output
.append("\n%s unreachable objects:" % unreachable
)
44 trash
[type(x
)] = trash
.get(type(x
), 0) + 1
45 trash
= [(v
, k
) for k
, v
in trash
.items()]
48 output
.append(" " + repr(pair
))
51 reqs
= get_instances(_cprequest
.Request
)
54 output
.append("\nMissing Request reference. Should be 1 in "
55 "this request thread and 1 in the main thread.")
57 output
.append("\nToo many Request references (%r)." % lenreqs
)
59 output
.append("Referrers for %s:" % repr(req
))
60 for ref
in gc
.get_referrers(req
):
62 output
.append(" %s" % repr(ref
))
65 resps
= get_instances(_cprequest
.Response
)
68 output
.append("\nMissing Response reference. Should be 1 in "
69 "this request thread and 1 in the main thread.")
71 output
.append("\nToo many Response references (%r)." % lenresps
)
73 output
.append("Referrers for %s:" % repr(resp
))
74 for ref
in gc
.get_referrers(resp
):
76 output
.append(" %s" % repr(ref
))
78 return "\n".join(output
)
79 gc_stats
.exposed
= True
81 cherrypy
.tree
.mount(Root())
82 setup_server
= staticmethod(setup_server
)
85 def test_threadlocal_garbage(self
):
89 host
= '%s:%s' % (self
.interface(), self
.PORT
)
90 if self
.scheme
== 'https':
91 c
= HTTPSConnection(host
)
93 c
= HTTPConnection(host
)
95 c
.putrequest('GET', '/')
97 response
= c
.getresponse()
98 body
= response
.read()
99 self
.assertEqual(response
.status
, 200)
100 self
.assertEqual(body
, ntob("Hello world!"))
107 for _
in range(ITERATIONS
):
108 t
= threading
.Thread(target
=getpage
)
115 self
.assertEqual(len(success
), ITERATIONS
)
117 self
.getPage("/gc_stats")
118 self
.assertBody("Statistics:")