sys.gettrace

Here are the examples of the python api sys.gettrace taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

68 Examples 7

Example 1

Project: qgisSpaceSyntaxToolkit
Source File: Console.py
View license
    def updateSysTrace(self):
        ## Install or uninstall  sys.settrace handler 
        
        if not self.ui.catchNextExceptionBtn.isChecked() and not self.ui.catchAllExceptionsBtn.isChecked():
            if sys.gettrace() == self.systrace:
                sys.settrace(None)
            return
        
        if self.ui.onlyUncaughtCheck.isChecked():
            if sys.gettrace() == self.systrace:
                sys.settrace(None)
        else:
            if sys.gettrace() is not None and sys.gettrace() != self.systrace:
                self.ui.onlyUncaughtCheck.setChecked(False)
                raise Exception("sys.settrace is in use; cannot monitor for caught exceptions.")
            else:
                sys.settrace(self.systrace)

Example 2

Project: pyqtgraph
Source File: Console.py
View license
    def updateSysTrace(self):
        ## Install or uninstall  sys.settrace handler 
        
        if not self.ui.catchNextExceptionBtn.isChecked() and not self.ui.catchAllExceptionsBtn.isChecked():
            if sys.gettrace() == self.systrace:
                sys.settrace(None)
            return
        
        if self.ui.onlyUncaughtCheck.isChecked():
            if sys.gettrace() == self.systrace:
                sys.settrace(None)
        else:
            if sys.gettrace() is not None and sys.gettrace() != self.systrace:
                self.ui.onlyUncaughtCheck.setChecked(False)
                raise Exception("sys.settrace is in use; cannot monitor for caught exceptions.")
            else:
                sys.settrace(self.systrace)

Example 3

View license
    def test_error_when_set_multiple(self):
        self.monitor._profile.replace(self.bar)
        self.assertIs(sys.gettrace(), self.bar)
        self.monitor._profile.replace(self.bar)
        self.assertIs(sys.gettrace(), self.bar)
        self.monitor._profile.recover()

        self.monitor._profile.replace(self.bar)
        self.assertIs(sys.gettrace(), self.bar)
        with self.assertRaises(RuntimeError):
            self.monitor._profile.replace(None)
            self.assertIs(sys.gettrace(), self.bar)
        self.monitor._profile.recover()
        self.assertIs(sys.gettrace(), self.old)

Example 4

Project: iot-utilities
Source File: test_sys.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'fatal error if run with a trace function')
    def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit)

Example 5

Project: python-mode
Source File: pytest.py
View license
@contextmanager
def replace_trace(trace=None):
    """A context manager that temporary replaces the trace function"""
    oldtrace = sys.gettrace()
    sys.settrace(trace)
    try:
        yield
    finally:
        # specific hack to work around a bug in pycoverage, see
        # https://bitbucket.org/ned/coveragepy/issue/123
        if (oldtrace is not None and not callable(oldtrace) and
            hasattr(oldtrace, 'pytrace')):
            oldtrace = oldtrace.pytrace
        sys.settrace(oldtrace)

Example 6

Project: brython
Source File: test_sys.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'fatal error if run with a trace function')
    def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit)

Example 7

Project: memory_profiler
Source File: memory_profiler.py
View license
    def enable(self):
        self._original_trace_function = sys.gettrace()
        if self.max_mem is not None:
            sys.settrace(self.trace_max_mem)
        else:
            sys.settrace(self.trace_memory_usage)

Example 8

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_loop_caller_importing(self):
        self.tracer.runfunc(traced_func_importing_caller, 1)

        expected = {
            ((os.path.splitext(trace.__file__)[0] + '.py', 'trace', 'Trace.runfunc'),
                (self.filemod + ('traced_func_importing_caller',))): 1,
            ((self.filemod + ('traced_func_simple_caller',)),
                (self.filemod + ('traced_func_linear',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_simple_caller',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_importing',))): 1,
            ((self.filemod + ('traced_func_importing',)),
                (fix_ext_py(testmod.__file__), 'testmod', 'func')): 1,
        }
        self.assertEqual(self.tracer.results().callers, expected)

Example 9

