22from typing import Any , Iterator , Optional
33
44import pytest
5-
65import cli_ui
76
8-
97class MessageRecorder :
108 """Helper class to tests emitted messages"""
119
1210 def __init__ (self ) -> None :
1311 cli_ui ._MESSAGES = []
12+ self .idx_find_next : int = 0
1413
1514 def start (self ) -> None :
1615 """Start recording messages"""
@@ -24,6 +23,7 @@ def stop(self) -> None:
2423 def reset (self ) -> None :
2524 """Reset the list"""
2625 cli_ui ._MESSAGES = []
26+ self .idx_find_next = 0
2727
2828 def find (self , pattern : str ) -> Optional [str ]:
2929 """Find a message in the list of recorded message
@@ -32,11 +32,57 @@ def find(self, pattern: str) -> Optional[str]:
3232 when looking for recorded message
3333 """
3434 regexp = re .compile (pattern )
35- for message in cli_ui ._MESSAGES :
35+ for idx , message in enumerate ( cli_ui ._MESSAGES ) :
3636 if re .search (regexp , message ):
37- return message
37+ if isinstance (message , str ):
38+ self .idx_find_next = idx + 1
39+ return message
3840 return None
3941
42+ def find_after (self , pattern : str ) -> Optional [str ]:
43+ """Same as 'find', but it check any message that comes
44+ after the last 'find'|'find_after'|'find_right_after'
45+
46+ :param pattern: regular expression pattern to use
47+ when looking for recorded message
48+ """
49+ regexp = re .compile (pattern )
50+ for idx , message in enumerate (cli_ui ._MESSAGES ):
51+ if idx < self .idx_find_next :
52+ continue
53+ if re .search (regexp , message ):
54+ if isinstance (message , str ):
55+ self .idx_find_next = idx + 1
56+ return message
57+ return None
58+
59+ def find_right_after (self , pattern : str ) -> Optional [str ]:
60+ """Same as 'find', but only check the message that is right after
61+ the one found last time. if no message was found before, the 1st
62+ message in buffer is checked
63+
64+ This is particulary usefull if we want to match only consecutive message.
65+ Calling this function can be repeated for further consecutive message match.
66+ """
67+ if len (cli_ui ._MESSAGES ) > self .idx_find_next :
68+ regexp = re .compile (pattern )
69+ message = cli_ui ._MESSAGES [self .idx_find_next ]
70+ if re .search (regexp , message ):
71+ if isinstance (message , str ):
72+ self .idx_find_next += 1
73+ return message
74+ return None
75+
76+ def find_eob (self ) -> bool : # find end of (the) buffer
77+ """If we want to be sure we are at the end of the message buffer
78+
79+ That means, that our last 'find' or 'find_ritht_after'
80+ matched the very last line of the message buffer"""
81+ if len (cli_ui ._MESSAGES ) == self .idx_find_next :
82+ return True
83+ else :
84+ return False
85+
4086
4187@pytest .fixture
4288def message_recorder (request : Any ) -> Iterator [MessageRecorder ]:
0 commit comments