Python sys.gettrace() Examples

The following are code examples for showing how to use sys.gettrace(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: NeoAnalysis   Author: neoanalysis   File: Console.py    (license) View Source Project 6 votes vote down vote up
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: NeoAnalysis   Author: neoanalysis   File: Console.py    (license) View Source Project 6 votes vote down vote up
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
Project: Taigabot   Author: FrozenPigs   File: test_errors.py    (license) View Source Project 6 votes vote down vote up
def test_element_cyclic_gc_none(self):
        # test if cyclic reference can crash etree
        Element = self.etree.Element

        # must disable tracing as it could change the refcounts
        trace_func = sys.gettrace()
        try:
            sys.settrace(None)
            gc.collect()

            count = sys.getrefcount(None)

            l = [Element('name'), Element('name')]
            l.append(l)

            del l
            gc.collect()

            self.assertEqual(sys.getrefcount(None), count)
        finally:
            sys.settrace(trace_func) 
Example 4
Project: raspbian-qemu   Author: meadowface   File: test_common.py    (license) View Source Project 6 votes vote down vote up
def callTool(self, args):
        """Call the raspbian-qemu tool with a check for a kept root.img."""
        # Clean up any root images so we can assert whether it's created
        # or not after the run.
        if os.path.exists(self.ROOT_IMG):
            os.unlink(self.ROOT_IMG)

        cmd = [TOOL]
        # Assume any time the trace function is set it's coverage and make
        # sure to spawn the tool under coverage as well.
        if sys.gettrace():
            cmd = ["python3-coverage", "run", "--parallel-mode"] + cmd
        subprocess.check_output(cmd + args, stderr=subprocess.STDOUT)

        # Now make sure root.img was created if request but not if it wasn't.
        # If created correctly, check its state and then clean it up.
        keep_root = "--keep-root" in args
        self.assertEqual(os.path.exists(self.ROOT_IMG), keep_root)
        if keep_root:
            self.assertOnlyUserReadable(self.ROOT_IMG)
            os.unlink(self.ROOT_IMG) 
Example 5
Project: pymoskito   Author: cklb   File: simulation_interface.py    (license) View Source Project 6 votes vote down vote up
def _sim_aftercare(self):
        # reset internal states
        self._sim_settings = None

        # delete modules
        for module in self._sim_modules.keys():
            del module
        self._sim_modules = {}

        # don't disconnect signals in debug-mode
        if sys.gettrace() is None:
            self.simThread.started.disconnect(self._worker.run)
            self._worker.state_changed.disconnect(self.simulation_state_changed)
            self._worker.work_done.disconnect(self.simThread.quit)
            self.simThread.finished.disconnect(self.thread_finished)

        # delete simulator
        self._logger.info("deleting simulator")
        del self._worker 
Example 6
Project: leetcode   Author: thomasyimgit   File: test_debugger.py    (license) View Source Project 6 votes vote down vote up
def test_ipdb_magics2():
    '''Test ipdb with a very short function.
    
    >>> old_trace = sys.gettrace()

    >>> def bar():
    ...     pass

    Run ipdb.

    >>> with PdbTestInput([
    ...    'continue',
    ... ]):
    ...     debugger.Pdb().runcall(bar)
    > <doctest ...>(2)bar()
          1 def bar():
    ----> 2    pass
    <BLANKLINE>
    ipdb> continue
    
    Restore previous trace function, e.g. for coverage.py    
    
    >>> sys.settrace(old_trace)
    ''' 
Example 7
Project: leetcode   Author: thomasyimgit   File: test_debugger.py    (license) View Source Project 6 votes vote down vote up
def can_quit():
    '''Test that quit work in ipydb

    >>> old_trace = sys.gettrace()

    >>> def bar():
    ...     pass

    >>> with PdbTestInput([
    ...    'quit',
    ... ]):
    ...     debugger.Pdb().runcall(bar)
    > <doctest ...>(2)bar()
            1 def bar():
    ----> 2    pass
    <BLANKLINE>
    ipdb> quit

    Restore previous trace function, e.g. for coverage.py

    >>> sys.settrace(old_trace)
    ''' 
Example 8
Project: leetcode   Author: thomasyimgit   File: test_debugger.py    (license) View Source Project 6 votes vote down vote up
def can_exit():
    '''Test that quit work in ipydb

    >>> old_trace = sys.gettrace()

    >>> def bar():
    ...     pass

    >>> with PdbTestInput([
    ...    'exit',
    ... ]):
    ...     debugger.Pdb().runcall(bar)
    > <doctest ...>(2)bar()
            1 def bar():
    ----> 2    pass
    <BLANKLINE>
    ipdb> exit

    Restore previous trace function, e.g. for coverage.py

    >>> sys.settrace(old_trace)
    ''' 
Example 9
Project: oil   Author: oilshell   File: pickletester.py    (license) View Source Project 6 votes vote down vote up
def no_tracing(func):
    """Decorator to temporarily turn off tracing for the duration of a test."""
    if not hasattr(sys, 'gettrace'):
        return func
    else:
        def wrapper(*args, **kwargs):
            original_trace = sys.gettrace()
            try:
                sys.settrace(None)
                return func(*args, **kwargs)
            finally:
                sys.settrace(original_trace)
        wrapper.__name__ = func.__name__
        return wrapper


# Return True if opcode code appears in the pickle, else False. 
Example 10
Project: python2-tracer   Author: extremecoders-re   File: pickletester.py    (license) View Source Project 6 votes vote down vote up
def no_tracing(func):
    """Decorator to temporarily turn off tracing for the duration of a test."""
    if not hasattr(sys, 'gettrace'):
        return func
    else:
        def wrapper(*args, **kwargs):
            original_trace = sys.gettrace()
            try:
                sys.settrace(None)
                return func(*args, **kwargs)
            finally:
                sys.settrace(original_trace)
        wrapper.__name__ = func.__name__
        return wrapper


# Return True if opcode code appears in the pickle, else False. 
Example 11
Project: web_ctp   Author: molebot   File: test_scope.py    (license) View Source Project 6 votes vote down vote up
def testInteractionWithTraceFunc(self):

        import sys
        def tracer(a,b,c):
            return tracer

        def adaptgetter(name, klass, getter):
            kind, des = getter
            if kind == 1:       # AV happens when stepping from this line to next
                if des == "":
                    des = "_%s__%s" % (klass.__name__, name)
                return lambda obj: getattr(obj, des)

        class TestClass:
            pass

        self.addCleanup(sys.settrace, sys.gettrace())
        sys.settrace(tracer)
        adaptgetter("foo", TestClass, (1, ""))
        sys.settrace(None)

        self.assertRaises(TypeError, sys.settrace) 
Example 12
Project: Repobot   Author: Desgard   File: test_debugger.py    (license) View Source Project 6 votes vote down vote up
def test_ipdb_magics2():
    '''Test ipdb with a very short function.
    
    >>> old_trace = sys.gettrace()

    >>> def bar():
    ...     pass

    Run ipdb.

    >>> with PdbTestInput([
    ...    'continue',
    ... ]):
    ...     debugger.Pdb().runcall(bar)
    > <doctest ...>(2)bar()
          1 def bar():
    ----> 2    pass
    <BLANKLINE>
    ipdb> continue
    
    Restore previous trace function, e.g. for coverage.py    
    
    >>> sys.settrace(old_trace)
    ''' 
Example 13
Project: Repobot   Author: Desgard   File: test_debugger.py    (license) View Source Project 6 votes vote down vote up
def can_quit():
    '''Test that quit work in ipydb

    >>> old_trace = sys.gettrace()

    >>> def bar():
    ...     pass

    >>> with PdbTestInput([
    ...    'quit',
    ... ]):
    ...     debugger.Pdb().runcall(bar)
    > <doctest ...>(2)bar()
            1 def bar():
    ----> 2    pass
    <BLANKLINE>
    ipdb> quit

    Restore previous trace function, e.g. for coverage.py

    >>> sys.settrace(old_trace)
    ''' 
Example 14
Project: Repobot   Author: Desgard   File: test_debugger.py    (license) View Source Project 6 votes vote down vote up
def can_exit():
    '''Test that quit work in ipydb

    >>> old_trace = sys.gettrace()

    >>> def bar():
    ...     pass

    >>> with PdbTestInput([
    ...    'exit',
    ... ]):
    ...     debugger.Pdb().runcall(bar)
    > <doctest ...>(2)bar()
            1 def bar():
    ----> 2    pass
    <BLANKLINE>
    ipdb> exit

    Restore previous trace function, e.g. for coverage.py

    >>> sys.settrace(old_trace)
    ''' 
Example 15
Project: extdbg   Author: duboviy   File: watcher.py    (license) View Source Project 6 votes vote down vote up
def log_lines():
    current_file = inspect.getframeinfo(sys._getframe(1)).filename
    pprint('Tracing is ON in %r' % current_file)

    def tracer(frame, event, arg):
        if event != 'line':
            return tracer

        info = inspect.getframeinfo(frame)
        code = info.code_context[0] if info.code_context else ''
        if info.filename == current_file:
            pprint('Executing %s:%s %s' % (info.filename, info.lineno, code))

        return tracer

    old_trace = sys.gettrace()

    def restore():
        sys.settrace(old_trace)

    sys.settrace(tracer)

    return restore 
Example 16
Project: ouroboros   Author: pybee   File: test_scope.py    (license) View Source Project 6 votes vote down vote up
def testInteractionWithTraceFunc(self):

        import sys
        def tracer(a,b,c):
            return tracer

        def adaptgetter(name, klass, getter):
            kind, des = getter
            if kind == 1:       # AV happens when stepping from this line to next
                if des == "":
                    des = "_%s__%s" % (klass.__name__, name)
                return lambda obj: getattr(obj, des)

        class TestClass:
            pass

        self.addCleanup(sys.settrace, sys.gettrace())
        sys.settrace(tracer)
        adaptgetter("foo", TestClass, (1, ""))
        sys.settrace(None)

        self.assertRaises(TypeError, sys.settrace) 
Example 17
Project: ouroboros   Author: pybee   File: test_sys.py    (license) View Source Project 6 votes vote down vote up
def test_recursionlimit_recovery(self):
        if hasattr(sys, 'gettrace') and sys.gettrace():
            self.skipTest('fatal error if run with a trace function')

        # 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 18
Project: artemis   Author: QUVA-Lab   File: test_child_processes.py    (license) View Source Project 6 votes vote down vote up
def test_remote_python_process():

    in_debug_mode = sys.gettrace() is not None

    p = RemotePythonProcess(
        function=partial(my_func, a=1, b=2),
        ip_address='localhost',
        )

    stdin , stdout, stderr = p.execute_child_process()
    time.sleep(.1)  # That autta be enough

    errtext = stderr.read()
    if in_debug_mode:
        assert errtext.startswith('pydev debugger: ')
    else:
        assert errtext == '', errtext
    assert stdout.read() == 'hello hello hello\n'
    assert p.get_return_value()==3 
Example 19
Project: kbe_server   Author: xiaohaoppy   File: test_scope.py    (license) View Source Project 6 votes vote down vote up
def testInteractionWithTraceFunc(self):

        import sys
        def tracer(a,b,c):
            return tracer

        def adaptgetter(name, klass, getter):
            kind, des = getter
            if kind == 1:       # AV happens when stepping from this line to next
                if des == "":
                    des = "_%s__%s" % (klass.__name__, name)
                return lambda obj: getattr(obj, des)

        class TestClass:
            pass

        self.addCleanup(sys.settrace, sys.gettrace())
        sys.settrace(tracer)
        adaptgetter("foo", TestClass, (1, ""))
        sys.settrace(None)

        self.assertRaises(TypeError, sys.settrace) 
Example 20
Project: blender   Author: gastrodia   File: test_debugger.py    (license) View Source Project 6 votes vote down vote up
def test_ipdb_magics2():
    '''Test ipdb with a very short function.
    
    >>> old_trace = sys.gettrace()

    >>> def bar():
    ...     pass

    Run ipdb.

    >>> with PdbTestInput([
    ...    'continue',
    ... ]):
    ...     debugger.Pdb().runcall(bar)
    > <doctest ...>(2)bar()
          1 def bar():
    ----> 2    pass
    <BLANKLINE>
    ipdb> continue
    
    Restore previous trace function, e.g. for coverage.py    
    
    >>> sys.settrace(old_trace)
    ''' 
Example 21
Project: blender   Author: gastrodia   File: test_debugger.py    (license) View Source Project 6 votes vote down vote up
def can_quit():
    '''Test that quit work in ipydb

    >>> old_trace = sys.gettrace()

    >>> def bar():
    ...     pass

    >>> with PdbTestInput([
    ...    'quit',
    ... ]):
    ...     debugger.Pdb().runcall(bar)
    > <doctest ...>(2)bar()
            1 def bar():
    ----> 2    pass
    <BLANKLINE>
    ipdb> quit

    Restore previous trace function, e.g. for coverage.py

    >>> sys.settrace(old_trace)
    ''' 
Example 22
Project: blender   Author: gastrodia   File: test_debugger.py    (license) View Source Project 6 votes vote down vote up
def can_exit():
    '''Test that quit work in ipydb

    >>> old_trace = sys.gettrace()

    >>> def bar():
    ...     pass

    >>> with PdbTestInput([
    ...    'exit',
    ... ]):
    ...     debugger.Pdb().runcall(bar)
    > <doctest ...>(2)bar()
            1 def bar():
    ----> 2    pass
    <BLANKLINE>
    ipdb> exit

    Restore previous trace function, e.g. for coverage.py

    >>> sys.settrace(old_trace)
    ''' 
Example 23
Project: yatta_reader   Author: sound88   File: test_debugger.py    (license) View Source Project 6 votes vote down vote up
def test_ipdb_magics2():
    '''Test ipdb with a very short function.
    
    >>> old_trace = sys.gettrace()

    >>> def bar():
    ...     pass

    Run ipdb.

    >>> with PdbTestInput([
    ...    'continue',
    ... ]):
    ...     debugger.Pdb().runcall(bar)
    > <doctest ...>(2)bar()
          1 def bar():
    ----> 2    pass
    <BLANKLINE>
    ipdb> continue
    
    Restore previous trace function, e.g. for coverage.py    
    
    >>> sys.settrace(old_trace)
    ''' 
Example 24
Project: yatta_reader   Author: sound88   File: test_debugger.py    (license) View Source Project 6 votes vote down vote up
def can_quit():
    '''Test that quit work in ipydb

    >>> old_trace = sys.gettrace()

    >>> def bar():
    ...     pass

    >>> with PdbTestInput([
    ...    'quit',
    ... ]):
    ...     debugger.Pdb().runcall(bar)
    > <doctest ...>(2)bar()
            1 def bar():
    ----> 2    pass
    <BLANKLINE>
    ipdb> quit

    Restore previous trace function, e.g. for coverage.py

    >>> sys.settrace(old_trace)
    ''' 
Example 25
Project: yatta_reader   Author: sound88   File: test_debugger.py    (license) View Source Project 6 votes vote down vote up
def can_exit():
    '''Test that quit work in ipydb

    >>> old_trace = sys.gettrace()

    >>> def bar():
    ...     pass

    >>> with PdbTestInput([
    ...    'exit',
    ... ]):
    ...     debugger.Pdb().runcall(bar)
    > <doctest ...>(2)bar()
            1 def bar():
    ----> 2    pass
    <BLANKLINE>
    ipdb> exit

    Restore previous trace function, e.g. for coverage.py

    >>> sys.settrace(old_trace)
    ''' 
Example 26
Project: nojs   Author: chrisdickinson   File: instrumentation_tracing.py    (license) View Source Project 5 votes vote down vote up
def no_tracing(f):
  @functools.wraps(f)
  def wrapper(*args, **kwargs):
    trace_func = sys.gettrace()
    try:
      sys.settrace(None)
      threading.settrace(None)
      return f(*args, **kwargs)
    finally:
      sys.settrace(trace_func)
      threading.settrace(trace_func)
  return wrapper 
Example 27
Project: flasky   Author: RoseOu   File: collector.py    (license) View Source Project 5 votes vote down vote up
def stop(self):
        """Stop this Tracer."""
        self.stopped = True
        if self.thread != threading.currentThread():
            # Called on a different thread than started us: we can't unhook
            # ourseves, but we've set the flag that we should stop, so we won't
            # do any more tracing.
            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(),))
        #print("Stopping tracer on %s" % threading.current_thread().ident)
        sys.settrace(None) 