Project: brython
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_inst_method_calling(self):
        obj = TracedClass(20)
        self.tracer.runfunc(obj.inst_method_calling, 1)

        expected = {
            self.filemod + ('TracedClass.inst_method_calling',): 1,
            self.filemod + ('TracedClass.inst_method_linear',): 1,
            self.filemod + ('traced_func_linear',): 1,
        }
        self.assertEqual(self.tracer.results().calledfuncs, expected)

Example 10

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_inst_method_calling(self):
        obj = TracedClass(20)
        self.tracer.runfunc(obj.inst_method_calling, 1)

        expected = {
            self.filemod + ('TracedClass.inst_method_calling',): 1,
            self.filemod + ('TracedClass.inst_method_linear',): 1,
            self.filemod + ('traced_func_linear',): 1,
        }
        self.assertEqual(self.tracer.results().calledfuncs, expected)

Example 11

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_loop_caller_importing(self):
        self.tracer.runfunc(traced_func_importing_caller, 1)

        expected = {
            ((os.path.splitext(trace.__file__)[0] + '.py', 'trace', 'Trace.runfunc'),
                (self.filemod + ('traced_func_importing_caller',))): 1,
            ((self.filemod + ('traced_func_simple_caller',)),
                (self.filemod + ('traced_func_linear',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_simple_caller',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_importing',))): 1,
            ((self.filemod + ('traced_func_importing',)),
                (fix_ext_py(testmod.__file__), 'testmod', 'func')): 1,
        }
        self.assertEqual(self.tracer.results().callers, expected)

Example 12

Project: karl
Source File: performance.py
View license
    def __enter__(self):
        self.savetrace = prev = sys.gettrace()
        if isinstance(prev, notrace) and isinstance(prev.prev, timetrace):
            self.inner = True
            self.frame_node = prev.prev.frame_node
        else:
            self.frame_node = FrameNode(None, None)
        sys.settrace(self)

Example 13

Project: TrustRouter
Source File: test_sys.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'fatal error if run with a trace function')
    def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit)

Example 14

Project: profilehooks
Source File: profilehooks.py
View license
        def __call__(self, *args, **kw):
            """Profile a singe call to the function."""
            self.ncalls += 1
            old_trace = sys.gettrace()
            try:
                return self.profiler.runcall(self.fn, args, kw)
            finally: # pragma: nocover
                sys.settrace(old_trace)

Example 15

Project: coveragepy
Source File: pytracer.py
View license
    def stop(self):
        """Stop this Tracer."""
        self.stopped = True
        if self.threading and self.thread.ident != self.threading.currentThread().ident:
            # Called on a different thread than started us: we can't unhook
            # ourselves, but we've set the flag that we should stop, so we
            # won't do any more tracing.
            return

        if self.warn:
            if sys.gettrace() != self._trace:
                msg = "Trace function changed, measurement is likely wrong: %r"
                self.warn(msg % (sys.gettrace(),))

        sys.settrace(None)

Example 16

Project: vprof
Source File: memory_profile.py
View license
    def __init__(self):
        self._all_code = set()
        self._events_list = deque()
        self._original_trace_function = sys.gettrace()
        self._pid = os.getpid()
        self._resulting_events = []
        self.mem_overhead = None

Example 17

View license
    def test_tracerInstalled(self):
        """
        L{trial.Options} handles C{"--coverage"} by installing a trace
        hook to record coverage information.
        """
        options = trial.Options()
        options.parseOptions(["--coverage"])
        self.assertEqual(sys.gettrace(), options.tracer.globaltrace)

Example 18

Project: withhacks
Source File: frameutils.py
View license
def _enable_tracing():
    """Enable system-wide tracing, if it wasn't already."""
    global _orig_sys_trace
    try:
        _orig_sys_trace = sys.gettrace()
    except AttributeError:
        _orig_sys_trace = None
    if _orig_sys_trace is None:
        sys.settrace(_dummy_sys_trace)

Example 19

Project: iot-utilities
Source File: test_sys.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'fatal error if run with a trace function')
    def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit)

Example 20

Project: iot-utilities
Source File: test_sys.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'fatal error if run with a trace function')
    def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit)

