File: test_pilot.py

package info (click to toggle)
textual 2.1.2-1.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 55,080 kB
  • sloc: python: 85,423; lisp: 1,669; makefile: 101
file content (452 lines) | stat: -rw-r--r-- 15,523 bytes parent folder | download | duplicates (2)
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
from string import punctuation
from typing import Type

import pytest

from textual import events, work
from textual._on import on
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Center, Middle
from textual.css.errors import StylesheetError
from textual.pilot import OutOfBounds
from textual.screen import Screen
from textual.widgets import Button, Label
from textual.worker import WorkerFailed

KEY_CHARACTERS_TO_TEST = "akTW03" + punctuation
"""Test some "simple" characters (letters + digits) and all punctuation."""


class CenteredButtonApp(App):
    CSS = """  # Ensure the button is 16 x 3
    Button {
        min-width: 16;
        max-width: 16;
        width: 16;
        min-height: 3;
        max-height: 3;
        height: 3;
    }
    """

    def compose(self):
        with Center():
            with Middle():
                yield Button()


class ManyLabelsApp(App):
    """Auxiliary app with a button following many labels."""

    AUTO_FOCUS = None  # So that there's no auto-scrolling.

    def compose(self):
        for idx in range(100):
            yield Label(f"label {idx}", id=f"label{idx}")
        yield Button()


async def test_pilot_press_ascii_chars():
    """Test that the pilot can press most ASCII characters as keys."""
    keys_pressed = []

    class TestApp(App[None]):
        def on_key(self, event: events.Key) -> None:
            keys_pressed.append(event.character)

    async with TestApp().run_test() as pilot:
        for char in KEY_CHARACTERS_TO_TEST:
            await pilot.press(char)
            assert keys_pressed[-1] == char


async def test_pilot_exception_catching_app_compose():
    """Ensuring that test frameworks are aware of exceptions
    inside compose methods when running via Pilot run_test()."""

    class FailingApp(App):
        def compose(self) -> ComposeResult:
            1 / 0
            yield Label("Beep")

    with pytest.raises(ZeroDivisionError):
        async with FailingApp().run_test():
            pass


async def test_pilot_exception_catching_widget_compose():
    class SomeScreen(Screen[None]):
        def compose(self) -> ComposeResult:
            1 / 0
            yield Label("Beep")

    class FailingApp(App[None]):
        def on_mount(self) -> None:
            self.push_screen(SomeScreen())

    with pytest.raises(ZeroDivisionError):
        async with FailingApp().run_test():
            pass


async def test_pilot_exception_catching_action():
    """Ensure that exceptions inside action handlers are presented
    to the test framework when running via Pilot run_test()."""

    class FailingApp(App):
        BINDINGS = [Binding("b", "beep", "beep")]

        def action_beep(self) -> None:
            1 / 0

    with pytest.raises(ZeroDivisionError):
        async with FailingApp().run_test() as pilot:
            await pilot.press("b")


async def test_pilot_exception_catching_worker():
    class SimpleAppThatCrashes(App[None]):
        def on_mount(self) -> None:
            self.crash()

        @work(name="crash")
        async def crash(self) -> None:
            1 / 0

    with pytest.raises(WorkerFailed) as exc:
        async with SimpleAppThatCrashes().run_test():
            pass
        assert exc.type is ZeroDivisionError


async def test_pilot_click_screen():
    """Regression test for https://github.com/Textualize/textual/issues/3395.

    Check we can use `Screen` as a selector for a click."""

    async with App().run_test() as pilot:
        await pilot.click("Screen")


async def test_pilot_hover_screen():
    """Regression test for https://github.com/Textualize/textual/issues/3395.

    Check we can use `Screen` as a selector for a hover."""

    async with App().run_test() as pilot:
        await pilot.hover("Screen")