Example 28
Project: flasky   Author: RoseOu   File: collector.py    (license) View Source Project 5 votes vote down vote up
def start(self):
        """Start collecting trace information."""
        if self._collectors:
            self._collectors[-1].pause()
        self._collectors.append(self)
        #print("Started: %r" % self._collectors, file=sys.stderr)

        # Check to see whether we had a fullcoverage tracer installed.
        traces0 = []
        if hasattr(sys, "gettrace"):
            fn0 = sys.gettrace()
            if fn0:
                tracer0 = getattr(fn0, '__self__', None)
                if tracer0:
                    traces0 = getattr(tracer0, 'traces', [])

        # Install the tracer on this thread.
        fn = self._start_tracer()

        for args in traces0:
            (frame, event, arg), lineno = args
            try:
                fn(frame, event, arg, lineno=lineno)
            except TypeError:
                raise Exception(
                    "fullcoverage must be run with the C trace function."
                )

        # Install our installation tracer in threading, to jump start other
        # threads.
        threading.settrace(self._installation_trace) 
Example 29
Project: hakkuframework   Author: 4shadoww   File: support.py    (license) View Source Project 5 votes vote down vote up
def no_tracing(func):
    """Decorator to temporarily turn off tracing for the duration of a test."""
    if not hasattr(sys, 'gettrace'):
        return func
    else:
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            original_trace = sys.gettrace()
            try:
                sys.settrace(None)
                return func(*args, **kwargs)
            finally:
                sys.settrace(original_trace)
        return wrapper 
