File: test_autocomplete.py

package info (click to toggle)
textual-textarea 0.17.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 720 kB
  • sloc: python: 3,195; makefile: 25
file content (280 lines) | stat: -rw-r--r-- 9,792 bytes parent folder | download
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
from __future__ import annotations

from pathlib import Path
from time import monotonic
from typing import Callable
from unittest.mock import MagicMock

import pytest
from textual.app import App
from textual.message import Message
from textual.widgets.text_area import Selection

from textual_textarea import TextEditor


@pytest.fixture
def word_completer() -> Callable[[str], list[tuple[str, str]]]:
    def _completer(prefix: str) -> list[tuple[str, str]]:
        words = [
            "satisfy",
            "season",
            "second",
            "seldom",
            "select",
            "self",
            "separate",
            "set",
            "space",
            "super",
        ]
        return [(w, w) for w in words if w.startswith(prefix)]

    return _completer


@pytest.fixture
def word_completer_with_types() -> Callable[[str], list[tuple[tuple[str, str], str]]]:
    def _completer(prefix: str) -> list[tuple[tuple[str, str], str]]:
        words = [
            "satisfy",
            "season",
            "second",
            "seldom",
            "select",
            "self",
            "separate",
            "set",
            "space",
            "super",
        ]
        return [((w, "word"), w) for w in words if w.startswith(prefix)]

    return _completer


@pytest.fixture
def member_completer() -> Callable[[str], list[tuple[str, str]]]:
    mock = MagicMock()
    mock.return_value = [("completion", "completion")]
    return mock


@pytest.mark.asyncio
async def test_autocomplete(
    app: App, word_completer: Callable[[str], list[tuple[str, str]]]
) -> None:
    messages: list[Message] = []
    async with app.run_test(message_hook=messages.append) as pilot:
        ta = app.query_one("#ta", expect_type=TextEditor)
        ta.word_completer = word_completer
        ta.focus()
        while ta.word_completer is None:
            await pilot.pause()

        start_time = monotonic()
        await pilot.press("s")
        while ta.completion_list.is_open is False:
            if monotonic() - start_time > 10:
                print("MESSAGES:")
                print("\n".join([str(m) for m in messages]))
                break
            await pilot.pause()
        assert ta.text_input
        assert ta.text_input.completer_active == "word"
        assert ta.completion_list.is_open is True
        assert ta.completion_list.option_count == 10
        first_offset = ta.completion_list.styles.offset

        await pilot.press("e")
        await app.workers.wait_for_complete()
        await pilot.pause()
        assert ta.text_input.completer_active == "word"
        assert ta.completion_list.is_open is True
        assert ta.completion_list.option_count == 7
        assert ta.completion_list.styles.offset == first_offset

        await pilot.press("z")  # sez, no matches
        await app.workers.wait_for_complete()
        await pilot.pause()
        assert ta.text_input.completer_active is None
        assert ta.completion_list.is_open is False

        # backspace when the list is not open doesn't re-open it
        await pilot.press("backspace")
        await app.workers.wait_for_complete()
        await pilot.pause()
        assert ta.text_input.completer_active is None
        assert ta.completion_list.is_open is False

        await pilot.press("l")  # sel
        await app.workers.wait_for_complete()
        await pilot.pause()
        assert ta.text_input.completer_active == "word"
        assert ta.completion_list.is_open is True
        assert ta.completion_list.option_count == 3
        assert ta.completion_list.styles.offset == first_offset

        await pilot.press("backspace")  # se
        await app.workers.wait_for_complete()
        await pilot.pause()
        assert ta.text_input.completer_active == "word"
        assert ta.completion_list.is_open is True
        assert ta.completion_list.option_count == 7
        assert ta.completion_list.styles.offset == first_offset

        await pilot.press("enter")
        await app.workers.wait_for_complete()
        await pilot.pause()
        assert ta.text_input.completer_active is None
        assert ta.completion_list.is_open is False
        assert ta.text == "season"
        assert ta.selection.end[1] == 6


