diff --git a/.gitignore b/.gitignore index 49ce83f..54c8f84 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,4 @@ ib_async.egg-info poetry.lock *.csv *.json +tests/__pycache__ \ No newline at end of file diff --git a/ib_async/util.py b/ib_async/util.py index 8462c51..d5a02c4 100644 --- a/ib_async/util.py +++ b/ib_async/util.py @@ -495,12 +495,10 @@ def patchAsyncio(): nest_asyncio.apply() -@functools.cache def getLoop(): """Get asyncio event loop or create one if it doesn't exist.""" try: - # https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop - loop = asyncio.get_running_loop() + loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) diff --git a/tests/test_util.py b/tests/test_util.py new file mode 100644 index 0000000..7ab07f4 --- /dev/null +++ b/tests/test_util.py @@ -0,0 +1,33 @@ +import asyncio +from threading import Thread + +from ib_async import util + + +def test_get_current_loop(): + loop = util.getLoop() + assert loop is not None + + +def test_create_new_loop(): + loop_holder = [] + + def target(): + loop_holder.append(util.getLoop()) + + thread1 = Thread(target=target) + thread1.start() + thread1.join() + assert loop_holder[0] is not None + + thread2 = Thread(target=target) + thread2.start() + thread2.join() + assert loop_holder[1] is not None + assert loop_holder[0] is not loop_holder[1] + + +def test_loop_can_be_set(): + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + assert util.getLoop() is loop