Example 30
Project: zippy   Author: securesystemslab   File: test_sys_settrace.py    (license) View Source Project 5 votes vote down vote up
def test_set_and_retrieve_none(self):
        sys.settrace(None)
        assert sys.gettrace() is None 
Example 31
Project: zippy   Author: securesystemslab   File: test_sys_settrace.py    (license) View Source Project 5 votes vote down vote up
def test_set_and_retrieve_func(self):
        def fn(*args):
            pass

        sys.settrace(fn)
        try:
            assert sys.gettrace() is fn
        finally:
            sys.settrace(None) 
Example 32
Project: oil   Author: oilshell   File: test_sys_settrace.py    (license) View Source Project 5 votes vote down vote up
def test_set_and_retrieve_none(self):
        sys.settrace(None)
        assert sys.gettrace() is None 
Example 33
Project: oil   Author: oilshell   File: test_sys_settrace.py    (license) View Source Project 5 votes vote down vote up
def test_set_and_retrieve_func(self):
        def fn(*args):
            pass

        sys.settrace(fn)
        try:
            assert sys.gettrace() is fn
        finally:
            sys.settrace(None) 
Example 34
Project: oil   Author: oilshell   File: test_threading.py    (license) View Source Project 5 votes vote down vote up
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
            _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 35
