Skip to content

Commit 620bf5b

Browse files
committed
refactor: flat is better than nested
1 parent 5e72961 commit 620bf5b

File tree

1 file changed

+26
-18
lines changed

1 file changed

+26
-18
lines changed

aresponses/main.py

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -102,27 +102,35 @@ def _host_matches(self, match_host):
102102
async def _find_response(self, request):
103103
host, path, path_qs, method = request.host, request.path, request.path_qs, request.method
104104
logger.info(f"Looking for match for {host} {path} {method}") # noqa
105-
i = 0
105+
i = -1
106106
for host_pattern, path_pattern, method_pattern, response, match_querystring in self._responses:
107+
i += 1
107108
if i > 0 and self._first_unordered_request is None:
108109
self._first_unordered_request = self._request_count
109-
if _text_matches_pattern(host_pattern, host):
110-
if (not match_querystring and _text_matches_pattern(path_pattern, path)) or (
111-
match_querystring and _text_matches_pattern(path_pattern, path_qs)
112-
):
113-
if _text_matches_pattern(method_pattern, method.lower()):
114-
del self._responses[i]
115-
116-
if callable(response):
117-
if asyncio.iscoroutinefunction(response):
118-
return await response(request)
119-
return response(request)
120-
121-
if isinstance(response, str):
122-
return self.Response(body=response)
123-
124-
return response
125-
i += 1
110+
111+
path_to_match = path_qs if match_querystring else path
112+
113+
if not _text_matches_pattern(host_pattern, host):
114+
continue
115+
116+
if not _text_matches_pattern(path_pattern, path_to_match):
117+
continue
118+
119+
if not _text_matches_pattern(method_pattern, method.lower()):
120+
continue
121+
122+
del self._responses[i]
123+
124+
if callable(response):
125+
if asyncio.iscoroutinefunction(response):
126+
return await response(request)
127+
return response(request)
128+
129+
if isinstance(response, str):
130+
return self.Response(body=response)
131+
132+
return response
133+
126134

127135
self._unmatched_requests.append(request)
128136

0 commit comments

Comments
 (0)