summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-cli/tests/test_clipboard.py
blob: 6296317bc8821f7fc5f90d3a8050d5799735205d (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
"""
The chat's clipboard: the platform's tools, run for real, and nothing when none
works. Fake `wl-copy`/`wl-paste` stand in for wl-clipboard, sharing one file.
"""

import shutil
import sys
import time

import pytest
from meshbay_cli.tui import clipboard

pytestmark = pytest.mark.skipif(sys.platform in ("win32", "darwin"),
                                reason="the Wayland and X11 tools")
# Found before a test leaves only the fake tools on PATH.
CAT, SLEEP = shutil.which("cat"), shutil.which("sleep")


@pytest.fixture
def wayland(tmp_path, monkeypatch):
    held = tmp_path / "held"
    bin_dir = tmp_path / "bin"
    bin_dir.mkdir()
    for name, body in (("wl-copy", f'{CAT} > "{held}"'), ("wl-paste", f'{CAT} "{held}"')):
        tool = bin_dir / name
        tool.write_text(f"#!/bin/sh\n{body}\n")
        tool.chmod(0o755)
    monkeypatch.setenv("PATH", str(bin_dir))
    monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-0")
    monkeypatch.delenv("DISPLAY", raising=False)
    return held


async def test_what_is_copied_is_what_is_pasted(wayland):
    assert await clipboard.write_text("héllo — 你好\nsecond") is True
    assert wayland.read_text(encoding="utf-8") == "héllo — 你好\nsecond"
    assert await clipboard.read_text() == "héllo — 你好\nsecond"


async def test_no_tool_is_none_not_an_error(tmp_path, monkeypatch):
    monkeypatch.setenv("PATH", str(tmp_path))
    monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-0")
    monkeypatch.setenv("DISPLAY", ":0")
    assert await clipboard.read_text() is None
    assert await clipboard.write_text("x") is False


async def test_a_failing_tool_is_skipped(wayland):
    (wayland.parent / "bin" / "wl-paste").write_text("#!/bin/sh\nexit 1\n")
    assert await clipboard.read_text() is None


async def test_a_hanging_tool_is_given_up(wayland, monkeypatch):
    (wayland.parent / "bin" / "wl-paste").write_text(f"#!/bin/sh\nexec {SLEEP} 30\n")
    monkeypatch.setattr(clipboard, "TIMEOUT", 0.3)
    started = time.monotonic()
    assert await clipboard.read_text() is None
    assert 0.3 <= time.monotonic() - started < 5