From a868a9ac13a2ac4a021a09c926b2564dccdfc70f Mon Sep 17 00:00:00 2001 From: Daniel Hahler Date: Thu, 28 Feb 2019 17:46:09 +0100 Subject: [PATCH] pdb: validate --pdbcls option --- src/_pytest/debugging.py | 27 ++++++++++++++++++++++----- testing/test_pdb.py | 14 ++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/_pytest/debugging.py b/src/_pytest/debugging.py index 6b401aa0b..d37728a15 100644 --- a/src/_pytest/debugging.py +++ b/src/_pytest/debugging.py @@ -3,6 +3,7 @@ from __future__ import absolute_import from __future__ import division from __future__ import print_function +import argparse import pdb import sys from doctest import UnexpectedException @@ -12,6 +13,24 @@ from _pytest.config import hookimpl def pytest_addoption(parser): + def validate_usepdb_cls(value): + try: + modname, classname = value.split(":") + except ValueError: + raise argparse.ArgumentTypeError( + "{!r} is not in the format 'modname:classname'".format(value) + ) + + try: + __import__(modname) + pdb_cls = getattr(sys.modules[modname], classname) + except Exception as exc: + raise argparse.ArgumentTypeError( + "could not get pdb class for {!r}: {}".format(value, exc) + ) + + return pdb_cls + group = parser.getgroup("general") group._addoption( "--pdb", @@ -23,6 +42,7 @@ def pytest_addoption(parser): "--pdbcls", dest="usepdb_cls", metavar="modulename:classname", + type=validate_usepdb_cls, help="start a custom interactive Python debugger on errors. " "For example: --pdbcls=IPython.terminal.debugger:TerminalPdb", ) @@ -35,11 +55,8 @@ def pytest_addoption(parser): def pytest_configure(config): - if config.getvalue("usepdb_cls"): - modname, classname = config.getvalue("usepdb_cls").split(":") - __import__(modname) - pdb_cls = getattr(sys.modules[modname], classname) - else: + pdb_cls = config.getvalue("usepdb_cls") + if not pdb_cls: pdb_cls = pdb.Pdb if config.getvalue("trace"): diff --git a/testing/test_pdb.py b/testing/test_pdb.py index 43d640614..f0cef2788 100644 --- a/testing/test_pdb.py +++ b/testing/test_pdb.py @@ -688,6 +688,20 @@ class TestPDB(object): result.stdout.fnmatch_lines(["*NameError*xxx*", "*1 error*"]) assert custom_pdb_calls == ["init", "reset", "interaction"] + def test_pdb_custom_cls_invalid(self, testdir): + result = testdir.runpytest_inprocess("--pdbcls=invalid") + result.stderr.fnmatch_lines( + [ + "*: error: argument --pdbcls: 'invalid' is not in the format 'modname:classname'" + ] + ) + result = testdir.runpytest_inprocess("--pdbcls=pdb:DoesNotExist") + result.stderr.fnmatch_lines( + [ + "*: error: argument --pdbcls: could not get pdb class for 'pdb:DoesNotExist':*" + ] + ) + def test_pdb_custom_cls_without_pdb(self, testdir, custom_pdb_calls): p1 = testdir.makepyfile("""xxx """) result = testdir.runpytest_inprocess("--pdbcls=_pytest:_CustomPdb", p1)