diff --git a/changelog/4051.trivial.rst b/changelog/4051.trivial.rst new file mode 100644 index 00000000000..401f3b1a850 --- /dev/null +++ b/changelog/4051.trivial.rst @@ -0,0 +1 @@ +Imrpove Error messaging when Invalid Python Syntax is passed through the ``-m`` option to limit what marks to run against. diff --git a/src/_pytest/mark/legacy.py b/src/_pytest/mark/legacy.py index ab016a0355b..0d0d852cebd 100644 --- a/src/_pytest/mark/legacy.py +++ b/src/_pytest/mark/legacy.py @@ -66,7 +66,10 @@ def __getitem__(self, subname): def matchmark(colitem, markexpr): """Tries to match on any marker names, attached to the given colitem.""" - return eval(markexpr, {}, MarkMapping.from_item(colitem)) + try: + return eval(markexpr, {}, MarkMapping.from_item(colitem)) + except SyntaxError as e: + raise SyntaxError(str(e) + "\nMarker expression must be valid Python!") def matchkeyword(colitem, keywordexpr): diff --git a/testing/test_mark.py b/testing/test_mark.py index ddeff278977..06bbe65f4ce 100644 --- a/testing/test_mark.py +++ b/testing/test_mark.py @@ -786,6 +786,18 @@ def test_unmarked(): deselected_tests = dlist[0].items assert len(deselected_tests) == 2 + def test_invalid_m_option(self, testdir): + testdir.makepyfile( + """ + def test_a(): + pass + """ + ) + result = testdir.runpytest("-m bogus/") + result.stdout.fnmatch_lines( + ["INTERNALERROR> Marker expression must be valid Python!"] + ) + def test_keywords_at_node_level(self, testdir): testdir.makepyfile( """