summaryrefslogtreecommitdiff
path: root/test/fs.py
blob: a2b67cbc3c54566970e1382ff92e4bb0317f503c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#!/usr/bin/env python3
import contextlib
import fcntl
import json
import os
import shutil
import select
import signal
import socket
from pathlib import Path
import subprocess
import struct
import sys
import tempfile
import termios
import threading
import time

from ninep import Client


@contextlib.contextmanager
def session(binary, root, name, *options, socket_name=None, file=None, tty=False, network=None,
            launch=None, inherited=None, terminal=None):
    # No pager of the caller's (a session's own PAGER, SYSTEMD_PAGER...):
    # its shells get the session's defaults, the ones under test.
    env = {key: value for key, value in os.environ.items()
           if not key.startswith('PARDES_') and 'PAGER' not in key}
    env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root),
               XDG_CONFIG_HOME=str(root / 'config'), PARDES_NOTIME='1',
               PARDES_DUMP=str(root / (name + '.dump.zon')))
    env.update(inherited or {})
    for language in ['RS', 'C', 'GO', 'TS', 'PY']:
        env['PARDES_LSP_' + language] = ''
    fixture = root / (name + '.txt')
    fixture.write_bytes(b'initial\n')
    address = root / ('pardes-9p-' + (socket_name or name) + '.sock')
    child = None
    master = slave = None
    reader = None
    try:
        args = [binary, '--detach=' + name, *options, str(file or fixture)]
        preexec = None
        if tty:
            master, slave = os.openpty()
            fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 24, 80, 0, 0))
            env['TERM'] = 'xterm-256color'
            args = [binary, '--tty', '--9p=' + (socket_name or name), *options, str(file or fixture)]
            preexec = lambda: fcntl.ioctl(0, termios.TIOCSCTTY, 0)
        if launch is not None:
            args = [binary, *launch]
        existing = set(root.glob('pardes-9p-*.sock'))
        child = subprocess.Popen(args, cwd=root, env=env, stdin=slave,
                                 stdout=slave if tty else subprocess.DEVNULL,
                                 stderr=subprocess.PIPE, start_new_session=True,
                                 preexec_fn=preexec)
        if terminal is not None:
            # Borrowed handles for input-driving probes, valid inside this context.
            terminal.update(pid=child.pid, input_fd=master)
        if launch is not None and socket_name is None:
            # Named by the session's pid: a terminal's session is forked
            # off the process launched, which stays as its stub.
            address = None
        if slave is not None:
            os.close(slave)
            slave = None
            def drain():
                try:
                    while os.read(master, 65536):
                        pass
                except OSError:
                    pass
            reader = threading.Thread(target=drain, daemon=True)
            reader.start()
        deadline = time.monotonic() + 10
        while address is None or not address.exists():
            if address is None:
                address = next(iter(set(root.glob('pardes-9p-*.sock')) - existing), None)
                if address is not None:
                    continue
            if child.poll() is not None:
                raise AssertionError((args, child.returncode, child.stderr.read().decode()))
            if time.monotonic() > deadline:
                raise TimeoutError('default 9P socket did not appear')
            time.sleep(.005)
        with Client(address) as client:
            if network is not None:
                for dial in client.read('/listeners').decode().splitlines():
                    parts = dial.split('!')
                    if parts[0] in ['tcp', 'quic']:
                        assert len(parts) == 3 and 0 < int(parts[2]) < 65536, dial
                        network[parts[0].upper()] = int(parts[2])
                assert set(network) == {'TCP', 'QUIC'}, network
            yield client, address
    finally:
        if terminal is not None:
            terminal.clear()
        if child is not None:
            if child.poll() is None:
                child.terminate()
            try:
                child.wait(timeout=5)
            except subprocess.TimeoutExpired:
                child.kill()
                child.wait()
            child.stderr.close()
        if slave is not None:
            os.close(slave)
        if master is not None:
            os.close(master)
        if reader is not None:
            reader.join(timeout=1)
            assert not reader.is_alive(), 'terminal reader did not stop'


def new_pane(client, contents):
    """An open of /pane/new makes a pane; the read names it."""
    serial = int(client.read('/pane/new'))
    if contents:
        client.write(f'/pane/{serial}/body', contents)
    return serial


def execute(client, serial, command):
    """A middle click on `command` from a pane."""
    client.write(f'/pane/{serial}/exec', f'{command}\n'.encode())


if __name__ == '__main__':
    raise SystemExit('fs.py is the helpers the developer tools share (session, new_pane, '
                     'execute); its tests are Zig now: zig build behaviour-test process-test')