Project: python2-tracer   Author: extremecoders-re   File: test_sys_settrace.py    (license) View Source Project 5 votes vote down vote up
def test_set_and_retrieve_none(self):
        sys.settrace(None)
        assert sys.gettrace() is None 
Example 36
Project: python2-tracer   Author: extremecoders-re   File: test_sys_settrace.py    (license) View Source Project 5 votes vote down vote up
def test_set_and_retrieve_func(self):
        def fn(*args):
            pass

        sys.settrace(fn)
        try:
            assert sys.gettrace() is fn
        finally:
            sys.settrace(None) 
Example 37
Project: python2-tracer   Author: extremecoders-re   File: test_threading.py    (license) View Source Project 5 votes vote down vote up
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
            _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 38
Project: packaging   Author: blockstack   File: support.py    (license) View Source Project 5 votes vote down vote up
def no_tracing(func):
    """Decorator to temporarily turn off tracing for the duration of a test."""
    if not hasattr(sys, 'gettrace'):
        return func
    else:
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            original_trace = sys.gettrace()
            try:
                sys.settrace(None)
                return func(*args, **kwargs)
            finally:
                sys.settrace(original_trace)
        return wrapper 
Example 39
Project: ml-utils   Author: LinxiFan   File: debug.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, run=True, *, _frame=1):
        """
        set _frame to 2 if you are inherting from ConditionalBlock and
        __enter__() is nested. Set _frame to N+1 for N levels of nesting.
        See `DebugBlock.__enter__`
        """
        self.run = run
        self.old_sys_trace = sys.gettrace()
        self._frame = _frame 
