import time import sys import threading import unittest #=============================================================================== # MyThreadWithoutTracing #=============================================================================== class MyThreadWithoutTracing(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.alive = True self.started = False def run(self): sys.settrace(None) #try to run this thread untraced self.started = True for _i in range(10): self.call_not_traced() time.sleep(1) self.alive = False def call_not_traced(self): pass #=============================================================================== # MyThreadWithTracing #=============================================================================== class MyThreadWithTracing(threading.Thread): def __init__(self, on_trace_callback): threading.Thread.__init__(self) self.alive = True self.on_trace_callback = on_trace_callback def my_trace(self, frame, event, arg): self.on_trace_callback(frame.f_code.co_name) def call_to_trace(self): pass def run(self): sys.settrace(self.my_trace) #and this one traced for _i in range(10): self.call_to_trace() time.sleep(1) self.alive = False #=============================================================================== # TestCase #=============================================================================== class TestCase(unittest.TestCase): def testJythonSetTraceWithThreads(self): self.traced = [] def OnTrace(co_name): self.traced.append(str(co_name)) thread_without_tracing = MyThreadWithoutTracing() thread_with_tracing = MyThreadWithTracing(OnTrace) thread_without_tracing.start() while not thread_without_tracing.started: time.sleep(.5) thread_with_tracing.start() print 'count to 10' while thread_without_tracing.alive or thread_with_tracing.alive: sys.stdout.write('.') time.sleep(1) print self.traced found_traced_occurrences = 0 for i in range(len(self.traced)): if self.traced[i] == 'call_to_trace': found_traced_occurrences += 1 self.assertEquals(10, found_traced_occurrences, "10 call_to_trace should be in %s" % self.traced) self.assert_('call_not_traced' not in self.traced, "call_not_traced shouldn't be in %s" % self.traced) #=============================================================================== # main #=============================================================================== if __name__ == '__main__': unittest.main()