code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def make_bindings(action_prefix: str = "") -> list[Binding]:
"""Make the binding list for testing an app.
Args:
action_prefix (str, optional): An optional prefix for the action name.
Returns:
list[Binding]: The resulting list of bindings.
"""
return [
Binding(key, f"{action_prefix}record('{key}')", key)
for key in [*AppKeyRecorder.ALPHAS, *MOVEMENT_KEYS]
] | Make the binding list for testing an app.
Args:
action_prefix (str, optional): An optional prefix for the action name.
Returns:
list[Binding]: The resulting list of bindings. | make_bindings | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
def __init__(self) -> None:
"""Initialise the recording app."""
super().__init__()
self.pressed_keys: list[str] = [] | Initialise the recording app. | __init__ | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
async def action_record(self, key: str) -> None:
"""Record a key, as used from a binding.
Args:
key (str): The name of the key to record.
"""
self.pressed_keys.append(key) | Record a key, as used from a binding.
Args:
key (str): The name of the key to record. | action_record | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
def all_recorded(self, marker_prefix: str = "") -> None:
"""Were all the bindings recorded from the presses?
Args:
marker_prefix (str, optional): An optional prefix for the result markers.
"""
assert self.pressed_keys == [f"{marker_prefix}{key}" for key in self.ALL_KEYS] | Were all the bindings recorded from the presses?
Args:
marker_prefix (str, optional): An optional prefix for the result markers. | all_recorded | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
async def test_pressing_alpha_on_app() -> None:
"""Test that pressing the alpha key, when it's bound on the app, results in an action fire."""
async with AppWithMovementKeysBound().run_test() as pilot:
await pilot.press(*AppKeyRecorder.ALPHAS)
await pilot.pause()
assert pilot.app.pressed_keys == [*AppKeyRecorder.ALPHAS] | Test that pressing the alpha key, when it's bound on the app, results in an action fire. | test_pressing_alpha_on_app | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
async def test_pressing_movement_keys_app() -> None:
"""Test that pressing the movement keys, when they're bound on the app, results in an action fire."""
async with AppWithMovementKeysBound().run_test() as pilot:
await pilot.press(*AppKeyRecorder.ALL_KEYS)
await pilot.pause()
pilot.app.all_recorded() | Test that pressing the movement keys, when they're bound on the app, results in an action fire. | test_pressing_movement_keys_app | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
async def test_focused_child_widget_with_movement_bindings() -> None:
"""A focused child widget with movement bindings should handle its own actions."""
async with AppWithWidgetWithBindings().run_test() as pilot:
await pilot.press(*AppKeyRecorder.ALL_KEYS)
pilot.app.all_recorded("locally_") | A focused child widget with movement bindings should handle its own actions. | test_focused_child_widget_with_movement_bindings | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
async def test_focused_child_widget_with_movement_bindings_on_screen() -> None:
"""A focused child widget, with movement bindings in the screen, should trigger screen actions."""
async with AppWithScreenWithBindingsWidgetNoBindings().run_test() as pilot:
await pilot.press(*AppKeyRecorder.ALL_KEYS)
pilot.app.all_recorded("screenly_") | A focused child widget, with movement bindings in the screen, should trigger screen actions. | test_focused_child_widget_with_movement_bindings_on_screen | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
async def test_contained_focused_child_widget_with_movement_bindings_on_screen() -> (
None
):
"""A contained focused child widget, with movement bindings in the screen, should trigger screen actions."""
async with AppWithScreenWithBindingsWrappedWidgetNoBindings().run_test() as pilot:
await pilot.press(*AppKeyRecorder.ALL_KEYS)
pilot.app.all_recorded("screenly_") | A contained focused child widget, with movement bindings in the screen, should trigger screen actions. | test_contained_focused_child_widget_with_movement_bindings_on_screen | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
async def test_focused_child_widget_with_movement_bindings_no_inherit() -> None:
"""A focused child widget with movement bindings and inherit_bindings=False should handle its own actions."""
async with AppWithWidgetWithBindingsNoInherit().run_test() as pilot:
await pilot.press(*AppKeyRecorder.ALL_KEYS)
pilot.app.all_recorded("locally_") | A focused child widget with movement bindings and inherit_bindings=False should handle its own actions. | test_focused_child_widget_with_movement_bindings_no_inherit | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
async def test_focused_child_widget_no_inherit_with_movement_bindings_on_screen() -> (
None
):
"""A focused child widget, that doesn't inherit bindings, with movement bindings in the screen, should trigger screen actions."""
async with AppWithScreenWithBindingsWidgetNoBindingsNoInherit().run_test() as pilot:
await pilot.press(*AppKeyRecorder.ALL_KEYS)
pilot.app.all_recorded("screenly_") | A focused child widget, that doesn't inherit bindings, with movement bindings in the screen, should trigger screen actions. | test_focused_child_widget_no_inherit_with_movement_bindings_on_screen | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
async def test_focused_child_widget_no_inherit_empty_bindings_with_movement_bindings_on_screen() -> (
None
):
"""A focused child widget, that doesn't inherit bindings and sets BINDINGS empty, with movement bindings in the screen, should trigger screen actions."""
async with AppWithScreenWithBindingsWidgetEmptyBindingsNoInherit().run_test() as pilot:
await pilot.press(*AppKeyRecorder.ALL_KEYS)
pilot.app.all_recorded("screenly_") | A focused child widget, that doesn't inherit bindings and sets BINDINGS empty, with movement bindings in the screen, should trigger screen actions. | test_focused_child_widget_no_inherit_empty_bindings_with_movement_bindings_on_screen | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
async def test_overlapping_priority_bindings() -> None:
"""Test an app stack with overlapping bindings."""
async with PriorityOverlapApp().run_test() as pilot:
await pilot.press(*"0abcdef")
assert pilot.app.pressed_keys == [
"widget_0",
"app_a",
"screen_b",
"widget_c",
"app_d",
"app_e",
"screen_f",
] | Test an app stack with overlapping bindings. | test_overlapping_priority_bindings | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
async def test_skip_action() -> None:
"""Test that a binding may be skipped by an action raising SkipAction"""
class Handle(Widget, can_focus=True):
BINDINGS = [("t", "test('foo')", "Test")]
def action_test(self, text: str) -> None:
self.app.exit(text)
no_handle_invoked = False
class NoHandle(Widget, can_focus=True):
BINDINGS = [("t", "test('bar')", "Test")]
def action_test(self, text: str) -> bool:
nonlocal no_handle_invoked
no_handle_invoked = True
raise SkipAction()
class SkipApp(App):
def compose(self) -> ComposeResult:
yield Handle(NoHandle())
def on_mount(self) -> None:
self.query_one(NoHandle).focus()
async with SkipApp().run_test() as pilot:
# Check the NoHandle widget has focus
assert pilot.app.query_one(NoHandle).has_focus
# Press the "t" key
await pilot.press("t")
# Check the action on the no handle widget was called
assert no_handle_invoked
# Check the return value, confirming that the action on Handle was called
assert pilot.app.return_value == "foo" | Test that a binding may be skipped by an action raising SkipAction | test_skip_action | python | Textualize/textual | tests/test_binding_inheritance.py | https://github.com/Textualize/textual/blob/master/tests/test_binding_inheritance.py | MIT |
async def test_visibility_changes() -> None:
"""Test changing visibility via code and CSS.
See https://github.com/Textualize/textual/issues/1355 as the motivation for these tests.
"""
class VisibleTester(App[None]):
"""An app for testing visibility changes."""
CSS = """
Widget {
height: 1fr;
}
.hidden {
visibility: hidden;
}
"""
def compose(self) -> ComposeResult:
yield VerticalScroll(
Widget(id="keep"), Widget(id="hide-via-code"), Widget(id="hide-via-css")
)
async with VisibleTester().run_test() as pilot:
assert pilot.app.query_one("#keep").visible is True
assert pilot.app.query_one("#hide-via-code").visible is True
assert pilot.app.query_one("#hide-via-css").visible is True
pilot.app.query_one("#hide-via-code").styles.visibility = "hidden"
await pilot.pause(0)
assert pilot.app.query_one("#keep").visible is True
assert pilot.app.query_one("#hide-via-code").visible is False
assert pilot.app.query_one("#hide-via-css").visible is True
pilot.app.query_one("#hide-via-css").set_class(True, "hidden")
await pilot.pause(0)
assert pilot.app.query_one("#keep").visible is True
assert pilot.app.query_one("#hide-via-code").visible is False
assert pilot.app.query_one("#hide-via-css").visible is False | Test changing visibility via code and CSS.
See https://github.com/Textualize/textual/issues/1355 as the motivation for these tests. | test_visibility_changes | python | Textualize/textual | tests/test_visible.py | https://github.com/Textualize/textual/blob/master/tests/test_visible.py | MIT |
async def test_visible_is_inherited() -> None:
"""Regression test for https://github.com/Textualize/textual/issues/3071"""
class InheritedVisibilityApp(App[None]):
CSS = """
#four {
visibility: visible;
}
#six {
visibility: hidden;
}
"""
def compose(self):
yield Widget(id="one")
with VerticalScroll(id="two"):
yield Widget(id="three")
with VerticalScroll(id="four"):
yield Widget(id="five")
with VerticalScroll(id="six"):
yield Widget(id="seven")
app = InheritedVisibilityApp()
async with app.run_test():
assert app.query_one("#one").visible
assert app.query_one("#two").visible
assert app.query_one("#three").visible
assert app.query_one("#four").visible
assert app.query_one("#five").visible
assert not app.query_one("#six").visible
assert not app.query_one("#seven").visible | Regression test for https://github.com/Textualize/textual/issues/3071 | test_visible_is_inherited | python | Textualize/textual | tests/test_visible.py | https://github.com/Textualize/textual/blob/master/tests/test_visible.py | MIT |
async def test_markdown_file_viewer_anchor_link(tmp_path, link: int) -> None:
"""Test https://github.com/Textualize/textual/issues/3094"""
async with MarkdownFileViewerApp(Path(tmp_path) / "test.md").run_test() as pilot:
# There's not really anything to test *for* here, but the lack of an
# exception is the win (before the fix this is testing it would have
# been FileNotFoundError).
await pilot.click(Markdown, Offset(2, link)) | Test https://github.com/Textualize/textual/issues/3094 | test_markdown_file_viewer_anchor_link | python | Textualize/textual | tests/test_markdownviewer.py | https://github.com/Textualize/textual/blob/master/tests/test_markdownviewer.py | MIT |
async def test_markdown_string_viewer_anchor_link(link: int) -> None:
"""Test https://github.com/Textualize/textual/issues/3094
Also https://github.com/Textualize/textual/pull/3244#issuecomment-1710278718."""
async with MarkdownStringViewerApp(
TEST_MARKDOWN.replace("{{file}}", "")
).run_test() as pilot:
# There's not really anything to test *for* here, but the lack of an
# exception is the win (before the fix this is testing it would have
# been FileNotFoundError).
await pilot.click(Markdown, Offset(2, link)) | Test https://github.com/Textualize/textual/issues/3094
Also https://github.com/Textualize/textual/pull/3244#issuecomment-1710278718. | test_markdown_string_viewer_anchor_link | python | Textualize/textual | tests/test_markdownviewer.py | https://github.com/Textualize/textual/blob/master/tests/test_markdownviewer.py | MIT |
async def test_headings_that_look_like_they_contain_markup(text: str) -> None:
"""Regression test for https://github.com/Textualize/textual/issues/3689.
Things that look like markup are escaped in markdown headings in the table of contents.
"""
document = f"# {text}"
async with MarkdownStringViewerApp(document).run_test() as pilot:
assert pilot.app.query_one(MD.MarkdownH1)._text == Text(text)
toc_tree = pilot.app.query_one(MD.MarkdownTableOfContents).query_one(Tree)
# The toc label looks like "I {text}" but the I is styled so we drop it.
toc_label = toc_tree.root.children[0].label
_, text_label = toc_label.divide([2])
assert text_label == Text(text) | Regression test for https://github.com/Textualize/textual/issues/3689.
Things that look like markup are escaped in markdown headings in the table of contents. | test_headings_that_look_like_they_contain_markup | python | Textualize/textual | tests/test_markdownviewer.py | https://github.com/Textualize/textual/blob/master/tests/test_markdownviewer.py | MIT |
async def test_hide() -> None:
"""Check that setting visibility produces Hide messages."""
# https://github.com/Textualize/textual/issues/3460
visibility: list[bool] = []
class ShowHideLabel(Label):
def on_show(self) -> None:
visibility.append(True)
def on_hide(self) -> None:
visibility.append(False)
class ShowHideApp(App[None]):
BINDINGS = [("space", "toggle_label")]
def compose(self) -> ComposeResult:
yield ShowHideLabel("Here I am")
def action_toggle_label(self) -> None:
self.query_one(ShowHideLabel).visible = not self.query_one(
ShowHideLabel
).visible
app = ShowHideApp()
async with app.run_test() as pilot:
assert visibility == [True]
await pilot.press("space")
assert visibility == [True, False]
await pilot.press("space")
assert visibility == [True, False, True] | Check that setting visibility produces Hide messages. | test_hide | python | Textualize/textual | tests/test_widget_visibility.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_visibility.py | MIT |
async def test_tabbed_content_switch_via_ui():
"""Check tab navigation via the user interface."""
class TabbedApp(App):
def compose(self) -> ComposeResult:
with TabbedContent():
with TabPane("foo", id="foo"):
yield Label("Foo", id="foo-label")
with TabPane("bar", id="bar"):
yield Label("Bar", id="bar-label")
with TabPane("baz", id="baz"):
yield Label("Baz", id="baz-label")
app = TabbedApp()
async with app.run_test() as pilot:
tabbed_content = app.query_one(TabbedContent)
# Check first tab
assert tabbed_content.active == "foo"
assert tabbed_content.active_pane.id == "foo"
await pilot.pause()
assert app.query_one("#foo-label").region
assert not app.query_one("#bar-label").region
assert not app.query_one("#baz-label").region
# Click second tab
await pilot.click(f"Tab#{ContentTab.add_prefix('bar')}")
assert tabbed_content.active == "bar"
assert tabbed_content.active_pane.id == "bar"
await pilot.pause()
assert not app.query_one("#foo-label").region
assert app.query_one("#bar-label").region
assert not app.query_one("#baz-label").region
# Click third tab
await pilot.click(f"Tab#{ContentTab.add_prefix('baz')}")
assert tabbed_content.active == "baz"
assert tabbed_content.active_pane.id == "baz"
await pilot.pause()
assert not app.query_one("#foo-label").region
assert not app.query_one("#bar-label").region
assert app.query_one("#baz-label").region
# Press left
await pilot.press("left")
assert tabbed_content.active == "bar"
await pilot.pause()
assert not app.query_one("#foo-label").region
assert app.query_one("#bar-label").region
assert not app.query_one("#baz-label").region
# Press right
await pilot.press("right")
assert tabbed_content.active == "baz"
await pilot.pause()
assert not app.query_one("#foo-label").region
assert not app.query_one("#bar-label").region
assert app.query_one("#baz-label").region | Check tab navigation via the user interface. | test_tabbed_content_switch_via_ui | python | Textualize/textual | tests/test_tabbed_content.py | https://github.com/Textualize/textual/blob/master/tests/test_tabbed_content.py | MIT |
async def test_tabbed_content_switch_via_code():
"""Check tab navigation via code."""
class TabbedApp(App):
def compose(self) -> ComposeResult:
with TabbedContent():
with TabPane("foo", id="foo"):
yield Label("Foo", id="foo-label")
with TabPane("bar", id="bar"):
yield Label("Bar", id="bar-label")
with TabPane("baz", id="baz"):
yield Label("Baz", id="baz-label")
app = TabbedApp()
async with app.run_test() as pilot:
tabbed_content = app.query_one(TabbedContent)
# Check first tab
assert tabbed_content.active == "foo"
assert app.query_one("#foo-label").region
assert not app.query_one("#bar-label").region
assert not app.query_one("#baz-label").region
# Click second tab
tabbed_content.active = "bar"
await pilot.pause()
assert not app.query_one("#foo-label").region
assert app.query_one("#bar-label").region
assert not app.query_one("#baz-label").region
# Click third tab
tabbed_content.active = "baz"
await pilot.pause()
assert not app.query_one("#foo-label").region
assert not app.query_one("#bar-label").region
assert app.query_one("#baz-label").region
# Check fail with non existent tab
with pytest.raises(ValueError):
tabbed_content.active = "X" | Check tab navigation via code. | test_tabbed_content_switch_via_code | python | Textualize/textual | tests/test_tabbed_content.py | https://github.com/Textualize/textual/blob/master/tests/test_tabbed_content.py | MIT |
async def test_unsetting_tabbed_content_active():
"""Check that setting `TabbedContent.active = ""` unsets active tab."""
messages = []
class TabbedApp(App[None]):
def compose(self) -> ComposeResult:
with TabbedContent(initial="bar"):
with TabPane("foo", id="foo"):
yield Label("Foo", id="foo-label")
with TabPane("bar", id="bar"):
yield Label("Bar", id="bar-label")
with TabPane("baz", id="baz"):
yield Label("Baz", id="baz-label")
def on_tabbed_content_cleared(self, event: TabbedContent.Cleared) -> None:
messages.append(event)
app = TabbedApp()
async with app.run_test() as pilot:
tabbed_content = app.query_one(TabbedContent)
assert bool(tabbed_content.active)
tabbed_content.active = ""
await pilot.pause()
assert len(messages) == 1
assert isinstance(messages[0], TabbedContent.Cleared) | Check that setting `TabbedContent.active = ""` unsets active tab. | test_unsetting_tabbed_content_active | python | Textualize/textual | tests/test_tabbed_content.py | https://github.com/Textualize/textual/blob/master/tests/test_tabbed_content.py | MIT |
async def test_tabbed_content_initial():
"""Checked tabbed content with non-default tab."""
class TabbedApp(App):
def compose(self) -> ComposeResult:
with TabbedContent(initial="bar"):
with TabPane("foo", id="foo"):
yield Label("Foo", id="foo-label")
with TabPane("bar", id="bar"):
yield Label("Bar", id="bar-label")
with TabPane("baz", id="baz"):
yield Label("Baz", id="baz-label")
app = TabbedApp()
async with app.run_test():
tabbed_content = app.query_one(TabbedContent)
assert tabbed_content.active == "bar"
# Check only bar is visible
assert not app.query_one("#foo-label").region
assert app.query_one("#bar-label").region
assert not app.query_one("#baz-label").region | Checked tabbed content with non-default tab. | test_tabbed_content_initial | python | Textualize/textual | tests/test_tabbed_content.py | https://github.com/Textualize/textual/blob/master/tests/test_tabbed_content.py | MIT |
async def test_disabling_nested_tabs():
"""Regression test for https://github.com/Textualize/textual/issues/3145."""
class TabbedApp(App):
def compose(self) -> ComposeResult:
with TabbedContent(id="tabbed-content"):
with TabPane("Tab Pane 1"):
yield Label("foo")
with TabPane("Tab Pane 2"):
yield Label("bar")
with TabPane("Tab Pane 3"):
with TabbedContent():
with TabPane("Inner Pane 1"):
yield Label("fizz")
with TabPane("Inner Pane 2"):
yield Label("bang")
app = TabbedApp()
async with app.run_test() as pilot:
tabber = app.query_one("#tabbed-content", expect_type=TabbedContent)
tabber.disable_tab("tab-1")
await pilot.pause()
tabber.enable_tab("tab-1")
await pilot.pause() | Regression test for https://github.com/Textualize/textual/issues/3145. | test_disabling_nested_tabs | python | Textualize/textual | tests/test_tabbed_content.py | https://github.com/Textualize/textual/blob/master/tests/test_tabbed_content.py | MIT |
async def test_hiding_nested_tabs():
"""Regression test for https://github.com/Textualize/textual/issues/3145."""
class TabbedApp(App):
def compose(self) -> ComposeResult:
with TabbedContent(id="tabbed-content"):
with TabPane("Tab Pane 1"):
yield Label("foo")
with TabPane("Tab Pane 2"):
yield Label("bar")
with TabPane("Tab Pane 3"):
with TabbedContent():
with TabPane("Inner Pane 1"):
yield Label("fizz")
with TabPane("Inner Pane 2"):
yield Label("bang")
app = TabbedApp()
async with app.run_test() as pilot:
tabber = app.query_one("#tabbed-content", expect_type=TabbedContent)
tabber.hide_tab("tab-1")
await pilot.pause()
tabber.show_tab("tab-1")
await pilot.pause() | Regression test for https://github.com/Textualize/textual/issues/3145. | test_hiding_nested_tabs | python | Textualize/textual | tests/test_tabbed_content.py | https://github.com/Textualize/textual/blob/master/tests/test_tabbed_content.py | MIT |
async def test_tabs_nested_in_tabbed_content_doesnt_crash():
"""Regression test for https://github.com/Textualize/textual/issues/3412"""
class TabsNestedInTabbedContent(App):
def compose(self) -> ComposeResult:
with TabbedContent():
with TabPane("Outer TabPane"):
yield Tabs("Inner Tab")
app = TabsNestedInTabbedContent()
async with app.run_test() as pilot:
await pilot.pause() | Regression test for https://github.com/Textualize/textual/issues/3412 | test_tabs_nested_in_tabbed_content_doesnt_crash | python | Textualize/textual | tests/test_tabbed_content.py | https://github.com/Textualize/textual/blob/master/tests/test_tabbed_content.py | MIT |
async def test_tabs_nested_doesnt_interfere_with_ancestor_tabbed_content():
"""When a Tabs is nested as a descendant in the DOM of a TabbedContent,
the messages posted from that Tabs should not interfere with the TabbedContent.
A TabbedContent should only handle messages from Tabs which are direct children.
Relates to https://github.com/Textualize/textual/issues/3412
"""
class TabsNestedInTabbedContent(App):
def compose(self) -> ComposeResult:
with TabbedContent():
with TabPane("OuterTab", id="outer1"):
yield Tabs(
Tab("Tab1", id="tab1"),
Tab("Tab2", id="tab2"),
id="inner-tabs",
)
app = TabsNestedInTabbedContent()
async with app.run_test():
inner_tabs = app.query_one("#inner-tabs", Tabs)
tabbed_content = app.query_one(TabbedContent)
assert inner_tabs.active_tab.id == "tab1"
assert tabbed_content.active == "outer1"
await inner_tabs.clear()
assert inner_tabs.active_tab is None
assert tabbed_content.active == "outer1" | When a Tabs is nested as a descendant in the DOM of a TabbedContent,
the messages posted from that Tabs should not interfere with the TabbedContent.
A TabbedContent should only handle messages from Tabs which are direct children.
Relates to https://github.com/Textualize/textual/issues/3412 | test_tabs_nested_doesnt_interfere_with_ancestor_tabbed_content | python | Textualize/textual | tests/test_tabbed_content.py | https://github.com/Textualize/textual/blob/master/tests/test_tabbed_content.py | MIT |
async def test_disabling_tab_within_tabbed_content_stays_isolated():
"""Disabling a tab within a tab pane should not affect the TabbedContent."""
class TabsNestedInTabbedContent(App):
def compose(self) -> ComposeResult:
with TabbedContent():
with TabPane("TabbedContent", id="duplicate"):
yield Tabs(
Tab("Tab1", id="duplicate"),
Tab("Tab2", id="stay-enabled"),
id="test-tabs",
)
app = TabsNestedInTabbedContent()
async with app.run_test() as pilot:
assert app.query_one("Tab#duplicate").disabled is False
assert app.query_one("TabPane#duplicate").disabled is False
app.query_one("#test-tabs", Tabs).disable("duplicate")
await pilot.pause()
assert app.query_one("Tab#duplicate").disabled is True
assert app.query_one("TabPane#duplicate").disabled is False | Disabling a tab within a tab pane should not affect the TabbedContent. | test_disabling_tab_within_tabbed_content_stays_isolated | python | Textualize/textual | tests/test_tabbed_content.py | https://github.com/Textualize/textual/blob/master/tests/test_tabbed_content.py | MIT |
async def test_freeze():
"""Regression test for https://github.com/Textualize/textual/issues/1608"""
app = MyApp()
with pytest.raises(Exception):
async with app.run_test():
raise Exception("never raised") | Regression test for https://github.com/Textualize/textual/issues/1608 | test_freeze | python | Textualize/textual | tests/test_freeze.py | https://github.com/Textualize/textual/blob/master/tests/test_freeze.py | MIT |
def test_bracketed_paste(parser):
"""When bracketed paste mode is enabled in the terminal emulator and
the user pastes in some text, it will surround the pasted input
with the escape codes "\x1b[200~" and "\x1b[201~". The text between
these codes corresponds to a single `Paste` event in Textual.
"""
pasted_text = "PASTED"
events = list(parser.feed(f"\x1b[200~{pasted_text}\x1b[201~"))
assert len(events) == 1
assert isinstance(events[0], Paste)
assert events[0].text == pasted_text | When bracketed paste mode is enabled in the terminal emulator and
the user pastes in some text, it will surround the pasted input
with the escape codes "\x1b[200~" and "\x1b[201~". The text between
these codes corresponds to a single `Paste` event in Textual. | test_bracketed_paste | python | Textualize/textual | tests/test_xterm_parser.py | https://github.com/Textualize/textual/blob/master/tests/test_xterm_parser.py | MIT |
def test_bracketed_paste_content_contains_escape_codes(parser):
"""When performing a bracketed paste, if the pasted content contains
supported ANSI escape sequences, it should not interfere with the paste,
and no escape sequences within the bracketed paste should be converted
into Textual events.
"""
pasted_text = "PAS\x0fTED"
events = list(parser.feed(f"\x1b[200~{pasted_text}\x1b[201~"))
assert len(events) == 1
assert events[0].text == pasted_text | When performing a bracketed paste, if the pasted content contains
supported ANSI escape sequences, it should not interfere with the paste,
and no escape sequences within the bracketed paste should be converted
into Textual events. | test_bracketed_paste_content_contains_escape_codes | python | Textualize/textual | tests/test_xterm_parser.py | https://github.com/Textualize/textual/blob/master/tests/test_xterm_parser.py | MIT |
def test_cant_match_escape_sequence_too_long(parser):
"""The sequence did not match, and we hit the maximum sequence search
length threshold, so each character should be issued as a key-press instead.
"""
sequence = "\x1b[123456789123456789123123456789123456789123"
events = list(parser.feed(sequence))
# Every character in the sequence is converted to a key press
assert len(events) == len(sequence)
assert all(isinstance(event, Key) for event in events)
# When we backtrack '\x1b' is translated to '^'
assert events[0].key == "circumflex_accent"
# The rest of the characters correspond to the expected key presses
events = events[1:]
for index, character in enumerate(sequence[1:]):
assert events[index].character == character | The sequence did not match, and we hit the maximum sequence search
length threshold, so each character should be issued as a key-press instead. | test_cant_match_escape_sequence_too_long | python | Textualize/textual | tests/test_xterm_parser.py | https://github.com/Textualize/textual/blob/master/tests/test_xterm_parser.py | MIT |
def test_unknown_sequence_followed_by_known_sequence(parser, chunk_size):
"""When we feed the parser an unknown sequence followed by a known
sequence. The characters in the unknown sequence are delivered as keys,
and the known escape sequence that follows is delivered as expected.
"""
unknown_sequence = "\x1b[?"
known_sequence = "\x1b[8~" # key = 'end'
sequence = unknown_sequence + known_sequence
events = []
for chunk in chunks(sequence, chunk_size):
events.append(parser.feed(chunk))
events = list(itertools.chain.from_iterable(list(event) for event in events))
print(repr([event.key for event in events]))
assert [event.key for event in events] == [
"escape",
"left_square_bracket",
"question_mark",
"end",
] | When we feed the parser an unknown sequence followed by a known
sequence. The characters in the unknown sequence are delivered as keys,
and the known escape sequence that follows is delivered as expected. | test_unknown_sequence_followed_by_known_sequence | python | Textualize/textual | tests/test_xterm_parser.py | https://github.com/Textualize/textual/blob/master/tests/test_xterm_parser.py | MIT |
def test_single_escape(parser):
"""A single \x1b should be interpreted as a single press of the Escape key"""
events = list(parser.feed("\x1b"))
events.extend(parser.feed(""))
assert [event.key for event in events] == ["escape"] | A single \x1b should be interpreted as a single press of the Escape key | test_single_escape | python | Textualize/textual | tests/test_xterm_parser.py | https://github.com/Textualize/textual/blob/master/tests/test_xterm_parser.py | MIT |
def test_double_escape(parser):
"""Test double escape."""
events = list(parser.feed("\x1b\x1b"))
events.extend(parser.feed(""))
print(events)
assert [event.key for event in events] == ["escape", "escape"] | Test double escape. | test_double_escape | python | Textualize/textual | tests/test_xterm_parser.py | https://github.com/Textualize/textual/blob/master/tests/test_xterm_parser.py | MIT |
def test_mouse_click(parser, sequence, event_type, shift, meta):
"""ANSI codes for mouse should be converted to Textual events"""
events = list(parser.feed(sequence))
assert len(events) == 1
event = events[0]
assert isinstance(event, event_type)
assert event.x == 49
assert event.y == 24
assert event.screen_x == 49
assert event.screen_y == 24
assert event.meta is meta
assert event.shift is shift | ANSI codes for mouse should be converted to Textual events | test_mouse_click | python | Textualize/textual | tests/test_xterm_parser.py | https://github.com/Textualize/textual/blob/master/tests/test_xterm_parser.py | MIT |
def test_mouse_scroll_up(parser, sequence, shift, meta):
"""Scrolling the mouse with and without modifiers held down.
We don't currently capture modifier keys in scroll events.
"""
events = list(parser.feed(sequence))
assert len(events) == 1
event = events[0]
assert isinstance(event, MouseScrollUp)
assert event.x == 17
assert event.y == 24
assert event.shift is shift
assert event.meta is meta | Scrolling the mouse with and without modifiers held down.
We don't currently capture modifier keys in scroll events. | test_mouse_scroll_up | python | Textualize/textual | tests/test_xterm_parser.py | https://github.com/Textualize/textual/blob/master/tests/test_xterm_parser.py | MIT |
def test_escape_sequence_resulting_in_multiple_keypresses(parser):
"""Some sequences are interpreted as more than 1 keypress"""
events = list(parser.feed("\x1b[2;4~"))
assert len(events) == 2
assert events[0].key == "escape"
assert events[1].key == "shift+insert" | Some sequences are interpreted as more than 1 keypress | test_escape_sequence_resulting_in_multiple_keypresses | python | Textualize/textual | tests/test_xterm_parser.py | https://github.com/Textualize/textual/blob/master/tests/test_xterm_parser.py | MIT |
def test_environ_int(monkeypatch):
"""Check minimum is applied."""
monkeypatch.setenv("FOO", "-1")
assert _get_environ_int("FOO", 1, minimum=0) == 0
monkeypatch.setenv("FOO", "0")
assert _get_environ_int("FOO", 1, minimum=0) == 0
monkeypatch.setenv("FOO", "1")
assert _get_environ_int("FOO", 1, minimum=0) == 1 | Check minimum is applied. | test_environ_int | python | Textualize/textual | tests/test_constants.py | https://github.com/Textualize/textual/blob/master/tests/test_constants.py | MIT |
def test_environ_bool(monkeypatch):
"""Anything other than "1" is False."""
monkeypatch.setenv("BOOL", "1")
assert _get_environ_bool("BOOL") is True
monkeypatch.setenv("BOOL", "")
assert _get_environ_bool("BOOL") is False
monkeypatch.setenv("BOOL", "0")
assert _get_environ_bool("BOOL") is False | Anything other than "1" is False. | test_environ_bool | python | Textualize/textual | tests/test_constants.py | https://github.com/Textualize/textual/blob/master/tests/test_constants.py | MIT |
def test_environ_port(monkeypatch):
"""Valid ports are between 0 and 65536."""
monkeypatch.setenv("PORT", "-1")
assert _get_environ_port("PORT", 80) == 80
monkeypatch.setenv("PORT", "0")
assert _get_environ_port("PORT", 80) == 0
monkeypatch.setenv("PORT", "65536")
assert _get_environ_port("PORT", 80) == 80 | Valid ports are between 0 and 65536. | test_environ_port | python | Textualize/textual | tests/test_constants.py | https://github.com/Textualize/textual/blob/master/tests/test_constants.py | MIT |
async def test_tab_label():
"""It should be possible to access a tab's label."""
assert Tab("Pilot").label_text == "Pilot" | It should be possible to access a tab's label. | test_tab_label | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_tab_relabel():
"""It should be possible to relabel a tab."""
tab = Tab("Pilot")
assert tab.label_text == "Pilot"
tab.label = "Aeryn"
assert tab.label_text == "Aeryn" | It should be possible to relabel a tab. | test_tab_relabel | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_compose_empty_tabs():
"""It should be possible to create an empty Tabs."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs()
async with TabsApp().run_test() as pilot:
assert pilot.app.query_one(Tabs).tab_count == 0
assert pilot.app.query_one(Tabs).active_tab is None | It should be possible to create an empty Tabs. | test_compose_empty_tabs | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_compose_tabs_from_strings():
"""It should be possible to create a Tabs from some strings."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs("John", "Aeryn", "Moya", "Pilot")
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 4
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1" | It should be possible to create a Tabs from some strings. | test_compose_tabs_from_strings | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_compose_tabs_from_tabs():
"""It should be possible to create a Tabs from some Tabs."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs(
Tab("John"),
Tab("Aeryn"),
Tab("Moya"),
Tab("Pilot"),
)
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 4
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1" | It should be possible to create a Tabs from some Tabs. | test_compose_tabs_from_tabs | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_add_tabs_later():
"""It should be possible to add tabs later on in the app's cycle."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs()
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 0
assert tabs.active_tab is None
await tabs.add_tab("John")
assert tabs.tab_count == 1
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
await tabs.add_tab("Aeryn")
assert tabs.tab_count == 2
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1" | It should be possible to add tabs later on in the app's cycle. | test_add_tabs_later | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_add_tab_before():
"""It should be possible to add a tab before another tab."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs("Pilot")
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 1
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == "tab-1"
await tabs.add_tab("John", before="tab-1")
assert tabs.tab_count == 2
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == "tab-1"
await tabs.add_tab("John", before=tabs.active_tab)
assert tabs.tab_count == 3
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == "tab-1" | It should be possible to add a tab before another tab. | test_add_tab_before | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_add_tab_before_badly():
"""Test exceptions from badly adding a tab before another."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs("Pilot")
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 1
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == "tab-1"
with pytest.raises(Tabs.TabError):
tabs.add_tab("John", before="this-is-not-a-tab")
assert tabs.tab_count == 1
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == "tab-1"
with pytest.raises(Tabs.TabError):
tabs.add_tab("John", before=Tab("I just made this up"))
assert tabs.tab_count == 1
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == "tab-1" | Test exceptions from badly adding a tab before another. | test_add_tab_before_badly | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_add_tab_after():
"""It should be possible to add a tab after another tab."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs("Pilot")
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 1
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == "tab-1"
await tabs.add_tab("John", after="tab-1")
assert tabs.tab_count == 2
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == "tab-1"
await tabs.add_tab("John", after=tabs.active_tab)
assert tabs.tab_count == 3
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == "tab-1" | It should be possible to add a tab after another tab. | test_add_tab_after | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_add_tab_after_badly():
"""Test exceptions from badly adding a tab after another."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs("Pilot")
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 1
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == "tab-1"
with pytest.raises(Tabs.TabError):
tabs.add_tab("John", after="this-is-not-a-tab")
assert tabs.tab_count == 1
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == "tab-1"
with pytest.raises(Tabs.TabError):
tabs.add_tab("John", after=Tab("I just made this up"))
assert tabs.tab_count == 1
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == "tab-1" | Test exceptions from badly adding a tab after another. | test_add_tab_after_badly | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_add_tab_before_and_after():
"""Attempting to add a tab before and after another is an error."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs("Pilot")
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 1
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == "tab-1"
with pytest.raises(Tabs.TabError):
tabs.add_tab("John", before="tab-1", after="tab-1") | Attempting to add a tab before and after another is an error. | test_add_tab_before_and_after | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_remove_tabs():
"""It should be possible to remove tabs."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs("John", "Aeryn", "Moya", "Pilot")
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 4
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
await tabs.remove_tab("tab-1")
assert tabs.tab_count == 3
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-2"
await tabs.remove_tab(tabs.query_one("#tab-2", Tab))
assert tabs.tab_count == 2
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-3"
await tabs.remove_tab("tab-does-not-exist")
assert tabs.tab_count == 2
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-3"
await tabs.remove_tab(None)
assert tabs.tab_count == 2
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-3"
await tabs.remove_tab("tab-3")
await tabs.remove_tab("tab-4")
assert tabs.tab_count == 0
assert tabs.active_tab is None | It should be possible to remove tabs. | test_remove_tabs | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_remove_tabs_reversed():
"""It should be possible to remove tabs."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs("John", "Aeryn", "Moya", "Pilot")
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 4
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
await tabs.remove_tab("tab-4")
assert tabs.tab_count == 3
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
await tabs.remove_tab("tab-3")
assert tabs.tab_count == 2
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
await tabs.remove_tab("tab-2")
assert tabs.tab_count == 1
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
await tabs.remove_tab("tab-1")
assert tabs.tab_count == 0
assert tabs.active_tab is None | It should be possible to remove tabs. | test_remove_tabs_reversed | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_clear_tabs():
"""It should be possible to clear all tabs."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs("John", "Aeryn", "Moya", "Pilot")
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 4
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
await tabs.clear()
assert tabs.tab_count == 0
assert tabs.active_tab is None | It should be possible to clear all tabs. | test_clear_tabs | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_change_active_from_code():
"""It should be possible to change the active tab from code.."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs("John", "Aeryn", "Moya", "Pilot")
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 4
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == tabs.active_tab.id
tabs.active = "tab-2"
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-2"
assert tabs.active == tabs.active_tab.id
tabs.active = ""
assert tabs.active_tab is None | It should be possible to change the active tab from code.. | test_change_active_from_code | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_navigate_tabs_with_keyboard():
"""It should be possible to navigate tabs with the keyboard."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs("John", "Aeryn", "Moya", "Pilot")
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 4
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == tabs.active_tab.id
await pilot.press("right")
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-2"
assert tabs.active == tabs.active_tab.id
await pilot.press("left")
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == tabs.active_tab.id
await pilot.press(*(["left"] * tabs.tab_count))
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
assert tabs.active == tabs.active_tab.id | It should be possible to navigate tabs with the keyboard. | test_navigate_tabs_with_keyboard | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_navigate_empty_tabs_with_keyboard():
"""It should be possible to navigate an empty tabs with the keyboard."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs()
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 0
assert tabs.active_tab is None
assert tabs.active == ""
await pilot.press("right")
assert tabs.active_tab is None
assert tabs.active == ""
await pilot.press("left")
assert tabs.active_tab is None
assert tabs.active == "" | It should be possible to navigate an empty tabs with the keyboard. | test_navigate_empty_tabs_with_keyboard | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_navigate_tabs_with_mouse():
"""It should be possible to navigate tabs with the mouse."""
class TabsApp(App[None]):
def compose(self) -> ComposeResult:
yield Tabs("John", "Aeryn", "Moya", "Pilot")
async with TabsApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
assert tabs.tab_count == 4
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1"
await pilot.click("#tab-2")
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-2"
await pilot.click("Underline", offset=(2, 0))
assert tabs.active_tab is not None
assert tabs.active_tab.id == "tab-1" | It should be possible to navigate tabs with the mouse. | test_navigate_tabs_with_mouse | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_startup_messages():
"""On startup there should be a tab activated message."""
async with TabsMessageCatchApp().run_test() as pilot:
assert pilot.app.intended_handlers == ["on_tabs_tab_activated"] | On startup there should be a tab activated message. | test_startup_messages | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_change_tab_with_code_messages():
"""Changing tab in code should result in an activated tab message."""
async with TabsMessageCatchApp().run_test() as pilot:
pilot.app.query_one(Tabs).active = "tab-2"
await pilot.pause()
assert pilot.app.intended_handlers == [
"on_tabs_tab_activated",
"on_tabs_tab_activated",
] | Changing tab in code should result in an activated tab message. | test_change_tab_with_code_messages | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_remove_tabs_messages():
"""Removing tabs should result in various messages."""
async with TabsMessageCatchApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
for n in range(4):
await tabs.remove_tab(f"tab-{n+1}")
await pilot.pause()
assert pilot.app.intended_handlers == [
"on_tabs_tab_activated",
"on_tabs_tab_activated",
"on_tabs_tab_activated",
"on_tabs_tab_activated",
"on_tabs_cleared",
] | Removing tabs should result in various messages. | test_remove_tabs_messages | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_reverse_remove_tabs_messages():
"""Removing tabs should result in various messages."""
async with TabsMessageCatchApp().run_test() as pilot:
tabs = pilot.app.query_one(Tabs)
for n in reversed(range(4)):
await tabs.remove_tab(f"tab-{n+1}")
await pilot.pause()
assert pilot.app.intended_handlers == [
"on_tabs_tab_activated",
"on_tabs_cleared",
] | Removing tabs should result in various messages. | test_reverse_remove_tabs_messages | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_keyboard_navigation_messages():
"""Keyboard navigation should result in the expected messages."""
async with TabsMessageCatchApp().run_test() as pilot:
await pilot.press("right")
await pilot.pause()
await pilot.press("left")
await pilot.pause()
assert pilot.app.intended_handlers == [
"on_tabs_tab_activated",
"on_tabs_tab_activated",
"on_tabs_tab_activated",
] | Keyboard navigation should result in the expected messages. | test_keyboard_navigation_messages | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_mouse_navigation_messages():
"""Mouse navigation should result in the expected messages."""
async with TabsMessageCatchApp().run_test() as pilot:
await pilot.click("#tab-2")
await pilot.pause()
await pilot.click("Underline", offset=(2, 0))
await pilot.pause()
assert pilot.app.intended_handlers == [
"on_tabs_tab_activated",
"on_tabs_tab_activated",
"on_tabs_tab_activated",
] | Mouse navigation should result in the expected messages. | test_mouse_navigation_messages | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
async def test_disabled_tab_is_not_activated_by_clicking_underline():
"""Regression test for https://github.com/Textualize/textual/issues/4701"""
class DisabledTabApp(App):
def compose(self) -> ComposeResult:
yield Tabs(
Tab("Enabled", id="enabled"),
Tab("Disabled", id="disabled", disabled=True),
)
app = DisabledTabApp()
async with app.run_test() as pilot:
# Click the underline beneath the disabled tab
await pilot.click(Tabs, offset=(14, 2))
tabs = pilot.app.query_one(Tabs)
assert tabs.active_tab is not None
assert tabs.active_tab.id == "enabled" | Regression test for https://github.com/Textualize/textual/issues/4701 | test_disabled_tab_is_not_activated_by_clicking_underline | python | Textualize/textual | tests/test_tabs.py | https://github.com/Textualize/textual/blob/master/tests/test_tabs.py | MIT |
def test_Integer_failure_description_when_NotANumber():
"""Regression test for https://github.com/Textualize/textual/issues/4413"""
validator = Integer()
result = validator.validate("x")
assert result.is_valid is False
assert result.failure_descriptions[0] == "Must be a valid integer." | Regression test for https://github.com/Textualize/textual/issues/4413 | test_Integer_failure_description_when_NotANumber | python | Textualize/textual | tests/test_validation.py | https://github.com/Textualize/textual/blob/master/tests/test_validation.py | MIT |
def check_quit(quit: bool | None) -> None:
"""Called when QuitScreen is dismissed."""
self.check_quit_called = True | Called when QuitScreen is dismissed. | action_request_quit.check_quit | python | Textualize/textual | tests/test_command.py | https://github.com/Textualize/textual/blob/master/tests/test_command.py | MIT |
def action_request_quit(self) -> None:
"""Action to display the quit dialog."""
def check_quit(quit: bool | None) -> None:
"""Called when QuitScreen is dismissed."""
self.check_quit_called = True
self.push_screen(QuitScreen(), check_quit) | Action to display the quit dialog. | action_request_quit | python | Textualize/textual | tests/test_command.py | https://github.com/Textualize/textual/blob/master/tests/test_command.py | MIT |
async def test_command_dismiss():
"""Regression test for https://github.com/Textualize/textual/issues/5512"""
app = ModalApp()
async with app.run_test() as pilot:
await pilot.press("ctrl+p", *"modal quit", "enter")
await pilot.pause()
await pilot.press("enter")
assert app.check_quit_called | Regression test for https://github.com/Textualize/textual/issues/5512 | test_command_dismiss | python | Textualize/textual | tests/test_command.py | https://github.com/Textualize/textual/blob/master/tests/test_command.py | MIT |
async def test_watch():
"""Test that changes to a watched reactive attribute happen immediately."""
class WatchApp(App):
count = reactive(0, init=False)
watcher_call_count = 0
def watch_count(self, value: int) -> None:
self.watcher_call_count = value
app = WatchApp()
async with app.run_test():
app.count += 1
assert app.watcher_call_count == 1
app.count += 1
assert app.watcher_call_count == 2
app.count -= 1
assert app.watcher_call_count == 1
app.count -= 1
assert app.watcher_call_count == 0 | Test that changes to a watched reactive attribute happen immediately. | test_watch | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_watch_async_init_false():
"""Ensure that async watchers are called eventually when set by user code"""
class WatchAsyncApp(App):
count = reactive(OLD_VALUE, init=False)
watcher_old_value = None
watcher_new_value = None
watcher_called_event = asyncio.Event()
async def watch_count(self, old_value: int, new_value: int) -> None:
self.watcher_old_value = old_value
self.watcher_new_value = new_value
self.watcher_called_event.set()
app = WatchAsyncApp()
async with app.run_test():
app.count = NEW_VALUE
assert app.count == NEW_VALUE # Value is set immediately
try:
await asyncio.wait_for(app.watcher_called_event.wait(), timeout=0.05)
except TimeoutError:
pytest.fail("Async watch method (watch_count) wasn't called within timeout")
assert app.count == NEW_VALUE # Sanity check
assert app.watcher_old_value == OLD_VALUE # old_value passed to watch method
assert app.watcher_new_value == NEW_VALUE # new_value passed to watch method | Ensure that async watchers are called eventually when set by user code | test_watch_async_init_false | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_watch_async_init_true():
"""Ensure that when init is True in a reactive, its async watcher gets called
by Textual eventually, even when the user does not set the value themselves."""
class WatchAsyncApp(App):
count = reactive(OLD_VALUE, init=True)
watcher_called_event = asyncio.Event()
watcher_old_value = None
watcher_new_value = None
async def watch_count(self, old_value: int, new_value: int) -> None:
self.watcher_old_value = old_value
self.watcher_new_value = new_value
self.watcher_called_event.set()
app = WatchAsyncApp()
async with app.run_test():
try:
await asyncio.wait_for(app.watcher_called_event.wait(), timeout=0.05)
except TimeoutError:
pytest.fail(
"Async watcher wasn't called within timeout when reactive init = True"
)
assert app.count == OLD_VALUE
assert app.watcher_old_value == OLD_VALUE
assert app.watcher_new_value == OLD_VALUE # The value wasn't changed | Ensure that when init is True in a reactive, its async watcher gets called
by Textual eventually, even when the user does not set the value themselves. | test_watch_async_init_true | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_reactive_with_callable_default():
"""A callable can be supplied as the default value for a reactive.
Textual will call it in order to retrieve the default value."""
class ReactiveCallable(App):
value = reactive(lambda: 123)
watcher_called_with = None
def watch_value(self, new_value):
self.watcher_called_with = new_value
app = ReactiveCallable()
async with app.run_test():
assert app.value == 123
assert app.watcher_called_with == 123 | A callable can be supplied as the default value for a reactive.
Textual will call it in order to retrieve the default value. | test_reactive_with_callable_default | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_validate_init_true():
"""When init is True for a reactive attribute, Textual should call the validator
AND the watch method when the app starts."""
validator_call_count = 0
class ValidatorInitTrue(App):
count = var(5, init=True)
def validate_count(self, value: int) -> int:
nonlocal validator_call_count
validator_call_count += 1
return value + 1
app = ValidatorInitTrue()
async with app.run_test():
app.count = 5
assert app.count == 6 # Validator should run, so value should be 5+1=6
assert validator_call_count == 1 | When init is True for a reactive attribute, Textual should call the validator
AND the watch method when the app starts. | test_validate_init_true | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_validate_init_true_set_before_dom_ready():
"""When init is True for a reactive attribute, Textual should call the validator
AND the watch method when the app starts."""
validator_call_count = 0
class ValidatorInitTrue(App):
count = var(5, init=True)
def validate_count(self, value: int) -> int:
nonlocal validator_call_count
validator_call_count += 1
return value + 1
app = ValidatorInitTrue()
app.count = 5
async with app.run_test():
assert app.count == 6 # Validator should run, so value should be 5+1=6
assert validator_call_count == 1 | When init is True for a reactive attribute, Textual should call the validator
AND the watch method when the app starts. | test_validate_init_true_set_before_dom_ready | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_reactive_inheritance():
"""Check that inheritance works as expected for reactives."""
class Primary(App):
foo = reactive(1)
bar = reactive("bar")
class Secondary(Primary):
foo = reactive(2)
egg = reactive("egg")
class Tertiary(Secondary):
baz = reactive("baz")
primary = Primary()
secondary = Secondary()
tertiary = Tertiary()
primary_reactive_count = len(primary._reactives)
# Secondary adds one new reactive
assert len(secondary._reactives) == primary_reactive_count + 1
Reactive._initialize_object(primary)
Reactive._initialize_object(secondary)
Reactive._initialize_object(tertiary)
# Primary doesn't have egg
with pytest.raises(AttributeError):
assert primary.egg
# primary has foo of 1
assert primary.foo == 1
# secondary has different reactive
assert secondary.foo == 2
# foo is accessible through tertiary
assert tertiary.foo == 2
with pytest.raises(AttributeError):
secondary.baz
assert tertiary.baz == "baz" | Check that inheritance works as expected for reactives. | test_reactive_inheritance | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_compute():
"""Check compute method is called."""
class ComputeApp(App):
count = var(0)
count_double = var(0)
def __init__(self) -> None:
self.start = 0
super().__init__()
def compute_count_double(self) -> int:
return self.start + self.count * 2
app = ComputeApp()
async with app.run_test():
assert app.count_double == 0
app.count = 1
assert app.count_double == 2
assert app.count_double == 2
app.count = 2
assert app.count_double == 4
app.start = 10
assert app.count_double == 14
with pytest.raises(AttributeError):
app.count_double = 100 | Check compute method is called. | test_compute | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
def watch_show_ac(self, show_ac: bool) -> None:
"""Called when show_ac changes."""
watch_called.append(show_ac) | Called when show_ac changes. | test_watch_compute.watch_show_ac | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_watch_compute():
"""Check that watching a computed attribute works."""
watch_called: list[bool] = []
class Calculator(App):
numbers = var("0")
show_ac = var(True)
value = var("")
def compute_show_ac(self) -> bool:
return self.value in ("", "0") and self.numbers == "0"
def watch_show_ac(self, show_ac: bool) -> None:
"""Called when show_ac changes."""
watch_called.append(show_ac)
app = Calculator()
# Referencing the value calls compute
# Setting any reactive values calls compute
async with app.run_test():
assert app.show_ac is True
app.value = "1"
assert app.show_ac is False
app.value = "0"
assert app.show_ac is True
app.numbers = "123"
assert app.show_ac is False
assert watch_called == [True, True, False, False, True, True, False, False] | Check that watching a computed attribute works. | test_watch_compute | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_public_and_private_watch() -> None:
"""If a reactive/var has public and private watches both should get called."""
calls: dict[str, bool] = {"private": False, "public": False}
class PrivateWatchTest(App):
counter = var(0, init=False)
def watch_counter(self) -> None:
calls["public"] = True
def _watch_counter(self) -> None:
calls["private"] = True
async with PrivateWatchTest().run_test() as pilot:
assert calls["private"] is False
assert calls["public"] is False
pilot.app.counter += 1
assert calls["private"] is True
assert calls["public"] is True | If a reactive/var has public and private watches both should get called. | test_public_and_private_watch | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_public_and_private_validate() -> None:
"""If a reactive/var has public and private validate both should get called."""
calls: dict[str, bool] = {"private": False, "public": False}
class PrivateValidateTest(App):
counter = var(0, init=False)
def validate_counter(self, _: int) -> None:
calls["public"] = True
def _validate_counter(self, _: int) -> None:
calls["private"] = True
async with PrivateValidateTest().run_test() as pilot:
assert calls["private"] is False
assert calls["public"] is False
pilot.app.counter += 1
assert calls["private"] is True
assert calls["public"] is True | If a reactive/var has public and private validate both should get called. | test_public_and_private_validate | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_public_and_private_validate_order() -> None:
"""The private validate should be called first."""
class ValidateOrderTest(App):
value = var(0, init=False)
def validate_value(self, value: int) -> int:
if value < 0:
return 42
return value
def _validate_value(self, value: int) -> int:
if value < 0:
return 73
return value
async with ValidateOrderTest().run_test() as pilot:
pilot.app.value = -10
assert pilot.app.value == 73 | The private validate should be called first. | test_public_and_private_validate_order | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_public_and_private_compute() -> None:
"""If a reactive/var has public and private compute both should get called."""
with pytest.raises(TooManyComputesError):
class PublicAndPrivateComputeTest(App):
counter = var(0, init=False)
def compute_counter(self):
pass
def _compute_counter(self):
pass | If a reactive/var has public and private compute both should get called. | test_public_and_private_compute | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_async_reactive_watch_callbacks_go_on_the_watcher():
"""Regression test for https://github.com/Textualize/textual/issues/3036.
This makes sure that async callbacks are called.
See the next test for sync callbacks.
"""
from_app = False
from_holder = False
class Holder(Widget):
attr = var(None)
def watch_attr(self):
nonlocal from_holder
from_holder = True
class MyApp(App):
def __init__(self):
super().__init__()
self.holder = Holder()
def on_mount(self):
self.watch(self.holder, "attr", self.callback)
def update(self):
self.holder.attr = "hello world"
async def callback(self):
nonlocal from_app
from_app = True
async with MyApp().run_test() as pilot:
pilot.app.update()
await pilot.pause()
assert from_holder
assert from_app | Regression test for https://github.com/Textualize/textual/issues/3036.
This makes sure that async callbacks are called.
See the next test for sync callbacks. | test_async_reactive_watch_callbacks_go_on_the_watcher | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_sync_reactive_watch_callbacks_go_on_the_watcher():
"""Regression test for https://github.com/Textualize/textual/issues/3036.
This makes sure that sync callbacks are called.
See the previous test for async callbacks.
"""
from_app = False
from_holder = False
class Holder(Widget):
attr = var(None)
def watch_attr(self):
nonlocal from_holder
from_holder = True
class MyApp(App):
def __init__(self):
super().__init__()
self.holder = Holder()
def on_mount(self):
self.watch(self.holder, "attr", self.callback)
def update(self):
self.holder.attr = "hello world"
def callback(self):
nonlocal from_app
from_app = True
async with MyApp().run_test() as pilot:
pilot.app.update()
await pilot.pause()
assert from_holder
assert from_app | Regression test for https://github.com/Textualize/textual/issues/3036.
This makes sure that sync callbacks are called.
See the previous test for async callbacks. | test_sync_reactive_watch_callbacks_go_on_the_watcher | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_set_reactive():
"""Test set_reactive doesn't call watchers."""
class MyWidget(Widget):
foo = reactive("")
def __init__(self, foo: str) -> None:
super().__init__()
self.set_reactive(MyWidget.foo, foo)
def watch_foo(self) -> None:
# Should never get here
1 / 0
class MyApp(App):
def compose(self) -> ComposeResult:
yield MyWidget("foobar")
app = MyApp()
async with app.run_test():
assert app.query_one(MyWidget).foo == "foobar" | Test set_reactive doesn't call watchers. | test_set_reactive | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_no_duplicate_external_watchers() -> None:
"""Make sure we skip duplicated watchers."""
counter = 0
class Holder(Widget):
attr = var(None)
class MyApp(App[None]):
def __init__(self) -> None:
super().__init__()
self.holder = Holder()
def on_mount(self) -> None:
self.watch(self.holder, "attr", self.callback)
self.watch(self.holder, "attr", self.callback)
def callback(self) -> None:
nonlocal counter
counter += 1
app = MyApp()
async with app.run_test():
assert counter == 1
app.holder.attr = 73
assert counter == 2 | Make sure we skip duplicated watchers. | test_no_duplicate_external_watchers | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_external_watch_init_does_not_propagate() -> None:
"""Regression test for https://github.com/Textualize/textual/issues/3878.
Make sure that when setting an extra watcher programmatically and `init` is set,
we init only the new watcher and not the other ones, but at the same
time make sure both watchers work in regular circumstances.
"""
logs: list[str] = []
class SomeWidget(Widget):
test_1: var[int] = var(0)
test_2: var[int] = var(0, init=False)
def watch_test_1(self) -> None:
logs.append("test_1")
def watch_test_2(self) -> None:
logs.append("test_2")
class InitOverrideApp(App[None]):
def compose(self) -> ComposeResult:
yield SomeWidget()
def on_mount(self) -> None:
def watch_test_2_extra() -> None:
logs.append("test_2_extra")
self.watch(self.query_one(SomeWidget), "test_2", watch_test_2_extra)
app = InitOverrideApp()
async with app.run_test():
assert logs == ["test_1", "test_2_extra"]
app.query_one(SomeWidget).test_2 = 73
assert logs.count("test_2_extra") == 2
assert logs.count("test_2") == 1 | Regression test for https://github.com/Textualize/textual/issues/3878.
Make sure that when setting an extra watcher programmatically and `init` is set,
we init only the new watcher and not the other ones, but at the same
time make sure both watchers work in regular circumstances. | test_external_watch_init_does_not_propagate | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_external_watch_init_does_not_propagate_to_externals() -> None:
"""Regression test for https://github.com/Textualize/textual/issues/3878.
Make sure that when setting an extra watcher programmatically and `init` is set,
we init only the new watcher and not the other ones (even if they were
added dynamically with `watch`), but at the same time make sure all watchers
work in regular circumstances.
"""
logs: list[str] = []
class SomeWidget(Widget):
test_var: var[int] = var(0)
class MyApp(App[None]):
def compose(self) -> ComposeResult:
yield SomeWidget()
def add_first_watcher(self) -> None:
def first_callback() -> None:
logs.append("first")
self.watch(self.query_one(SomeWidget), "test_var", first_callback)
def add_second_watcher(self) -> None:
def second_callback() -> None:
logs.append("second")
self.watch(self.query_one(SomeWidget), "test_var", second_callback)
app = MyApp()
async with app.run_test():
assert logs == []
app.add_first_watcher()
assert logs == ["first"]
app.add_second_watcher()
assert logs == ["first", "second"]
app.query_one(SomeWidget).test_var = 73
assert logs == ["first", "second", "first", "second"] | Regression test for https://github.com/Textualize/textual/issues/3878.
Make sure that when setting an extra watcher programmatically and `init` is set,
we init only the new watcher and not the other ones (even if they were
added dynamically with `watch`), but at the same time make sure all watchers
work in regular circumstances. | test_external_watch_init_does_not_propagate_to_externals | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_message_sender_from_reactive() -> None:
"""Test that the sender of a message comes from the reacting widget."""
message_senders: list[MessagePump | None] = []
class TestWidget(Widget):
test_var: var[int] = var(0, init=False)
class TestMessage(Message):
pass
def watch_test_var(self) -> None:
self.post_message(self.TestMessage())
def make_reaction(self) -> None:
self.test_var += 1
class TestContainer(Widget):
def compose(self) -> ComposeResult:
yield TestWidget()
def on_test_widget_test_message(self, event: TestWidget.TestMessage) -> None:
nonlocal message_senders
message_senders.append(event._sender)
class TestApp(App[None]):
def compose(self) -> ComposeResult:
yield TestContainer()
async with TestApp().run_test() as pilot:
assert message_senders == []
pilot.app.query_one(TestWidget).make_reaction()
await pilot.pause()
assert message_senders == [pilot.app.query_one(TestWidget)] | Test that the sender of a message comes from the reacting widget. | test_message_sender_from_reactive | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_mutate_reactive() -> None:
"""Test explicitly mutating reactives"""
watched_names: list[list[str]] = []
class TestWidget(Widget):
names: reactive[list[str]] = reactive(list)
def watch_names(self, names: list[str]) -> None:
watched_names.append(names.copy())
class TestApp(App):
def compose(self) -> ComposeResult:
yield TestWidget()
app = TestApp()
async with app.run_test():
widget = app.query_one(TestWidget)
# watch method called on startup
assert watched_names == [[]]
# Mutate the list
widget.names.append("Paul")
# No changes expected
assert watched_names == [[]]
# Explicitly mutate the reactive
widget.mutate_reactive(TestWidget.names)
# Watcher will be invoked
assert watched_names == [[], ["Paul"]]
# Make further modifications
widget.names.append("Jessica")
widget.names.remove("Paul")
# No change expected
assert watched_names == [[], ["Paul"]]
# Explicit mutation
widget.mutate_reactive(TestWidget.names)
# Watcher should be invoked
assert watched_names == [[], ["Paul"], ["Jessica"]] | Test explicitly mutating reactives | test_mutate_reactive | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
async def test_mutate_reactive_data_bind() -> None:
"""https://github.com/Textualize/textual/issues/4825"""
# Record mutations to TestWidget.messages
widget_messages: list[list[str]] = []
class TestWidget(Widget):
messages: reactive[list[str]] = reactive(list, init=False)
def watch_messages(self, names: list[str]) -> None:
widget_messages.append(names.copy())
class TestApp(App):
messages: reactive[list[str]] = reactive(list, init=False)
def compose(self) -> ComposeResult:
yield TestWidget().data_bind(TestApp.messages)
app = TestApp()
async with app.run_test():
test_widget = app.query_one(TestWidget)
assert widget_messages == [[]]
assert test_widget.messages == []
# Should be the same instance
assert app.messages is test_widget.messages
# Mutate app
app.messages.append("foo")
# Mutations aren't detected
assert widget_messages == [[]]
assert app.messages == ["foo"]
assert test_widget.messages == ["foo"]
# Explicitly mutate app reactive
app.mutate_reactive(TestApp.messages)
# Mutating app, will also invoke watchers on any data binds
assert widget_messages == [[], ["foo"]]
assert app.messages == ["foo"]
assert test_widget.messages == ["foo"] | https://github.com/Textualize/textual/issues/4825 | test_mutate_reactive_data_bind | python | Textualize/textual | tests/test_reactive.py | https://github.com/Textualize/textual/blob/master/tests/test_reactive.py | MIT |
def test_dim_apply():
"""Check dim filter changes color and resets dim attribute."""
dim_filter = DimFilter()
segments = [Segment("Hello, World!", Style.parse("dim #ffffff on #0000ff"))]
dimmed_segments = dim_filter.apply(segments, Color(0, 0, 0))
expected = [Segment("Hello, World!", Style.parse("not dim #7f7fff on #0000ff"))]
assert dimmed_segments == expected | Check dim filter changes color and resets dim attribute. | test_dim_apply | python | Textualize/textual | tests/test_line_filter.py | https://github.com/Textualize/textual/blob/master/tests/test_line_filter.py | MIT |
async def test_multiple_tasks() -> None:
"""Check RLock prevents other tasks from acquiring lock."""
lock = RLock()
started: list[int] = []
done: list[int] = []
async def test_task(n: int) -> None:
started.append(n)
async with lock:
done.append(n)
async with lock:
assert done == []
task1 = asyncio.create_task(test_task(1))
assert sorted(started) == []
task2 = asyncio.create_task(test_task(2))
await asyncio.sleep(0)
assert sorted(started) == [1, 2]
await task1
assert 1 in done
await task2
assert 2 in done | Check RLock prevents other tasks from acquiring lock. | test_multiple_tasks | python | Textualize/textual | tests/test_rlock.py | https://github.com/Textualize/textual/blob/master/tests/test_rlock.py | MIT |
async def test_on_button_pressed() -> None:
"""Test handlers with @on decorator."""
pressed: list[str] = []
class ButtonApp(App):
def compose(self) -> ComposeResult:
yield Button("OK", id="ok")
yield Button("Cancel", classes="exit cancel")
yield Button("Quit", classes="exit quit")
@on(Button.Pressed, "#ok")
def ok(self):
pressed.append("ok")
@on(Button.Pressed, ".exit")
def exit(self):
pressed.append("exit")
@on(Button.Pressed, ".exit.quit")
def _(self):
pressed.append("quit")
def on_button_pressed(self):
pressed.append("default")
app = ButtonApp()
async with app.run_test() as pilot:
await pilot.press("enter", "tab", "enter", "tab", "enter")
await pilot.pause()
assert pressed == [
"ok", # Matched ok first
"default", # on_button_pressed matched everything
"exit", # Cancel button, matches exit
"default", # on_button_pressed matched everything
"exit", # Quit button pressed, matched exit and _
"quit", # Matched previous button
"default", # on_button_pressed matched everything
] | Test handlers with @on decorator. | test_on_button_pressed | python | Textualize/textual | tests/test_on.py | https://github.com/Textualize/textual/blob/master/tests/test_on.py | MIT |
async def test_on_inheritance() -> None:
"""Test on decorator and inheritance."""
pressed: list[str] = []
class MyWidget(Widget):
def compose(self) -> ComposeResult:
yield Button("OK", id="ok")
# Also called
@on(Button.Pressed, "#ok")
def ok(self):
pressed.append("MyWidget.ok base")
class DerivedWidget(MyWidget):
# Should be called first
@on(Button.Pressed, "#ok")
def ok(self):
pressed.append("MyWidget.ok derived")
class ButtonApp(App):
def compose(self) -> ComposeResult:
yield DerivedWidget()
app = ButtonApp()
async with app.run_test() as pilot:
await pilot.press("tab", "enter")
expected = ["MyWidget.ok derived", "MyWidget.ok base"]
assert pressed == expected | Test on decorator and inheritance. | test_on_inheritance | python | Textualize/textual | tests/test_on.py | https://github.com/Textualize/textual/blob/master/tests/test_on.py | MIT |
def test_on_bad_selector() -> None:
"""Check bad selectors raise an error."""
with pytest.raises(OnDecoratorError):
@on(Button.Pressed, "@")
def foo():
pass | Check bad selectors raise an error. | test_on_bad_selector | python | Textualize/textual | tests/test_on.py | https://github.com/Textualize/textual/blob/master/tests/test_on.py | MIT |
def test_on_no_control() -> None:
"""Check messages with no 'control' attribute raise an error."""
class CustomMessage(Message):
pass
with pytest.raises(OnDecoratorError):
@on(CustomMessage, "#foo")
def foo():
pass | Check messages with no 'control' attribute raise an error. | test_on_no_control | python | Textualize/textual | tests/test_on.py | https://github.com/Textualize/textual/blob/master/tests/test_on.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.