Example 21

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_inst_method_calling(self):
        obj = TracedClass(20)
        self.tracer.runfunc(obj.inst_method_calling, 1)

        expected = {
            self.filemod + ('TracedClass.inst_method_calling',): 1,
            self.filemod + ('TracedClass.inst_method_linear',): 1,
            self.filemod + ('traced_func_linear',): 1,
        }
        self.assertEqual(self.tracer.results().calledfuncs, expected)

Example 22

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_inst_method_calling(self):
        obj = TracedClass(20)
        self.tracer.runfunc(obj.inst_method_calling, 1)

        expected = {
            self.filemod + ('TracedClass.inst_method_calling',): 1,
            self.filemod + ('TracedClass.inst_method_linear',): 1,
            self.filemod + ('traced_func_linear',): 1,
        }
        self.assertEqual(self.tracer.results().calledfuncs, expected)

Example 23

Project: peek
Source File: tracer.py
View license
    def stop(self):
        """
        Stop this Tracer.
        """
        if hasattr(sys, "gettrace") and self.log:
            if sys.gettrace() != self._trace:
                msg = "Trace function changed, measurement is likely wrong: %r"
                print >> sys.stdout, msg % sys.gettrace()
        sys.settrace(None)

Example 24

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_loop_caller_importing(self):
        self.tracer.runfunc(traced_func_importing_caller, 1)

        expected = {
            ((os.path.splitext(trace.__file__)[0] + '.py', 'trace', 'Trace.runfunc'),
                (self.filemod + ('traced_func_importing_caller',))): 1,
            ((self.filemod + ('traced_func_simple_caller',)),
                (self.filemod + ('traced_func_linear',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_simple_caller',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_importing',))): 1,
            ((self.filemod + ('traced_func_importing',)),
                (fix_ext_py(testmod.__file__), 'testmod', 'func')): 1,
        }
        self.assertEqual(self.tracer.results().callers, expected)

Example 25

Project: python-hunter
Source File: tracer.py
View license
    def trace(self, predicate):
        self._handler = predicate
        if self.threading_support:
            self._threading_previous = getattr(threading, '_trace_hook', None)
            threading.settrace(self)
        self._previous = sys.gettrace()
        sys.settrace(self)
        return self

Example 26

View license
    def setUp(self):
        self.old = sys.gettrace()

        def foo():
            pass

        def bar(frame, event, arg):
            pass
        self.foo = foo
        self.bar = bar
        self.monitor = MockNativeMonitor()

Example 27

Project: iot-utilities
Source File: test_sys.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'fatal error if run with a trace function')
    def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit)

Example 28

View license
    def test_tracerInstalled(self):
        """
        L{trial.Options} handles C{"--coverage"} by installing a trace
        hook to record coverage information.
        """
        options = trial.Options()
        options.parseOptions(["--coverage"])
        self.assertEqual(sys.gettrace(), options.tracer.globaltrace)

Example 29

Project: pikos
Source File: trace_function_manager.py
View license
    def replace(self, function):
        """ Set a new function in sys.settrace.

        If the function has been already set and it is not the same as before
        then RuntimeError is raised.

        """
        if hasattr(self, 'previous'):
            if function != sys.gettrace():
                raise RuntimeError(
                    'Cannot replace profile function more than once')
            return
        else:
            self.previous = sys.gettrace()
        if has_threading:
            threading.settrace(function)
        sys.settrace(function)

Example 30

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_inst_method_calling(self):
        obj = TracedClass(20)
        self.tracer.runfunc(obj.inst_method_calling, 1)

        expected = {
            self.filemod + ('TracedClass.inst_method_calling',): 1,
            self.filemod + ('TracedClass.inst_method_linear',): 1,
            self.filemod + ('traced_func_linear',): 1,
        }
        self.assertEqual(self.tracer.results().calledfuncs, expected)

Example 31

Project: python-mode
Source File: pytest.py
View license
@contextmanager
def replace_trace(trace=None):
    """A context manager that temporary replaces the trace function"""
    oldtrace = sys.gettrace()
    sys.settrace(trace)
    try:
        yield
    finally:
        # specific hack to work around a bug in pycoverage, see
        # https://bitbucket.org/ned/coveragepy/issue/123
        if (oldtrace is not None and not callable(oldtrace) and
            hasattr(oldtrace, 'pytrace')):
            oldtrace = oldtrace.pytrace
        sys.settrace(oldtrace)

