File: test_query.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 (366 lines) | stat: -rw-r--r-- 11,395 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
import pytest

from textual.app import App, ComposeResult
from textual.color import Color
from textual.containers import Container
from textual.css.query import (
    DeclarationError,
    InvalidQueryFormat,
    NoMatches,
    TooManyMatches,
    WrongType,
)
from textual.widget import Widget
from textual.widgets import Input, Label


def test_query_errors():
    app = App()

    with pytest.raises(InvalidQueryFormat):
        app.query_one("foo_bar")

    with pytest.raises(InvalidQueryFormat):
        app.query("foo_bar")

    with pytest.raises(InvalidQueryFormat):
        app.query("1")

    with pytest.raises(InvalidQueryFormat):
        app.query_one("1")


def test_query():
    class View(Widget):
        pass

    class View2(View):
        pass

    class App(Widget):
        pass

    app = App()
    main_view = View(id="main")
    help_view = View2(id="help")
    app._add_child(main_view)
    app._add_child(help_view)

    widget1 = Widget(id="widget1")
    widget2 = Widget(id="widget2")
    sidebar = Widget(id="sidebar")
    sidebar.add_class("float")

    helpbar = Widget(id="helpbar")
    helpbar.add_class("float")

    main_view._add_child(widget1)
    main_view._add_child(widget2)
    main_view._add_child(sidebar)

    sub_view = View(id="sub")
    sub_view.add_class("-subview")
    main_view._add_child(sub_view)

    tooltip = Widget(id="tooltip")
    tooltip.add_class("float", "transient")
    sub_view._add_child(tooltip)

    help = Widget(id="markdown")
    help_view._add_child(help)
    help_view._add_child(helpbar)

    # repeat tests to account for caching
    for repeat in range(3):
        assert list(app.query_children()) == [main_view, help_view]
        assert list(app.query_children("*")) == [main_view, help_view]
        assert list(app.query_children("#help")) == [help_view]
        assert list(main_view.query_children(".float")) == [sidebar]

        assert list(app.query("Frob")) == []
        assert list(app.query(".frob")) == []
        assert list(app.query("#frob")) == []

        assert not app.query("NotAnApp")

        assert list(app.query("App")) == []  # Root is not included in queries
        assert list(app.query("#main")) == [main_view]
        assert list(app.query("View#main")) == [main_view]
        assert list(app.query("View2#help")) == [help_view]
        assert list(app.query("#widget1")) == [widget1]
        assert list(app.query("#Widget1")) == []  # Note case.
        assert list(app.query("#widget2")) == [widget2]
        assert list(app.query("#Widget2")) == []  # Note case.

        assert list(app.query("Widget.float")) == [sidebar, tooltip, helpbar]
        assert list(app.query(Widget).filter(".float")) == [sidebar, tooltip, helpbar]
        assert list(
            app.query(Widget)
            .exclude("App")
            .exclude("#sub")
            .exclude("#markdown")
            .exclude("#main")
            .exclude("#help")
            .exclude("#widget1")
            .exclude("#widget2")
        ) == [sidebar, tooltip, helpbar]
        assert list(reversed(app.query("Widget.float"))) == [helpbar, tooltip, sidebar]
        assert list(app.query("Widget.float").results(Widget)) == [
            sidebar,
            tooltip,
            helpbar,
        ]
        assert list(app.query("Widget.float").results()) == [
            sidebar,
            tooltip,
            helpbar,
        ]
        assert list(app.query("Widget.float").results(View)) == []
        assert app.query_one("#widget1") == widget1
        assert app.query_one("#widget1", Widget) == widget1
        with pytest.raises(TooManyMatches):
            _ = app.query_exactly_one(Widget)

        assert app.query("Widget.float")[0] == sidebar
        assert app.query("Widget.float")[0:2] == [sidebar, tooltip]

        assert list(app.query("Widget.float.transient")) == [tooltip]

        assert list(app.query("App > View")) == [main_view, help_view]
        assert list(app.query("App > View#help")) == [help_view]
        assert list(app.query("App > View#main .float ")) == [sidebar, tooltip]
        assert list(app.query("View > View")) == [sub_view]

        assert list(app.query("#help *")) == [help, helpbar]
        assert list(app.query("#main *")) == [
            widget1,
            widget2,
            sidebar,
            sub_view,
            tooltip,
        ]

        assert list(app.query("View")) == [main_view, sub_view, help_view]
        assert list(app.query("#widget1, #widget2")) == [widget1, widget2]
        assert list(app.query("#widget1 , #widget2")) == [widget1, widget2]
        assert list(app.query("#widget1, #widget2, App")) == [widget1, widget2]

        assert app.query(".float").first() == sidebar
        assert app.query(".float").last() == helpbar

        with pytest.raises(NoMatches):
            _ = app.query(".no_such_class").first()
        with pytest.raises(NoMatches):
            _ = app.query(".no_such_class").last()

        with pytest.raises(WrongType):
            _ = app.query(".float").first(View)
        with pytest.raises(WrongType):
            _ = app.query(".float").last(View)


