Skip to content
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

Fix stream replay in validators #1678

Merged
merged 3 commits into from
Mar 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions connexion/validators/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,14 @@ def _insert_messages(
receive: Receive, *, messages: t.Iterable[t.MutableMapping[str, t.Any]]
) -> Receive:
"""Insert messages at the start of the `receive` channel."""
# Ensure that messages is an iterator so each message is replayed once.
message_iterator = iter(messages)

async def receive_() -> t.MutableMapping[str, t.Any]:
for message in messages:
return message
return await receive()
try:
return next(message_iterator)
except StopIteration:
return await receive()

return receive_

Expand Down
29 changes: 28 additions & 1 deletion tests/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import pytest
from connexion.exceptions import BadRequestProblem
from connexion.uri_parsing import Swagger2URIParser
from connexion.validators.parameter import ParameterValidator
from connexion.validators import AbstractRequestBodyValidator, ParameterValidator
from starlette.datastructures import QueryParams


Expand Down Expand Up @@ -140,3 +140,30 @@ def test_parameter_validator(monkeypatch):
with pytest.raises(BadRequestProblem) as exc:
validator.validate_request(request)
assert exc.value.detail.startswith("'x' is not one of ['a', 'b']")


async def test_stream_replay():
messages = [
{"body": b"message 1", "more_body": True},
{"body": b"message 2", "more_body": False},
]

async def receive():
return b""

wrapped_receive = AbstractRequestBodyValidator._insert_messages(
receive, messages=messages
)

replay = []
more_body = True
while more_body:
message = await wrapped_receive()
replay.append(message)
more_body = message.get("more_body", False)

assert len(replay) <= len(
messages
), "Replayed more messages than received, break out of while loop"

assert messages == replay