-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
pytester: LineMatcher: typing, docs, consecutive line matching #6653
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
09a0e45
testing/test_pytester.py: cosmetics
blueyed b10ab02
Use TypeError instead of AssertionError for no sequence
blueyed 2681b0a
typing: pytester: LineMatcher
blueyed 50f81db
revisit/improve docstrings
blueyed 5256542
pytester.LineMatcher: add support for matching lines consecutively
blueyed File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Add support for matching lines consecutively with :attr:`LineMatcher <_pytest.pytester.LineMatcher>`'s :func:`~_pytest.pytester.LineMatcher.fnmatch_lines` and :func:`~_pytest.pytester.LineMatcher.re_match_lines`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -413,8 +413,8 @@ class RunResult: | |
def __init__( | ||
self, | ||
ret: Union[int, ExitCode], | ||
outlines: Sequence[str], | ||
errlines: Sequence[str], | ||
outlines: List[str], | ||
errlines: List[str], | ||
duration: float, | ||
) -> None: | ||
try: | ||
|
@@ -1327,49 +1327,32 @@ class LineMatcher: | |
|
||
The constructor takes a list of lines without their trailing newlines, i.e. | ||
``text.splitlines()``. | ||
|
||
""" | ||
|
||
def __init__(self, lines): | ||
def __init__(self, lines: List[str]) -> None: | ||
self.lines = lines | ||
self._log_output = [] | ||
self._log_output = [] # type: List[str] | ||
|
||
def str(self): | ||
"""Return the entire original text.""" | ||
return "\n".join(self.lines) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This was moved to the end, otherwise |
||
|
||
def _getlines(self, lines2): | ||
def _getlines(self, lines2: Union[str, Sequence[str], Source]) -> Sequence[str]: | ||
if isinstance(lines2, str): | ||
lines2 = Source(lines2) | ||
if isinstance(lines2, Source): | ||
lines2 = lines2.strip().lines | ||
return lines2 | ||
|
||
def fnmatch_lines_random(self, lines2): | ||
"""Check lines exist in the output using in any order. | ||
|
||
Lines are checked using ``fnmatch.fnmatch``. The argument is a list of | ||
lines which have to occur in the output, in any order. | ||
|
||
def fnmatch_lines_random(self, lines2: Sequence[str]) -> None: | ||
"""Check lines exist in the output in any order (using :func:`python:fnmatch.fnmatch`). | ||
""" | ||
self._match_lines_random(lines2, fnmatch) | ||
|
||
def re_match_lines_random(self, lines2): | ||
"""Check lines exist in the output using ``re.match``, in any order. | ||
|
||
The argument is a list of lines which have to occur in the output, in | ||
any order. | ||
|
||
def re_match_lines_random(self, lines2: Sequence[str]) -> None: | ||
"""Check lines exist in the output in any order (using :func:`python:re.match`). | ||
""" | ||
self._match_lines_random(lines2, lambda name, pat: re.match(pat, name)) | ||
|
||
def _match_lines_random(self, lines2, match_func): | ||
"""Check lines exist in the output. | ||
|
||
The argument is a list of lines which have to occur in the output, in | ||
any order. Each line can contain glob whildcards. | ||
self._match_lines_random(lines2, lambda name, pat: bool(re.match(pat, name))) | ||
|
||
""" | ||
def _match_lines_random( | ||
self, lines2: Sequence[str], match_func: Callable[[str, str], bool] | ||
) -> None: | ||
lines2 = self._getlines(lines2) | ||
for line in lines2: | ||
for x in self.lines: | ||
|
@@ -1380,46 +1363,67 @@ def _match_lines_random(self, lines2, match_func): | |
self._log("line %r not found in output" % line) | ||
raise ValueError(self._log_text) | ||
|
||
def get_lines_after(self, fnline): | ||
def get_lines_after(self, fnline: str) -> Sequence[str]: | ||
"""Return all lines following the given line in the text. | ||
|
||
The given line can contain glob wildcards. | ||
|
||
""" | ||
for i, line in enumerate(self.lines): | ||
if fnline == line or fnmatch(line, fnline): | ||
return self.lines[i + 1 :] | ||
raise ValueError("line %r not found in output" % fnline) | ||
|
||
def _log(self, *args): | ||
def _log(self, *args) -> None: | ||
self._log_output.append(" ".join(str(x) for x in args)) | ||
|
||
@property | ||
def _log_text(self): | ||
def _log_text(self) -> str: | ||
return "\n".join(self._log_output) | ||
|
||
def fnmatch_lines(self, lines2): | ||
"""Search captured text for matching lines using ``fnmatch.fnmatch``. | ||
def fnmatch_lines( | ||
self, lines2: Sequence[str], *, consecutive: bool = False | ||
) -> None: | ||
"""Check lines exist in the output (using :func:`python:fnmatch.fnmatch`). | ||
|
||
The argument is a list of lines which have to match and can use glob | ||
wildcards. If they do not match a pytest.fail() is called. The | ||
matches and non-matches are also shown as part of the error message. | ||
|
||
:param lines2: string patterns to match. | ||
:param consecutive: match lines consecutive? | ||
""" | ||
__tracebackhide__ = True | ||
self._match_lines(lines2, fnmatch, "fnmatch") | ||
self._match_lines(lines2, fnmatch, "fnmatch", consecutive=consecutive) | ||
|
||
def re_match_lines(self, lines2): | ||
"""Search captured text for matching lines using ``re.match``. | ||
def re_match_lines( | ||
self, lines2: Sequence[str], *, consecutive: bool = False | ||
) -> None: | ||
"""Check lines exist in the output (using :func:`python:re.match`). | ||
|
||
The argument is a list of lines which have to match using ``re.match``. | ||
If they do not match a pytest.fail() is called. | ||
|
||
The matches and non-matches are also shown as part of the error message. | ||
|
||
:param lines2: string patterns to match. | ||
:param consecutive: match lines consecutively? | ||
""" | ||
__tracebackhide__ = True | ||
self._match_lines(lines2, lambda name, pat: re.match(pat, name), "re.match") | ||
self._match_lines( | ||
lines2, | ||
lambda name, pat: bool(re.match(pat, name)), | ||
"re.match", | ||
consecutive=consecutive, | ||
) | ||
|
||
def _match_lines(self, lines2, match_func, match_nickname): | ||
def _match_lines( | ||
self, | ||
lines2: Sequence[str], | ||
match_func: Callable[[str, str], bool], | ||
match_nickname: str, | ||
*, | ||
consecutive: bool = False | ||
) -> None: | ||
"""Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``. | ||
|
||
:param list[str] lines2: list of string patterns to match. The actual | ||
|
@@ -1429,28 +1433,40 @@ def _match_lines(self, lines2, match_func, match_nickname): | |
pattern | ||
:param str match_nickname: the nickname for the match function that | ||
will be logged to stdout when a match occurs | ||
:param consecutive: match lines consecutively? | ||
""" | ||
assert isinstance(lines2, collections.abc.Sequence) | ||
if not isinstance(lines2, collections.abc.Sequence): | ||
raise TypeError("invalid type for lines2: {}".format(type(lines2).__name__)) | ||
lines2 = self._getlines(lines2) | ||
lines1 = self.lines[:] | ||
nextline = None | ||
extralines = [] | ||
__tracebackhide__ = True | ||
wnick = len(match_nickname) + 1 | ||
started = False | ||
for line in lines2: | ||
nomatchprinted = False | ||
while lines1: | ||
nextline = lines1.pop(0) | ||
if line == nextline: | ||
self._log("exact match:", repr(line)) | ||
started = True | ||
break | ||
elif match_func(nextline, line): | ||
self._log("%s:" % match_nickname, repr(line)) | ||
self._log( | ||
"{:>{width}}".format("with:", width=wnick), repr(nextline) | ||
) | ||
started = True | ||
break | ||
else: | ||
if consecutive and started: | ||
msg = "no consecutive match: {!r}".format(line) | ||
self._log(msg) | ||
self._log( | ||
"{:>{width}}".format("with:", width=wnick), repr(nextline) | ||
) | ||
self._fail(msg) | ||
if not nomatchprinted: | ||
self._log( | ||
"{:>{width}}".format("nomatch:", width=wnick), repr(line) | ||
|
@@ -1464,23 +1480,27 @@ def _match_lines(self, lines2, match_func, match_nickname): | |
self._fail(msg) | ||
self._log_output = [] | ||
|
||
def no_fnmatch_line(self, pat): | ||
def no_fnmatch_line(self, pat: str) -> None: | ||
"""Ensure captured lines do not match the given pattern, using ``fnmatch.fnmatch``. | ||
|
||
:param str pat: the pattern to match lines. | ||
""" | ||
__tracebackhide__ = True | ||
self._no_match_line(pat, fnmatch, "fnmatch") | ||
|
||
def no_re_match_line(self, pat): | ||
def no_re_match_line(self, pat: str) -> None: | ||
"""Ensure captured lines do not match the given pattern, using ``re.match``. | ||
|
||
:param str pat: the regular expression to match lines. | ||
""" | ||
__tracebackhide__ = True | ||
self._no_match_line(pat, lambda name, pat: re.match(pat, name), "re.match") | ||
self._no_match_line( | ||
pat, lambda name, pat: bool(re.match(pat, name)), "re.match" | ||
) | ||
|
||
def _no_match_line(self, pat, match_func, match_nickname): | ||
def _no_match_line( | ||
self, pat: str, match_func: Callable[[str, str], bool], match_nickname: str | ||
) -> None: | ||
"""Ensure captured lines does not have a the given pattern, using ``fnmatch.fnmatch`` | ||
|
||
:param str pat: the pattern to match lines | ||
|
@@ -1501,8 +1521,12 @@ def _no_match_line(self, pat, match_func, match_nickname): | |
self._log("{:>{width}}".format("and:", width=wnick), repr(line)) | ||
self._log_output = [] | ||
|
||
def _fail(self, msg): | ||
def _fail(self, msg: str) -> None: | ||
__tracebackhide__ = True | ||
log_text = self._log_text | ||
self._log_output = [] | ||
pytest.fail(log_text) | ||
|
||
def str(self) -> str: | ||
"""Return the entire original text.""" | ||
return "\n".join(self.lines) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This has to be a list, since
pop
is used.