From b34bd149f2fe86a38e7f8117f8604aa5fab3dedc Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Thu, 3 Nov 2022 18:56:23 -0400 Subject: [PATCH] fix: properly measure strange use of wildcard alternatives in match/case. #1421 --- CHANGES.rst | 5 ++++- coverage/parser.py | 5 ++++- tests/test_arcs.py | 13 +++++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index f3be6387f..9453f1ae3 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -20,7 +20,10 @@ development at the same time, such as 4.5.x and 5.0. Unreleased ---------- -Nothing yet. +- Fixed a mis-measurement of a strange use of wildcard alternatives in + match/case statements, closing `issue 1421`_. + +.. _issue 1421: https://github.com/nedbat/coveragepy/issues/1421 .. _changes_6-6-0b1: diff --git a/coverage/parser.py b/coverage/parser.py index 8b2a9ac54..c4fef9ceb 100644 --- a/coverage/parser.py +++ b/coverage/parser.py @@ -1041,7 +1041,10 @@ def _handle__Match(self, node): had_wildcard = False for case in node.cases: case_start = self.line_for_node(case.pattern) - if isinstance(case.pattern, ast.MatchAs): + pattern = case.pattern + while isinstance(pattern, ast.MatchOr): + pattern = pattern.patterns[-1] + if isinstance(pattern, ast.MatchAs): had_wildcard = True self.add_arc(last_start, case_start, "the pattern on line {lineno} always matched") from_start = ArcStart(case_start, cause="the pattern on line {lineno} never matched") diff --git a/tests/test_arcs.py b/tests/test_arcs.py index d907e8c7b..1f2e50d71 100644 --- a/tests/test_arcs.py +++ b/tests/test_arcs.py @@ -1362,6 +1362,19 @@ def test_match_case_without_wildcard(self): ) assert self.stdout() == "None\nno go\ngo: n\n" + def test_absurd_wildcard(self): + # https://github.com/nedbat/coveragepy/issues/1421 + self.check_coverage("""\ + def absurd(x): + match x: + case (3 | 99 | (999 | _)): + print("default") + absurd(5) + """, + arcz=".1 15 5. .2 23 34 4.", + ) + assert self.stdout() == "default\n" + class OptimizedIfTest(CoverageTest): """Tests of if statements being optimized away."""