forked from your-tools/python-cli-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconftest.py
More file actions
94 lines (76 loc) · 3.06 KB
/
conftest.py
File metadata and controls
94 lines (76 loc) · 3.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import re
from typing import Any, Iterator, Optional
import pytest
import cli_ui
class MessageRecorder:
"""Helper class to tests emitted messages"""
def __init__(self) -> None:
cli_ui._MESSAGES = []
self.idx_find_next: int = 0
def start(self) -> None:
"""Start recording messages"""
cli_ui.CONFIG["record"] = True
def stop(self) -> None:
"""Stop recording messages"""
cli_ui.CONFIG["record"] = False
cli_ui._MESSAGES = []
def reset(self) -> None:
"""Reset the list"""
cli_ui._MESSAGES = []
self.idx_find_next = 0
def find(self, pattern: str) -> Optional[str]:
"""Find a message in the list of recorded message
:param pattern: regular expression pattern to use
when looking for recorded message
"""
regexp = re.compile(pattern)
for idx, message in enumerate(cli_ui._MESSAGES):
if re.search(regexp, message):
if isinstance(message, str):
self.idx_find_next = idx + 1
return message
return None
def find_after(self, pattern: str) -> Optional[str]:
"""Same as 'find', but it check any message that comes
after the last 'find'|'find_after'|'find_right_after'
:param pattern: regular expression pattern to use
when looking for recorded message
"""
regexp = re.compile(pattern)
for idx, message in enumerate(cli_ui._MESSAGES):
if idx < self.idx_find_next:
continue
if re.search(regexp, message):
if isinstance(message, str):
self.idx_find_next = idx + 1
return message
return None
def find_right_after(self, pattern: str) -> Optional[str]:
"""Same as 'find', but only check the message that is right after
the one found last time. if no message was found before, the 1st
message in buffer is checked
This is particulary usefull if we want to match only consecutive message.
Calling this function can be repeated for further consecutive message match.
"""
if len(cli_ui._MESSAGES) > self.idx_find_next:
regexp = re.compile(pattern)
message = cli_ui._MESSAGES[self.idx_find_next]
if re.search(regexp, message):
if isinstance(message, str):
self.idx_find_next += 1
return message
return None
def find_eob(self) -> bool: # find end of (the) buffer
"""If we want to be sure we are at the end of the message buffer
That means, that our last 'find' or 'find_ritht_after'
matched the very last line of the message buffer"""
if len(cli_ui._MESSAGES) == self.idx_find_next:
return True
else:
return False
@pytest.fixture
def message_recorder(request: Any) -> Iterator[MessageRecorder]:
recorder = MessageRecorder()
recorder.start()
yield recorder
recorder.stop()