@pytest.mark.parametrize(
    ["method", "screen_size", "offset"],
    [
        #
        ("click", (80, 24), (100, 12)),  # Right of screen.
        ("click", (80, 24), (100, 36)),  # Bottom-right of screen.
        ("click", (80, 24), (50, 36)),  # Under screen.
        ("click", (80, 24), (-10, 36)),  # Bottom-left of screen.
        ("click", (80, 24), (-10, 12)),  # Left of screen.
        ("click", (80, 24), (-10, -2)),  # Top-left of screen.
        ("click", (80, 24), (50, -2)),  # Above screen.
        ("click", (80, 24), (100, -2)),  # Top-right of screen.
        #
        ("click", (5, 5), (7, 3)),  # Right of screen.
        ("click", (5, 5), (7, 7)),  # Bottom-right of screen.
        ("click", (5, 5), (3, 7)),  # Under screen.
        ("click", (5, 5), (-1, 7)),  # Bottom-left of screen.
        ("click", (5, 5), (-1, 3)),  # Left of screen.
        ("click", (5, 5), (-1, -1)),  # Top-left of screen.
        ("click", (5, 5), (3, -1)),  # Above screen.
        ("click", (5, 5), (7, -1)),  # Top-right of screen.
        #
        ("hover", (80, 24), (100, 12)),  # Right of screen.
        ("hover", (80, 24), (100, 36)),  # Bottom-right of screen.
        ("hover", (80, 24), (50, 36)),  # Under screen.
        ("hover", (80, 24), (-10, 36)),  # Bottom-left of screen.
        ("hover", (80, 24), (-10, 12)),  # Left of screen.
        ("hover", (80, 24), (-10, -2)),  # Top-left of screen.
        ("hover", (80, 24), (50, -2)),  # Above screen.
        ("hover", (80, 24), (100, -2)),  # Top-right of screen.
        #
        ("hover", (5, 5), (7, 3)),  # Right of screen.
        ("hover", (5, 5), (7, 7)),  # Bottom-right of screen.
        ("hover", (5, 5), (3, 7)),  # Under screen.
        ("hover", (5, 5), (-1, 7)),  # Bottom-left of screen.
        ("hover", (5, 5), (-1, 3)),  # Left of screen.
        ("hover", (5, 5), (-1, -1)),  # Top-left of screen.
        ("hover", (5, 5), (3, -1)),  # Above screen.
        ("hover", (5, 5), (7, -1)),  # Top-right of screen.
        #
        ("mouse_down", (80, 24), (100, 12)),  # Right of screen.
        ("mouse_down", (80, 24), (100, 36)),  # Bottom-right of screen.
        ("mouse_down", (80, 24), (50, 36)),  # Under screen.
        ("mouse_down", (80, 24), (-10, 36)),  # Bottom-left of screen.
        ("mouse_down", (80, 24), (-10, 12)),  # Left of screen.
        ("mouse_down", (80, 24), (-10, -2)),  # Top-left of screen.
        ("mouse_down", (80, 24), (50, -2)),  # Above screen.
        ("mouse_down", (80, 24), (100, -2)),  # Top-right of screen.
        #
        ("mouse_down", (5, 5), (7, 3)),  # Right of screen.
        ("mouse_down", (5, 5), (7, 7)),  # Bottom-right of screen.
        ("mouse_down", (5, 5), (3, 7)),  # Under screen.
        ("mouse_down", (5, 5), (-1, 7)),  # Bottom-left of screen.
        ("mouse_down", (5, 5), (-1, 3)),  # Left of screen.
        ("mouse_down", (5, 5), (-1, -1)),  # Top-left of screen.
        ("mouse_down", (5, 5), (3, -1)),  # Above screen.
        ("mouse_down", (5, 5), (7, -1)),  # Top-right of screen.
        #
        ("mouse_up", (80, 24), (100, 12)),  # Right of screen.
        ("mouse_up", (80, 24), (100, 36)),  # Bottom-right of screen.
        ("mouse_up", (80, 24), (50, 36)),  # Under screen.
        ("mouse_up", (80, 24), (-10, 36)),  # Bottom-left of screen.
        ("mouse_up", (80, 24), (-10, 12)),  # Left of screen.
        ("mouse_up", (80, 24), (-10, -2)),  # Top-left of screen.
        ("mouse_up", (80, 24), (50, -2)),  # Above screen.
        ("mouse_up", (80, 24), (100, -2)),  # Top-right of screen.
        #
        ("mouse_up", (5, 5), (7, 3)),  # Right of screen.
        ("mouse_up", (5, 5), (7, 7)),  # Bottom-right of screen.
        ("mouse_up", (5, 5), (3, 7)),  # Under screen.
        ("mouse_up", (5, 5), (-1, 7)),  # Bottom-left of screen.
        ("mouse_up", (5, 5), (-1, 3)),  # Left of screen.
        ("mouse_up", (5, 5), (-1, -1)),  # Top-left of screen.
        ("mouse_up", (5, 5), (3, -1)),  # Above screen.
        ("mouse_up", (5, 5), (7, -1)),  # Top-right of screen.
    ],
)
async def test_pilot_target_outside_screen_errors(method, screen_size, offset):
    """Make sure that targeting a click/hover completely outside of the screen errors."""
    app = App()
    async with app.run_test(size=screen_size) as pilot:
        pilot_method = getattr(pilot, method)
        with pytest.raises(OutOfBounds):
            await pilot_method(offset=offset)