def test_query_classes():
    class App(Widget):
        pass

    class ClassTest(Widget):
        pass

    CHILD_COUNT = 100

    # Create a fake app to hold everything else.
    app = App()

    # Now spin up a bunch of children.
    for n in range(CHILD_COUNT):
        app._add_child(ClassTest(id=f"child{n}"))

    # Let's just be 100% sure everything was created fine.
    assert len(app.query(ClassTest)) == CHILD_COUNT

    # Now, let's check there are *no* children with the test class.
    assert len(app.query(".test")) == 0

    # Add classes via set_classes
    app.query(ClassTest).set_classes("foo bar")
    assert (len(app.query(".foo"))) == CHILD_COUNT
    assert (len(app.query(".bar"))) == CHILD_COUNT

    # Reset classes
    app.query(ClassTest).set_classes("")
    assert (len(app.query(".foo"))) == 0
    assert (len(app.query(".bar"))) == 0

    # Repeat, to check setting empty iterable
    app.query(ClassTest).set_classes("foo bar")
    assert (len(app.query(".foo"))) == CHILD_COUNT
    assert (len(app.query(".bar"))) == CHILD_COUNT

    app.query(ClassTest).set_classes([])
    assert (len(app.query(".foo"))) == 0
    assert (len(app.query(".bar"))) == 0

    # Add the test class to everything and then check again.
    app.query(ClassTest).add_class("test")
    assert len(app.query(".test")) == CHILD_COUNT

    # Remove the test class from everything then try again.
    app.query(ClassTest).remove_class("test")
    assert len(app.query(".test")) == 0

    # Add the test class to everything using set_class.
    app.query(ClassTest).set_class(True, "test")
    assert len(app.query(".test")) == CHILD_COUNT

    # Remove the test class from everything using set_class.
    app.query(ClassTest).set_class(False, "test")
    assert len(app.query(".test")) == 0

    # Add the test class to everything using toggle_class.
    app.query(ClassTest).toggle_class("test")
    assert len(app.query(".test")) == CHILD_COUNT

    # Remove the test class from everything using toggle_class.
    app.query(ClassTest).toggle_class("test")
    assert len(app.query(".test")) == 0


def test_invalid_query():
    class App(Widget):
        pass

    app = App()

    with pytest.raises(InvalidQueryFormat):
        app.query("#3")

    with pytest.raises(InvalidQueryFormat):
        app.query("#foo").exclude("#2")


async def test_universal_selector_doesnt_select_self():
    class ExampleApp(App):
        def compose(self) -> ComposeResult:
            yield Container(
                Widget(
                    Widget(),
                    Widget(
                        Widget(),
                    ),
                ),
                Widget(),
                id="root-container",
            )

    app = ExampleApp()
    async with app.run_test():
        container = app.query_one("#root-container", Container)
        query = container.query("*")
        results = list(query.results())
        assert len(results) == 5
        assert not any(node.id == "root-container" for node in results)


async def test_query_set_styles_invalid_css_raises_error():
    app = App()
    async with app.run_test():
        with pytest.raises(DeclarationError):
            app.query(Widget).set_styles(css="random-rule: 1fr;")


async def test_query_set_styles_kwds():
    class LabelApp(App):
        def compose(self):
            yield Label("Some text")

    app = LabelApp()
    async with app.run_test():
        # Sanity check.
        assert app.query_one(Label).styles.color != Color(255, 0, 0)
        app.query(Label).set_styles(color="red")
        assert app.query_one(Label).styles.color == Color(255, 0, 0)


async def test_query_set_styles_css_and_kwds():
    class LabelApp(App):
        def compose(self):
            yield Label("Some text")

    app = LabelApp()
    async with app.run_test():
        # Sanity checks.
        lbl = app.query_one(Label)
        assert lbl.styles.color != Color(255, 0, 0)
        assert lbl.styles.background != Color(255, 0, 0)

        app.query(Label).set_styles(css="background: red;", color="red")
        assert app.query_one(Label).styles.color == Color(255, 0, 0)
        assert app.query_one(Label).styles.background == Color(255, 0, 0)


async def test_query_set_styles_css():
    class LabelApp(App):
        def compose(self):
            yield Label("Some text")

    app = LabelApp()
    async with app.run_test():
        # Sanity checks.
        lbl = app.query_one(Label)
        assert lbl.styles.color != Color(255, 0, 0)
        assert lbl.styles.background != Color(255, 0, 0)

        app.query(Label).set_styles(css="background: red; color: red;")
        assert app.query_one(Label).styles.color == Color(255, 0, 0)
        assert app.query_one(Label).styles.background == Color(255, 0, 0)


@pytest.mark.parametrize(
    "args", [(False, False), (True, False), (True, True), (False, True)]
)
async def test_query_refresh(args):
    refreshes = []

    class MyWidget(Widget):
        def refresh(self, *, repaint=None, layout=None, recompose=None):
            super().refresh(repaint=repaint, layout=layout)
            refreshes.append((repaint, layout))

    class MyApp(App):
        def compose(self):
            yield MyWidget()

    app = MyApp()
    async with app.run_test() as pilot:
        app.query(MyWidget).refresh(repaint=args[0], layout=args[1])
        assert refreshes[-1] == args


async def test_query_focus_blur():
    class FocusApp(App):
        AUTO_FOCUS = None

        def compose(self) -> ComposeResult:
            yield Input(id="foo")
            yield Input(id="bar")
            yield Input(id="baz")

    app = FocusApp()
    async with app.run_test() as pilot:
        # Nothing focused
        assert app.focused is None
        # Focus first input
        app.query(Input).focus()
        await pilot.pause()
        assert app.focused.id == "foo"
        # Blur inputs
        app.query(Input).blur()
        await pilot.pause()
        assert app.focused is None
        # Focus another
        app.query("#bar").focus()
        await pilot.pause()
        assert app.focused.id == "bar"
        # Focus non existing
        app.query("#egg").focus()
        assert app.focused.id == "bar"