|
2 | 2 | Unittests for main module. |
3 | 3 | """ |
4 | 4 |
|
| 5 | +import asyncio |
5 | 6 | import json |
6 | 7 | import os |
7 | 8 | import pwd |
8 | 9 | import sys |
9 | 10 |
|
10 | 11 | import pytest |
11 | 12 |
|
12 | | -import libkirk.sut |
| 13 | +import libkirk |
13 | 14 | import libkirk.com |
14 | 15 | import libkirk.main |
| 16 | +import libkirk.sut |
| 17 | +from libkirk.evt import EventsHandler |
| 18 | + |
| 19 | + |
| 20 | +@pytest.fixture(autouse=True) |
| 21 | +def isolated_loop(monkeypatch): |
| 22 | + """ |
| 23 | + Give every TestMain test its own event loop so that |
| 24 | + libkirk.main.run() cannot cancel tasks belonging to |
| 25 | + other (async) tests, and cannot leave the shared |
| 26 | + session loop in a dirty state. |
| 27 | + """ |
| 28 | + # Remember which loop the session is using so we can restore it. |
| 29 | + session_loop = libkirk.get_event_loop() |
| 30 | + |
| 31 | + loop = asyncio.new_event_loop() |
| 32 | + asyncio.set_event_loop(loop) |
| 33 | + |
| 34 | + # Re-discover plugins now that the isolated loop is current, so that |
| 35 | + # every asyncio.Lock() inside plugin __init__ methods binds to this loop. |
| 36 | + currdir = os.path.dirname(os.path.realpath(libkirk.com.__file__)) |
| 37 | + libkirk.com.discover(os.path.join(currdir, "channels"), extend=False) |
| 38 | + libkirk.sut.discover(currdir, extend=False) |
| 39 | + |
| 40 | + fresh_events = EventsHandler() |
| 41 | + monkeypatch.setattr(libkirk, "get_event_loop", lambda: loop) |
| 42 | + monkeypatch.setattr(libkirk, "events", fresh_events) |
| 43 | + |
| 44 | + yield loop |
| 45 | + |
| 46 | + # Drain and close the isolated loop. |
| 47 | + try: |
| 48 | + libkirk.cancel_tasks(loop) |
| 49 | + if not loop.is_closed(): |
| 50 | + loop.run_until_complete(fresh_events.stop()) |
| 51 | + finally: |
| 52 | + if not loop.is_closed(): |
| 53 | + loop.close() |
| 54 | + # Restore the session loop so subsequent async tests still work. |
| 55 | + asyncio.set_event_loop(session_loop) |
15 | 56 |
|
16 | 57 |
|
17 | 58 | class TestMain: |
|
0 commit comments