Example 40
Project: islam-buddy   Author: hamir   File: support.py    (license) View Source Project 5 votes vote down vote up
def no_tracing(func):
    """Decorator to temporarily turn off tracing for the duration of a test."""
    if not hasattr(sys, 'gettrace'):
        return func
    else:
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            original_trace = sys.gettrace()
            try:
                sys.settrace(None)
                return func(*args, **kwargs)
            finally:
                sys.settrace(original_trace)
        return wrapper 
Example 41
Project: web_ctp   Author: molebot   File: test_pdb.py    (license) View Source Project 5 votes vote down vote up
def __enter__(self):
        self.real_stdin = sys.stdin
        sys.stdin = _FakeInput(self.input)
        self.orig_trace = sys.gettrace() if hasattr(sys, 'gettrace') else None 
Example 42
Project: web_ctp   Author: molebot   File: test_scope.py    (license) View Source Project 5 votes vote down vote up
def testLocalsClass_WithTrace(self):
        # Issue23728: after the trace function returns, the locals()
        # dictionary is used to update all variables, this used to
        # include free variables. But in class statements, free
        # variables are not inserted...
        import sys
        self.addCleanup(sys.settrace, sys.gettrace())
        sys.settrace(lambda a,b,c:None)
        x = 12

        class C:
            def f(self):
                return x

        self.assertEqual(x, 12) # Used to raise UnboundLocalError 