@pytest.mark.parametrize(
    ["method", "offset"],
    [
        ("click", (0, 0)),  # Top-left corner.
        ("click", (40, 0)),  # Top edge.
        ("click", (79, 0)),  # Top-right corner.
        ("click", (79, 12)),  # Right edge.
        ("click", (79, 23)),  # Bottom-right corner.
        ("click", (40, 23)),  # Bottom edge.
        ("click", (40, 23)),  # Bottom-left corner.
        ("click", (0, 12)),  # Left edge.
        ("click", (40, 12)),  # Right in the middle.
        #
        ("hover", (0, 0)),  # Top-left corner.
        ("hover", (40, 0)),  # Top edge.
        ("hover", (79, 0)),  # Top-right corner.
        ("hover", (79, 12)),  # Right edge.
        ("hover", (79, 23)),  # Bottom-right corner.
        ("hover", (40, 23)),  # Bottom edge.
        ("hover", (40, 23)),  # Bottom-left corner.
        ("hover", (0, 12)),  # Left edge.
        ("hover", (40, 12)),  # Right in the middle.
        #
        ("mouse_down", (0, 0)),  # Top-left corner.
        ("mouse_down", (40, 0)),  # Top edge.
        ("mouse_down", (79, 0)),  # Top-right corner.
        ("mouse_down", (79, 12)),  # Right edge.
        ("mouse_down", (79, 23)),  # Bottom-right corner.
        ("mouse_down", (40, 23)),  # Bottom edge.
        ("mouse_down", (40, 23)),  # Bottom-left corner.
        ("mouse_down", (0, 12)),  # Left edge.
        ("mouse_down", (40, 12)),  # Right in the middle.
        #
        ("mouse_up", (0, 0)),  # Top-left corner.
        ("mouse_up", (40, 0)),  # Top edge.
        ("mouse_up", (79, 0)),  # Top-right corner.
        ("mouse_up", (79, 12)),  # Right edge.
        ("mouse_up", (79, 23)),  # Bottom-right corner.
        ("mouse_up", (40, 23)),  # Bottom edge.
        ("mouse_up", (40, 23)),  # Bottom-left corner.
        ("mouse_up", (0, 12)),  # Left edge.
        ("mouse_up", (40, 12)),  # Right in the middle.
    ],
)
async def test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system(
    method, offset
):
    """Make sure that the coordinate system for the click is the correct one.

    Especially relevant because I kept getting confused about the way it works.
    """
    app = ManyLabelsApp()
    async with app.run_test(size=(80, 24)) as pilot:
        app.query_one("#label99").scroll_visible(animate=False)
        await pilot.pause()

        pilot_method = getattr(pilot, method)
        await pilot_method(offset=offset)


@pytest.mark.parametrize(
    ["method", "target"],
    [
        ("click", "#label0"),
        ("click", "#label90"),
        ("click", Button),
        #
        ("hover", "#label0"),
        ("hover", "#label90"),
        ("hover", Button),
        #
        ("mouse_down", "#label0"),
        ("mouse_down", "#label90"),
        ("mouse_down", Button),
        #
        ("mouse_up", "#label0"),
        ("mouse_up", "#label90"),
        ("mouse_up", Button),
    ],
)
async def test_pilot_target_on_widget_that_is_not_visible_errors(method, target):
    """Make sure that clicking a widget that is not scrolled into view raises an error."""
    app = ManyLabelsApp()
    async with app.run_test(size=(80, 5)) as pilot:
        app.query_one("#label50").scroll_visible(animate=False)
        await pilot.pause()

        pilot_method = getattr(pilot, method)
        with pytest.raises(OutOfBounds):
            await pilot_method(target)


