Skip to content

Commit bb0ce07

Browse files
committed
test: extract common function
because it looks awful
1 parent 9303e8b commit bb0ce07

File tree

3 files changed

+27
-16
lines changed

3 files changed

+27
-16
lines changed

testing/external/common/client.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,17 @@ async def gatherer():
8989
yield gatherer()
9090
yield
9191

92+
async def run_client_until_test_done(self, local_port: int, load_timeout: float = MERCY_TM) -> AsyncGenerator:
93+
'''Provide this wrapper because it's very difficult to understand connect_to_nonebot'''
94+
cl_conn = self.connect_to_nonebot(local_port, load_timeout)
95+
await cl_conn.__anext__()
96+
task = asyncio.create_task(await cl_conn.__anext__())
97+
await asyncio.sleep(0)
98+
yield self
99+
task.cancel()
100+
await cl_conn.__anext__()
101+
self.stop_nonebot()
102+
92103
async def wait_for_matching_log(self, *pats: str, tm: float = MERCY_TM):
93104
while True:
94105
try:

testing/external/common/pytest.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import asyncio
2+
3+
import pytest
4+
5+
6+
class AsyncTestCase:
7+
@pytest.fixture(scope='class')
8+
def event_loop(self):
9+
loop = asyncio.new_event_loop()
10+
asyncio.set_event_loop(loop)
11+
yield loop
12+
loop.close()

testing/external/test_command/test_basics_work/runner.py

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,12 @@
66
import nonebot
77
import testing.external.common.default_config as dc
88
from testing.external.common.client import TESTER_ID, Client, run_nonebot_in_thread
9+
from testing.external.common.pytest import AsyncTestCase
910
from testing.external.common.port import available_port
1011

1112

1213
@pytest.mark.asyncio
13-
class TestBasicsWork:
14-
@pytest.fixture(scope='class')
15-
def event_loop(self):
16-
loop = asyncio.new_event_loop()
17-
asyncio.set_event_loop(loop)
18-
yield loop
19-
loop.close()
20-
14+
class TestBasicsWork(AsyncTestCase):
2115
@pytest.fixture(scope='class')
2216
async def cl(self):
2317
nonebot.init(dc)
@@ -27,14 +21,8 @@ async def cl(self):
2721
cl.patch_nonebot()
2822

2923
run_nonebot_in_thread()
30-
cl_conn = cl.connect_to_nonebot(available_port)
31-
await cl_conn.__anext__()
32-
task = asyncio.create_task(await cl_conn.__anext__())
33-
await asyncio.sleep(0)
34-
yield cl
35-
task.cancel()
36-
await cl_conn.__anext__()
37-
cl.stop_nonebot()
24+
async for p in cl.run_client_until_test_done(available_port):
25+
yield p
3826

3927
async def test_everyone_ping(self, cl: Client):
4028
cl.proxy.send_private_msg('/ping')

0 commit comments

Comments
 (0)