@@ -1333,3 +1333,73 @@ def test_wait(httpserver):
13331333 )
13341334 if self ._waiting_settings .raise_assertions and not waiting .result :
13351335 self .check_assertions ()
1336+
1337+ def iter_matching_requests (self , matcher : RequestMatcher ) -> Iterable [tuple [Request , Response ]]:
1338+ """
1339+ Queries log for matching requests.
1340+
1341+
1342+ :param matcher: the matcher object to match requests
1343+ :return: an iterator with request-response pair from the log
1344+ """
1345+
1346+ for request , response in self .log :
1347+ if matcher .match (request ):
1348+ yield (request , response )
1349+
1350+ def get_matching_requests_count (self , matcher : RequestMatcher ) -> int :
1351+ """
1352+ Queries the log for matching requests, returning the number of log
1353+ entries matching for the specified matcher.
1354+
1355+ :param matcher: the matcher object to match requests
1356+ :return: the number of log entries matching
1357+ """
1358+ return len (list (self .iter_matching_requests (matcher )))
1359+
1360+ def assert_request_made (self , matcher : RequestMatcher , * , count : int = 1 ):
1361+ """
1362+ Check the amount of log entries matching for the matcher specified. By
1363+ default it verifies that exactly one request matching for the matcher
1364+ specified. The expected count can be customized with the count kwarg
1365+ (including zero, which asserts that no requests made for the given
1366+ matcher).
1367+
1368+ :param matcher: the matcher object to match requests
1369+ :param count: the expected number of matches in the log
1370+ :return: ``None`` if the assert succeeded, raises
1371+ :py:class:`AssertionError` if not.
1372+ """
1373+
1374+ matching_count = self .get_matching_requests_count (matcher )
1375+ if matching_count != count :
1376+ similar_requests : list [Request ] = []
1377+ for request , _ in self .log :
1378+ if request .path == matcher .uri :
1379+ similar_requests .append (request )
1380+
1381+ assert_msg_lines = [
1382+ f"Matching request found { matching_count } times but expected { count } times." ,
1383+ f"Expected request: { matcher } " ,
1384+ ]
1385+
1386+ if similar_requests :
1387+ assert_msg_lines .append (f"Found { len (similar_requests )} similar request(s):" )
1388+ for request in similar_requests :
1389+ assert_msg_lines .extend (
1390+ (
1391+ "--- Similar Request Start" ,
1392+ f"Path: { request .path } " ,
1393+ f"Method: { request .method } " ,
1394+ f"Body: { request .get_data ()!r} " ,
1395+ f"Headers: { request .headers } " ,
1396+ f"Query String: { request .query_string .decode ('utf-8' )!r} " ,
1397+ "--- Similar Request End" ,
1398+ )
1399+ )
1400+ else :
1401+ assert_msg_lines .append ("No similar requests found." )
1402+
1403+ assert_msg = "\n " .join (assert_msg_lines ) + "\n "
1404+
1405+ assert matching_count == count , assert_msg
0 commit comments