Example 32

Project: rootpy
Source File: test_roothandler.py
View license
def test_tracing_is_broken():
    def mytrace(*args):
        pass

    orig_trace = sys.gettrace()
    sys.settrace(mytrace)

    try:
        ROOT.Error("rootpy.logger.tests", "Test tracing OK")
    except ROOTError:
        pass
    else:
        assert False, "Should have thrown"

    should_be_mytrace = sys.gettrace()
    sys.settrace(orig_trace)

    assert should_be_mytrace != mytrace, "Tracing is fixed?! Awesome. Now fix the test."

Example 33

Project: profilehooks
Source File: profilehooks.py
View license
    def __call__(self, *args, **kw):
        """Profile a singe call to the function."""
        self.ncalls += 1
        if TraceFuncCoverage.tracing: # pragma: nocover
            return self.fn(*args, **kw)
        old_trace = sys.gettrace()
        try:
            TraceFuncCoverage.tracing = True
            return self.tracer.runfunc(self.fn, *args, **kw)
        finally: # pragma: nocover
            sys.settrace(old_trace)
            TraceFuncCoverage.tracing = False

Example 34

Project: iot-utilities
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_loop_caller_importing(self):
        self.tracer.runfunc(traced_func_importing_caller, 1)

        expected = {
            ((os.path.splitext(trace.__file__)[0] + '.py', 'trace', 'Trace.runfunc'),
                (self.filemod + ('traced_func_importing_caller',))): 1,
            ((self.filemod + ('traced_func_simple_caller',)),
                (self.filemod + ('traced_func_linear',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_simple_caller',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_importing',))): 1,
            ((self.filemod + ('traced_func_importing',)),
                (fix_ext_py(testmod.__file__), 'testmod', 'func')): 1,
        }
        self.assertEqual(self.tracer.results().callers, expected)

Example 35

Project: coveragepy
Source File: pytracer.py
View license
    def stop(self):
        """Stop this Tracer."""
        self.stopped = True
        if self.threading and self.thread.ident != self.threading.currentThread().ident:
            # Called on a different thread than started us: we can't unhook
            # ourselves, but we've set the flag that we should stop, so we
            # won't do any more tracing.
            return

        if self.warn:
            if sys.gettrace() != self._trace:
                msg = "Trace function changed, measurement is likely wrong: %r"
                self.warn(msg % (sys.gettrace(),))

        sys.settrace(None)

Example 36

