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 test_on_attribute_not_listed() -> None:
"""Check `on` checks if the attribute is in ALLOW_SELECTOR_MATCH."""
class CustomMessage(Message):
pass
with pytest.raises(OnDecoratorError):
@on(CustomMessage, foo="bar")
def foo():
pass | Check `on` checks if the attribute is in ALLOW_SELECTOR_MATCH. | test_on_attribute_not_listed | python | Textualize/textual | tests/test_on.py | https://github.com/Textualize/textual/blob/master/tests/test_on.py | MIT |
async def test_fire_on_inherited_message() -> None:
"""Handlers should fire when descendant messages are posted."""
posted: list[str] = []
class InheritTestApp(App[None]):
def compose(self) -> ComposeResult:
yield MessageSender()
@on(MessageSender.Parent)
def catch_parent(self) -> None:
posted.append("parent")
@on(MessageSender.Child)
def catch_child(self) -> None:
posted.append("child")
def on_mount(self) -> None:
self.query_one(MessageSender).post_parent()
self.query_one(MessageSender).post_child()
async with InheritTestApp().run_test():
pass
assert posted == ["parent", "child", "parent"] | Handlers should fire when descendant messages are posted. | test_fire_on_inherited_message | python | Textualize/textual | tests/test_on.py | https://github.com/Textualize/textual/blob/master/tests/test_on.py | MIT |
async def test_fire_inherited_on_single_handler() -> None:
"""Test having parent/child messages on a single handler."""
posted: list[str] = []
class InheritTestApp(App[None]):
def compose(self) -> ComposeResult:
yield MessageSender()
@on(MessageSender.Parent)
@on(MessageSender.Child)
def catch_either(self, event: MessageSender.Parent) -> None:
posted.append(f"either {event.__class__.__name__}")
def on_mount(self) -> None:
self.query_one(MessageSender).post_parent()
self.query_one(MessageSender).post_child()
async with InheritTestApp().run_test():
pass
assert posted == ["either Parent", "either Child"] | Test having parent/child messages on a single handler. | test_fire_inherited_on_single_handler | python | Textualize/textual | tests/test_on.py | https://github.com/Textualize/textual/blob/master/tests/test_on.py | MIT |
async def test_fire_inherited_on_single_handler_multi_selector() -> None:
"""Test having parent/child messages on a single handler but with different selectors."""
posted: list[str] = []
class InheritTestApp(App[None]):
def compose(self) -> ComposeResult:
yield MessageSender(classes="a b")
@on(MessageSender.Parent, ".y")
@on(MessageSender.Child, ".y")
@on(MessageSender.Parent, ".a.b")
@on(MessageSender.Child, ".a.b")
@on(MessageSender.Parent, ".a")
@on(MessageSender.Child, ".a")
@on(MessageSender.Parent, ".b")
@on(MessageSender.Child, ".b")
@on(MessageSender.Parent, ".x")
@on(MessageSender.Child, ".x")
def catch_either(self, event: MessageSender.Parent) -> None:
posted.append(f"either {event.__class__.__name__}")
@on(MessageSender.Child, ".a, .x")
def catch_selector_list_one_miss(self, event: MessageSender.Parent) -> None:
posted.append(f"selector list one miss {event.__class__.__name__}")
@on(MessageSender.Child, ".a, .b")
def catch_selector_list_two_hits(self, event: MessageSender.Parent) -> None:
posted.append(f"selector list two hits {event.__class__.__name__}")
@on(MessageSender.Child, ".a.b")
def catch_selector_combined_hits(self, event: MessageSender.Parent) -> None:
posted.append(f"combined hits {event.__class__.__name__}")
@on(MessageSender.Child, ".a.x")
def catch_selector_combined_miss(self, event: MessageSender.Parent) -> None:
posted.append(f"combined miss {event.__class__.__name__}")
def on_mount(self) -> None:
self.query_one(MessageSender).post_parent()
self.query_one(MessageSender).post_child()
async with InheritTestApp().run_test():
pass
assert posted == [
"either Parent",
"either Child",
"selector list one miss Child",
"selector list two hits Child",
"combined hits Child",
] | Test having parent/child messages on a single handler but with different selectors. | test_fire_inherited_on_single_handler_multi_selector | python | Textualize/textual | tests/test_on.py | https://github.com/Textualize/textual/blob/master/tests/test_on.py | MIT |
async def test_fire_on_inherited_message_plus_mixins() -> None:
"""Handlers should fire when descendant messages are posted, without mixins messing things up."""
posted: list[str] = []
class InheritTestApp(App[None]):
def compose(self) -> ComposeResult:
yield MixinMessageSender()
@on(MixinMessageSender.Parent)
def catch_parent(self) -> None:
posted.append("parent")
@on(MixinMessageSender.Child)
def catch_child(self) -> None:
posted.append("child")
def on_mount(self) -> None:
self.query_one(MixinMessageSender).post_parent()
self.query_one(MixinMessageSender).post_child()
async with InheritTestApp().run_test():
pass
assert posted == ["parent", "child", "parent"] | Handlers should fire when descendant messages are posted, without mixins messing things up. | test_fire_on_inherited_message_plus_mixins | python | Textualize/textual | tests/test_on.py | https://github.com/Textualize/textual/blob/master/tests/test_on.py | MIT |
def test_no_match():
"""Check non matching score of zero."""
matcher = Matcher("x")
assert matcher.match("foo") == 0 | Check non matching score of zero. | test_no_match | python | Textualize/textual | tests/test_fuzzy.py | https://github.com/Textualize/textual/blob/master/tests/test_fuzzy.py | MIT |
def test_match_single_group():
"""Check that single groups rang higher."""
matcher = Matcher("abc")
assert matcher.match("foo abc bar") > matcher.match("fooa barc") | Check that single groups rang higher. | test_match_single_group | python | Textualize/textual | tests/test_fuzzy.py | https://github.com/Textualize/textual/blob/master/tests/test_fuzzy.py | MIT |
def test_boosted_matches():
"""Check first word matchers rank higher."""
matcher = Matcher("ss")
# First word matchers should score higher
assert matcher.match("Save Screenshot") > matcher.match("Show Keys abcde") | Check first word matchers rank higher. | test_boosted_matches | python | Textualize/textual | tests/test_fuzzy.py | https://github.com/Textualize/textual/blob/master/tests/test_fuzzy.py | MIT |
def test_resolve_fraction_unit():
"""Test resolving fraction units in combination with minimum widths."""
widget1 = Widget()
widget2 = Widget()
widget3 = Widget()
widget1.styles.width = "1fr"
widget1.styles.min_width = 20
widget2.styles.width = "2fr"
widget2.styles.min_width = 10
widget3.styles.width = "1fr"
styles = (widget1.styles, widget2.styles, widget3.styles)
# Try with width 80.
# Fraction unit should one fourth of width
assert resolve_fraction_unit(
styles,
Size(80, 24),
Size(80, 24),
Fraction(80),
resolve_dimension="width",
) == Fraction(20)
# Try with width 50
# First widget is fixed at 20
# Remaining three widgets have 30 to play with
# Fraction is 10
assert resolve_fraction_unit(
styles,
Size(80, 24),
Size(80, 24),
Fraction(50),
resolve_dimension="width",
) == Fraction(10)
# Try with width 35
# First widget fixed at 20
# Fraction is 5
assert resolve_fraction_unit(
styles,
Size(80, 24),
Size(80, 24),
Fraction(35),
resolve_dimension="width",
) == Fraction(5)
# Try with width 32
# First widget fixed at 20
# Second widget is fixed at 10
# Remaining widget has all the space
# Fraction is 2
assert resolve_fraction_unit(
styles,
Size(80, 24),
Size(80, 24),
Fraction(32),
resolve_dimension="width",
) == Fraction(2) | Test resolving fraction units in combination with minimum widths. | test_resolve_fraction_unit | python | Textualize/textual | tests/test_resolve.py | https://github.com/Textualize/textual/blob/master/tests/test_resolve.py | MIT |
def test_resolve_fraction_unit_stress_test():
"""Check for zero division errors."""
# https://github.com/Textualize/textual/issues/2673
widget = Widget()
styles = widget.styles
styles.width = "1fr"
# We're mainly checking for the absence of zero division errors,
# which is a reoccurring theme for this code.
for remaining_space in range(1, 51, 10):
for max_width in range(1, remaining_space):
styles.max_width = max_width
for width in range(1, remaining_space, 2):
size = Size(width, 24)
resolved_unit = resolve_fraction_unit(
[styles, styles, styles],
size,
size,
Fraction(remaining_space),
"width",
)
assert resolved_unit <= remaining_space | Check for zero division errors. | test_resolve_fraction_unit_stress_test | python | Textualize/textual | tests/test_resolve.py | https://github.com/Textualize/textual/blob/master/tests/test_resolve.py | MIT |
def test_resolve_issue_2502():
"""Test https://github.com/Textualize/textual/issues/2502"""
widget = Widget()
widget.styles.width = "1fr"
widget.styles.min_width = 11
assert isinstance(
resolve_fraction_unit(
(widget.styles,),
Size(80, 24),
Size(80, 24),
Fraction(10),
resolve_dimension="width",
),
Fraction,
) | Test https://github.com/Textualize/textual/issues/2502 | test_resolve_issue_2502 | python | Textualize/textual | tests/test_resolve.py | https://github.com/Textualize/textual/blob/master/tests/test_resolve.py | MIT |
async def test_markdown_nodes(
document: str, expected_nodes: list[Widget | list[Widget]]
) -> None:
"""A Markdown document should parse into the expected Textual node list."""
def markdown_nodes(root: Widget) -> Iterator[MarkdownBlock]:
for node in root.children:
if isinstance(node, MarkdownBlock):
yield node
yield from markdown_nodes(node)
async with MarkdownApp(document).run_test() as pilot:
assert [
node.__class__ for node in markdown_nodes(pilot.app.query_one(Markdown))
] == expected_nodes | A Markdown document should parse into the expected Textual node list. | test_markdown_nodes | python | Textualize/textual | tests/test_markdown.py | https://github.com/Textualize/textual/blob/master/tests/test_markdown.py | MIT |
async def test_softbreak_split_links_rendered_correctly() -> None:
"""Test for https://github.com/Textualize/textual/issues/2805"""
document = """\
My site [has
this
URL](https://example.com)\
"""
async with MarkdownApp(document).run_test() as pilot:
markdown = pilot.app.query_one(Markdown)
paragraph = markdown.children[0]
assert isinstance(paragraph, MD.MarkdownParagraph)
assert paragraph._text.plain == "My site has this URL"
expected_spans = [
Span(8, 11, Style(meta={"@click": "link('https://example.com')"})),
Span(11, 12, Style(meta={"@click": "link('https://example.com')"})),
Span(12, 16, Style(meta={"@click": "link('https://example.com')"})),
Span(16, 17, Style(meta={"@click": "link('https://example.com')"})),
Span(17, 20, Style(meta={"@click": "link('https://example.com')"})),
]
assert paragraph._text.spans == expected_spans | Test for https://github.com/Textualize/textual/issues/2805 | test_softbreak_split_links_rendered_correctly | python | Textualize/textual | tests/test_markdown.py | https://github.com/Textualize/textual/blob/master/tests/test_markdown.py | MIT |
async def test_load_non_existing_file() -> None:
"""Loading a file that doesn't exist should result in the obvious error."""
async with MarkdownApp("").run_test() as pilot:
with pytest.raises(FileNotFoundError):
await pilot.app.query_one(Markdown).load(
Path("---this-does-not-exist---.it.is.not.a.md")
) | Loading a file that doesn't exist should result in the obvious error. | test_load_non_existing_file | python | Textualize/textual | tests/test_markdown.py | https://github.com/Textualize/textual/blob/master/tests/test_markdown.py | MIT |
async def test_goto_anchor(anchor: str, found: bool) -> None:
"""Going to anchors should return a boolean: whether the anchor was found."""
document = "# Hello There\n\nGeneral.\n"
async with MarkdownApp(document).run_test() as pilot:
markdown = pilot.app.query_one(Markdown)
assert markdown.goto_anchor(anchor) is found | Going to anchors should return a boolean: whether the anchor was found. | test_goto_anchor | python | Textualize/textual | tests/test_markdown.py | https://github.com/Textualize/textual/blob/master/tests/test_markdown.py | MIT |
async def test_update_of_document_posts_table_of_content_update_message() -> None:
"""Updating the document should post a TableOfContentsUpdated message."""
messages: list[str] = []
class TableOfContentApp(App[None]):
def compose(self) -> ComposeResult:
yield Markdown("# One\n\n#Two\n")
@on(Markdown.TableOfContentsUpdated)
def log_table_of_content_update(
self, event: Markdown.TableOfContentsUpdated
) -> None:
nonlocal messages
messages.append(event.__class__.__name__)
async with TableOfContentApp().run_test() as pilot:
assert messages == ["TableOfContentsUpdated"]
await pilot.app.query_one(Markdown).update("")
await pilot.pause()
assert messages == ["TableOfContentsUpdated", "TableOfContentsUpdated"] | Updating the document should post a TableOfContentsUpdated message. | test_update_of_document_posts_table_of_content_update_message | python | Textualize/textual | tests/test_markdown.py | https://github.com/Textualize/textual/blob/master/tests/test_markdown.py | MIT |
async def test_link_in_markdown_table_posts_message_when_clicked():
"""A link inside a markdown table should post a `Markdown.LinkClicked`
message when clicked.
Regression test for https://github.com/Textualize/textual/issues/4683
"""
markdown_table = """\
| Textual Links |
| ------------------------------------------------ |
| [GitHub](https://github.com/textualize/textual/) |
| [Documentation](https://textual.textualize.io/) |\
"""
class MarkdownTableApp(App):
messages = []
def compose(self) -> ComposeResult:
yield Markdown(markdown_table, open_links=False)
@on(Markdown.LinkClicked)
def log_markdown_link_clicked(
self,
event: Markdown.LinkClicked,
) -> None:
self.messages.append(event.__class__.__name__)
app = MarkdownTableApp()
async with app.run_test() as pilot:
await pilot.click(Markdown, offset=(3, 3))
assert app.messages == ["LinkClicked"] | A link inside a markdown table should post a `Markdown.LinkClicked`
message when clicked.
Regression test for https://github.com/Textualize/textual/issues/4683 | test_link_in_markdown_table_posts_message_when_clicked | python | Textualize/textual | tests/test_markdown.py | https://github.com/Textualize/textual/blob/master/tests/test_markdown.py | MIT |
async def test_compositor_scroll_placements():
"""Regression test for https://github.com/Textualize/textual/issues/5249
The Static should remain visible.
"""
class ScrollApp(App):
CSS = """
Screen {
overflow: scroll;
}
Container {
width: 200vw;
}
#hello {
width: 20;
height: 10;
offset: 50 10;
background: blue;
color: white;
}
"""
def compose(self) -> ComposeResult:
with Container():
yield Static("Hello", id="hello")
def on_mount(self) -> None:
self.query_one("Screen").scroll_to(20, 0, animate=False)
app = ScrollApp()
async with app.run_test() as pilot:
await pilot.pause()
static = app.query_one("#hello")
widgets = app.screen._compositor.visible_widgets
# The static wasn't scrolled out of view, and should be visible
# This wasn't the case <= v0.86.1
assert static in widgets | Regression test for https://github.com/Textualize/textual/issues/5249
The Static should remain visible. | test_compositor_scroll_placements | python | Textualize/textual | tests/test_compositor.py | https://github.com/Textualize/textual/blob/master/tests/test_compositor.py | MIT |
async def test_animate_height() -> None:
"""Test animating styles.height works."""
# Styles.height is a scalar, which makes it more complicated to animate
app = AnimApp()
async with app.run_test() as pilot:
static = app.query_one(Static)
assert static.size.height == 1
assert static.styles.height.value == 1
static.styles.animate("height", 100, duration=0.5, easing="linear")
start = perf_counter()
# Wait for the animation to finished
await pilot.wait_for_animation()
elapsed = perf_counter() - start
# Check that the full time has elapsed
assert elapsed >= 0.5
# Check the height reached the maximum
assert static.styles.height.value == 100 | Test animating styles.height works. | test_animate_height | python | Textualize/textual | tests/test_animation.py | https://github.com/Textualize/textual/blob/master/tests/test_animation.py | MIT |
async def test_scheduling_animation() -> None:
"""Test that scheduling an animation works."""
app = AnimApp()
delay = 0.1
async with app.run_test() as pilot:
styles = app.query_one(Static).styles
styles.background = "black"
styles.animate("background", "white", delay=delay, duration=0)
# Still black immediately after call, animation hasn't started yet due to `delay`
assert styles.background.rgb == (0, 0, 0)
await pilot.wait_for_scheduled_animations()
assert styles.background.rgb == (255, 255, 255) | Test that scheduling an animation works. | test_scheduling_animation | python | Textualize/textual | tests/test_animation.py | https://github.com/Textualize/textual/blob/master/tests/test_animation.py | MIT |
async def test_wait_for_current_animations() -> None:
"""Test that we can wait only for the current animations taking place."""
app = AnimApp()
delay = 10
async with app.run_test() as pilot:
styles = app.query_one(Static).styles
styles.animate("height", 100, duration=0.1)
start = perf_counter()
styles.animate("height", 200, duration=0.1, delay=delay)
# Wait for the first animation to finish
await pilot.wait_for_animation()
elapsed = perf_counter() - start
assert elapsed < (delay / 2) | Test that we can wait only for the current animations taking place. | test_wait_for_current_animations | python | Textualize/textual | tests/test_animation.py | https://github.com/Textualize/textual/blob/master/tests/test_animation.py | MIT |
async def test_wait_for_current_and_scheduled_animations() -> None:
"""Test that we can wait for current and scheduled animations."""
app = AnimApp()
async with app.run_test() as pilot:
styles = app.query_one(Static).styles
start = perf_counter()
styles.animate("height", 50, duration=0.01)
styles.animate("background", "black", duration=0.01, delay=0.05)
await pilot.wait_for_scheduled_animations()
elapsed = perf_counter() - start
assert elapsed >= 0.06
assert styles.background.rgb == (0, 0, 0) | Test that we can wait for current and scheduled animations. | test_wait_for_current_and_scheduled_animations | python | Textualize/textual | tests/test_animation.py | https://github.com/Textualize/textual/blob/master/tests/test_animation.py | MIT |
async def test_reverse_animations() -> None:
"""Test that you can create reverse animations.
Regression test for #1372 https://github.com/Textualize/textual/issues/1372
"""
app = AnimApp()
async with app.run_test() as pilot:
static = app.query_one(Static)
styles = static.styles
# Starting point.
styles.background = "black"
assert styles.background.rgb == (0, 0, 0)
# First, make sure we can go from black to white and back, step by step.
styles.animate("background", "white", duration=0.01)
await pilot.wait_for_animation()
assert styles.background.rgb == (255, 255, 255)
styles.animate("background", "black", duration=0.01)
await pilot.wait_for_animation()
assert styles.background.rgb == (0, 0, 0)
# Now, the actual test is to make sure we go back to black if creating both at once.
styles.animate("background", "white", duration=0.01)
styles.animate("background", "black", duration=0.01)
await pilot.wait_for_animation()
assert styles.background.rgb == (0, 0, 0) | Test that you can create reverse animations.
Regression test for #1372 https://github.com/Textualize/textual/issues/1372 | test_reverse_animations | python | Textualize/textual | tests/test_animation.py | https://github.com/Textualize/textual/blob/master/tests/test_animation.py | MIT |
async def test_schedule_reverse_animations() -> None:
"""Test that you can schedule reverse animations.
Regression test for #1372 https://github.com/Textualize/textual/issues/1372
"""
app = AnimApp()
async with app.run_test() as pilot:
static = app.query_one(Static)
styles = static.styles
# Starting point.
styles.background = "black"
assert styles.background.rgb == (0, 0, 0)
# First, make sure we can go from black to white and back, step by step.
styles.animate("background", "white", delay=0.01, duration=0.01)
await pilot.wait_for_scheduled_animations()
assert styles.background.rgb == (255, 255, 255)
styles.animate("background", "black", delay=0.01, duration=0.01)
await pilot.wait_for_scheduled_animations()
assert styles.background.rgb == (0, 0, 0)
# Now, the actual test is to make sure we go back to black if scheduling both at once.
styles.animate("background", "white", delay=0.025, duration=0.05)
# While the black -> white animation runs, start the white -> black animation.
styles.animate("background", "black", delay=0.05, duration=0.01)
await pilot.wait_for_scheduled_animations()
assert styles.background.rgb == (0, 0, 0) | Test that you can schedule reverse animations.
Regression test for #1372 https://github.com/Textualize/textual/issues/1372 | test_schedule_reverse_animations | python | Textualize/textual | tests/test_animation.py | https://github.com/Textualize/textual/blob/master/tests/test_animation.py | MIT |
async def test_cancel_app_animation() -> None:
"""It should be possible to cancel a running app animation."""
async with CancelAnimApp().run_test() as pilot:
pilot.app.animate("counter", value=0, final_value=1000, duration=60)
await pilot.pause()
assert pilot.app.animator.is_being_animated(pilot.app, "counter")
await pilot.app.stop_animation("counter")
assert not pilot.app.animator.is_being_animated(pilot.app, "counter") | It should be possible to cancel a running app animation. | test_cancel_app_animation | python | Textualize/textual | tests/test_animation.py | https://github.com/Textualize/textual/blob/master/tests/test_animation.py | MIT |
async def test_cancel_app_non_animation() -> None:
"""It should be possible to attempt to cancel a non-running app animation."""
async with CancelAnimApp().run_test() as pilot:
assert not pilot.app.animator.is_being_animated(pilot.app, "counter")
await pilot.app.stop_animation("counter")
assert not pilot.app.animator.is_being_animated(pilot.app, "counter") | It should be possible to attempt to cancel a non-running app animation. | test_cancel_app_non_animation | python | Textualize/textual | tests/test_animation.py | https://github.com/Textualize/textual/blob/master/tests/test_animation.py | MIT |
async def test_cancel_widget_animation() -> None:
"""It should be possible to cancel a running widget animation."""
async with CancelAnimApp().run_test() as pilot:
widget = pilot.app.query_one(CancelAnimWidget)
widget.animate("counter", value=0, final_value=1000, duration=60)
await pilot.pause()
assert pilot.app.animator.is_being_animated(widget, "counter")
await widget.stop_animation("counter")
assert not pilot.app.animator.is_being_animated(widget, "counter") | It should be possible to cancel a running widget animation. | test_cancel_widget_animation | python | Textualize/textual | tests/test_animation.py | https://github.com/Textualize/textual/blob/master/tests/test_animation.py | MIT |
async def test_cancel_widget_non_animation() -> None:
"""It should be possible to attempt to cancel a non-running widget animation."""
async with CancelAnimApp().run_test() as pilot:
widget = pilot.app.query_one(CancelAnimWidget)
assert not pilot.app.animator.is_being_animated(widget, "counter")
await widget.stop_animation("counter")
assert not pilot.app.animator.is_being_animated(widget, "counter") | It should be possible to attempt to cancel a non-running widget animation. | test_cancel_widget_non_animation | python | Textualize/textual | tests/test_animation.py | https://github.com/Textualize/textual/blob/master/tests/test_animation.py | MIT |
async def test_unmount() -> None:
"""Test unmount events are received in reverse DOM order."""
unmount_ids: list[str] = []
class UnmountWidget(Container):
def on_unmount(self, event: events.Unmount):
unmount_ids.append(
f"{self.__class__.__name__}#{self.id}-{self.parent is not None}-{len(self._nodes)}"
)
class MyScreen(Screen):
def compose(self) -> ComposeResult:
yield UnmountWidget(
UnmountWidget(
UnmountWidget(id="bar1"), UnmountWidget(id="bar2"), id="bar"
),
UnmountWidget(
UnmountWidget(id="baz1"), UnmountWidget(id="baz2"), id="baz"
),
id="top",
)
def on_unmount(self, event: events.Unmount):
unmount_ids.append(f"{self.__class__.__name__}#{self.id}")
class UnmountApp(App):
async def on_mount(self) -> None:
await self.push_screen(MyScreen(id="main"))
app = UnmountApp()
async with app.run_test() as pilot:
await pilot.exit(None)
expected = [
"UnmountWidget#bar1-True-0",
"UnmountWidget#bar2-True-0",
"UnmountWidget#baz1-True-0",
"UnmountWidget#baz2-True-0",
"UnmountWidget#bar-True-0",
"UnmountWidget#baz-True-0",
"UnmountWidget#top-True-0",
"MyScreen#main",
]
assert unmount_ids == expected | Test unmount events are received in reverse DOM order. | test_unmount | python | Textualize/textual | tests/test_unmount.py | https://github.com/Textualize/textual/blob/master/tests/test_unmount.py | MIT |
async def test_remove_single_widget():
"""It should be possible to the only widget on a screen."""
async with App().run_test() as pilot:
widget = Static()
assert not widget.is_attached
await pilot.app.mount(widget)
assert widget.is_attached
assert len(pilot.app.screen._nodes) == 1
await pilot.app.query_one(Static).remove()
assert not widget.is_attached
assert len(pilot.app.screen._nodes) == 0 | It should be possible to the only widget on a screen. | test_remove_single_widget | python | Textualize/textual | tests/test_widget_removing.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_removing.py | MIT |
async def test_many_remove_all_widgets():
"""It should be possible to remove all widgets on a multi-widget screen."""
async with App().run_test() as pilot:
await pilot.app.mount(*[Static() for _ in range(10)])
assert len(pilot.app.screen._nodes) == 10
await pilot.app.query(Static).remove()
assert len(pilot.app.screen._nodes) == 0 | It should be possible to remove all widgets on a multi-widget screen. | test_many_remove_all_widgets | python | Textualize/textual | tests/test_widget_removing.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_removing.py | MIT |
async def test_many_remove_some_widgets():
"""It should be possible to remove some widgets on a multi-widget screen."""
async with App().run_test() as pilot:
await pilot.app.mount(*[Static(classes=f"is-{n % 2}") for n in range(10)])
assert len(pilot.app.screen._nodes) == 10
await pilot.app.query(".is-0").remove()
assert len(pilot.app.screen._nodes) == 5 | It should be possible to remove some widgets on a multi-widget screen. | test_many_remove_some_widgets | python | Textualize/textual | tests/test_widget_removing.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_removing.py | MIT |
async def test_remove_branch():
"""It should be possible to remove a whole branch in the DOM."""
async with App().run_test() as pilot:
await pilot.app.mount(
Container(Container(Container(Container(Container(Static()))))),
Static(),
Container(Container(Container(Container(Container(Static()))))),
)
assert len(pilot.app.screen.walk_children(with_self=False)) == 13
await pilot.app.screen._nodes[0].remove()
assert len(pilot.app.screen.walk_children(with_self=False)) == 7 | It should be possible to remove a whole branch in the DOM. | test_remove_branch | python | Textualize/textual | tests/test_widget_removing.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_removing.py | MIT |
async def test_remove_overlap():
"""It should be possible to remove an overlapping collection of widgets."""
async with App().run_test() as pilot:
await pilot.app.mount(
Container(Container(Container(Container(Container(Static()))))),
Static(),
Container(Container(Container(Container(Container(Static()))))),
)
assert len(pilot.app.screen.walk_children(with_self=False)) == 13
await pilot.app.query(Container).remove()
assert len(pilot.app.screen.walk_children(with_self=False)) == 1 | It should be possible to remove an overlapping collection of widgets. | test_remove_overlap | python | Textualize/textual | tests/test_widget_removing.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_removing.py | MIT |
async def test_remove_move_focus():
"""Removing a focused widget should settle focus elsewhere."""
async with App().run_test() as pilot:
buttons = [Button(str(n)) for n in range(10)]
await pilot.app.mount(Container(*buttons[:5]), Container(*buttons[5:]))
assert len(pilot.app.screen._nodes) == 2
assert len(pilot.app.screen.walk_children(with_self=False)) == 12
assert pilot.app.focused is None
await pilot.press("tab")
assert pilot.app.focused is not None
assert pilot.app.focused == buttons[0]
await pilot.app.screen._nodes[0].remove()
assert len(pilot.app.screen._nodes) == 1
assert len(pilot.app.screen.walk_children(with_self=False)) == 6
assert pilot.app.focused is not None
assert pilot.app.focused == buttons[9] | Removing a focused widget should settle focus elsewhere. | test_remove_move_focus | python | Textualize/textual | tests/test_widget_removing.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_removing.py | MIT |
async def test_widget_remove_order() -> None:
"""A Widget.remove of a top-level widget should cause bottom-first removal."""
removals: list[str] = []
class Removable(Container):
def on_unmount(self, _):
removals.append(self.id if self.id is not None else "unknown")
async with App().run_test() as pilot:
await pilot.app.mount(
Removable(Removable(Removable(id="grandchild"), id="child"), id="parent")
)
assert len(pilot.app.screen.walk_children(with_self=False)) == 3
await pilot.app.screen._nodes[0].remove()
assert len(pilot.app.screen.walk_children(with_self=False)) == 0
assert removals == ["grandchild", "child", "parent"] | A Widget.remove of a top-level widget should cause bottom-first removal. | test_widget_remove_order | python | Textualize/textual | tests/test_widget_removing.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_removing.py | MIT |
async def test_query_remove_order():
"""A DOMQuery.remove of a top-level widget should cause bottom-first removal."""
removals: list[str] = []
class Removable(Container):
def on_unmount(self, _):
removals.append(self.id if self.id is not None else "unknown")
async with App().run_test() as pilot:
await pilot.app.mount(
Removable(Removable(Removable(id="grandchild"), id="child"), id="parent")
)
assert len(pilot.app.screen.walk_children(with_self=False)) == 3
await pilot.app.query(Removable).remove()
assert len(pilot.app.screen.walk_children(with_self=False)) == 0
assert removals == ["grandchild", "child", "parent"] | A DOMQuery.remove of a top-level widget should cause bottom-first removal. | test_query_remove_order | python | Textualize/textual | tests/test_widget_removing.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_removing.py | MIT |
def test_round_trip(data: object) -> None:
"""Test the data may be encoded then decoded"""
encoded = dump(data)
assert isinstance(encoded, bytes)
decoded = load(encoded)
assert data == decoded | Test the data may be encoded then decoded | test_round_trip | python | Textualize/textual | tests/test_binary_encode.py | https://github.com/Textualize/textual/blob/master/tests/test_binary_encode.py | MIT |
def test_empty_list():
"""Does an empty node list report as being empty?"""
assert len(NodeList()) == 0 | Does an empty node list report as being empty? | test_empty_list | python | Textualize/textual | tests/test_node_list.py | https://github.com/Textualize/textual/blob/master/tests/test_node_list.py | MIT |
def test_add_one():
"""Does adding a node to the node list report as having one item?"""
nodes = NodeList()
nodes._append(Widget())
assert len(nodes) == 1 | Does adding a node to the node list report as having one item? | test_add_one | python | Textualize/textual | tests/test_node_list.py | https://github.com/Textualize/textual/blob/master/tests/test_node_list.py | MIT |
def test_length_hint():
"""Check length hint dunder method."""
nodes = NodeList()
assert nodes.__length_hint__() == 0
nodes._append(Widget())
nodes._append(Widget())
nodes._append(Widget())
assert nodes.__length_hint__() == 3 | Check length hint dunder method. | test_length_hint | python | Textualize/textual | tests/test_node_list.py | https://github.com/Textualize/textual/blob/master/tests/test_node_list.py | MIT |
def test_repeat_add_one():
"""Does adding the same item to the node list ignore the additional adds?"""
nodes = NodeList()
widget = Widget()
for _ in range(1000):
nodes._append(widget)
assert len(nodes) == 1 | Does adding the same item to the node list ignore the additional adds? | test_repeat_add_one | python | Textualize/textual | tests/test_node_list.py | https://github.com/Textualize/textual/blob/master/tests/test_node_list.py | MIT |
def test_truthy():
"""Does a node list act as a truthy object?"""
nodes = NodeList()
assert not bool(nodes)
nodes._append(Widget())
assert bool(nodes) | Does a node list act as a truthy object? | test_truthy | python | Textualize/textual | tests/test_node_list.py | https://github.com/Textualize/textual/blob/master/tests/test_node_list.py | MIT |
def test_contains():
"""Can we check if a widget is (not) within the list?"""
widget = Widget()
nodes = NodeList()
assert widget not in nodes
nodes._append(widget)
assert widget in nodes
assert Widget() not in nodes | Can we check if a widget is (not) within the list? | test_contains | python | Textualize/textual | tests/test_node_list.py | https://github.com/Textualize/textual/blob/master/tests/test_node_list.py | MIT |
def test_index():
"""Can we get the index of a widget in the list?"""
widget = Widget()
nodes = NodeList()
with pytest.raises(ValueError):
_ = nodes.index(widget)
nodes._append(widget)
assert nodes.index(widget) == 0 | Can we get the index of a widget in the list? | test_index | python | Textualize/textual | tests/test_node_list.py | https://github.com/Textualize/textual/blob/master/tests/test_node_list.py | MIT |
def test_remove():
"""Can we remove a widget we've added?"""
widget = Widget()
nodes = NodeList()
nodes._append(widget)
assert widget in nodes
nodes._remove(widget)
assert widget not in nodes | Can we remove a widget we've added? | test_remove | python | Textualize/textual | tests/test_node_list.py | https://github.com/Textualize/textual/blob/master/tests/test_node_list.py | MIT |
def test_clear():
"""Can we clear the list?"""
nodes = NodeList()
assert len(nodes) == 0
widgets = [Widget() for _ in range(1000)]
for widget in widgets:
nodes._append(widget)
assert len(nodes) == 1000
for widget in widgets:
assert widget in nodes
nodes._clear()
assert len(nodes) == 0
for widget in widgets:
assert widget not in nodes | Can we clear the list? | test_clear | python | Textualize/textual | tests/test_node_list.py | https://github.com/Textualize/textual/blob/master/tests/test_node_list.py | MIT |
def test_box_normalization():
"""Check that none or hidden is normalized to empty string."""
styles = Styles()
styles.border_left = ("none", "red")
assert styles.border_left == ("", Color.parse("red")) | Check that none or hidden is normalized to empty string. | test_box_normalization | python | Textualize/textual | tests/test_style_properties.py | https://github.com/Textualize/textual/blob/master/tests/test_style_properties.py | MIT |
def test_text_style_none_with_others(style_attr):
"""Style "none" mixed with others should give custom Textual exception."""
styles = Styles()
with pytest.raises(StyleValueError):
setattr(styles, style_attr, "bold none underline italic") | Style "none" mixed with others should give custom Textual exception. | test_text_style_none_with_others | python | Textualize/textual | tests/test_style_properties.py | https://github.com/Textualize/textual/blob/master/tests/test_style_properties.py | MIT |
def test_text_style_set_to_none(style_attr):
"""Setting text style to "none" should clear the styles."""
styles = Styles()
setattr(styles, style_attr, "bold underline italic")
assert getattr(styles, style_attr) != Style.null()
setattr(styles, style_attr, "none")
assert getattr(styles, style_attr) == Style.null() | Setting text style to "none" should clear the styles. | test_text_style_set_to_none | python | Textualize/textual | tests/test_style_properties.py | https://github.com/Textualize/textual/blob/master/tests/test_style_properties.py | MIT |
def test_inherited_bindings():
"""Test if binding merging is done correctly when (not) inheriting bindings."""
class A(DOMNode):
BINDINGS = [("a", "a", "a")]
class B(A):
BINDINGS = [("b", "b", "b")]
class C(B, inherit_bindings=False):
BINDINGS = [("c", "c", "c")]
class D(C, inherit_bindings=False):
pass
class E(D):
BINDINGS = [("e", "e", "e")]
a = A()
assert list(a._bindings.key_to_bindings.keys()) == ["a"]
b = B()
assert list(b._bindings.key_to_bindings.keys()) == ["a", "b"]
c = C()
assert list(c._bindings.key_to_bindings.keys()) == ["c"]
d = D()
assert not list(d._bindings.key_to_bindings.keys())
e = E()
assert list(e._bindings.key_to_bindings.keys()) == ["e"] | Test if binding merging is done correctly when (not) inheriting bindings. | test_inherited_bindings | python | Textualize/textual | tests/test_dom.py | https://github.com/Textualize/textual/blob/master/tests/test_dom.py | MIT |
def test_component_classes_inheritance():
"""Test if component classes are inherited properly."""
class A(DOMNode):
COMPONENT_CLASSES = {"a-1", "a-2"}
class B(A, inherit_component_classes=False):
COMPONENT_CLASSES = {"b-1"}
class C(B):
COMPONENT_CLASSES = {"c-1", "c-2"}
class D(C):
pass
class E(D):
COMPONENT_CLASSES = {"e-1"}
class F(E, inherit_component_classes=False):
COMPONENT_CLASSES = {"f-1"}
node = DOMNode()
node_cc = node._get_component_classes()
a = A()
a_cc = a._get_component_classes()
b = B()
b_cc = b._get_component_classes()
c = C()
c_cc = c._get_component_classes()
d = D()
d_cc = d._get_component_classes()
e = E()
e_cc = e._get_component_classes()
f = F()
f_cc = f._get_component_classes()
assert node_cc == frozenset()
assert a_cc == {"a-1", "a-2"}
assert b_cc == {"b-1"}
assert c_cc == {"b-1", "c-1", "c-2"}
assert d_cc == c_cc
assert e_cc == {"b-1", "c-1", "c-2", "e-1"}
assert f_cc == {"f-1"} | Test if component classes are inherited properly. | test_component_classes_inheritance | python | Textualize/textual | tests/test_dom.py | https://github.com/Textualize/textual/blob/master/tests/test_dom.py | MIT |
def search():
"""
a
/ \
b c
/ / \
d e f
"""
a = DOMNode(id="a")
b = DOMNode(id="b")
c = DOMNode(id="c")
d = DOMNode(id="d")
e = DOMNode(id="e")
f = DOMNode(id="f")
a._add_child(b)
a._add_child(c)
b._add_child(d)
c._add_child(e)
c._add_child(f)
yield a | a
/ \
b c
/ / \
d e f | search | python | Textualize/textual | tests/test_dom.py | https://github.com/Textualize/textual/blob/master/tests/test_dom.py | MIT |
def test_id_validation(identifier: str):
"""Regression tests for https://github.com/Textualize/textual/issues/3954."""
with pytest.raises(BadIdentifier):
DOMNode(id=identifier) | Regression tests for https://github.com/Textualize/textual/issues/3954. | test_id_validation | python | Textualize/textual | tests/test_dom.py | https://github.com/Textualize/textual/blob/master/tests/test_dom.py | MIT |
async def test_character_bindings():
"""Test you can bind to a character as well as a longer key name."""
counter = 0
class BindApp(App):
BINDINGS = [(".,~,space", "increment", "foo")]
def action_increment(self) -> None:
nonlocal counter
counter += 1
app = BindApp()
async with app.run_test() as pilot:
await pilot.press(".")
await pilot.pause()
assert counter == 1
await pilot.press("~")
await pilot.pause()
assert counter == 2
await pilot.press(" ")
await pilot.pause()
assert counter == 3
await pilot.press("x")
await pilot.pause()
assert counter == 3 | Test you can bind to a character as well as a longer key name. | test_character_bindings | python | Textualize/textual | tests/test_keys.py | https://github.com/Textualize/textual/blob/master/tests/test_keys.py | MIT |
def test_simple_slug(text: str, expected: str) -> None:
"""The simple slug function should produce the expected slug."""
assert slug(text) == expected | The simple slug function should produce the expected slug. | test_simple_slug | python | Textualize/textual | tests/test_slug.py | https://github.com/Textualize/textual/blob/master/tests/test_slug.py | MIT |
def test_tracked_slugs(tracker: TrackedSlugs, text: str, expected: str) -> None:
"""The tracked slugging class should produce the expected slugs."""
assert tracker.slug(text) == expected | The tracked slugging class should produce the expected slugs. | test_tracked_slugs | python | Textualize/textual | tests/test_slug.py | https://github.com/Textualize/textual/blob/master/tests/test_slug.py | MIT |
def test_batch_update():
"""Test `batch_update` context manager"""
app = App()
assert app._batch_count == 0 # Start at zero
with app.batch_update():
assert app._batch_count == 1 # Increments in context manager
with app.batch_update():
assert app._batch_count == 2 # Nested updates
assert app._batch_count == 1 # Exiting decrements
assert app._batch_count == 0 # Back to zero | Test `batch_update` context manager | test_batch_update | python | Textualize/textual | tests/test_app.py | https://github.com/Textualize/textual/blob/master/tests/test_app.py | MIT |
async def test_early_exit():
"""Test exiting early doesn't cause issues."""
from textual.app import App
class AppExit(App):
def compose(self):
yield Static("Hello")
def on_mount(self) -> None:
# Exit after creating app
self.exit()
app = AppExit()
async with app.run_test():
pass | Test exiting early doesn't cause issues. | test_early_exit | python | Textualize/textual | tests/test_app.py | https://github.com/Textualize/textual/blob/master/tests/test_app.py | MIT |
def test_early_exit_inline():
"""Test exiting early in inline mode doesn't break."""
class AppExit(App[None]):
def compose(self):
yield Static("Hello")
def on_mount(self) -> None:
# Exit after creating app
self.exit()
app = AppExit()
app.run(inline=True, inline_no_clear=True) | Test exiting early in inline mode doesn't break. | test_early_exit_inline | python | Textualize/textual | tests/test_app.py | https://github.com/Textualize/textual/blob/master/tests/test_app.py | MIT |
async def test_search_with_simple_commands():
"""Test search with a list of SimpleCommands and ensure callbacks are invoked."""
called = False
def callback():
nonlocal called
called = True
app = App[None]()
commands = [
SimpleCommand("Test Command", callback, "A test command"),
SimpleCommand("Another Command", callback, "Another test command"),
]
async with app.run_test() as pilot:
await app.search_commands(commands)
await pilot.press("enter", "enter")
assert called | Test search with a list of SimpleCommands and ensure callbacks are invoked. | test_search_with_simple_commands | python | Textualize/textual | tests/test_app.py | https://github.com/Textualize/textual/blob/master/tests/test_app.py | MIT |
async def test_search_with_tuples():
"""Test search with a list of tuples and ensure callbacks are invoked.
In this case we also have no help text in the tuples.
"""
called = False
def callback():
nonlocal called
called = True
app = App[None]()
commands = [
("Test Command", callback),
("Another Command", callback),
]
async with app.run_test() as pilot:
await app.search_commands(commands)
await pilot.press("enter", "enter")
assert called | Test search with a list of tuples and ensure callbacks are invoked.
In this case we also have no help text in the tuples. | test_search_with_tuples | python | Textualize/textual | tests/test_app.py | https://github.com/Textualize/textual/blob/master/tests/test_app.py | MIT |
async def test_search_with_empty_list():
"""Test search with an empty command list doesn't crash."""
app = App[None]()
async with app.run_test():
await app.search_commands([]) | Test search with an empty command list doesn't crash. | test_search_with_empty_list | python | Textualize/textual | tests/test_app.py | https://github.com/Textualize/textual/blob/master/tests/test_app.py | MIT |
async def raw_click(pilot: Pilot, selector: str, times: int = 1):
"""A lower level click function that doesn't use the Pilot,
and so doesn't bypass the click chain logic in App.on_event."""
app = pilot.app
kwargs = _get_mouse_message_arguments(app.query_one(selector))
for _ in range(times):
app.post_message(events.MouseDown(**kwargs))
app.post_message(events.MouseUp(**kwargs))
await pilot.pause() | A lower level click function that doesn't use the Pilot,
and so doesn't bypass the click chain logic in App.on_event. | raw_click | python | Textualize/textual | tests/test_app.py | https://github.com/Textualize/textual/blob/master/tests/test_app.py | MIT |
async def test_click_chain_offset_changes_mid_chain():
"""If we're in the middle of a click chain (e.g. we've double clicked), and the third click
comes in at a different offset, that third click should be considered a single click.
"""
click_count = 0
class MyApp(App[None]):
# Ensure clicks are always within the time threshold
CLICK_CHAIN_TIME_THRESHOLD = 1000.0
def compose(self) -> ComposeResult:
yield Label("Click me!", id="one")
yield Label("Another button!", id="two")
def on_click(self, event: events.Click) -> None:
nonlocal click_count
click_count = event.chain
async with MyApp().run_test() as pilot:
await raw_click(pilot, "#one", times=2) # Double click
assert click_count == 2
await raw_click(pilot, "#two") # Single click (because different widget)
assert click_count == 1 | If we're in the middle of a click chain (e.g. we've double clicked), and the third click
comes in at a different offset, that third click should be considered a single click. | test_click_chain_offset_changes_mid_chain | python | Textualize/textual | tests/test_app.py | https://github.com/Textualize/textual/blob/master/tests/test_app.py | MIT |
async def test_move_child_no_direction() -> None:
"""Test moving a widget in a child list."""
async with App().run_test() as pilot:
child = Widget()
await pilot.app.mount(child)
with pytest.raises(WidgetError):
pilot.app.screen.move_child(child) | Test moving a widget in a child list. | test_move_child_no_direction | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
async def test_move_child_both_directions() -> None:
"""Test calling move_child with more than one direction."""
async with App().run_test() as pilot:
child = Widget()
await pilot.app.mount(child)
with pytest.raises(WidgetError):
pilot.app.screen.move_child(child, before=1, after=2) | Test calling move_child with more than one direction. | test_move_child_both_directions | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
async def test_move_child_not_our_child() -> None:
"""Test attempting to move a child that isn't ours."""
async with App().run_test() as pilot:
child = Widget()
await pilot.app.mount(child)
with pytest.raises(WidgetError):
pilot.app.screen.move_child(Widget(), before=child) | Test attempting to move a child that isn't ours. | test_move_child_not_our_child | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
async def test_move_child_to_outside() -> None:
"""Test attempting to move relative to a widget that isn't a child."""
async with App().run_test() as pilot:
child = Widget()
await pilot.app.mount(child)
with pytest.raises(WidgetError):
pilot.app.screen.move_child(child, before=Widget()) | Test attempting to move relative to a widget that isn't a child. | test_move_child_to_outside | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
async def test_move_child_index_in_relation_to_itself_index(reference: str) -> None:
"""Regression test for https://github.com/Textualize/textual/issues/1743"""
widget = Widget()
child = 0
kwargs = {reference: 0}
async with App().run_test() as pilot:
await pilot.app.screen.mount(widget)
pilot.app.screen.move_child(child, **kwargs) # Shouldn't raise an error. | Regression test for https://github.com/Textualize/textual/issues/1743 | test_move_child_index_in_relation_to_itself_index | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
async def test_move_child_index_in_relation_to_itself_widget(reference: str) -> None:
"""Regression test for https://github.com/Textualize/textual/issues/1743"""
widget = Widget()
child = 0
kwargs = {reference: widget}
async with App().run_test() as pilot:
await pilot.app.screen.mount(widget)
pilot.app.screen.move_child(child, **kwargs) # Shouldn't raise an error. | Regression test for https://github.com/Textualize/textual/issues/1743 | test_move_child_index_in_relation_to_itself_widget | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
async def test_move_child_widget_in_relation_to_itself_index(reference: str) -> None:
"""Regression test for https://github.com/Textualize/textual/issues/1743"""
widget = Widget()
child = widget
kwargs = {reference: 0}
async with App().run_test() as pilot:
await pilot.app.screen.mount(widget)
pilot.app.screen.move_child(child, **kwargs) # Shouldn't raise an error. | Regression test for https://github.com/Textualize/textual/issues/1743 | test_move_child_widget_in_relation_to_itself_index | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
async def test_move_child_widget_in_relation_to_itself_widget(reference: str) -> None:
"""Regression test for https://github.com/Textualize/textual/issues/1743"""
widget = Widget()
child = widget
kwargs = {reference: widget}
async with App().run_test() as pilot:
await pilot.app.screen.mount(widget)
pilot.app.screen.move_child(child, **kwargs) # Shouldn't raise an error. | Regression test for https://github.com/Textualize/textual/issues/1743 | test_move_child_widget_in_relation_to_itself_widget | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
async def test_move_past_end_of_child_list() -> None:
"""Test attempting to move past the end of the child list."""
async with App().run_test() as pilot:
widgets = [Widget(id=f"widget-{n}") for n in range(10)]
container = Widget(*widgets)
await pilot.app.mount(container)
with pytest.raises(WidgetError):
container.move_child(widgets[0], before=len(widgets) + 10) | Test attempting to move past the end of the child list. | test_move_past_end_of_child_list | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
async def test_move_before_end_of_child_list() -> None:
"""Test attempting to move before the end of the child list."""
async with App().run_test() as pilot:
widgets = [Widget(id=f"widget-{n}") for n in range(10)]
container = Widget(*widgets)
await pilot.app.mount(container)
with pytest.raises(WidgetError):
container.move_child(widgets[0], before=-(len(widgets) + 10)) | Test attempting to move before the end of the child list. | test_move_before_end_of_child_list | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
async def test_move_before_permutations() -> None:
"""Test the different permutations of moving one widget before another."""
widgets = [Widget(id=f"widget-{n}") for n in range(10)]
perms = (
(1, 0),
(widgets[1], 0),
(1, widgets[0]),
(widgets[1], widgets[0]),
)
for child, target in perms:
async with App[None]().run_test() as pilot:
container = Widget(*widgets)
await pilot.app.mount(container)
container.move_child(child, before=target)
assert container._nodes[0].id == "widget-1"
assert container._nodes[1].id == "widget-0"
assert container._nodes[2].id == "widget-2" | Test the different permutations of moving one widget before another. | test_move_before_permutations | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
async def test_move_after_permutations() -> None:
"""Test the different permutations of moving one widget after another."""
widgets = [Widget(id=f"widget-{n}") for n in range(10)]
perms = ((0, 1), (widgets[0], 1), (0, widgets[1]), (widgets[0], widgets[1]))
for child, target in perms:
async with App[None]().run_test() as pilot:
container = Widget(*widgets)
await pilot.app.mount(container)
await pilot.pause()
container.move_child(child, after=target)
assert container._nodes[0].id == "widget-1"
assert container._nodes[1].id == "widget-0"
assert container._nodes[2].id == "widget-2" | Test the different permutations of moving one widget after another. | test_move_after_permutations | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
async def test_move_child_after_last_child() -> None:
"""Test moving after a child after the last child."""
async with App().run_test() as pilot:
widgets = [Widget(id=f"widget-{n}") for n in range(10)]
container = Widget(*widgets)
await pilot.app.mount(container)
container.move_child(widgets[0], after=widgets[-1])
assert container._nodes[0].id == "widget-1"
assert container._nodes[-1].id == "widget-0" | Test moving after a child after the last child. | test_move_child_after_last_child | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
async def test_move_child_after_last_numeric_location() -> None:
"""Test moving after a child after the last child's numeric position."""
async with App().run_test() as pilot:
widgets = [Widget(id=f"widget-{n}") for n in range(10)]
container = Widget(*widgets)
await pilot.app.mount(container)
container.move_child(widgets[0], after=widgets[9])
assert container._nodes[0].id == "widget-1"
assert container._nodes[-1].id == "widget-0" | Test moving after a child after the last child's numeric position. | test_move_child_after_last_numeric_location | python | Textualize/textual | tests/test_widget_child_moving.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_child_moving.py | MIT |
def test_simple_animation():
"""Test an animation from one float to another."""
# Thing that may be animated
animate_test = AnimateTest()
# Fake wall-clock time
time = 100.0
# Object that does the animation
animation = SimpleAnimation(
animate_test,
"foo",
time,
3.0,
start_value=20.0,
end_value=50.0,
final_value=None,
easing=lambda x: x,
)
assert animate_test.foo == 0.0
assert animation(time) is False
assert animate_test.foo == 20.0
assert animation(time + 1.0) is False
assert animate_test.foo == 30.0
assert animation(time + 2.0) is False
assert animate_test.foo == 40.0
assert animation(time + 2.9) is False # Not quite final value
assert animate_test.foo == pytest.approx(49.0)
assert animation(time + 3.0) is True # True to indicate animation is complete
assert animate_test.foo is None # This is final_value
assert animation(time + 3.0) is True
assert animate_test.foo is None | Test an animation from one float to another. | test_simple_animation | python | Textualize/textual | tests/test_animator.py | https://github.com/Textualize/textual/blob/master/tests/test_animator.py | MIT |
def test_simple_animation_duration_zero():
"""Test animation handles duration of 0."""
# Thing that may be animated
animatable = AnimateTest()
# Fake wall-clock time
time = 100.0
# Object that does the animation
animation = SimpleAnimation(
animatable,
"foo",
time,
0.0,
start_value=20.0,
end_value=50.0,
final_value=50.0,
easing=lambda x: x,
)
assert animation(time) is True # Duration is 0, so this is last value
assert animatable.foo == 50.0
assert animation(time + 1.0) is True
assert animatable.foo == 50.0 | Test animation handles duration of 0. | test_simple_animation_duration_zero | python | Textualize/textual | tests/test_animator.py | https://github.com/Textualize/textual/blob/master/tests/test_animator.py | MIT |
def test_simple_animation_reverse():
"""Test an animation from one float to another, where the end value is less than the start."""
# Thing that may be animated
animate_Test = AnimateTest()
# Fake wall-clock time
time = 100.0
# Object that does the animation
animation = SimpleAnimation(
animate_Test,
"foo",
time,
3.0,
start_value=50.0,
end_value=20.0,
final_value=20.0,
easing=lambda x: x,
)
assert animation(time) is False
assert animate_Test.foo == 50.0
assert animation(time + 1.0) is False
assert animate_Test.foo == 40.0
assert animation(time + 2.0) is False
assert animate_Test.foo == 30.0
assert animation(time + 3.0) is True
assert animate_Test.foo == 20.0 | Test an animation from one float to another, where the end value is less than the start. | test_simple_animation_reverse | python | Textualize/textual | tests/test_animator.py | https://github.com/Textualize/textual/blob/master/tests/test_animator.py | MIT |
def test_animatable():
"""Test SimpleAnimation works with the Animatable protocol"""
animate_test = AnimateTest()
# Fake wall-clock time
time = 100.0
# Object that does the animation
animation = SimpleAnimation(
animate_test,
"bar",
time,
3.0,
start_value=Animatable(20.0),
end_value=Animatable(50.0),
final_value=Animatable(50.0),
easing=lambda x: x,
)
assert animation(time) is False
assert animate_test.bar.value == 20.0
assert animation(time + 1.0) is False
assert animate_test.bar.value == 30.0
assert animation(time + 2.0) is False
assert animate_test.bar.value == 40.0
assert animation(time + 2.9) is False
assert animate_test.bar.value == pytest.approx(49.0)
assert animation(time + 3.0) is True # True to indicate animation is complete
assert animate_test.bar.value == 50.0 | Test SimpleAnimation works with the Animatable protocol | test_animatable | python | Textualize/textual | tests/test_animator.py | https://github.com/Textualize/textual/blob/master/tests/test_animator.py | MIT |
async def test_no_initial_display() -> None:
"""Test starting a content switcher with nothing shown."""
async with SwitcherApp().run_test() as pilot:
assert pilot.app.query_one(ContentSwitcher).current is None
assert all(
not child.display for child in pilot.app.query_one(ContentSwitcher).children
)
assert pilot.app.query_one(ContentSwitcher).visible_content is None | Test starting a content switcher with nothing shown. | test_no_initial_display | python | Textualize/textual | tests/test_content_switcher.py | https://github.com/Textualize/textual/blob/master/tests/test_content_switcher.py | MIT |
async def test_initial_display() -> None:
"""Test starting a content switcher with a widget initially shown."""
async with SwitcherApp("w3").run_test() as pilot:
assert pilot.app.query_one(ContentSwitcher).current == "w3"
for child in pilot.app.query_one(ContentSwitcher).children:
assert child.display is (child.id == "w3")
assert pilot.app.query_one(
ContentSwitcher
).visible_content is pilot.app.query_one("#w3") | Test starting a content switcher with a widget initially shown. | test_initial_display | python | Textualize/textual | tests/test_content_switcher.py | https://github.com/Textualize/textual/blob/master/tests/test_content_switcher.py | MIT |
async def test_no_initial_display_then_set() -> None:
"""Test starting a content switcher with nothing shown then setting the display."""
async with SwitcherApp().run_test() as pilot:
assert pilot.app.query_one(ContentSwitcher).current is None
assert all(
not child.display for child in pilot.app.query_one(ContentSwitcher).children
)
assert pilot.app.query_one(ContentSwitcher).visible_content is None
pilot.app.query_one(ContentSwitcher).current = "w3"
assert pilot.app.query_one(ContentSwitcher).current == "w3"
for child in pilot.app.query_one(ContentSwitcher).children:
assert child.display is (child.id == "w3")
assert pilot.app.query_one(
ContentSwitcher
).visible_content is pilot.app.query_one("#w3") | Test starting a content switcher with nothing shown then setting the display. | test_no_initial_display_then_set | python | Textualize/textual | tests/test_content_switcher.py | https://github.com/Textualize/textual/blob/master/tests/test_content_switcher.py | MIT |
async def test_initial_display_then_change() -> None:
"""Test starting a content switcher with a widget initially shown then changing it."""
async with SwitcherApp("w3").run_test() as pilot:
assert pilot.app.query_one(ContentSwitcher).current == "w3"
for child in pilot.app.query_one(ContentSwitcher).children:
assert child.display is (child.id == "w3")
assert pilot.app.query_one(
ContentSwitcher
).visible_content is pilot.app.query_one("#w3")
pilot.app.query_one(ContentSwitcher).current = "w2"
assert pilot.app.query_one(ContentSwitcher).current == "w2"
for child in pilot.app.query_one(ContentSwitcher).children:
assert child.display is (child.id == "w2")
assert pilot.app.query_one(
ContentSwitcher
).visible_content is pilot.app.query_one("#w2") | Test starting a content switcher with a widget initially shown then changing it. | test_initial_display_then_change | python | Textualize/textual | tests/test_content_switcher.py | https://github.com/Textualize/textual/blob/master/tests/test_content_switcher.py | MIT |
async def test_initial_display_then_hide() -> None:
"""Test starting a content switcher with a widget initially shown then hide all."""
async with SwitcherApp("w3").run_test() as pilot:
assert pilot.app.query_one(ContentSwitcher).current == "w3"
for child in pilot.app.query_one(ContentSwitcher).children:
assert child.display is (child.id == "w3")
pilot.app.query_one(ContentSwitcher).current = None
assert pilot.app.query_one(ContentSwitcher).current is None
assert all(
not child.display for child in pilot.app.query_one(ContentSwitcher).children
) | Test starting a content switcher with a widget initially shown then hide all. | test_initial_display_then_hide | python | Textualize/textual | tests/test_content_switcher.py | https://github.com/Textualize/textual/blob/master/tests/test_content_switcher.py | MIT |
async def test_initial_display_unknown_id() -> None:
"""Test setting an initial display to an unknown widget ID."""
with pytest.raises(NoMatches):
async with SwitcherApp("does-not-exist").run_test():
pass | Test setting an initial display to an unknown widget ID. | test_initial_display_unknown_id | python | Textualize/textual | tests/test_content_switcher.py | https://github.com/Textualize/textual/blob/master/tests/test_content_switcher.py | MIT |
async def test_set_current_to_unknown_id() -> None:
"""Test attempting to switch to an unknown widget ID."""
async with SwitcherApp().run_test() as pilot:
assert pilot.app.query_one(ContentSwitcher).current is None
assert all(
not child.display for child in pilot.app.query_one(ContentSwitcher).children
)
with pytest.raises(NoMatches):
pilot.app.query_one(ContentSwitcher).current = "does-not-exist" | Test attempting to switch to an unknown widget ID. | test_set_current_to_unknown_id | python | Textualize/textual | tests/test_content_switcher.py | https://github.com/Textualize/textual/blob/master/tests/test_content_switcher.py | MIT |
async def test_horizontal_vs_horizontalscroll_scrolling():
"""Check the default scrollbar behaviours for `Horizontal` and `HorizontalScroll`."""
class HorizontalsApp(App[None]):
CSS = """
Screen {
layout: vertical;
}
"""
def compose(self) -> ComposeResult:
with Horizontal():
for _ in range(10):
yield Label("How is life going? " * 3 + " | ")
with HorizontalScroll():
for _ in range(10):
yield Label("How is life going? " * 3 + " | ")
WIDTH = 80
HEIGHT = 24
app = HorizontalsApp()
async with app.run_test(size=(WIDTH, HEIGHT)):
horizontal = app.query_one(Horizontal)
horizontal_scroll = app.query_one(HorizontalScroll)
assert horizontal.size.height == horizontal_scroll.size.height
assert horizontal.scrollbars_enabled == (False, False)
assert horizontal_scroll.scrollbars_enabled == (False, True) | Check the default scrollbar behaviours for `Horizontal` and `HorizontalScroll`. | test_horizontal_vs_horizontalscroll_scrolling | python | Textualize/textual | tests/test_containers.py | https://github.com/Textualize/textual/blob/master/tests/test_containers.py | MIT |
async def test_vertical_vs_verticalscroll_scrolling():
"""Check the default scrollbar behaviours for `Vertical` and `VerticalScroll`."""
class VerticalsApp(App[None]):
CSS = """
Screen {
layout: horizontal;
}
"""
def compose(self) -> ComposeResult:
with Vertical():
for _ in range(10):
yield Label("How is life going?\n" * 3 + "\n\n")
with VerticalScroll():
for _ in range(10):
yield Label("How is life going?\n" * 3 + "\n\n")
WIDTH = 80
HEIGHT = 24
app = VerticalsApp()
async with app.run_test(size=(WIDTH, HEIGHT)):
vertical = app.query_one(Vertical)
vertical_scroll = app.query_one(VerticalScroll)
assert vertical.size.width == vertical_scroll.size.width
assert vertical.scrollbars_enabled == (False, False)
assert vertical_scroll.scrollbars_enabled == (True, False) | Check the default scrollbar behaviours for `Vertical` and `VerticalScroll`. | test_vertical_vs_verticalscroll_scrolling | python | Textualize/textual | tests/test_containers.py | https://github.com/Textualize/textual/blob/master/tests/test_containers.py | MIT |
async def test_center_container():
"""Check the size of the container `Center`."""
class CenterApp(App[None]):
def compose(self) -> ComposeResult:
with Center():
yield Label("<>\n<>\n<>")
app = CenterApp()
async with app.run_test():
center = app.query_one(Center)
assert center.size.width == app.size.width
assert center.size.height == 3 | Check the size of the container `Center`. | test_center_container | python | Textualize/textual | tests/test_containers.py | https://github.com/Textualize/textual/blob/master/tests/test_containers.py | MIT |
async def test_middle_container():
"""Check the size of the container `Middle`."""
class MiddleApp(App[None]):
def compose(self) -> ComposeResult:
with Middle():
yield Label("1234")
app = MiddleApp()
async with app.run_test():
middle = app.query_one(Middle)
assert middle.size.width == 4
assert middle.size.height == app.size.height | Check the size of the container `Middle`. | test_middle_container | python | Textualize/textual | tests/test_containers.py | https://github.com/Textualize/textual/blob/master/tests/test_containers.py | MIT |
async def test_scrollbar_zero_thickness():
"""Ensuring that scrollbars can be set to zero thickness."""
class ScrollbarZero(App):
CSS = """* {
scrollbar-size: 0 0;
scrollbar-size-vertical: 0; /* just exercising the parser */
scrollbar-size-horizontal: 0; /* exercise the parser */
}
"""
def compose(self) -> ComposeResult:
with Vertical():
for _ in range(10):
yield Label("Hello, world!")
app = ScrollbarZero()
async with app.run_test(size=(8, 6)):
pass | Ensuring that scrollbars can be set to zero thickness. | test_scrollbar_zero_thickness | python | Textualize/textual | tests/test_containers.py | https://github.com/Textualize/textual/blob/master/tests/test_containers.py | MIT |
async def test_suspend_not_supported() -> None:
"""Suspending when not supported should raise an error."""
async with App().run_test() as pilot:
# Pilot uses the headless driver, the headless driver doesn't
# support suspend, and so...
with pytest.raises(SuspendNotSupported):
with pilot.app.suspend():
pass | Suspending when not supported should raise an error. | test_suspend_not_supported | python | Textualize/textual | tests/test_suspend.py | https://github.com/Textualize/textual/blob/master/tests/test_suspend.py | MIT |
async def test_suspend_supported(capfd: pytest.CaptureFixture[str]) -> None:
"""Suspending when supported should call the relevant driver methods."""
calls: set[str] = set()
class HeadlessSuspendDriver(HeadlessDriver):
@property
def is_headless(self) -> bool:
return False
@property
def can_suspend(self) -> bool:
return True
def suspend_application_mode(self) -> None:
nonlocal calls
calls.add("suspend")
def resume_application_mode(self) -> None:
nonlocal calls
calls.add("resume")
class SuspendApp(App[None]):
def on_suspend(self, _) -> None:
nonlocal calls
calls.add("suspend signal")
def on_resume(self, _) -> None:
nonlocal calls
calls.add("resume signal")
def on_mount(self) -> None:
self.app_suspend_signal.subscribe(self, self.on_suspend, immediate=True)
self.app_resume_signal.subscribe(self, self.on_resume, immediate=True)
async with SuspendApp(driver_class=HeadlessSuspendDriver).run_test(
headless=False
) as pilot:
calls = set()
with pilot.app.suspend():
_ = capfd.readouterr() # Clear the existing buffer.
print("USE THEM TOGETHER.", end="", flush=True)
print("USE THEM IN PEACE.", file=sys.stderr, end="", flush=True)
assert ("USE THEM TOGETHER.", "USE THEM IN PEACE.") == capfd.readouterr()
assert calls == {"suspend", "resume", "suspend signal", "resume signal"} | Suspending when supported should call the relevant driver methods. | test_suspend_supported | python | Textualize/textual | tests/test_suspend.py | https://github.com/Textualize/textual/blob/master/tests/test_suspend.py | MIT |
async def test_links() -> None:
"""Regression test for https://github.com/Textualize/textual/issues/4536"""
messages: list[str] = []
class LinkLabel(Label):
def action_bell_message(self, message: str) -> None:
nonlocal messages
messages.append(f"label {message}")
class HomeScreen(Screen[None]):
def compose(self) -> ComposeResult:
yield LinkLabel("[@click=app.bell_message('foo')]Ring the bell![/]")
yield LinkLabel("[@click=screen.bell_message('bar')]Ring the bell![/]")
yield LinkLabel("[@click=bell_message('baz')]Ring the bell![/]")
def action_bell_message(self, message: str) -> None:
nonlocal messages
messages.append(f"screen {message}")
class ScreenNamespace(App[None]):
def get_default_screen(self) -> HomeScreen:
return HomeScreen()
def action_bell_message(self, message: str) -> None:
nonlocal messages
messages.append(f"app {message}")
async with ScreenNamespace().run_test() as pilot:
await pilot.click(offset=(5, 0))
await pilot.click(offset=(5, 1))
await pilot.click(offset=(5, 2))
assert messages == ["app foo", "screen bar", "label baz"] | Regression test for https://github.com/Textualize/textual/issues/4536 | test_links | python | Textualize/textual | tests/test_links.py | https://github.com/Textualize/textual/blob/master/tests/test_links.py | MIT |
def test_border_title_single_line():
"""The border_title gets set to a single line even when multiple lines are provided."""
widget = Widget()
assert widget.border_title is None
widget.border_title = None
assert widget.border_title is None
widget.border_title = ""
assert widget.border_title == ""
widget.border_title = "How is life\ngoing for you?"
assert widget.border_title == "How is life"
widget.border_title = "How is life\n\rgoing for you?"
assert widget.border_title == "How is life"
widget.border_title = "Sorry you \r\n have to \n read this."
assert widget.border_title == "Sorry you "
widget.border_title = "[red]This also \n works with markup \n involved.[/]"
assert widget.border_title == "[red]This also [/red]"
widget.border_title = Text.from_markup("[bold]Hello World")
assert widget.border_title == "[bold]Hello World[/bold]" | The border_title gets set to a single line even when multiple lines are provided. | test_border_title_single_line | python | Textualize/textual | tests/test_border.py | https://github.com/Textualize/textual/blob/master/tests/test_border.py | MIT |
def test_border_subtitle_single_line():
"""The border_subtitle gets set to a single line even when multiple lines are provided."""
widget = Widget()
widget.border_subtitle = ""
assert widget.border_subtitle == ""
widget.border_subtitle = "How is life\ngoing for you?"
assert widget.border_subtitle == "How is life"
widget.border_subtitle = "How is life\n\rgoing for you?"
assert widget.border_subtitle == "How is life"
widget.border_subtitle = "Sorry you \r\n have to \n read this."
assert widget.border_subtitle == "Sorry you "
widget.border_subtitle = "[red]This also \n works with markup \n involved.[/]"
assert widget.border_subtitle == "[red]This also [/red]"
widget.border_subtitle = Text.from_markup("[bold]Hello World")
assert widget.border_subtitle == "[bold]Hello World[/bold]" | The border_subtitle gets set to a single line even when multiple lines are provided. | test_border_subtitle_single_line | python | Textualize/textual | tests/test_border.py | https://github.com/Textualize/textual/blob/master/tests/test_border.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.