@pytest.mark.asyncio
async def test_autocomplete_with_types(
    app: App,
    word_completer_with_types: Callable[[str], list[tuple[tuple[str, str], str]]],
) -> None:
    messages: list[Message] = []
    word_completer = word_completer_with_types
    async with app.run_test(message_hook=messages.append) as pilot:
        ta = app.query_one("#ta", expect_type=TextEditor)
        ta.word_completer = word_completer
        ta.focus()
        while ta.word_completer is None:
            await pilot.pause()

        start_time = monotonic()
        await pilot.press("s")
        while ta.completion_list.is_open is False:
            if monotonic() - start_time > 10:
                print("MESSAGES:")
                print("\n".join([str(m) for m in messages]))
                break
            await pilot.pause()
        assert ta.text_input
        assert ta.text_input.completer_active == "word"
        assert ta.completion_list.is_open is True
        assert ta.completion_list.option_count == 10
        first_offset = ta.completion_list.styles.offset

        await pilot.press("e")
        await app.workers.wait_for_complete()
        await pilot.pause()
        assert ta.text_input.completer_active == "word"
        assert ta.completion_list.is_open is True
        assert ta.completion_list.option_count == 7
        assert ta.completion_list.styles.offset == first_offset

        await pilot.press("z")  # sez, no matches
        await app.workers.wait_for_complete()
        await pilot.pause()
        assert ta.text_input.completer_active is None
        assert ta.completion_list.is_open is False

        # backspace when the list is not open doesn't re-open it
        await pilot.press("backspace")
        await app.workers.wait_for_complete()
        await pilot.pause()
        assert ta.text_input.completer_active is None
        assert ta.completion_list.is_open is False

        await pilot.press("l")  # sel
        await app.workers.wait_for_complete()
        await pilot.pause()
        assert ta.text_input.completer_active == "word"
        assert ta.completion_list.is_open is True
        assert ta.completion_list.option_count == 3
        assert ta.completion_list.styles.offset == first_offset

        await pilot.press("backspace")  # se
        await app.workers.wait_for_complete()
        await pilot.pause()
        assert ta.text_input.completer_active == "word"
        assert ta.completion_list.is_open is True
        assert ta.completion_list.option_count == 7
        assert ta.completion_list.styles.offset == first_offset

        await pilot.press("enter")
        await app.workers.wait_for_complete()
        await pilot.pause()
        assert ta.text_input.completer_active is None
        assert ta.completion_list.is_open is False
        assert ta.text == "season"
        assert ta.selection.end[1] == 6


@pytest.mark.asyncio
async def test_autocomplete_paths(app: App, data_dir: Path) -> None:
    messages: list[Message] = []
    async with app.run_test(message_hook=messages.append) as pilot:
        ta = app.query_one("#ta", expect_type=TextEditor)
        ta.focus()
        test_path = str(data_dir / "test_validator")
        ta.text = test_path
        await pilot.pause()
        ta.selection = Selection((0, len(test_path)), (0, len(test_path)))

        start_time = monotonic()
        await pilot.press("slash")
        while ta.completion_list.is_open is False:
            if monotonic() - start_time > 10:
                print("MESSAGES:")
                print("\n".join([str(m) for m in messages]))
                break
            await pilot.pause()
        assert ta.text_input
        assert ta.text_input.completer_active == "path"
        assert ta.completion_list.is_open is True
        assert ta.completion_list.option_count == 2


@pytest.mark.parametrize(
    "text,keys,expected_prefix",
    [
        ("foo bar", ["full_stop"], "bar."),
        ("foo 'bar'", ["full_stop"], "'bar'."),
        ("foo `bar`", ["full_stop"], "`bar`."),
        ('foo "bar"', ["full_stop"], '"bar".'),
        ("foo bar", ["colon"], "bar:"),
        ("foo bar", ["colon", "colon"], "bar::"),
        ('foo "bar"', ["colon", "colon"], '"bar"::'),
        ("foo bar", ["full_stop", "quotation_mark"], 'bar."'),
        ('foo "bar"', ["full_stop", "quotation_mark"], '"bar"."'),
    ],
)
@pytest.mark.asyncio
async def test_autocomplete_members(
    app: App,
    member_completer: MagicMock,
    text: str,
    keys: list[str],
    expected_prefix: str,
) -> None:
    messages: list[Message] = []
    async with app.run_test(message_hook=messages.append) as pilot:
        ta = app.query_one("#ta", expect_type=TextEditor)
        ta.member_completer = member_completer
        ta.focus()
        while ta.member_completer is None:
            await pilot.pause()
        ta.text = text
        ta.selection = Selection((0, len(text)), (0, len(text)))
        await pilot.pause()
        for key in keys:
            await pilot.press(key)

        start_time = monotonic()
        while ta.completion_list.is_open is False:
            if monotonic() - start_time > 10:
                print("MESSAGES:")
                print("\n".join([str(m) for m in messages]))
                break
            await pilot.pause()

        member_completer.assert_called_with(expected_prefix)
        assert ta.text_input is not None
        assert ta.text_input.completer_active == "member"
        assert ta.completion_list.is_open is True