django_api: Extract send_event_on_commit helper.

django-stubs 4.2.1 gives transaction.on_commit a more accurate type
annotation, but this exposed that mypy can’t handle the lambda default
parameters that we use to recapture loop variables such as

    for stream_id in public_stream_ids:
        peer_user_ids = …
        event = …

        transaction.on_commit(
            lambda event=event, peer_user_ids=peer_user_ids: send_event(
                realm, event, peer_user_ids
            )
        )

https://github.com/python/mypy/issues/15459

A workaround that mypy accepts is

        transaction.on_commit(
            (
                lambda event, peer_user_ids: lambda: send_event(
                    realm, event, peer_user_ids
                )
            )(event, peer_user_ids)
        )

But that’s kind of ugly and potentially error-prone, so let’s make a
helper function for this very common pattern.

        send_event_on_commit(realm, event, peer_user_ids)

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg
2023-06-17 11:53:07 -07:00
committed by Tim Abbott
parent 77c146b8b0
commit 7657cb4a0f
22 changed files with 114 additions and 180 deletions

View File

@@ -1060,7 +1060,7 @@ class ReactionAPIEventTest(EmojiReactionBase):
"reaction_type": "unicode_emoji",
}
with self.capture_send_event_calls(expected_num_events=1) as events:
with mock.patch("zerver.actions.reactions.send_event") as m:
with mock.patch("zerver.tornado.django_api.queue_json_publish") as m:
m.side_effect = AssertionError(
"Events should be sent only after the transaction commits!"
)
@@ -1143,7 +1143,7 @@ class ReactionAPIEventTest(EmojiReactionBase):
)
with self.capture_send_event_calls(expected_num_events=1):
with mock.patch("zerver.actions.reactions.send_event") as m:
with mock.patch("zerver.tornado.django_api.queue_json_publish") as m:
m.side_effect = AssertionError(
"Events should be sent only after the transaction commits."
)