Project: brython
Source File: test_trace.py
View license
    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                     'pre-existing trace function throws off measurements')
    def test_loop_caller_importing(self):
        self.tracer.runfunc(traced_func_importing_caller, 1)

        expected = {
            ((os.path.splitext(trace.__file__)[0] + '.py', 'trace', 'Trace.runfunc'),
                (self.filemod + ('traced_func_importing_caller',))): 1,
            ((self.filemod + ('traced_func_simple_caller',)),
                (self.filemod + ('traced_func_linear',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_simple_caller',))): 1,
            ((self.filemod + ('traced_func_importing_caller',)),
                (self.filemod + ('traced_func_importing',))): 1,
            ((self.filemod + ('traced_func_importing',)),
                (fix_ext_py(testmod.__file__), 'testmod', 'func')): 1,
        }
        self.assertEqual(self.tracer.results().callers, expected)

Example 37

Project: dtcov
Source File: dt_tracer.py
View license
    def stop(self):
        """Stop this Tracer."""
        if stopping:
            return
        if hasattr(sys, "gettrace") and self.warn:
            if sys.gettrace() != self._trace:
                msg = "Trace function changed, measurement is likely wrong: %r"
                self.warn(msg % sys.gettrace())
        sys.settrace(None)
        global stopping
        stopping = True

Example 38

Project: karl
Source File: performance.py
View license
    def __enter__(self):
        self.savetrace = prev = sys.gettrace()
        if isinstance(prev, notrace) and isinstance(prev.prev, timetrace):
            self.inner = True
            self.frame_node = prev.prev.frame_node
        else:
            self.frame_node = FrameNode(None, None)
        sys.settrace(self)

Example 39

View license
    def test_error_when_unset(self):
        with self.assertRaises(RuntimeError):
            self.monitor._profile.recover()
        self.assertIs(sys.gettrace(), self.old)

Example 40

Project: karl
Source File: performance.py
View license
    def __enter__(self):
        self.prev = sys.gettrace()
        sys.settrace(self)

Example 41

Project: karl
Source File: performance.py
View license
    def __enter__(self):
        self.prev = sys.gettrace()
        sys.settrace(self)

Example 42

Project: feat
Source File: time.py
View license
def _debugger_scale():
    if sys.gettrace() is None:
        return 1
    else:
        return 4

Example 43

Project: feat
Source File: common.py
View license
    def assert_not_skipped(self):
        if self.skip_coverage and sys.gettrace():
            raise unittest.SkipTest("Test Skipped during coverage")

Example 44

Project: iot-utilities
Source File: test_sys_settrace.py
View license
    def test_exception_arguments(self):
        def f():
            x = 0
            # this should raise an error
            x.no_such_attr
        def g(frame, event, arg):
            if (event == 'exception'):
                type, exception, trace = arg
                self.assertIsInstance(exception, Exception)
            return g

        existing = sys.gettrace()
        try:
            sys.settrace(g)
            try:
                f()
            except AttributeError:
                # this is expected
                pass
        finally:
            sys.settrace(existing)

Example 45

Project: feat
Source File: common.py
View license
    def assert_not_skipped(self):
        if self.skip_coverage and sys.gettrace():
            raise SkipTest("Test Skipped during coverage")

Example 46

Project: iot-utilities
Source File: test_threading.py
View license
    @cpython_only
    def test_frame_tstate_tracing(self):
        # Issue #14432: Crash when a generator is created in a C thread that is
        # destroyed while the generator is still used. The issue was that a
        # generator contains a frame, and the frame kept a reference to the
        # Python state of the destroyed C thread. The crash occurs when a trace
        # function is setup.

        def noop_trace(frame, event, arg):
            # no operation
            return noop_trace

        def generator():
            while 1:
                yield "generator"

        def callback():
            if callback.gen is None:
                callback.gen = generator()
            return next(callback.gen)
        callback.gen = None

        old_trace = sys.gettrace()
        sys.settrace(noop_trace)
        try:
            # Install a trace function
            threading.settrace(noop_trace)

            # Create a generator in a C thread which exits after the call
            import _testcapi
            _testcapi.call_in_temporary_c_thread(callback)

            # Call the generator in a different Python thread, check that the
            # generator didn't keep a reference to the destroyed thread state
            for test in range(3):
                # The trace function is still called here
                callback()
        finally:
            sys.settrace(old_trace)

Example 47

Project: brython
Source File: test_sys_settrace.py
View license
    def test_exception_arguments(self):
        def f():
            x = 0
            # this should raise an error
            x.no_such_attr
        def g(frame, event, arg):
            if (event == 'exception'):
                type, exception, trace = arg
                self.assertIsInstance(exception, Exception)
            return g

        existing = sys.gettrace()
        try:
            sys.settrace(g)
            try:
                f()
            except AttributeError:
                # this is expected
                pass
        finally:
            sys.settrace(existing)

Example 48

Project: feat
Source File: common.py
View license
    def assert_not_skipped(self):
        if self.skip_coverage and sys.gettrace():
            raise SkipTest("Test Skipped during coverage")

Example 49

Project: iktomi
Source File: functools.py
View license
    def test_return_locals_debugger_events(self):
        '''Insure debugging function gets events for function decorated with
        return_locals at least the same as for function itself.'''
        def collect_events(func):
            events = []
            def tracer(frame, event, args):
                events.append((frame.f_code, event))
                return tracer
            old_tracer = sys.gettrace()
            sys.settrace(tracer)
            try:
                func()
            finally:
                sys.settrace(old_tracer)
            return events
        def inner():
            return 2
        def outer():
            a = 1
            b = inner()
        events1 = set(collect_events(outer))
        events2 = set(collect_events(return_locals(outer)))
        self.assertTrue(events2.issuperset(events1))

Example 50

Project: feat
Source File: common.py
View license
    def assert_not_skipped(self):
        if self.skip_coverage and sys.gettrace():
            raise SkipTest("Test Skipped during coverage")