Находки в опенсорсе: Python
983 subscribers
4 photos
221 links
Легкие задачки в опенсорсе из мира Python

Чат: @opensource_findings_chat
Download Telegram
🚀 New issue to ag2ai/faststream by @melenudo
📝 Bug: auto_commit is always True in Confluent Kafka (#2610)

Describe the bug

Even if you use the deprecated autocommit subscriber parameter, or if you use the ack_policy parameter with a value other than AckPolicy.ACK_FIRST, the consumer will set enable.auto.commit to True.

How to reproduce

from asyncio import sleep
from pydantic import BaseModel, Field, NonNegativeFloat

from faststream import FastStream, Logger
from faststream.confluent import KafkaBroker


class DataBasic(BaseModel):
data: NonNegativeFloat = Field(
..., examples=[0.5], description="Float data example"
)


broker = KafkaBroker("localhost:9092")
app = FastStream(broker)


@broker.publisher("output_data")
@broker.subscriber("input_data", group_id="my-group", auto_commit=False)
async def on_input_data(msg: DataBasic, logger: Logger) -> DataBasic:
logger.info(msg)
await sleep(20)
return DataBasic(data=msg.data + 1.0)


You can run this snippet (using the deprecated
auto_commit; the same behavior can be observed if you use ack_policy=AckPolicy.ACK).

In Kafka, you will notice that the message is automatically committed before
on_input_data finishes.

You can also debug the code and observe that in the consumer:

https://github.com/ag2ai/faststream/blob/8a4c60bdae02c7632c15ff1a1d15b268da6e095d/faststream/confluent/helpers/client.py#L236

self.config always has the property enable.auto.commit to True


Expected behavior
When use
@subscriber(...,ack_policy=AckPolicy.ACK) the autocommit must be disabled (same behavior for a policy different than AckPolicy.ACK_FIRST)

Observed behavior
enable.auto.commit is always True ignoring subscriber parameters.

Environment

Running FastStream 0.6.2 with CPython 3.12.9 on Darwin


#goodfirstissue #bug

sent via relator
🚀 New issue to ag2ai/faststream by @HelgeKrueger
📝 Bug: additional "Subscribe" in docs (#2617)

Describe the bug

In the sidebar, the subscriber is called "my_subscriberSubscribe" instead of "my_subscriber"

How to reproduce

from faststream import FastStream
from faststream.rabbit import RabbitBroker


broker = RabbitBroker()

@broker.subscriber("queue", title="my_subscriber")
async def test(): ...

app = FastStream(broker)

then run uv run faststream docs serve main:app

Screenshots

🖼️Image#good_first_issue #bug

sent via relator
1
🚀 New issue to ag2ai/faststream by @jsonvot
📝 Bug: The coexistence issue between URL and virtualhost (#2652)


Describe the bug

import asyncio
from faststream.rabbit import RabbitBroker

async def pub():
broker = RabbitBroker('amqp://guest:guest@localhost:5672/', virtualhost='/domestic-aed') # 1

#broker = RabbitBroker('amqp://guest:guest@localhost:5672', virtualhost='//domestic-aed') # 2
#broker = RabbitBroker('amqp://guest:guest@localhost:5672/', virtualhost='//domestic-aed') # 3
#broker = RabbitBroker('amqp://guest:guest@localhost:5672//domestic-aed') # 4

#broker = RabbitBroker('amqp://guest:guest@localhost:5672', virtualhost='/domestic-aed') # 5
async with broker:
await broker.publish(
"Hi!",
queue="test-queue",
exchange="test-exchange"
)
asyncio.run(pub())

In version v0.5.33, the first method works properly, and the trailing slash (/) at the end of the URL cannot be omitted. However, in versions >=0.5.34, due to additional handling of virtualhost, only parameter-based formats like 2, 3, 4 and 5 are supported.
I believe method 5 is the most intuitive and should be handled correctly, but it is currently treated as an invalid format. Using this method will result in the following error:
🖼️Image

Environment
faststream[rabbit]>=0.5.34


#bug #good_first_issue #faststream #ag2ai
sent via relator
🚀 New issue to ag2ai/faststream by @GrigoriyKuzevanov
📝 Bug: min_idle_time ignored when group and consumer are specified (#2678)


Describe the bug
When a StreamSub has both 'group' and 'consumer', and 'min_idle_time' specified, Faststream uses 'XREADGROUP' instead of 'XAUTOCALIM'

How to reproduce
Include source code:

from faststream import FastStream
from faststream.redis import RedisBroker, StreamSub

broker = RedisBroker("redis://localhost:6379")

@broker.subscriber(
stream=StreamSub(
"orders",
group="processors",
consumer="claimer",
min_idle_time=10000, # Should trigger XAUTOCLAIM
)
)
async def claiming_handler(msg):
print("Should use XAUTOCLAIM, but uses XREADGROUP")


app = FastStream(broker)

Redis MONITOR output shows:

XREADGROUP GROUP processors claimer BLOCK 100 STREAMS orders >

Expected behavior

XAUTOCLAIM orders processors claimer 10000 0-0 COUNT 1

Observed behavior
I suppose that a root cause in faststream/redis/subscriber/use_cases/stream_subscriber, method _StreamHandlerMixin.start():

if stream.group and stream.consumer:  # ← Checked FIRST
# Uses XREADGROUP
...
elif self.stream_sub.min_idle_time is None:
# Uses XREAD
...
else:
# Uses XAUTOCLAIM ← Never reached when group is set!
...

Or i just misunderstand the logic.

Environment
Running FastStream 0.6.3 with CPython 3.12.3 on Linux


#bug #good_first_issue #faststream #ag2ai
sent via relator
🚀 New issue to wemake-services/wemake-python-styleguide by @luminoso
📝 False positive for WPS457 when using asyncio to control loops (#3573)


What's wrong

For the code:

import asyncio


async def infinite_loop() -> None:
try:
while True:
await asyncio.sleep(1)
print("I'm alive. And doing work.")
except asyncio.CancelledError:
print("Loop cancelled")


t = asyncio.create_task(infinite_loop())
await asyncio.sleep(5)
t.cancel()

WPS457: Found an infinite while loop is raised. But infinite loop is being handled. Just not within the while loop.

How it should be

Not to raise WPS457.

Not 100% sure here if it is the best practice or not.
Also probably the solution is too complex and is just easier to add a noqa in the code.

Flake8 version and plugins

{
"platform": {
"python_implementation": "CPython",
"python_version": "3.13.9",
"system": "Linux"
},
"plugins": [
{
"plugin": "mccabe",
"version": "0.7.0"
},
{
"plugin": "pycodestyle",
"version": "2.14.0"
},
{
"plugin": "pyflakes",
"version": "3.4.0"
},
{
"plugin": "wemake-python-styleguide",
"version": "1.4.0"
}
],
"version": "7.3.0"
}

pip information

pip 25.3 from /var/home/luminoso/.local/lib/python3.14/site-packages/pip (python 3.14)
anyio==4.11.0
archspec==0.2.5
argcomplete==3.6.3
asttokens==3.0.0
attrs==25.4.0
boto3==1.42.4
botocore==1.42.4
Brlapi==0.8.7
Brotli==1.1.0
certifi==2025.7.9
charset-normalizer==3.4.3
click==8.1.7
conda==25.11.0
conda-package-handling==2.4.0
conda_package_streaming==0.11.0
cupshelpers==1.0
dasbus==1.7
dbus-python==1.4.0
decorator==5.2.1
distro==1.9.0
executing==2.2.1
fedora-third-party==0.10
file-magic==0.4.0
frozendict==2.4.6
gbinder-python==1.1.2
h11==0.16.0
httpcore==1.0.9
httpx==0.28.1
idna==3.10
ipython==8.37.0
jedi==0.19.2
jmespath==1.0.1
jsonpatch==1.33
jsonpointer==2.4
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
langtable==0.0.69
louis==3.33.0
matplotlib-inline==0.1.7
menuinst==2.3.1
mercurial==7.1.1
mutagen==1.47.0
nftables==0.1
olefile==0.47
packaging==25.0
parso==0.8.5
pexpect==4.9.0
pillow==11.3.0
platformdirs==4.2.2
pluggy==1.6.0
progressbar2==4.5.0
prompt_toolkit==3.0.41
psutil==7.0.0
ptyprocess==0.7.0
pure_eval==0.2.3
PyAudio==0.2.13
pycairo==1.28.0
pyclip==0.7.0
pycosat==0.6.6
pycryptodomex==3.23.0
pycups==2.0.4
pyenchant==3.2.2
pygdbmi==0.11.0.0
Pygments==2.19.1
PyGObject==3.54.5
pyinotify==0.9.6
PySocks==1.7.1
python-dateutil==2.9.0.post0
python-linux-procfs==0.7.3
python-utils==3.9.1
pyudev==0.24.3
pyxdg==0.27
PyYAML==6.0.2
pyynl @ file:///builddir/build/BUILD/kernel-6.17.10-build/kernel-6.17.10/linux-6.17.10-300.fc43.x86_64/tools/net/ynl
RapidFuzz==3.12.2
referencing==0.36.2
regex==2025.10.23
requests==2.32.5
rpds-py==0.27.0
rpm==6.0.0
rpmautospec==0.8.3
rpmautospec-core==0.1.5
ruamel.yaml==0.18.16
ruamel.yaml.clib==0.2.12
s3transfer==0.16.0
selinux @ file:///builddir/build/BUILD/libselinux-3.9-build/libselinux-3.9/src
sentry-sdk==2.35.0
sepolicy @ file:///builddir/build/BUILD/policycoreutils-3.9-build/selinux-3.9/python/sepolicy
setools==4.6.0
setuptools==78.1.1
six==1.17.0
sniffio==1.3.1
sos==4.10.1
stack_data==0.6.3
tqdm==4.67.1
traitlets==5.14.3
typing_extensions==4.15.0
urllib3==2.5.0
wcwidth==0.2.13
websockets==15.0.1
yt-dlp==2025.10.22
zstandard==0.25.0

OS information

$ lsb_release -a
LSB Version: n/a
Distributor ID: Fedora
Description: Fedora Linux 43.20251209.0 (Kinoite)
Release: 43
Codename: n/a


#bug #help_wanted #levelstarter #good_first_issue #wemake_python_styleguide #wps
sent via relator
1
🚀 New issue to ag2ai/faststream by @esinevgeny
📝 Bug: ValueError while calling redis client.xautoclaim (#2736)


Describe the bug
ValueError while calling xautoclaim

How to reproduce
Use the next route and launch the faststream, if there are messages with PENDING status in stream the issue will be observed

@broker.subscriber(
stream=StreamSub("test:test", group="workers",
consumer="worker",
min_idle_time=5000)
)
async def worker(msg: RedisStreamMessage, redis: Redis):
logger.error(f"Claim {msg.correlation_id}")
await msg.ack(redis=redis, group="workers")

Actual
Traceback (most recent call last):
File "/venv/lib64/python3.12/site-packages/faststream/redis/subscriber/usecases/basic.py", line 91, in _consume
await self._get_msgs(*args)
File "/venv/lib64/python3.12/site-packages/faststream/redis/subscriber/usecases/stream_subscriber.py", line 341, in _get_msgs
for stream_name, msgs in await read(self.last_id):
^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/lib64/python3.12/site-packages/faststream/redis/subscriber/usecases/stream_subscriber.py", line 140, in read
(next_id, messages, _) = stream_message
^^^^^^^^^^^^^^^^^^^^^^
ValueError: not enough values to unpack (expected 3, got 2)

Environment
Running FastStream 0.6.5 with CPython 3.12.11 on Linux
redis 7.1.0

Also checked on redis 5.3.0


#bug #good_first_issue #faststream #ag2ai
sent via relator
🚀 New issue to wemake-services/django-modern-rest by @sobolevn
📝 Fix `Sequence[SyncAuth | AsyncAuth]` to be `Sequence[SyncAuth] | Sequence[AsyncAuth]` (#408)


I've made a mistake in modify and validate typing:

django-modern-rest/django_modern_rest/endpoint.py

Line 411 in 65d7638

I used Sequence[SyncAuth | AsyncAuth] instead of Sequence[SyncAuth] | Sequence[AsyncAuth].
Here's the difference: https://mypy-play.net/?mypy=latest&python=3.12&flags=strict&gist=487fad8c5bdaa2e7d2b4e84a3fa25a6d

We need to fix the typings of @modify and @validate and add a typesafety/ test that providing both sync and async auth at the same time is a type error.

This issue is created for people who make their first (!) contribution :)
Please, let them feel welcome!


#bug #good_first_issue #help_wanted #django_modern_rest
sent via relator
🚀 New issue to wemake-services/wemake-python-styleguide by @sobolevn
📝 False positive for `WPS430` with whitelisted name (#3589)


def wrap_handler(
method: _MethodSyncHandler | _MethodAsyncHandler,
) -> SyncErrorHandlerT | AsyncErrorHandlerT:
if inspect.iscoroutinefunction(method):

@wraps(method)
async def decorator(
endpoint: 'Endpoint',
controller: 'Controller[BaseSerializer]',
exc: Exception,
) -> HttpResponse:
return await method( # type: ignore[no-any-return]
controller.active_blueprint,
endpoint,
controller,
exc,
)

else:

@wraps(method)
def decorator(
endpoint: 'Endpoint',
controller: 'Controller[BaseSerializer]',
exc: Exception,
) -> HttpResponse:
return method( # type: ignore[return-value]
controller.active_blueprint,
endpoint,
controller,
exc,
)

return decorator

This code falsy raises two WPS430 violations.

  69:9     WPS430 Found nested function: factory
async def factory(
^

84:9 WPS430 Found nested function: factory
def factory(
^

But, the name is correct. decorator name is in whitelist of names. This is a false positive.
We need to fix it and add a test case.


#bug #help_wanted #levelstarter #good_first_issue #wemake_python_styleguide #wps
sent via relator
🚀 New issue to wemake-services/wemake-python-styleguide by @sobolevn
📝 `WPS617` false positive with keyword args (#3596)


self._media_by_precedence = sorted(
(
media_type
for parser in self._parsers.values()
if (media_type := MediaType(parser.content_type)).quality != 0
),
key=lambda media: (media.specificity, media.quality), # noqa: WPS617
reverse=True,
)

It says:

django_modern_rest/negotiation.py

52:17 WPS617 Found lambda assigned as an attribute
key=lambda media: (media.specificity, media.quality),
^

Which is clearly a bug, it is a named param, not an attribute.
PRs are welcome, this is easy to fix.


#bug #help_wanted #levelstarter #good_first_issue #wemake_python_styleguide #wps
sent via relator
🚀 New issue to ag2ai/faststream by @yann-combarnous
📝 Bug: AsyncAPI documentation fails when Confluent uses oauth bearer authentication (#2774)


Describe the bug
When using Confluent Kafka with oauthbearer authentication, the generated AsyncAPI schema is:

 "securitySchemes":{"oauthbearer":{"type":"oauth2","$ref":""}}

An empty $ref: "" causes the AsyncAPI React component to attempt file resolution via readFile. This is a FastStream bug in schema generation.

How to reproduce
Include source code:

from faststream.confluent import KafkaBroker

broker = KafkaBroker(
config={ ...config... },
security=SASLOAuthBearer(use_ssl=True)
)
...

Expected behavior
AsyncAPI documentation is correctly generated.

Observed behavior
It fails with a file cannot be read error.

Screenshots
If applicable, attach screenshots to help illustrate the problem.

Environment
Running FastStream 0.6.5 with CPython 3.13.11 on Darwin

Additional context


#bug #good_first_issue #faststream #ag2ai
sent via relator
🚀 New issue to wemake-services/wemake-python-styleguide by @sobolevn
📝 `WPS457` false positive with `while` in `try` / `except` (#3603)


I have the following code:

def factory() -> Iterator[bytes]:
try:
while True: # noqa: WPS457
yield async_to_sync(async_anext)(iterator)
except StopAsyncIteration:
pass

It should not raise WPS457, because while is in try / except.
It can clearly raise and we handle the error. So, it is not infinite.

PRs are welcome! 👍


#bug #help_wanted #levelstarter #good_first_issue #wemake_python_styleguide #wps
sent via relator
🚀 New issue to wemake-services/django-modern-rest by @sobolevn
📝 Test `Controller[BaseSerializer]` corner case (#749)


Currently we don't test that Controller[BaseSerializer] is not a valid way of creating a controller class.
It must accept subclasses for BaseSerializer, but not BaseSerializer itself.

We need:

• a test case here https://github.com/wemake-services/django-modern-rest/blob/master/tests/test_unit/test_controllers/test_extend_controller.py
• a possible fix to raise an error when BaseSerializer is given to a controller here:

 django-modern-rest/dmr/controller.py

 Lines 157 to 164 in acb9c17

This is a very easy task, so new contributors are very welcome!


#bug #good_first_issue #help_wanted #django_modern_rest
sent via relator
🚀 New issue to ag2ai/faststream by @hmvp
📝 Bug: topic patterns are not correctly documented (#2804)


Describe the bug
When using a pattern for a kafka topic the generated asyncapi spec (and docs) does not include that handler

How to reproduce
With something along the lines of:

broker = KafkaBroker(...)

router = KafkaRouter()

@router.subscriber(pattern="some.wildcard.topic.*")
def handle_event(event: Event): ...

broker.include_router(router)

app = AsgiFastStream(
broker,
asyncapi_path="/docs",
)

Expected behavior
The subscriber is included in the asyncapi spec and docs. As far as I can see the asyncapi spec actually allows for this even when using Path variables.

Observed behavior
The asyncapi docs don't contain that subscriber.

Screenshots

Environment
Running FastStream 0.6.7 with CPython 3.14.0 on Linux

Additional context


#bug #good_first_issue #faststream #ag2ai
sent via relator
🚀 New issue to ag2ai/faststream by @dumpler
📝 Bug: Logger not properly passed to Confluent Kafka Producer and AdminClient (#2691)


Describe the bug

There are two related issues with logger configuration in the Confluent Kafka components:

1.

 Late Logger Setup in AsyncConfluentProducer

 In faststream/confluent/helpers/client.py at line 46, the Producer object is created before the _setup() method is called for loger_state. This results in the Producer receiving a NoSetLoggerObject instead of the intended logger passed during initialization.

2.

 Missing Logger in AdminClient
 The AdminClient in AdminService does not accept a logger parameter, even though it should. Currently, only the configuration is passed, leaving the AdminClient without proper logging.

How to reproduce
Include source code:

import logging

import uvicorn
from fastapi import FastAPI
from faststream.confluent.fastapi import KafkaRouter

logger = logging.getLogger("faststream")

router = KafkaRouter(
bootstrap_servers="kafka:9092",
enable_idempotence=True,
allow_auto_create_topics=False,
schema_url="/asyncapi",
include_in_schema=True,
logger=logger,
)

app = FastAPI()
app.include_router(router)

uvicorn.run(app, host="0.0.0.0", port=8000)

Expected behavior

1. The Producer in AsyncConfluentProducer should use the logger passed to KafkaRouter.
2. The AdminClient should inherit the same logger as other components.

Observed behavior

1. The Producer uses NoSetLoggerObject instead of the provided logger.
2. The AdminClient lacks logger configuration, leading to potential silent failures or inadequate logging.

Environment
Running FastStream 0.6.3 with CPython 3.13.1 on Linux


#bug #good_first_issue #faststream #ag2ai
sent via relator
🚀 New issue to wemake-services/django-modern-rest by @LesPrimus
📝 UnsolvableAnnotationsError when subclassing a concrete Controller subclass` (#873)


What's wrong?

Bug: UnsolvableAnnotationsError when subclassing a concrete Controller subclass

Description

When creating an intermediate concrete controller class and then subclassing it,
__init_subclass__ raises UnsolvableAnnotationsError even though the serializer
is already resolved on the parent.

Reproduction

from dmr import Controller
from dmr.plugins.pydantic import PydanticSerializer
from dmr.serializer import BaseSerializer


class BaseController[T: BaseSerializer](Controller[T]):
pass


class PydanticController(BaseController[PydanticSerializer]):
pass


# This raises UnsolvableAnnotationsError
class UserController(PydanticController):
def get(self) -> ...:
...

Error

dmr.exceptions.UnsolvableAnnotationsError: Type args () are not correct for <class 'UserController'>,
at least 1 type arg must be provided

Expected behavior

UserController should inherit the serializer from its concrete parent PydanticController,
which already has serializer = PydanticSerializer set.


--

Thanks for the awesome library, I just started exploring it and I'm really enjoying it so far!

--

### How it should be?

Subclassing a concrete `Controller` subclass (one that already has a resolved serializer)
should work without requiring the type argument to be re-specified.

`UserController(PydanticController)` should behave the same as `UserController(BaseController[PydanticSerializer])`.

### Used versions

- `django-modern-rest==0.5.0`
- `Python 3.14.0`

### OS information

- `Linux tuxedo-stellaris 6.17.0-111019-tuxedo x86_64 (Ubuntu 24.04)`


#bug #good_first_issue #help_wanted #django_modern_rest
sent via relator
🚀 New issue to wemake-services/django-modern-rest by @Peopl3s
📝 TagSchema and RoleSchema do not enforce max_length, causing unhandled DB errors (#944)


What's wrong?

The Tag and Role Django models define name = CharField(max_length=100), but the corresponding Pydantic schemas accept any-length strings.

class TagSchema(pydantic.BaseModel):
name: str <!-----------------------------HERE

class RoleSchema(pydantic.BaseModel):
name: str <!-----------------------------HERE

When a client sends a name longer than 100 characters, Pydantic validation passes (HTTP 422 is never raised), and the value reaches the database layer where PostgreSQL raises DataError: value too long for type character varying(100). This results in an unhandled 500 instead of a proper 422 validation error. On SQLite the value is silently stored without truncation, masking the bug in tests.

How it should be?

Add max_length constraints to match the model definition:

                                                                                                                                                                                                            class TagSchema(pydantic.BaseModel):                  
name: str = Field(max_length=100)
class RoleSchema(pydantic.BaseModel):
name: str = Field(max_length=100)

Used versions

0.7.0

OS information

MacOS


#bug #good_first_issue #help_wanted #django_modern_rest
sent via relator
🚀 New issue to ag2ai/faststream by @zueve
📝 Bug: (#2868)


Describe the bug
Can't forward client_rack to aiokafka consumer through FastStream Kafka API.

How to reproduce
Include source code:

from faststream import FastStream

from faststream.kafka import KafkaBroker

# Attempt to configure at broker level

broker = KafkaBroker(
"localhost:9092",
client_rack="us-east-1a", # not supported
)
app = FastStream(broker)

And/Or steps to reproduce the behaviour:

1. Create a KafkaBroker.
2. Try to pass client_rack to the broker constructor.
3. Observe that the parameter is not accepted.
4. There is no alternative way to configure it via subscriber(...) either.

Expected behavior
KafkaBroker should allow passing client_rack (or generic consumer kwargs) and forward it to the underlying aiokafka.AIOKafkaConsumer.

Observed behavior
client_rack is not supported in KafkaBroker constructor, nor in subscriber configuration, so it cannot be passed to aiokafka.

Screenshots
N/A.

Environment
Running FastStream 0.6.7 with CPython 3.14.5 on Linux

Additional context
aiokafka.AIOKafkaConsumer supports client_rack since 0.14.0 version


#bug #good_first_issue #aiokafka #faststream #ag2ai
sent via relator
🚀 New issue to wemake-services/django-modern-rest by @sobolevn
📝 Flaky test: `test_redis_sync_leaky_bucket` (#1043)


Output:

 ______________________ test_redis_sync_leaky_bucket[True] ______________________
tests/test_integration/test_throttling/test_backends/test_redis_backend/test_redis_backend.py:110: in test_redis_sync_leaky_bucket
assert response.status_code == HTTPStatus.TOO_MANY_REQUESTS
E assert 200 == <HTTPStatus.TOO_MANY_REQUESTS: 429>
E + where 200 = <HttpResponse status_code=200, "application/json">.status_code
E + and <HTTPStatus.TOO_MANY_REQUESTS: 429> = HTTPStatus.TOO_MANY_REQUESTS
================================ tests coverage ================================

=========================== short test summary info ============================
FAILED tests/test_integration/test_throttling/test_backends/test_redis_backend/test_redis_backend.py::test_redis_sync_leaky_bucket[True] - assert 200 == <HTTPStatus.TOO_MANY_REQUESTS: 429>
+ where 200 = <HttpResponse status_code=200, "application/json">.status_code
+ and <HTTPStatus.TOO_MANY_REQUESTS: 429> = HTTPStatus.TOO_MANY_REQUESTS
============ 1 failed, 2479 passed, 10 skipped in 243.50s (0:04:03) ============


It fails from time to time: https://github.com/wemake-services/django-modern-rest/actions/runs/26490639540/job/78007463856?pr=1042


#bug #good_first_issue #help_wanted #django_modern_rest
sent via relator
🚀 New issue to wemake-services/django-modern-rest by @sobolevn
📝 Flaky test: `test_sse_ping_with_last` (#1046)


Happened on mypyc wheels cp314-macosx_x86_64

  =================================== FAILURES ===================================
___________________________ test_sse_ping_with_last ____________________________

dmr_async_rf = <dmr.test.DMRAsyncRequestFactory object at 0x114ddad60>

@pytest.mark.asyncio
async def test_sse_ping_with_last(
dmr_async_rf: DMRAsyncRequestFactory,
) -> None:
"""Ensures that valid sse produces valid results."""
request = dmr_async_rf.post('/whatever/', data={'produce_last': True})

response = await dmr_async_rf.wrap(_PingSSE.as_view()(request))

assert isinstance(response, StreamingResponse)
assert response.streaming
assert response.status_code == HTTPStatus.OK
assert response.headers == {
'Cache-Control': 'no-cache',
'Content-Type': 'text/event-stream',
'X-Accel-Buffering': 'no',
'Connection': 'keep-alive',
}
> assert await get_streaming_content(response) == (
b'data: 1\r\n'
b'\r\n'
b': ping\r\n'
b'\r\n'
b'data: 2\r\n'
b'\r\n'
b': ping\r\n'
b'\r\n'
b': ping\r\n'
b'\r\n'
b'data: 3\r\n'
b'\r\n'
)
E AssertionError: assert b'data: 1\r\n...ta: 3\r\n\r\n' == b'data: 1\r\n...ta: 3\r\n\r\n'
E
E At index 42 diff: b'd' != b':'
E
E Full diff:
E - (b'data: 1\r\n\r\n: ping\r\n\r\ndata: 2\r\n\r\n: ping\r\n\r\n: ping\r\n\r\ndata'
E ? --------------
E + (b'data: 1\r\n\r\n: ping\r\n\r\ndata: 2\r\n\r\n: ping\r\n\r\ndata: 3\r\n\r\n')
E ? +++++++++++ +
E - b': 3\r\n\r\n')

For some reason data: 3 was not sent.
Let's fix it.


#bug #good_first_issue #help_wanted #django_modern_rest
sent via relator