@pytest.mark.parametrize("method", ["click", "hover", "mouse_down", "mouse_up"])
async def test_pilot_target_widget_under_another_widget(method):
    """The targeting method should return False when the targeted widget is covered."""

    class ObscuredButton(App):
        CSS = """
        Label {
            width: 30;
            height: 5;
        }
        """

        def compose(self):
            yield Button()
            yield Label()

        def on_mount(self):
            self.query_one(Label).styles.offset = (0, -3)

    app = ObscuredButton()
    async with app.run_test() as pilot:
        await pilot.pause()
        pilot_method = getattr(pilot, method)
        assert (await pilot_method(Button)) is False


@pytest.mark.parametrize("method", ["click", "hover", "mouse_down", "mouse_up"])
async def test_pilot_target_visible_widget(method):
    """The targeting method should return True when the targeted widget is hit."""

    class ObscuredButton(App):
        def compose(self):
            yield Button()

    app = ObscuredButton()
    async with app.run_test() as pilot:
        await pilot.pause()
        pilot_method = getattr(pilot, method)
        assert (await pilot_method(Button)) is True


@pytest.mark.parametrize(
    ["method", "offset"],
    [
        ("click", (0, 0)),
        ("click", (2, 0)),
        ("click", (10, 23)),
        ("click", (70, 0)),
        #
        ("hover", (0, 0)),
        ("hover", (2, 0)),
        ("hover", (10, 23)),
        ("hover", (70, 0)),
        #
        ("mouse_down", (0, 0)),
        ("mouse_down", (2, 0)),
        ("mouse_down", (10, 23)),
        ("mouse_down", (70, 0)),
        #
        ("mouse_up", (0, 0)),
        ("mouse_up", (2, 0)),
        ("mouse_up", (10, 23)),
        ("mouse_up", (70, 0)),
    ],
)
async def test_pilot_target_screen_always_true(method, offset):
    app = ManyLabelsApp()
    async with app.run_test(size=(80, 24)) as pilot:
        pilot_method = getattr(pilot, method)
        assert (await pilot_method(offset=offset)) is True


async def test_pilot_resize_terminal():
    app = App()
    async with app.run_test(size=(80, 24)) as pilot:
        # Sanity checks.
        assert app.size == (80, 24)
        assert app.screen.size == (80, 24)
        await pilot.resize_terminal(27, 15)
        await pilot.pause()
        assert app.size == (27, 15)
        assert app.screen.size == (27, 15)


async def test_fail_early():
    # https://github.com/Textualize/textual/issues/3282
    class MyApp(App):
        CSS_PATH = "foo.tcss"

    app = MyApp()
    with pytest.raises(StylesheetError):
        async with app.run_test() as pilot:
            await pilot.press("enter")


async def test_click_by_widget():
    """Test that click accept a Widget instance."""
    pressed = False

    class TestApp(CenteredButtonApp):
        def on_button_pressed(self):
            nonlocal pressed
            pressed = True

    app = TestApp()
    async with app.run_test() as pilot:
        button = app.query_one(Button)
        assert not pressed
        await pilot.click(button)
        assert pressed


@pytest.mark.parametrize("times", [1, 2, 3])
async def test_click_times(times: int):
    """Test that Pilot.click() can be called with a `times` argument."""

    events_received: list[Type[events.Event]] = []

    class TestApp(App[None]):
        def compose(self) -> ComposeResult:
            yield Label("Click counter")

        @on(events.Click)
        @on(events.MouseDown)
        @on(events.MouseUp)
        def on_label_clicked(self, event: events.Event):
            events_received.append(event.__class__)

    app = TestApp()
    async with app.run_test() as pilot:
        await pilot.click(Label, times=times)
        assert (
            events_received == [events.MouseDown, events.MouseUp, events.Click] * times
        )