|
| 1 | +# Only Run tests on MacOS and Linux |
| 2 | +import shutil |
| 3 | +import pytest |
| 4 | +import json |
| 5 | +import asyncio |
| 6 | +import sys |
| 7 | + |
| 8 | +# Skip this whole module on Windows. The terminal API leads |
| 9 | +# to timeouts on Windows CI. |
| 10 | +if sys.platform.startswith('win'): |
| 11 | + pytest.skip("Terminal API tests time out on Windows.", allow_module_level=True) |
| 12 | + |
| 13 | + |
| 14 | +@pytest.fixture |
| 15 | +def terminal_path(tmp_path): |
| 16 | + subdir = tmp_path.joinpath('terminal_path') |
| 17 | + subdir.mkdir() |
| 18 | + |
| 19 | + yield subdir |
| 20 | + |
| 21 | + shutil.rmtree(str(subdir), ignore_errors=True) |
| 22 | + |
| 23 | + |
| 24 | +async def test_terminal_create(fetch): |
| 25 | + await fetch( |
| 26 | + 'api', 'terminals', |
| 27 | + method='POST', |
| 28 | + allow_nonstandard_methods=True, |
| 29 | + ) |
| 30 | + |
| 31 | + resp_list = await fetch( |
| 32 | + 'api', 'terminals', |
| 33 | + method='GET', |
| 34 | + allow_nonstandard_methods=True, |
| 35 | + ) |
| 36 | + |
| 37 | + data = json.loads(resp_list.body.decode()) |
| 38 | + |
| 39 | + assert len(data) == 1 |
| 40 | + |
| 41 | + |
| 42 | +async def test_terminal_create_with_kwargs(fetch, ws_fetch, terminal_path): |
| 43 | + resp_create = await fetch( |
| 44 | + 'api', 'terminals', |
| 45 | + method='POST', |
| 46 | + body=json.dumps({'cwd': str(terminal_path)}), |
| 47 | + allow_nonstandard_methods=True, |
| 48 | + ) |
| 49 | + |
| 50 | + data = json.loads(resp_create.body.decode()) |
| 51 | + term_name = data['name'] |
| 52 | + |
| 53 | + resp_get = await fetch( |
| 54 | + 'api', 'terminals', term_name, |
| 55 | + method='GET', |
| 56 | + allow_nonstandard_methods=True, |
| 57 | + ) |
| 58 | + |
| 59 | + data = json.loads(resp_get.body.decode()) |
| 60 | + |
| 61 | + assert data['name'] == term_name |
| 62 | + |
| 63 | + |
| 64 | +async def test_terminal_create_with_cwd(fetch, ws_fetch, terminal_path): |
| 65 | + resp = await fetch( |
| 66 | + 'api', 'terminals', |
| 67 | + method='POST', |
| 68 | + body=json.dumps({'cwd': str(terminal_path)}), |
| 69 | + allow_nonstandard_methods=True, |
| 70 | + ) |
| 71 | + |
| 72 | + data = json.loads(resp.body.decode()) |
| 73 | + term_name = data['name'] |
| 74 | + |
| 75 | + ws = await ws_fetch( |
| 76 | + 'terminals', 'websocket', term_name |
| 77 | + ) |
| 78 | + |
| 79 | + ws.write_message(json.dumps(['stdin', 'pwd\r\n'])) |
| 80 | + |
| 81 | + message_stdout = '' |
| 82 | + while True: |
| 83 | + try: |
| 84 | + message = await asyncio.wait_for(ws.read_message(), timeout=1.0) |
| 85 | + except asyncio.TimeoutError: |
| 86 | + break |
| 87 | + |
| 88 | + message = json.loads(message) |
| 89 | + |
| 90 | + if message[0] == 'stdout': |
| 91 | + message_stdout += message[1] |
| 92 | + |
| 93 | + ws.close() |
| 94 | + |
| 95 | + assert str(terminal_path) in message_stdout |
0 commit comments