Skip to content

Commit c64522d

Browse files
committed
add tests for Task reentrancy and call_sync
1 parent a8d0f7f commit c64522d

1 file changed

Lines changed: 58 additions & 7 deletions

File tree

tests/test_qeventloop.py

Lines changed: 58 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -791,22 +791,73 @@ async def mycoro():
791791
loop.run_until_complete(mycoro())
792792
assert not loop.is_running()
793793

794+
def test_task_recursion_fails(loop, application):
795+
"""Re-entering the event loop from a Task will fail if there is another
796+
runnable task."""
797+
async_called = False
798+
main_called = False
799+
800+
async def async_job():
801+
nonlocal async_called
802+
async_called = True
794803

795-
def test_call_sync(loop):
796-
"""Verify that call_sync works as expected."""
797-
called = False
804+
def sync_callback():
805+
asyncio.create_task(async_job())
806+
assert not async_called
807+
application.processEvents()
808+
assert not async_called
809+
return 1
810+
811+
async def main():
812+
nonlocal main_called
813+
res = sync_callback()
814+
assert res == 1
815+
main_called = True
816+
817+
exceptions= []
818+
loop.set_exception_handler(lambda loop, context: exceptions.append(context))
819+
820+
loop.run_until_complete(main())
821+
assert main_called, "The main function should have been called"
822+
823+
# We will now have an error in there, because the task 'async_job' could not
824+
# be entered, because the task 'main' was still being executed by the event loop.
825+
assert len(exceptions) == 1
826+
assert isinstance(exceptions[0]["exception"], RuntimeError)
827+
828+
829+
def test_call_sync(loop, application):
830+
"""Re-entering the event loop from a Task will fail if there is another
831+
runnable task."""
832+
async_called = False
833+
main_called = False
834+
835+
async def async_job():
836+
nonlocal async_called
837+
async_called = True
798838

799839
def sync_callback():
800-
nonlocal called
801-
called = True
840+
asyncio.create_task(async_job())
841+
assert not async_called
842+
application.processEvents()
843+
assert async_called
802844
return 1
803845

804846
async def main():
847+
nonlocal main_called
805848
res = await qasync.call_sync(sync_callback)
806849
assert res == 1
807-
850+
main_called = True
851+
852+
exceptions= []
853+
loop.set_exception_handler(lambda loop, context: exceptions.append(context))
854+
808855
loop.run_until_complete(main())
809-
assert called, "The sync callback should have been called"
856+
assert main_called, "The main function should have been called"
857+
858+
# We will now have an error in there, because the task 'async_job' could not
859+
# be entered, because the task 'main' was still being executed by the event loop.
860+
assert len(exceptions) == 0
810861

811862

812863
def test_slow_callback_duration_logging(loop, caplog):

0 commit comments

Comments
 (0)