Python pytest.set_trace() Examples

The following are 24 code examples of pytest.set_trace(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pytest , or try the search function .
Example #1
Source File: test_debugging.py    From pytest with MIT License 6 votes vote down vote up
def test_pdb_used_in_generate_tests(self, testdir):
        p1 = testdir.makepyfile(
            """
            import pytest
            def pytest_generate_tests(metafunc):
                pytest.set_trace()
                x = 5
            def test_foo(a):
                pass
        """
        )
        child = testdir.spawn_pytest(str(p1))
        child.expect("x = 5")
        child.expect("Pdb")
        child.sendeof()
        self.flush(child) 
Example #2
Source File: conftest.py    From aerospike-client-python with Apache License 2.0 6 votes vote down vote up
def put_data(request):
    put_data.key = None
    put_data.keys = []
    put_data.client = None

    def put_key(client, _key, _record, _meta=None, _policy=None):
        put_data.key = _key
        put_data.client = client
        try:
            client.remove(_key)
        except:
            pass
        put_data.keys.append(put_data.key)
        return client.put(_key, _record, _meta, _policy)

    def remove_key():
        try:
            # pytest.set_trace()
            for key in put_data.keys:
                put_data.client.remove(key)
        except:
            pass

    request.addfinalizer(remove_key)
    return put_key 
Example #3
Source File: test_DataFrameModel.py    From qtpandas with MIT License 6 votes vote down vote up
def test_bool(self, model, index, value, qtbool):
        dataFrame = pandas.DataFrame([value], columns=['A'])
        dataFrame['A'] = dataFrame['A'].astype(numpy.bool_)
        model.setDataFrame(dataFrame)
        assert not model.dataFrame().empty
        assert model.dataFrame() is dataFrame

        assert index.isValid()
        model.enableEditing(True)
        # pytest.set_trace()
        # everything is already set as false and since Qt.Unchecked = 0, 0 == False
        # therefore the assert will fail without further constraints
        assert model.setData(index, qtbool) == value
        assert model.data(index, role=Qt.DisplayRole) == value
        assert model.data(index, role=Qt.EditRole) == value
        assert model.data(index, role=Qt.CheckStateRole) == qtbool
        assert model.data(index, role=DATAFRAME_ROLE) == value
        assert isinstance(model.data(index, role=DATAFRAME_ROLE), numpy.bool_) 
Example #4
Source File: test_debugging.py    From pytest with MIT License 6 votes vote down vote up
def test_raises_bdbquit_with_eoferror(testdir):
    """It is not guaranteed that DontReadFromInput's read is called."""

    p1 = testdir.makepyfile(
        """
        def input_without_read(*args, **kwargs):
            raise EOFError()

        def test(monkeypatch):
            import builtins
            monkeypatch.setattr(builtins, "input", input_without_read)
            __import__('pdb').set_trace()
        """
    )
    result = testdir.runpytest(str(p1))
    result.stdout.fnmatch_lines(["E *BdbQuit", "*= 1 failed in*"])
    assert result.ret == 1 
Example #5
Source File: test_debugging.py    From pytest with MIT License 6 votes vote down vote up
def test_pdb_not_altered(self, testdir):
        p1 = testdir.makepyfile(
            """
            import pdb
            def test_1():
                pdb.set_trace()
                assert 0
        """
        )
        child = testdir.spawn_pytest(str(p1))
        child.expect("test_1")
        child.expect("Pdb")
        child.sendline("c")
        rest = child.read().decode("utf8")
        assert "1 failed" in rest
        assert "reading from stdin while output" not in rest
        TestPDB.flush(child) 
Example #6
Source File: test_debugging.py    From pytest with MIT License 6 votes vote down vote up
def test_doctest_set_trace_quit(self, testdir):
        p1 = testdir.makepyfile(
            """
            def function_1():
                '''
                >>> __import__('pdb').set_trace()
                '''
        """
        )
        # NOTE: does not use pytest.set_trace, but Python's patched pdb,
        #       therefore "-s" is required.
        child = testdir.spawn_pytest("--doctest-modules --pdb -s %s" % p1)
        child.expect("Pdb")
        child.sendline("q")
        rest = child.read().decode("utf8")

        assert "! _pytest.outcomes.Exit: Quitting debugger !" in rest
        assert "= no tests ran in" in rest
        assert "BdbQuit" not in rest
        assert "UNEXPECTED EXCEPTION" not in rest 
Example #7
Source File: test_debugging.py    From pytest with MIT License 6 votes vote down vote up
def test_pdb_and_capsys(self, testdir):
        p1 = testdir.makepyfile(
            """
            import pytest
            def test_1(capsys):
                print("hello1")
                pytest.set_trace()
        """
        )
        child = testdir.spawn_pytest(str(p1))
        child.expect("test_1")
        child.send("capsys.readouterr()\n")
        child.expect("hello1")
        child.sendeof()
        child.read()
        self.flush(child) 
Example #8
Source File: test_debugging.py    From pytest with MIT License 6 votes vote down vote up
def test_pdb_set_trace_kwargs(self, testdir):
        p1 = testdir.makepyfile(
            """
            import pytest
            def test_1():
                i = 0
                print("hello17")
                pytest.set_trace(header="== my_header ==")
                x = 3
                assert 0
        """
        )
        child = testdir.spawn_pytest(str(p1))
        child.expect("== my_header ==")
        assert "PDB set_trace" not in child.before.decode()
        child.expect("Pdb")
        child.sendline("c")
        rest = child.read().decode("utf-8")
        assert "1 failed" in rest
        assert "def test_1" in rest
        assert "hello17" in rest  # out is captured
        self.flush(child) 
Example #9
Source File: test_DataFrameModel.py    From pandas-qt with MIT License 6 votes vote down vote up
def test_bool(self, model, index, value, qtbool):
        dataFrame = pandas.DataFrame([value], columns=['A'])
        dataFrame['A'] = dataFrame['A'].astype(numpy.bool_)
        model.setDataFrame(dataFrame)
        assert not model.dataFrame().empty
        assert model.dataFrame() is dataFrame

        assert index.isValid()
        model.enableEditing(True)
        # pytest.set_trace()
        # everything is already set as false and since Qt.Unchecked = 0, 0 == False
        # therefore the assert will fail without further constraints
        assert model.setData(index, qtbool) == value
        assert model.data(index, role=Qt.DisplayRole) == value
        assert model.data(index, role=Qt.EditRole) == value
        assert model.data(index, role=Qt.CheckStateRole) == qtbool
        assert model.data(index, role=DATAFRAME_ROLE) == value
        assert isinstance(model.data(index, role=DATAFRAME_ROLE), numpy.bool_) 
Example #10
Source File: test_debugging.py    From pytest with MIT License 6 votes vote down vote up
def custom_debugger_hook():
    called = []

    # install dummy debugger class and track which methods were called on it
    class _CustomDebugger:
        def __init__(self, *args, **kwargs):
            called.append("init")

        def reset(self):
            called.append("reset")

        def interaction(self, *args):
            called.append("interaction")

        def set_trace(self, frame):
            print("**CustomDebugger**")
            called.append("set_trace")

    _pytest._CustomDebugger = _CustomDebugger  # type: ignore
    yield called
    del _pytest._CustomDebugger  # type: ignore 
Example #11
Source File: test_debugging.py    From pytest with MIT License 6 votes vote down vote up
def test_pdb_interaction_capturing_simple(self, testdir):
        p1 = testdir.makepyfile(
            """
            import pytest
            def test_1():
                i = 0
                print("hello17")
                pytest.set_trace()
                i == 1
                assert 0
        """
        )
        child = testdir.spawn_pytest(str(p1))
        child.expect(r"test_1\(\)")
        child.expect("i == 1")
        child.expect("Pdb")
        child.sendline("c")
        rest = child.read().decode("utf-8")
        assert "AssertionError" in rest
        assert "1 failed" in rest
        assert "def test_1" in rest
        assert "hello17" in rest  # out is captured
        self.flush(child) 
Example #12
Source File: test_debugging.py    From pytest with MIT License 6 votes vote down vote up
def test_pdb_set_trace_interception(self, testdir):
        p1 = testdir.makepyfile(
            """
            import pdb
            def test_1():
                pdb.set_trace()
        """
        )
        child = testdir.spawn_pytest(str(p1))
        child.expect("test_1")
        child.expect("Pdb")
        child.sendline("q")
        rest = child.read().decode("utf8")
        assert "no tests ran" in rest
        assert "reading from stdin while output" not in rest
        assert "BdbQuit" not in rest
        self.flush(child) 
Example #13
Source File: test_debugging.py    From pytest with MIT License 5 votes vote down vote up
def test_pdb_used_outside_test(self, testdir):
        p1 = testdir.makepyfile(
            """
            import pytest
            pytest.set_trace()
            x = 5
        """
        )
        child = testdir.spawn("{} {}".format(sys.executable, p1))
        child.expect("x = 5")
        child.expect("Pdb")
        child.sendeof()
        self.flush(child) 
Example #14
Source File: test_pgexecute.py    From pgcli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_view_definition(executor):
    run(executor, "create table tbl1 (a text, b numeric)")
    run(executor, "create view vw1 AS SELECT * FROM tbl1")
    run(executor, "create materialized view mvw1 AS SELECT * FROM tbl1")
    result = executor.view_definition("vw1")
    assert "FROM tbl1" in result
    # import pytest; pytest.set_trace()
    result = executor.view_definition("mvw1")
    assert "MATERIALIZED VIEW" in result 
Example #15
Source File: test_debugging.py    From pytest with MIT License 5 votes vote down vote up
def test_pdb_custom_cls_with_set_trace(self, testdir, monkeypatch):
        testdir.makepyfile(
            custom_pdb="""
            class CustomPdb(object):
                def __init__(self, *args, **kwargs):
                    skip = kwargs.pop("skip")
                    assert skip == ["foo.*"]
                    print("__init__")
                    super(CustomPdb, self).__init__(*args, **kwargs)

                def set_trace(*args, **kwargs):
                    print('custom set_trace>')
         """
        )
        p1 = testdir.makepyfile(
            """
            import pytest

            def test_foo():
                pytest.set_trace(skip=['foo.*'])
        """
        )
        monkeypatch.setenv("PYTHONPATH", str(testdir.tmpdir))
        child = testdir.spawn_pytest("--pdbcls=custom_pdb:CustomPdb %s" % str(p1))

        child.expect("__init__")
        child.expect("custom set_trace>")
        self.flush(child) 
Example #16
Source File: test_debugging.py    From pytest with MIT License 5 votes vote down vote up
def test_sys_breakpointhook_configure_and_unconfigure(self, testdir, arg):
        """
        Test that sys.breakpointhook is set to the custom Pdb class once configured, test that
        hook is reset to system value once pytest has been unconfigured
        """
        testdir.makeconftest(
            """
            import sys
            from pytest import hookimpl
            from _pytest.debugging import pytestPDB

            def pytest_configure(config):
                config._cleanup.append(check_restored)

            def check_restored():
                assert sys.breakpointhook == sys.__breakpointhook__

            def test_check():
                assert sys.breakpointhook == pytestPDB.set_trace
        """
        )
        testdir.makepyfile(
            """
            def test_nothing(): pass
        """
        )
        args = (arg,) if arg else ()
        result = testdir.runpytest_subprocess(*args)
        result.stdout.fnmatch_lines(["*1 passed in *"]) 
Example #17
Source File: test_debugging.py    From pytest with MIT License 5 votes vote down vote up
def test_pdb_custom_cls(self, testdir, custom_debugger_hook):
        p1 = testdir.makepyfile(
            """
            def test_nothing():
                breakpoint()
        """
        )
        result = testdir.runpytest_inprocess(
            "--pdb", "--pdbcls=_pytest:_CustomDebugger", p1
        )
        result.stdout.fnmatch_lines(["*CustomDebugger*", "*1 passed*"])
        assert custom_debugger_hook == ["init", "set_trace"] 
Example #18
Source File: test_debugging.py    From pytest with MIT License 5 votes vote down vote up
def test_environ_custom_class(self, testdir, custom_debugger_hook, arg):
        testdir.makeconftest(
            """
            import os
            import sys

            os.environ['PYTHONBREAKPOINT'] = '_pytest._CustomDebugger.set_trace'

            def pytest_configure(config):
                config._cleanup.append(check_restored)

            def check_restored():
                assert sys.breakpointhook == sys.__breakpointhook__

            def test_check():
                import _pytest
                assert sys.breakpointhook is _pytest._CustomDebugger.set_trace
        """
        )
        testdir.makepyfile(
            """
            def test_nothing(): pass
        """
        )
        args = (arg,) if arg else ()
        result = testdir.runpytest_subprocess(*args)
        result.stdout.fnmatch_lines(["*1 passed in *"]) 
Example #19
Source File: test_debugging.py    From pytest with MIT License 5 votes vote down vote up
def test_pdb_without_capture(self, testdir):
        p1 = testdir.makepyfile(
            """
            import pytest
            def test_1():
                pytest.set_trace()
        """
        )
        child = testdir.spawn_pytest("-s %s" % p1)
        child.expect(r">>> PDB set_trace >>>")
        child.expect("Pdb")
        child.sendline("c")
        child.expect(r">>> PDB continue >>>")
        child.expect("1 passed")
        self.flush(child) 
Example #20
Source File: test_debugging.py    From pytest with MIT License 5 votes vote down vote up
def test_pdbcls_via_local_module(testdir):
    """It should be imported in pytest_configure or later only."""
    p1 = testdir.makepyfile(
        """
        def test():
            print("before_set_trace")
            __import__("pdb").set_trace()
        """,
        mypdb="""
        class Wrapped:
            class MyPdb:
                def set_trace(self, *args):
                    print("set_trace_called", args)

                def runcall(self, *args, **kwds):
                    print("runcall_called", args, kwds)
        """,
    )
    result = testdir.runpytest(
        str(p1), "--pdbcls=really.invalid:Value", syspathinsert=True
    )
    result.stdout.fnmatch_lines(
        [
            "*= FAILURES =*",
            "E * --pdbcls: could not import 'really.invalid:Value': No module named *really*",
        ]
    )
    assert result.ret == 1

    result = testdir.runpytest(
        str(p1), "--pdbcls=mypdb:Wrapped.MyPdb", syspathinsert=True
    )
    assert result.ret == 0
    result.stdout.fnmatch_lines(["*set_trace_called*", "* 1 passed in *"])

    # Ensure that it also works with --trace.
    result = testdir.runpytest(
        str(p1), "--pdbcls=mypdb:Wrapped.MyPdb", "--trace", syspathinsert=True
    )
    assert result.ret == 0
    result.stdout.fnmatch_lines(["*runcall_called*", "* 1 passed in *"]) 
Example #21
Source File: test_debugging.py    From pytest with MIT License 5 votes vote down vote up
def test_pdb_interaction_capturing_twice(self, testdir):
        p1 = testdir.makepyfile(
            """
            import pytest
            def test_1():
                i = 0
                print("hello17")
                pytest.set_trace()
                x = 3
                print("hello18")
                pytest.set_trace()
                x = 4
                assert 0
        """
        )
        child = testdir.spawn_pytest(str(p1))
        child.expect(r"PDB set_trace \(IO-capturing turned off\)")
        child.expect("test_1")
        child.expect("x = 3")
        child.expect("Pdb")
        child.sendline("c")
        child.expect(r"PDB continue \(IO-capturing resumed\)")
        child.expect(r"PDB set_trace \(IO-capturing turned off\)")
        child.expect("x = 4")
        child.expect("Pdb")
        child.sendline("c")
        child.expect("_ test_1 _")
        child.expect("def test_1")
        rest = child.read().decode("utf8")
        assert "Captured stdout call" in rest
        assert "hello17" in rest  # out is captured
        assert "hello18" in rest  # out is captured
        assert "1 failed" in rest
        self.flush(child) 
Example #22
Source File: test_debugging.py    From pytest with MIT License 5 votes vote down vote up
def test_pdb_wrapper_class_is_reused(testdir):
    p1 = testdir.makepyfile(
        """
        def test():
            __import__("pdb").set_trace()
            __import__("pdb").set_trace()

            import mypdb
            instances = mypdb.instances
            assert len(instances) == 2
            assert instances[0].__class__ is instances[1].__class__
        """,
        mypdb="""
        instances = []

        class MyPdb:
            def __init__(self, *args, **kwargs):
                instances.append(self)

            def set_trace(self, *args):
                print("set_trace_called", args)
        """,
    )
    result = testdir.runpytest(str(p1), "--pdbcls=mypdb:MyPdb", syspathinsert=True)
    assert result.ret == 0
    result.stdout.fnmatch_lines(
        ["*set_trace_called*", "*set_trace_called*", "* 1 passed in *"]
    ) 
Example #23
Source File: test_debugging.py    From pytest with MIT License 4 votes vote down vote up
def test_pdb_suspends_fixture_capturing(testdir, fixture):
    """Using "-s" with pytest should suspend/resume fixture capturing."""
    p1 = testdir.makepyfile(
        """
        def test_inner({fixture}):
            import sys

            print("out_inner_before")
            sys.stderr.write("err_inner_before\\n")

            __import__("pdb").set_trace()

            print("out_inner_after")
            sys.stderr.write("err_inner_after\\n")

            out, err = {fixture}.readouterr()
            assert out =="out_inner_before\\nout_inner_after\\n"
            assert err =="err_inner_before\\nerr_inner_after\\n"
        """.format(
            fixture=fixture
        )
    )

    child = testdir.spawn_pytest(str(p1) + " -s")

    child.expect("Pdb")
    before = child.before.decode("utf8")
    assert (
        "> PDB set_trace (IO-capturing turned off for fixture %s) >" % (fixture)
        in before
    )

    # Test that capturing is really suspended.
    child.sendline("p 40 + 2")
    child.expect("Pdb")
    assert "\r\n42\r\n" in child.before.decode("utf8")

    child.sendline("c")
    rest = child.read().decode("utf8")
    assert "out_inner" not in rest
    assert "err_inner" not in rest

    TestPDB.flush(child)
    assert child.exitstatus == 0
    assert "= 1 passed in" in rest
    assert "> PDB continue (IO-capturing resumed for fixture %s) >" % (fixture) in rest 
Example #24
Source File: mock_builder_base_class.py    From f5-openstack-agent with Apache License 2.0 4 votes vote down vote up
def mock_method(self, target, call_cnt=1, expected_args=[],
                    static=None, **kwargs):
        """An example mock_{method} ABC method

        This is an ABC providing an example.  As a developer, to see how this
        framework works, simply...
            1. Comment out the raise (but please do not commit the raise)
            2. Comment out the raise in self.fully_mocked_target method
            3. Do a pytest.set_trace at the beginning of this method
                a. The beginning of check_mocks()
                b. The beginning of fully_mocked_target()
            4. Do the following python code in this directory:
                import conftest
                foo = conftest.MockBuilder()
                target = foo.fully_mocked_target()
                foo.mock_method(target, 1, tuple([]))
                target.method()
                foo.check_mocks()

        A standard test within a TesterClass should simply use one of the
        following:
            - fully_mocked_target
            - partially_mocked_target
            - standalone_builder
            - neutron_only_builder
            - bigip_only_builder
            - fully_int_builder
        Please see the ABCM for these.

        NOTE: this ABCM type cannot be a fixture becuase the builder is
        factoried after pytest performs its fixture isolation at compile time.

        NOTE: due to this the attributes starting with '_mock_' are considered
        as part of the algorithm; thus, please do not overload this attr type.

        Additional Kwargs and their meanings (as children should follow):
            - call_cnt: the number of times the mocked method is called in
              production
            - expected_args: the expected args for at least one call within
              the production code during the test.  Note that this means that
              only one of the mocked-method's calls... see check_mocks() for
              how this is validated
            - static: A static value that will be used in favor over setting
              the mocked method to a mock.Mock
        """
        raise NotImplementedError("This is only an example")
        if not target:
            target = MockBuilderBase.fully_mocked_target()
        self._mockfactory(target.method, static, call_cnt, expected_args,
                          kwargs)
        return target