Example 43
Project: web_ctp   Author: molebot   File: regrtest.py    (license) View Source Project 5 votes vote down vote up
def get_sys_gettrace(self):
        return sys.gettrace() 
Example 44
Project: web_ctp   Author: molebot   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def no_tracing(func):
    """Decorator to temporarily turn off tracing for the duration of a test."""
    if not hasattr(sys, 'gettrace'):
        return func
    else:
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            original_trace = sys.gettrace()
            try:
                sys.settrace(None)
                return func(*args, **kwargs)
            finally:
                sys.settrace(original_trace)
        return wrapper 
Example 45
Project: web_ctp   Author: molebot   File: test_sys_settrace.py    (license) View Source Project 5 votes vote down vote up
def test_set_and_retrieve_none(self):
        sys.settrace(None)
        assert sys.gettrace() is None 
Example 46
Project: web_ctp   Author: molebot   File: test_sys_settrace.py    (license) View Source Project 5 votes vote down vote up
def test_set_and_retrieve_func(self):
        def fn(*args):
            pass

        sys.settrace(fn)
        try:
            assert sys.gettrace() is fn
        finally:
            sys.settrace(None) 
Example 47
Project: web_ctp   Author: molebot   File: test_sys_settrace.py    (license) View Source Project 5 votes vote down vote up
def setUp(self):
        self.addCleanup(sys.settrace, sys.gettrace()) 
Example 48
Project: web_ctp   Author: molebot   File: test_sys_settrace.py    (license) View Source Project 5 votes vote down vote up
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)


# 'Jump' tests: assigning to frame.f_lineno within a trace function
# moves the execution position - it's how debuggers implement a Jump
# command (aka. "Set next statement"). 
Example 49
Project: web_ctp   Author: molebot   File: test_sys_settrace.py    (license) View Source Project 5 votes vote down vote up
def setUp(self):
        self.addCleanup(sys.settrace, sys.gettrace())
        sys.settrace(None) 
Example 50
Project: web_ctp   Author: molebot   File: test_trace.py    (license) View Source Project 5 votes vote down vote up
def setUp(self):
        self.my_py_filename = fix_ext_py(__file__)
        self.addCleanup(sys.settrace, sys.gettrace())