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 |
---|---|---|---|---|---|---|---|
async def test_switch_screen_no_op():
"""Regression test for https://github.com/Textualize/textual/issues/2650"""
class MyScreen(Screen):
pass
class MyApp(App[None]):
SCREENS = {"screen": MyScreen}
def on_mount(self):
self.push_screen("screen")
app = MyApp()
async with app.run_test():
screen_id = id(app.screen)
app.switch_screen("screen")
assert screen_id == id(app.screen)
app.switch_screen("screen")
assert screen_id == id(app.screen) | Regression test for https://github.com/Textualize/textual/issues/2650 | test_switch_screen_no_op | python | Textualize/textual | tests/test_screens.py | https://github.com/Textualize/textual/blob/master/tests/test_screens.py | MIT |
async def test_switch_screen_updates_results_callback_stack():
"""Regression test for https://github.com/Textualize/textual/issues/2650"""
class ScreenA(Screen):
pass
class ScreenB(Screen):
pass
class MyApp(App[None]):
SCREENS = {
"a": ScreenA,
"b": ScreenB,
}
def callback(self, _):
return 42
def on_mount(self):
self.push_screen("a", self.callback)
app = MyApp()
async with app.run_test():
assert len(app.screen._result_callbacks) == 1
assert app.screen._result_callbacks[-1].callback(None) == 42
app.switch_screen("b")
assert len(app.screen._result_callbacks) == 1
assert app.screen._result_callbacks[-1].callback is None | Regression test for https://github.com/Textualize/textual/issues/2650 | test_switch_screen_updates_results_callback_stack | python | Textualize/textual | tests/test_screens.py | https://github.com/Textualize/textual/blob/master/tests/test_screens.py | MIT |
async def test_push_screen_wait_for_dismiss() -> None:
"""Test push_screen returns result."""
class QuitScreen(Screen[bool]):
BINDINGS = [
("y", "quit(True)"),
("n", "quit(False)"),
]
def action_quit(self, quit: bool) -> None:
self.dismiss(quit)
results: list[bool] = []
class ScreensApp(App):
BINDINGS = [("x", "exit")]
@work
async def action_exit(self) -> None:
result = await self.push_screen(QuitScreen(), wait_for_dismiss=True)
results.append(result)
app = ScreensApp()
# Press X to exit, then Y to dismiss, expect True result
async with app.run_test() as pilot:
await pilot.press("x", "y")
assert results == [True]
results.clear()
app = ScreensApp()
# Press X to exit, then N to dismiss, expect False result
async with app.run_test() as pilot:
await pilot.press("x", "n")
assert results == [False] | Test push_screen returns result. | test_push_screen_wait_for_dismiss | python | Textualize/textual | tests/test_screens.py | https://github.com/Textualize/textual/blob/master/tests/test_screens.py | MIT |
async def test_push_screen_wait_for_dismiss_no_worker() -> None:
"""Test wait_for_dismiss raises NoActiveWorker when not using workers."""
class QuitScreen(Screen[bool]):
BINDINGS = [
("y", "quit(True)"),
("n", "quit(False)"),
]
def action_quit(self, quit: bool) -> None:
self.dismiss(quit)
results: list[bool] = []
class ScreensApp(App):
BINDINGS = [("x", "exit")]
async def action_exit(self) -> None:
result = await self.push_screen(QuitScreen(), wait_for_dismiss=True)
results.append(result)
app = ScreensApp()
# using `wait_for_dismiss` outside of a worker should raise NoActiveWorker
with pytest.raises(NoActiveWorker):
async with app.run_test() as pilot:
await pilot.press("x", "y") | Test wait_for_dismiss raises NoActiveWorker when not using workers. | test_push_screen_wait_for_dismiss_no_worker | python | Textualize/textual | tests/test_screens.py | https://github.com/Textualize/textual/blob/master/tests/test_screens.py | MIT |
async def test_default_custom_screen() -> None:
"""Test we can override the default screen."""
class CustomScreen(Screen):
pass
class CustomScreenApp(App):
def get_default_screen(self) -> Screen:
return CustomScreen()
app = CustomScreenApp()
async with app.run_test():
assert len(app.screen_stack) == 1
assert isinstance(app.screen_stack[0], CustomScreen)
assert app.screen is app.screen_stack[0] | Test we can override the default screen. | test_default_custom_screen | python | Textualize/textual | tests/test_screens.py | https://github.com/Textualize/textual/blob/master/tests/test_screens.py | MIT |
async def test_disallow_screen_instances() -> None:
"""Test that screen instances are disallowed."""
class CustomScreen(Screen):
pass
with pytest.raises(ValueError):
class Bad(App):
SCREENS = {"a": CustomScreen()} # type: ignore
with pytest.raises(ValueError):
class Worse(App):
MODES = {"a": CustomScreen()} # type: ignore
# While we're here, let's make sure that other types
# are disallowed.
with pytest.raises(TypeError):
class Terrible(App):
MODES = {"a": 42, "b": CustomScreen} # type: ignore
with pytest.raises(TypeError):
class Worst(App):
MODES = {"OK": CustomScreen, 1: 2} # type: ignore | Test that screen instances are disallowed. | test_disallow_screen_instances | python | Textualize/textual | tests/test_screens.py | https://github.com/Textualize/textual/blob/master/tests/test_screens.py | MIT |
async def test_worker_cancellation():
"""Regression test for https://github.com/Textualize/textual/issues/4884
The MRE below was pushing a screen in an exclusive worker.
This was previously breaking because the second time the worker was launched,
it cancelled the first one which was awaiting the screen.
"""
from textual import on, work
from textual.app import App
from textual.containers import Vertical
from textual.screen import Screen
from textual.widgets import Button, Footer, Label
class InfoScreen(Screen[bool]):
def __init__(self, question: str) -> None:
self.question = question
super().__init__()
def compose(self) -> ComposeResult:
yield Vertical(
Label(self.question, id="info-label"),
Button("Ok", variant="primary", id="ok"),
id="info-vertical",
)
yield Footer()
@on(Button.Pressed, "#ok")
def handle_ok(self) -> None:
self.dismiss(True) # Changed the `dismiss` result to compatible type
class ExampleApp(App):
BINDINGS = [("i", "info", "Info")]
screen_count = 0
def compose(self) -> ComposeResult:
yield Label("This is the default screen")
yield Footer()
@work(exclusive=True)
async def action_info(self) -> None:
# Since this is an exclusive worker, the second time it is called,
# the original `push_screen_wait` is also cancelled
self.screen_count += 1
await self.push_screen_wait(
InfoScreen(f"This is info screen #{self.screen_count}")
)
app = ExampleApp()
async with app.run_test() as pilot:
# Press i twice to launch 2 InfoScreens
await pilot.press("i")
await pilot.press("i")
# Press enter to activate button to dismiss them
await pilot.press("enter")
await pilot.press("enter") | Regression test for https://github.com/Textualize/textual/issues/4884
The MRE below was pushing a screen in an exclusive worker.
This was previously breaking because the second time the worker was launched,
it cancelled the first one which was awaiting the screen. | test_worker_cancellation | python | Textualize/textual | tests/test_screens.py | https://github.com/Textualize/textual/blob/master/tests/test_screens.py | MIT |
async def test_get_screen_with_expected_type():
"""Test get_screen with expected type works"""
class BadScreen(Screen[None]):
pass
class MyScreen(Screen[None]):
def compose(self):
yield Label()
yield Button()
class MyApp(App[None]):
SCREENS = {"my_screen": MyScreen}
def on_mount(self):
self.push_screen("my_screen")
app = MyApp()
async with app.run_test():
screen = app.get_screen("my_screen")
# Should be fine
assert isinstance(screen, MyScreen)
screen = app.get_screen("my_screen", MyScreen)
# Should be fine
assert isinstance(screen, MyScreen)
# TypeError because my_screen is not a BadScreen
with pytest.raises(TypeError):
screen = app.get_screen("my_screen", BadScreen) | Test get_screen with expected type works | test_get_screen_with_expected_type | python | Textualize/textual | tests/test_screens.py | https://github.com/Textualize/textual/blob/master/tests/test_screens.py | MIT |
async def test_remove_row_and_update():
"""Regression test for https://github.com/Textualize/textual/issues/3470 -
Crash when attempting to remove and update the same cell."""
app = DataTableApp()
async with app.run_test() as pilot:
table: DataTable = app.query_one(DataTable)
table.add_column("A", key="A")
table.add_row("1", key="1")
table.update_cell("1", "A", "X", update_width=True)
table.remove_row("1")
await pilot.pause() | Regression test for https://github.com/Textualize/textual/issues/3470 -
Crash when attempting to remove and update the same cell. | test_remove_row_and_update | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_remove_column_and_update():
"""Regression test for https://github.com/Textualize/textual/issues/3470 -
Crash when attempting to remove and update the same cell."""
app = DataTableApp()
async with app.run_test() as pilot:
table: DataTable = app.query_one(DataTable)
table.add_column("A", key="A")
table.add_row("1", key="1")
table.update_cell("1", "A", "X", update_width=True)
table.remove_column("A")
await pilot.pause() | Regression test for https://github.com/Textualize/textual/issues/3470 -
Crash when attempting to remove and update the same cell. | test_remove_column_and_update | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_update_cell_invalid_column_key():
"""Regression test for https://github.com/Textualize/textual/issues/3335"""
app = DataTableApp()
async with app.run_test():
table = app.query_one(DataTable)
table.add_column("Column1", key="C1")
table.add_row("TargetValue", key="R1")
with pytest.raises(CellDoesNotExist):
table.update_cell("R1", "INVALID_COLUMN", "New Value") | Regression test for https://github.com/Textualize/textual/issues/3335 | test_update_cell_invalid_column_key | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_datatable_click_cell_cursor():
"""When the cell cursor is used, and we click, we emit a CellHighlighted
*and* a CellSelected message for the cell that was clicked.
Regression test for https://github.com/Textualize/textual/issues/1723"""
app = DataTableApp()
async with app.run_test() as pilot:
table = app.query_one(DataTable)
column_key = table.add_column("ABC")
table.add_row("123")
row_key = table.add_row("456")
await pilot.click(offset=Offset(1, 2))
# There's two CellHighlighted events since a cell is highlighted on initial load,
# then when we click, another cell is highlighted (and selected).
assert app.message_names == [
"CellHighlighted",
"CellHighlighted",
"CellSelected",
]
cell_highlighted_event: DataTable.CellHighlighted = app.messages[1]
assert cell_highlighted_event.value == "456"
assert cell_highlighted_event.cell_key == CellKey(row_key, column_key)
assert cell_highlighted_event.coordinate == Coordinate(1, 0)
cell_selected_event: DataTable.CellSelected = app.messages[2]
assert cell_selected_event.value == "456"
assert cell_selected_event.cell_key == CellKey(row_key, column_key)
assert cell_selected_event.coordinate == Coordinate(1, 0) | When the cell cursor is used, and we click, we emit a CellHighlighted
*and* a CellSelected message for the cell that was clicked.
Regression test for https://github.com/Textualize/textual/issues/1723 | test_datatable_click_cell_cursor | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_click_row_cursor():
"""When the row cursor is used, and we click, we emit a RowHighlighted
*and* a RowSelected message for the row that was clicked."""
app = DataTableApp()
async with app.run_test() as pilot:
table = app.query_one(DataTable)
table.cursor_type = "row"
table.add_column("ABC")
table.add_row("123")
row_key = table.add_row("456")
await pilot.click(offset=Offset(1, 2))
assert app.message_names == ["RowHighlighted", "RowHighlighted", "RowSelected"]
row_highlighted: DataTable.RowHighlighted = app.messages[1]
assert row_highlighted.row_key == row_key
assert row_highlighted.cursor_row == 1
row_selected: DataTable.RowSelected = app.messages[2]
assert row_selected.row_key == row_key
assert row_highlighted.cursor_row == 1 | When the row cursor is used, and we click, we emit a RowHighlighted
*and* a RowSelected message for the row that was clicked. | test_click_row_cursor | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_click_column_cursor():
"""When the column cursor is used, and we click, we emit a ColumnHighlighted
*and* a ColumnSelected message for the column that was clicked."""
app = DataTableApp()
async with app.run_test() as pilot:
table = app.query_one(DataTable)
table.cursor_type = "column"
column_key = table.add_column("ABC")
table.add_row("123")
table.add_row("456")
await pilot.click(offset=Offset(1, 2))
assert app.message_names == [
"ColumnHighlighted",
"ColumnHighlighted",
"ColumnSelected",
]
column_highlighted: DataTable.ColumnHighlighted = app.messages[1]
assert column_highlighted.column_key == column_key
assert column_highlighted.cursor_column == 0
column_selected: DataTable.ColumnSelected = app.messages[2]
assert column_selected.column_key == column_key
assert column_highlighted.cursor_column == 0 | When the column cursor is used, and we click, we emit a ColumnHighlighted
*and* a ColumnSelected message for the column that was clicked. | test_click_column_cursor | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_hover_coordinate():
"""Ensure that the hover_coordinate reactive is updated as expected."""
app = DataTableApp()
async with app.run_test() as pilot:
table = app.query_one(DataTable)
table.add_column("ABC")
table.add_row("123")
table.add_row("456")
await pilot.pause()
assert table.hover_coordinate == Coordinate(0, 0)
await pilot.hover(DataTable, offset=Offset(2, 2))
assert table.hover_coordinate == Coordinate(1, 0) | Ensure that the hover_coordinate reactive is updated as expected. | test_hover_coordinate | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_hover_mouse_leave():
"""When the mouse cursor leaves the DataTable, there should be no hover highlighting."""
app = DataTableApp()
async with app.run_test() as pilot:
table = app.query_one(DataTable)
table.add_column("ABC")
table.add_row("123")
await pilot.pause()
assert table.hover_coordinate == Coordinate(0, 0)
# Hover over a cell, and the hover cursor is visible
await pilot.hover(DataTable, offset=Offset(1, 1))
assert table._show_hover_cursor
# Move our cursor away from the DataTable, and the hover cursor is hidden
await pilot.hover(DataTable, offset=Offset(20, 20))
assert not table._show_hover_cursor | When the mouse cursor leaves the DataTable, there should be no hover highlighting. | test_hover_mouse_leave | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_header_selected():
"""Ensure that a HeaderSelected event gets posted when we click
on the header in the DataTable."""
app = DataTableApp()
async with app.run_test() as pilot:
table = app.query_one(DataTable)
column_key = table.add_column("number")
table.add_row(3)
click_location = Offset(3, 0) # Click the header
await pilot.click(DataTable, offset=click_location)
message: DataTable.HeaderSelected = app.messages[-1]
assert message.label == Text("number")
assert message.column_index == 0
assert message.column_key == column_key
# Now hide the header and click in the exact same place - no additional message emitted.
table.show_header = False
await pilot.click(DataTable, offset=click_location)
await pilot.pause()
assert app.message_names.count("HeaderSelected") == 1 | Ensure that a HeaderSelected event gets posted when we click
on the header in the DataTable. | test_header_selected | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_row_label_selected():
"""Ensure that the DataTable sends a RowLabelSelected event when
the user clicks on a row label."""
app = DataTableApp()
async with app.run_test() as pilot:
table = app.query_one(DataTable)
table.add_column("number")
row_key = table.add_row(3, label="A")
await pilot.pause()
await pilot.click(DataTable, offset=Offset(1, 1))
message: DataTable.RowLabelSelected = app.messages[-1]
assert message.label == Text("A")
assert message.row_index == 0
assert message.row_key == row_key
# Now hide the row label and click in the same place - no additional message emitted.
table.show_row_labels = False
await pilot.click(DataTable, offset=Offset(1, 1))
assert app.message_names.count("RowLabelSelected") == 1 | Ensure that the DataTable sends a RowLabelSelected event when
the user clicks on a row label. | test_row_label_selected | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_sort_coordinate_and_key_access():
"""Ensure that, after sorting, that coordinates and cell keys
can still be used to retrieve the correct cell."""
app = DataTableApp()
async with app.run_test():
table = app.query_one(DataTable)
column = table.add_column("number")
row_three = table.add_row(3)
row_one = table.add_row(1)
row_two = table.add_row(2)
# Items inserted in correct initial positions (before sort)
assert table.get_cell_at(Coordinate(0, 0)) == 3
assert table.get_cell_at(Coordinate(1, 0)) == 1
assert table.get_cell_at(Coordinate(2, 0)) == 2
table.sort(column)
# The keys still refer to the same cells...
assert table.get_cell(row_one, column) == 1
assert table.get_cell(row_two, column) == 2
assert table.get_cell(row_three, column) == 3
# ...even though the values under the coordinates have changed...
assert table.get_cell_at(Coordinate(0, 0)) == 1
assert table.get_cell_at(Coordinate(1, 0)) == 2
assert table.get_cell_at(Coordinate(2, 0)) == 3
assert table.ordered_rows[0].key == row_one
assert table.ordered_rows[1].key == row_two
assert table.ordered_rows[2].key == row_three | Ensure that, after sorting, that coordinates and cell keys
can still be used to retrieve the correct cell. | test_sort_coordinate_and_key_access | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_sort_reverse_coordinate_and_key_access():
"""Ensure that, after sorting, that coordinates and cell keys
can still be used to retrieve the correct cell."""
app = DataTableApp()
async with app.run_test():
table = app.query_one(DataTable)
column = table.add_column("number")
row_three = table.add_row(3)
row_one = table.add_row(1)
row_two = table.add_row(2)
# Items inserted in correct initial positions (before sort)
assert table.get_cell_at(Coordinate(0, 0)) == 3
assert table.get_cell_at(Coordinate(1, 0)) == 1
assert table.get_cell_at(Coordinate(2, 0)) == 2
table.sort(column, reverse=True)
# The keys still refer to the same cells...
assert table.get_cell(row_one, column) == 1
assert table.get_cell(row_two, column) == 2
assert table.get_cell(row_three, column) == 3
# ...even though the values under the coordinates have changed...
assert table.get_cell_at(Coordinate(0, 0)) == 3
assert table.get_cell_at(Coordinate(1, 0)) == 2
assert table.get_cell_at(Coordinate(2, 0)) == 1
assert table.ordered_rows[0].key == row_three
assert table.ordered_rows[1].key == row_two
assert table.ordered_rows[2].key == row_one | Ensure that, after sorting, that coordinates and cell keys
can still be used to retrieve the correct cell. | test_sort_reverse_coordinate_and_key_access | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_reuse_row_key_after_clear():
"""Regression test for https://github.com/Textualize/textual/issues/1806"""
app = DataTableApp()
async with app.run_test():
table = app.query_one(DataTable)
table.add_columns("A", "B")
table.add_row(0, 1, key="ROW1")
table.add_row(2, 3, key="ROW2")
table.clear()
table.add_row(4, 5, key="ROW1") # Reusing the same keys as above
table.add_row(7, 8, key="ROW2")
assert table.get_row("ROW1") == [4, 5]
assert table.get_row("ROW2") == [7, 8] | Regression test for https://github.com/Textualize/textual/issues/1806 | test_reuse_row_key_after_clear | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_reuse_column_key_after_clear():
"""Regression test for https://github.com/Textualize/textual/issues/1806"""
app = DataTableApp()
async with app.run_test():
table = app.query_one(DataTable)
table.add_column("A", key="COLUMN1")
table.add_column("B", key="COLUMN2")
table.clear(columns=True)
table.add_column("C", key="COLUMN1") # Reusing the same keys as above
table.add_column("D", key="COLUMN2")
table.add_row(1, 2)
assert list(table.get_column("COLUMN1")) == [1]
assert list(table.get_column("COLUMN2")) == [2] | Regression test for https://github.com/Textualize/textual/issues/1806 | test_reuse_column_key_after_clear | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_scrolling_cursor_into_view():
"""Regression test for https://github.com/Textualize/textual/issues/2459"""
class ScrollingApp(DataTableApp):
CSS = "DataTable { height: 100%; }"
def key_c(self):
self.query_one(DataTable).cursor_coordinate = Coordinate(200, 0)
app = ScrollingApp()
async with app.run_test() as pilot:
table = app.query_one(DataTable)
table.add_column("n")
table.add_rows([(n,) for n in range(300)])
await pilot.pause()
await pilot.press("c")
await pilot.pause()
assert table.scroll_y > 100 | Regression test for https://github.com/Textualize/textual/issues/2459 | test_scrolling_cursor_into_view | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_unset_hover_highlight_when_no_table_cell_under_mouse():
"""When there isn't a table cell under the mouse cursor, there should be no
hover highlighting.
Regression test for #2909 https://github.com/Textualize/textual/issues/2909
"""
app = DataTableApp()
async with app.run_test() as pilot:
table = app.query_one(DataTable)
table.add_column("ABC")
table.add_row("123")
await pilot.pause()
assert table.hover_coordinate == Coordinate(0, 0)
# Hover over a cell, and the hover cursor is visible
await pilot.hover(DataTable, offset=Offset(1, 1))
assert table._show_hover_cursor
# Move our cursor so it is outside any table cells but still within
# the widget, and the hover cursor is hidden
await pilot.hover(DataTable, offset=Offset(42, 1))
assert not table._show_hover_cursor | When there isn't a table cell under the mouse cursor, there should be no
hover highlighting.
Regression test for #2909 https://github.com/Textualize/textual/issues/2909 | test_unset_hover_highlight_when_no_table_cell_under_mouse | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_sort_by_all_columns_no_key():
"""Test sorting a `DataTable` by all columns."""
app = DataTableApp()
async with app.run_test():
table = app.query_one(DataTable)
a, b, c = table.add_columns("A", "B", "C")
table.add_row(1, 3, 8)
table.add_row(2, 9, 5)
table.add_row(1, 1, 9)
assert table.get_row_at(0) == [1, 3, 8]
assert table.get_row_at(1) == [2, 9, 5]
assert table.get_row_at(2) == [1, 1, 9]
table.sort()
assert table.get_row_at(0) == [1, 1, 9]
assert table.get_row_at(1) == [1, 3, 8]
assert table.get_row_at(2) == [2, 9, 5]
table.sort(reverse=True)
assert table.get_row_at(0) == [2, 9, 5]
assert table.get_row_at(1) == [1, 3, 8]
assert table.get_row_at(2) == [1, 1, 9] | Test sorting a `DataTable` by all columns. | test_sort_by_all_columns_no_key | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_sort_by_multiple_columns_no_key():
"""Test sorting a `DataTable` by multiple columns."""
app = DataTableApp()
async with app.run_test():
table = app.query_one(DataTable)
a, b, c = table.add_columns("A", "B", "C")
table.add_row(1, 3, 8)
table.add_row(2, 9, 5)
table.add_row(1, 1, 9)
table.sort(a, b, c)
assert table.get_row_at(0) == [1, 1, 9]
assert table.get_row_at(1) == [1, 3, 8]
assert table.get_row_at(2) == [2, 9, 5]
table.sort(a, c, b)
assert table.get_row_at(0) == [1, 3, 8]
assert table.get_row_at(1) == [1, 1, 9]
assert table.get_row_at(2) == [2, 9, 5]
table.sort(c, a, b, reverse=True)
assert table.get_row_at(0) == [1, 1, 9]
assert table.get_row_at(1) == [1, 3, 8]
assert table.get_row_at(2) == [2, 9, 5]
table.sort(a, c)
assert table.get_row_at(0) == [1, 3, 8]
assert table.get_row_at(1) == [1, 1, 9]
assert table.get_row_at(2) == [2, 9, 5] | Test sorting a `DataTable` by multiple columns. | test_sort_by_multiple_columns_no_key | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_sort_by_function_sum():
"""Test sorting a `DataTable` using a custom sort function."""
def custom_sort(row_data):
return sum(row_data)
row_data = (
[1, 3, 8], # SUM=12
[2, 9, 5], # SUM=16
[1, 1, 9], # SUM=11
)
app = DataTableApp()
async with app.run_test():
table = app.query_one(DataTable)
a, b, c = table.add_columns("A", "B", "C")
for i, row in enumerate(row_data):
table.add_row(*row)
# Sorting by all columns
table.sort(a, b, c, key=custom_sort)
sorted_row_data = sorted(row_data, key=sum)
for i, row in enumerate(sorted_row_data):
assert table.get_row_at(i) == row
# Passing a sort function but no columns also sorts by all columns
table.sort(key=custom_sort)
sorted_row_data = sorted(row_data, key=sum)
for i, row in enumerate(sorted_row_data):
assert table.get_row_at(i) == row
table.sort(a, b, c, key=custom_sort, reverse=True)
sorted_row_data = sorted(row_data, key=sum, reverse=True)
for i, row in enumerate(sorted_row_data):
assert table.get_row_at(i) == row | Test sorting a `DataTable` using a custom sort function. | test_sort_by_function_sum | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_add_row_expands_column_widths():
"""Regression test for https://github.com/Textualize/textual/issues/1026."""
app = DataTableApp()
async with app.run_test() as pilot:
table = app.query_one(DataTable)
table.add_column("First")
table.add_column("Second", width=10)
await pilot.pause()
assert (
table.ordered_columns[0].get_render_width(table)
== 5 + 2 * _DEFAULT_CELL_X_PADDING
)
assert (
table.ordered_columns[1].get_render_width(table)
== 10 + 2 * _DEFAULT_CELL_X_PADDING
)
table.add_row("a" * 20, "a" * 20)
await pilot.pause()
assert (
table.ordered_columns[0].get_render_width(table)
== 20 + 2 * _DEFAULT_CELL_X_PADDING
)
assert (
table.ordered_columns[1].get_render_width(table)
== 10 + 2 * _DEFAULT_CELL_X_PADDING
) | Regression test for https://github.com/Textualize/textual/issues/1026. | test_add_row_expands_column_widths | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_move_cursor_respects_animate_parameter():
"""Regression test for https://github.com/Textualize/textual/issues/3840
Make sure that the call to `_scroll_cursor_into_view` from `move_cursor` happens
before the call from the watcher method from `cursor_coordinate`.
The former should animate because we call it with `animate=True` whereas the later
should not.
"""
scrolls = []
class _DataTable(DataTable):
def _scroll_cursor_into_view(self, animate=False):
nonlocal scrolls
scrolls.append(animate)
super()._scroll_cursor_into_view(animate)
class LongDataTableApp(App):
def compose(self):
yield _DataTable()
def on_mount(self):
dt = self.query_one(_DataTable)
dt.add_columns("one", "two")
for _ in range(100):
dt.add_row("one", "two")
def key_s(self):
table = self.query_one(_DataTable)
table.move_cursor(row=99, animate=True)
app = LongDataTableApp()
async with app.run_test() as pilot:
await pilot.press("s")
assert scrolls == [True, False] | Regression test for https://github.com/Textualize/textual/issues/3840
Make sure that the call to `_scroll_cursor_into_view` from `move_cursor` happens
before the call from the watcher method from `cursor_coordinate`.
The former should animate because we call it with `animate=True` whereas the later
should not. | test_move_cursor_respects_animate_parameter | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_clicking_border_link_doesnt_crash():
"""Regression test for https://github.com/Textualize/textual/issues/4410"""
class DataTableWithBorderLinkApp(App):
CSS = """
DataTable {
border: solid red;
}
"""
link_clicked = False
def compose(self) -> ComposeResult:
yield DataTable()
def on_mount(self) -> None:
table = self.query_one(DataTable)
table.border_title = "[@click=app.test_link]Border Link[/]"
def action_test_link(self) -> None:
self.link_clicked = True
app = DataTableWithBorderLinkApp()
async with app.run_test() as pilot:
# Test clicking the link in the border doesn't crash with KeyError: 'row'
await pilot.click(DataTable, offset=(5, 0))
assert app.link_clicked is True | Regression test for https://github.com/Textualize/textual/issues/4410 | test_clicking_border_link_doesnt_crash | python | Textualize/textual | tests/test_data_table.py | https://github.com/Textualize/textual/blob/master/tests/test_data_table.py | MIT |
async def test_call_later() -> None:
"""Check that call later makes a call."""
app = CallLaterApp()
called_event = asyncio.Event()
async with app.run_test():
app.call_later(called_event.set)
await asyncio.wait_for(called_event.wait(), 1) | Check that call later makes a call. | test_call_later | python | Textualize/textual | tests/test_call_x_schedulers.py | https://github.com/Textualize/textual/blob/master/tests/test_call_x_schedulers.py | MIT |
async def test_call_after_refresh() -> None:
"""Check that call later makes a call after a refresh."""
app = CallLaterApp()
display_count = -1
called_event = asyncio.Event()
callback_message_pump: MessagePump | None = None
def callback() -> None:
nonlocal display_count
nonlocal callback_message_pump
called_event.set()
display_count = app.display_count
callback_message_pump = active_message_pump.get()
async with app.run_test():
app.call_after_refresh(callback)
await asyncio.wait_for(called_event.wait(), 1)
app_display_count = app.display_count
assert app_display_count == display_count
# Should be app because the callback should be in the same context as app
assert callback_message_pump is app | Check that call later makes a call after a refresh. | test_call_after_refresh | python | Textualize/textual | tests/test_call_x_schedulers.py | https://github.com/Textualize/textual/blob/master/tests/test_call_x_schedulers.py | MIT |
def test_nested_and_convoluted_tuple_arguments(
action_string: str, expected_arguments: tuple[Any]
) -> None:
"""Test that tuple arguments are parsed correctly."""
_, _, args = parse(action_string)
assert args == expected_arguments | Test that tuple arguments are parsed correctly. | test_nested_and_convoluted_tuple_arguments | python | Textualize/textual | tests/test_actions.py | https://github.com/Textualize/textual/blob/master/tests/test_actions.py | MIT |
def test_parse_action_nested_special_character_arguments(
action_string: str, expected_arguments: tuple[Any]
) -> None:
"""Test that special characters nested in strings are handled correctly.
See also: https://github.com/Textualize/textual/issues/2088
"""
_, _, args = parse(action_string)
assert args == expected_arguments | Test that special characters nested in strings are handled correctly.
See also: https://github.com/Textualize/textual/issues/2088 | test_parse_action_nested_special_character_arguments | python | Textualize/textual | tests/test_actions.py | https://github.com/Textualize/textual/blob/master/tests/test_actions.py | MIT |
def test_size_with_height():
"""Test Size.with_height"""
assert Size(1, 2).with_height(10) == Size(1, 10) | Test Size.with_height | test_size_with_height | python | Textualize/textual | tests/test_geometry.py | https://github.com/Textualize/textual/blob/master/tests/test_geometry.py | MIT |
def test_size_with_width():
"""Test Size.with_width"""
assert Size(1, 2).with_width(10) == Size(10, 2) | Test Size.with_width | test_size_with_width | python | Textualize/textual | tests/test_geometry.py | https://github.com/Textualize/textual/blob/master/tests/test_geometry.py | MIT |
def _extract_content(lines: list[Strip]) -> list[str]:
"""Extract the text content from lines."""
content = ["".join(segment.text for segment in line) for line in lines]
return content | Extract the text content from lines. | _extract_content | python | Textualize/textual | tests/test_styles_cache.py | https://github.com/Textualize/textual/blob/master/tests/test_styles_cache.py | MIT |
def test_no_styles():
"""Test that empty style returns the content un-altered"""
content = [
Strip([Segment("foo")]),
Strip([Segment("bar")]),
Strip([Segment("baz")]),
]
styles = Styles()
cache = StylesCache()
lines = cache.render(
styles,
Size(3, 3),
Color.parse("blue"),
Color.parse("green"),
content.__getitem__,
None,
None,
content_size=Size(3, 3),
)
style = Style.from_color(bgcolor=Color.parse("green").rich_color)
expected = [
Strip([Segment("foo", style)], 3),
Strip([Segment("bar", style)], 3),
Strip([Segment("baz", style)], 3),
]
print(lines[0])
print(expected[0])
assert lines == expected | Test that empty style returns the content un-altered | test_no_styles | python | Textualize/textual | tests/test_styles_cache.py | https://github.com/Textualize/textual/blob/master/tests/test_styles_cache.py | MIT |
def test_dirty_cache() -> None:
"""Check that we only render content once or if it has been marked as dirty."""
content = [
Strip([Segment("foo")]),
Strip([Segment("bar")]),
Strip([Segment("baz")]),
]
rendered_lines: list[int] = []
def get_content_line(y: int) -> Strip:
rendered_lines.append(y)
return content[y]
styles = Styles()
styles.padding = 1
styles.border = ("heavy", "white")
cache = StylesCache()
lines = cache.render(
styles,
Size(7, 7),
Color.parse("blue"),
Color.parse("green"),
get_content_line,
None,
None,
content_size=Size(3, 3),
)
assert rendered_lines == [0, 1, 2]
del rendered_lines[:]
text_content = _extract_content(lines)
expected_text = [
"┏━━━━━┓",
"┃ ┃",
"┃ foo ┃",
"┃ bar ┃",
"┃ baz ┃",
"┃ ┃",
"┗━━━━━┛",
]
assert text_content == expected_text
# Re-render styles, check that content was not requested
lines = cache.render(
styles,
Size(7, 7),
Color.parse("blue"),
Color.parse("green"),
get_content_line,
None,
None,
content_size=Size(3, 3),
)
assert rendered_lines == []
del rendered_lines[:]
text_content = _extract_content(lines)
assert text_content == expected_text
# Mark 2 lines as dirty
cache.set_dirty(Region(0, 2, 7, 2))
lines = cache.render(
styles,
Size(7, 7),
Color.parse("blue"),
Color.parse("green"),
get_content_line,
None,
None,
content_size=Size(3, 3),
)
assert rendered_lines == [0, 1]
text_content = _extract_content(lines)
assert text_content == expected_text | Check that we only render content once or if it has been marked as dirty. | test_dirty_cache | python | Textualize/textual | tests/test_styles_cache.py | https://github.com/Textualize/textual/blob/master/tests/test_styles_cache.py | MIT |
async def test_file_deletion(tmp_path):
"""In some environments, a file can become temporarily unavailable during saving.
This test ensures the FileMonitor is robust enough to handle a file temporarily being
unavailable, and that it recovers when the file becomes available again.
Regression test for: https://github.com/Textualize/textual/issues/3996
"""
def make_file():
path = tmp_path / "will_be_deleted.tcss"
path.write_text("#foo { color: dodgerblue; }")
return path
callback_counter = 0
def callback():
nonlocal callback_counter
callback_counter += 1
path = make_file()
file_monitor = FileMonitor([path], callback)
# Ensure the file monitor survives after the file is gone
await file_monitor()
os.remove(path)
# The file is now unavailable, but we don't crash here
await file_monitor()
await file_monitor()
# Despite multiple checks, the file was only available for the first check,
# and we only fire the callback while the file is available.
assert callback_counter == 1
# The file is made available again.
make_file()
# Since the file is available, the callback should fire when the FileMonitor is called
await file_monitor()
assert callback_counter == 2 | In some environments, a file can become temporarily unavailable during saving.
This test ensures the FileMonitor is robust enough to handle a file temporarily being
unavailable, and that it recovers when the file becomes available again.
Regression test for: https://github.com/Textualize/textual/issues/3996 | test_file_deletion | python | Textualize/textual | tests/test_file_monitor.py | https://github.com/Textualize/textual/blob/master/tests/test_file_monitor.py | MIT |
async def test_empty_paste():
"""Regression test for https://github.com/Textualize/textual/issues/2563."""
paste_events = []
class MyInput(Input):
def on_paste(self, event):
super()._on_paste(event)
paste_events.append(event)
class PasteApp(App):
def compose(self):
yield MyInput()
def key_p(self):
self.query_one(MyInput).post_message(events.Paste(""))
app = PasteApp()
async with app.run_test() as pilot:
app.set_focus(None)
await pilot.press("p")
assert app.query_one(MyInput).value == ""
assert len(paste_events) == 1
assert paste_events[0].text == "" | Regression test for https://github.com/Textualize/textual/issues/2563. | test_empty_paste | python | Textualize/textual | tests/test_paste.py | https://github.com/Textualize/textual/blob/master/tests/test_paste.py | MIT |
async def test_no_tip_gets_no_tooltip() -> None:
"""If there is no tooltip, none should show."""
async with TooltipApp().run_test(tooltips=True) as pilot:
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.hover("#mr-pink")
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.pause(TOOLTIP_TIMEOUT)
assert pilot.app.query_one("#textual-tooltip").display is False | If there is no tooltip, none should show. | test_no_tip_gets_no_tooltip | python | Textualize/textual | tests/test_tooltips.py | https://github.com/Textualize/textual/blob/master/tests/test_tooltips.py | MIT |
async def test_tip_gets_a_tooltip() -> None:
"""If there is a tooltip, it should show."""
async with TooltipApp().run_test(tooltips=True) as pilot:
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.hover("#mr-blue")
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.pause(TOOLTIP_TIMEOUT)
assert pilot.app.query_one("#textual-tooltip").display is True | If there is a tooltip, it should show. | test_tip_gets_a_tooltip | python | Textualize/textual | tests/test_tooltips.py | https://github.com/Textualize/textual/blob/master/tests/test_tooltips.py | MIT |
async def test_mouse_move_removes_a_tooltip() -> None:
"""If there is a mouse move when there is a tooltip, it should disappear."""
async with TooltipApp().run_test(tooltips=True) as pilot:
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.hover("#mr-blue")
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.pause(TOOLTIP_TIMEOUT)
assert pilot.app.query_one("#textual-tooltip").display is True
await pilot.hover("#mr-pink")
await pilot.pause(TOOLTIP_TIMEOUT)
assert pilot.app.query_one("#textual-tooltip").display is False | If there is a mouse move when there is a tooltip, it should disappear. | test_mouse_move_removes_a_tooltip | python | Textualize/textual | tests/test_tooltips.py | https://github.com/Textualize/textual/blob/master/tests/test_tooltips.py | MIT |
async def test_removing_tipper_should_remove_tooltip() -> None:
"""If the tipping widget is removed, it should remove the tooltip."""
async with TooltipApp().run_test(tooltips=True) as pilot:
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.hover("#mr-blue")
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.pause(TOOLTIP_TIMEOUT)
assert pilot.app.query_one("#textual-tooltip").display is True
await pilot.app.query_one("#mr-blue").remove()
await pilot.pause()
assert pilot.app.query_one("#textual-tooltip").display is False | If the tipping widget is removed, it should remove the tooltip. | test_removing_tipper_should_remove_tooltip | python | Textualize/textual | tests/test_tooltips.py | https://github.com/Textualize/textual/blob/master/tests/test_tooltips.py | MIT |
async def test_making_tipper_invisible_should_remove_tooltip() -> None:
"""If the tipping widget is made invisible, it should remove the tooltip."""
async with TooltipApp().run_test(tooltips=True) as pilot:
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.hover("#mr-blue")
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.pause(TOOLTIP_TIMEOUT)
assert pilot.app.query_one("#textual-tooltip").display is True
pilot.app.query_one("#mr-blue").visible = False
await pilot.pause()
assert pilot.app.query_one("#textual-tooltip").display is False | If the tipping widget is made invisible, it should remove the tooltip. | test_making_tipper_invisible_should_remove_tooltip | python | Textualize/textual | tests/test_tooltips.py | https://github.com/Textualize/textual/blob/master/tests/test_tooltips.py | MIT |
async def test_making_tipper_not_displayed_should_remove_tooltip() -> None:
"""If the tipping widget is made display none, it should remove the tooltip."""
async with TooltipApp().run_test(tooltips=True) as pilot:
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.hover("#mr-blue")
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.pause(TOOLTIP_TIMEOUT)
assert pilot.app.query_one("#textual-tooltip").display is True
pilot.app.query_one("#mr-blue").display = False
await pilot.pause()
assert pilot.app.query_one("#textual-tooltip").display is False | If the tipping widget is made display none, it should remove the tooltip. | test_making_tipper_not_displayed_should_remove_tooltip | python | Textualize/textual | tests/test_tooltips.py | https://github.com/Textualize/textual/blob/master/tests/test_tooltips.py | MIT |
async def test_making_tipper_shuffle_away_should_remove_tooltip() -> None:
"""If the tipping widget moves from under the cursor, it should remove the tooltip."""
async with TooltipApp().run_test(tooltips=True) as pilot:
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.hover("#mr-blue")
assert pilot.app.query_one("#textual-tooltip").display is False
await pilot.pause(TOOLTIP_TIMEOUT)
assert pilot.app.query_one("#textual-tooltip").display is True
await pilot.app.mount(Static(id="mr-brown"), before="#mr-blue")
await pilot.pause()
assert pilot.app.query_one("#textual-tooltip").display is False | If the tipping widget moves from under the cursor, it should remove the tooltip. | test_making_tipper_shuffle_away_should_remove_tooltip | python | Textualize/textual | tests/test_tooltips.py | https://github.com/Textualize/textual/blob/master/tests/test_tooltips.py | MIT |
async def test_signal():
"""Test signal subscribe"""
called = 0
class TestLabel(Label):
def on_mount(self) -> None:
def signal_result(_):
nonlocal called
called += 1
assert isinstance(self.app, TestApp)
self.app.test_signal.subscribe(self, signal_result)
class TestApp(App):
BINDINGS = [("space", "signal")]
def __init__(self) -> None:
self.test_signal: Signal[str] = Signal(self, "coffee ready")
super().__init__()
def compose(self) -> ComposeResult:
yield TestLabel()
def action_signal(self) -> None:
self.test_signal.publish("foo")
app = TestApp()
async with app.run_test() as pilot:
# Check default called is 0
assert called == 0
# Action should publish signal
await pilot.press("space")
assert called == 1
# Check a second time
await pilot.press("space")
assert called == 2
# Removed the owner object
await app.query_one(TestLabel).remove()
# Check nothing is called
await pilot.press("space")
assert called == 2
# Add a new test label
await app.mount(TestLabel())
# Check callback again
await pilot.press("space")
assert called == 3
# Unsubscribe
app.test_signal.unsubscribe(app.query_one(TestLabel))
# Check nothing to update
await pilot.press("space")
assert called == 3 | Test signal subscribe | test_signal | python | Textualize/textual | tests/test_signal.py | https://github.com/Textualize/textual/blob/master/tests/test_signal.py | MIT |
def test_signal_errors():
"""Check exceptions raised by Signal class."""
app = App()
test_signal = Signal(app, "test")
label = Label()
# Check subscribing a non-running widget is an error
with pytest.raises(SignalError):
test_signal.subscribe(label, lambda _: None) | Check exceptions raised by Signal class. | test_signal_errors | python | Textualize/textual | tests/test_signal.py | https://github.com/Textualize/textual/blob/master/tests/test_signal.py | MIT |
def test_repr():
"""Check the repr doesn't break."""
app = App()
test_signal = Signal(app, "test")
assert isinstance(repr(test_signal), str) | Check the repr doesn't break. | test_repr | python | Textualize/textual | tests/test_signal.py | https://github.com/Textualize/textual/blob/master/tests/test_signal.py | MIT |
async def test_widget_construct():
"""Regression test for https://github.com/Textualize/textual/issues/5042"""
# Check that constructing the widget outside of the app, doesn't invoke code that
# expects an active app.
class MyApp(App):
def __init__(self) -> None:
super().__init__()
self.button = Button()
self.data_table = DataTable()
self.footer = Footer()
self.header = Header()
self.input = Input()
self.label = Label()
self.loading_indicator = LoadingIndicator()
self.log_ = Log()
self.option_list = OptionList()
self.rich_log = RichLog()
self.switch = Switch()
self.text_area = TextArea(language="python")
app = MyApp()
async with app.run_test():
pass | Regression test for https://github.com/Textualize/textual/issues/5042 | test_widget_construct | python | Textualize/textual | tests/test_widget.py | https://github.com/Textualize/textual/blob/master/tests/test_widget.py | MIT |
async def test_loading():
"""Test setting the loading reactive."""
class LoadingApp(App):
def compose(self) -> ComposeResult:
yield Label("Hello, World")
async with LoadingApp().run_test() as pilot:
app = pilot.app
label = app.query_one(Label)
assert label.loading == False
assert label._cover_widget is None
label.loading = True
await pilot.pause()
assert label._cover_widget is not None
label.loading = True # Setting to same value is a null-op
await pilot.pause()
assert label._cover_widget is not None
label.loading = False
await pilot.pause()
assert label._cover_widget is None
label.loading = False # Setting to same value is a null-op
await pilot.pause()
assert label._cover_widget is None | Test setting the loading reactive. | test_loading | python | Textualize/textual | tests/test_widget.py | https://github.com/Textualize/textual/blob/master/tests/test_widget.py | MIT |
async def test_loading_button():
"""Test loading indicator renders buttons unclickable."""
counter = 0
class LoadingApp(App):
def compose(self) -> ComposeResult:
yield Button("Hello, World", action="app.inc")
def action_inc(self) -> None:
nonlocal counter
counter += 1
async with LoadingApp().run_test() as pilot:
# Sanity check
assert counter == 0
button = pilot.app.query_one(Button)
button.active_effect_duration = 0
# Click the button to advance the counter
await pilot.click(button)
assert counter == 1
# Set the button to loading state
button.loading = True
# A click should do nothing
await pilot.click(button)
assert counter == 1
# Set the button to not loading
button.loading = False
# Click should advance counter
await pilot.click(button)
assert counter == 2 | Test loading indicator renders buttons unclickable. | test_loading_button | python | Textualize/textual | tests/test_widget.py | https://github.com/Textualize/textual/blob/master/tests/test_widget.py | MIT |
async def test_render_returns_text():
"""Test that render processes console markup when returning a string."""
# Regression test for https://github.com/Textualize/textual/issues/3918
class SimpleWidget(Widget):
def render(self) -> str:
return "Hello [b]World[/b]!"
widget = SimpleWidget()
render_result = widget._render()
assert isinstance(render_result, Content)
assert render_result.plain == "Hello World!" | Test that render processes console markup when returning a string. | test_render_returns_text | python | Textualize/textual | tests/test_widget.py | https://github.com/Textualize/textual/blob/master/tests/test_widget.py | MIT |
async def test_sort_children() -> None:
"""Test the sort_children method."""
class SortApp(App):
def compose(self) -> ComposeResult:
with Container(id="container"):
yield Label("three", id="l3")
yield Label("one", id="l1")
yield Label("four", id="l4")
yield Label("two", id="l2")
app = SortApp()
async with app.run_test():
container = app.query_one("#container", Container)
assert [label.id for label in container.query(Label)] == [
"l3",
"l1",
"l4",
"l2",
]
container.sort_children(key=attrgetter("id"))
assert [label.id for label in container.query(Label)] == [
"l1",
"l2",
"l3",
"l4",
]
container.sort_children(key=attrgetter("id"), reverse=True)
assert [label.id for label in container.query(Label)] == [
"l4",
"l3",
"l2",
"l1",
] | Test the sort_children method. | test_sort_children | python | Textualize/textual | tests/test_widget.py | https://github.com/Textualize/textual/blob/master/tests/test_widget.py | MIT |
async def test_sort_children_no_key() -> None:
"""Test sorting with no key."""
class SortApp(App):
def compose(self) -> ComposeResult:
with Container(id="container"):
yield Label("three", id="l3")
yield Label("one", id="l1")
yield Label("four", id="l4")
yield Label("two", id="l2")
app = SortApp()
async with app.run_test():
container = app.query_one("#container", Container)
assert [label.id for label in container.query(Label)] == [
"l3",
"l1",
"l4",
"l2",
]
# Without a key, the sort order is the order children were instantiated
container.sort_children()
assert [label.id for label in container.query(Label)] == [
"l3",
"l1",
"l4",
"l2",
]
container.sort_children(reverse=True)
assert [label.id for label in container.query(Label)] == [
"l2",
"l4",
"l1",
"l3",
] | Test sorting with no key. | test_sort_children_no_key | python | Textualize/textual | tests/test_widget.py | https://github.com/Textualize/textual/blob/master/tests/test_widget.py | MIT |
def test_bad_widget_name_raised() -> None:
"""Ensure error is raised when bad class names are used for widgets."""
with pytest.raises(BadWidgetName):
class lowercaseWidget(Widget):
pass | Ensure error is raised when bad class names are used for widgets. | test_bad_widget_name_raised | python | Textualize/textual | tests/test_widget.py | https://github.com/Textualize/textual/blob/master/tests/test_widget.py | MIT |
def test_lazy_loading() -> None:
"""Regression test for https://github.com/Textualize/textual/issues/5077
Check that the lazy loading magic doesn't break attribute access.
"""
with pytest.raises(ImportError):
from textual.widgets import Foo # nopycln: import
from textual import widgets
from textual.widgets import Label
assert not hasattr(widgets, "foo")
assert not hasattr(widgets, "bar")
assert hasattr(widgets, "Label") | Regression test for https://github.com/Textualize/textual/issues/5077
Check that the lazy loading magic doesn't break attribute access. | test_lazy_loading | python | Textualize/textual | tests/test_widget.py | https://github.com/Textualize/textual/blob/master/tests/test_widget.py | MIT |
async def test_click_line_api_border():
"""Regression test for https://github.com/Textualize/textual/issues/5634"""
class MyApp(App):
def compose(self) -> ComposeResult:
self.my_log = Log()
self.my_log.styles.border = ("round", "white")
yield self.my_log
app = MyApp()
async with app.run_test() as pilot:
await pilot.pause()
await pilot.click("Log", (10, 0)) | Regression test for https://github.com/Textualize/textual/issues/5634 | test_click_line_api_border | python | Textualize/textual | tests/test_widget.py | https://github.com/Textualize/textual/blob/master/tests/test_widget.py | MIT |
async def test_pilot_press_ascii_chars():
"""Test that the pilot can press most ASCII characters as keys."""
keys_pressed = []
class TestApp(App[None]):
def on_key(self, event: events.Key) -> None:
keys_pressed.append(event.character)
async with TestApp().run_test() as pilot:
for char in KEY_CHARACTERS_TO_TEST:
await pilot.press(char)
assert keys_pressed[-1] == char | Test that the pilot can press most ASCII characters as keys. | test_pilot_press_ascii_chars | python | Textualize/textual | tests/test_pilot.py | https://github.com/Textualize/textual/blob/master/tests/test_pilot.py | MIT |
async def test_pilot_exception_catching_app_compose():
"""Ensuring that test frameworks are aware of exceptions
inside compose methods when running via Pilot run_test()."""
class FailingApp(App):
def compose(self) -> ComposeResult:
1 / 0
yield Label("Beep")
with pytest.raises(ZeroDivisionError):
async with FailingApp().run_test():
pass | Ensuring that test frameworks are aware of exceptions
inside compose methods when running via Pilot run_test(). | test_pilot_exception_catching_app_compose | python | Textualize/textual | tests/test_pilot.py | https://github.com/Textualize/textual/blob/master/tests/test_pilot.py | MIT |
async def test_pilot_exception_catching_action():
"""Ensure that exceptions inside action handlers are presented
to the test framework when running via Pilot run_test()."""
class FailingApp(App):
BINDINGS = [Binding("b", "beep", "beep")]
def action_beep(self) -> None:
1 / 0
with pytest.raises(ZeroDivisionError):
async with FailingApp().run_test() as pilot:
await pilot.press("b") | Ensure that exceptions inside action handlers are presented
to the test framework when running via Pilot run_test(). | test_pilot_exception_catching_action | python | Textualize/textual | tests/test_pilot.py | https://github.com/Textualize/textual/blob/master/tests/test_pilot.py | MIT |
async def test_pilot_click_screen():
"""Regression test for https://github.com/Textualize/textual/issues/3395.
Check we can use `Screen` as a selector for a click."""
async with App().run_test() as pilot:
await pilot.click("Screen") | Regression test for https://github.com/Textualize/textual/issues/3395.
Check we can use `Screen` as a selector for a click. | test_pilot_click_screen | python | Textualize/textual | tests/test_pilot.py | https://github.com/Textualize/textual/blob/master/tests/test_pilot.py | MIT |
async def test_pilot_hover_screen():
"""Regression test for https://github.com/Textualize/textual/issues/3395.
Check we can use `Screen` as a selector for a hover."""
async with App().run_test() as pilot:
await pilot.hover("Screen") | Regression test for https://github.com/Textualize/textual/issues/3395.
Check we can use `Screen` as a selector for a hover. | test_pilot_hover_screen | python | Textualize/textual | tests/test_pilot.py | https://github.com/Textualize/textual/blob/master/tests/test_pilot.py | MIT |
async def test_pilot_target_outside_screen_errors(method, screen_size, offset):
"""Make sure that targeting a click/hover completely outside of the screen errors."""
app = App()
async with app.run_test(size=screen_size) as pilot:
pilot_method = getattr(pilot, method)
with pytest.raises(OutOfBounds):
await pilot_method(offset=offset) | Make sure that targeting a click/hover completely outside of the screen errors. | test_pilot_target_outside_screen_errors | python | Textualize/textual | tests/test_pilot.py | https://github.com/Textualize/textual/blob/master/tests/test_pilot.py | MIT |
async def test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system(
method, offset
):
"""Make sure that the coordinate system for the click is the correct one.
Especially relevant because I kept getting confused about the way it works.
"""
app = ManyLabelsApp()
async with app.run_test(size=(80, 24)) as pilot:
app.query_one("#label99").scroll_visible(animate=False)
await pilot.pause()
pilot_method = getattr(pilot, method)
await pilot_method(offset=offset) | Make sure that the coordinate system for the click is the correct one.
Especially relevant because I kept getting confused about the way it works. | test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system | python | Textualize/textual | tests/test_pilot.py | https://github.com/Textualize/textual/blob/master/tests/test_pilot.py | MIT |
async def test_pilot_target_on_widget_that_is_not_visible_errors(method, target):
"""Make sure that clicking a widget that is not scrolled into view raises an error."""
app = ManyLabelsApp()
async with app.run_test(size=(80, 5)) as pilot:
app.query_one("#label50").scroll_visible(animate=False)
await pilot.pause()
pilot_method = getattr(pilot, method)
with pytest.raises(OutOfBounds):
await pilot_method(target) | Make sure that clicking a widget that is not scrolled into view raises an error. | test_pilot_target_on_widget_that_is_not_visible_errors | python | Textualize/textual | tests/test_pilot.py | https://github.com/Textualize/textual/blob/master/tests/test_pilot.py | MIT |
async def test_pilot_target_widget_under_another_widget(method):
"""The targeting method should return False when the targeted widget is covered."""
class ObscuredButton(App):
CSS = """
Label {
width: 30;
height: 5;
}
"""
def compose(self):
yield Button()
yield Label()
def on_mount(self):
self.query_one(Label).styles.offset = (0, -3)
app = ObscuredButton()
async with app.run_test() as pilot:
await pilot.pause()
pilot_method = getattr(pilot, method)
assert (await pilot_method(Button)) is False | The targeting method should return False when the targeted widget is covered. | test_pilot_target_widget_under_another_widget | python | Textualize/textual | tests/test_pilot.py | https://github.com/Textualize/textual/blob/master/tests/test_pilot.py | MIT |
async def test_pilot_target_visible_widget(method):
"""The targeting method should return True when the targeted widget is hit."""
class ObscuredButton(App):
def compose(self):
yield Button()
app = ObscuredButton()
async with app.run_test() as pilot:
await pilot.pause()
pilot_method = getattr(pilot, method)
assert (await pilot_method(Button)) is True | The targeting method should return True when the targeted widget is hit. | test_pilot_target_visible_widget | python | Textualize/textual | tests/test_pilot.py | https://github.com/Textualize/textual/blob/master/tests/test_pilot.py | MIT |
async def test_click_by_widget():
"""Test that click accept a Widget instance."""
pressed = False
class TestApp(CenteredButtonApp):
def on_button_pressed(self):
nonlocal pressed
pressed = True
app = TestApp()
async with app.run_test() as pilot:
button = app.query_one(Button)
assert not pressed
await pilot.click(button)
assert pressed | Test that click accept a Widget instance. | test_click_by_widget | python | Textualize/textual | tests/test_pilot.py | https://github.com/Textualize/textual/blob/master/tests/test_pilot.py | MIT |
async def test_click_times(times: int):
"""Test that Pilot.click() can be called with a `times` argument."""
events_received: list[Type[events.Event]] = []
class TestApp(App[None]):
def compose(self) -> ComposeResult:
yield Label("Click counter")
@on(events.Click)
@on(events.MouseDown)
@on(events.MouseUp)
def on_label_clicked(self, event: events.Event):
events_received.append(event.__class__)
app = TestApp()
async with app.run_test() as pilot:
await pilot.click(Label, times=times)
assert (
events_received == [events.MouseDown, events.MouseUp, events.Click] * times
) | Test that Pilot.click() can be called with a `times` argument. | test_click_times | python | Textualize/textual | tests/test_pilot.py | https://github.com/Textualize/textual/blob/master/tests/test_pilot.py | MIT |
async def test_dynamic_disabled():
"""Check we can dynamically disable bindings."""
actions = []
class DynamicApp(App):
BINDINGS = [
("a", "register('a')", "A"),
("b", "register('b')", "B"),
("c", "register('c')", "B"),
]
def action_register(self, key: str) -> None:
actions.append(key)
def check_action(
self, action: str, parameters: tuple[object, ...]
) -> bool | None:
if action == "register":
if parameters == ("b",):
return False
if parameters == ("c",):
return None
return True
app = DynamicApp()
async with app.run_test() as pilot:
await pilot.press("a", "b", "c")
assert actions == ["a"] | Check we can dynamically disable bindings. | test_dynamic_disabled | python | Textualize/textual | tests/test_dynamic_bindings.py | https://github.com/Textualize/textual/blob/master/tests/test_dynamic_bindings.py | MIT |
async def test_dispatch_key_valid_key_alias():
"""When you press tab or ctrl+i, it comes through as a tab key event, but handlers for
tab and ctrl+i are both considered valid."""
widget = ValidWidget()
result = await dispatch_key(widget, Key(key="tab", character="\t"))
assert result is True
assert widget.called_by == widget.key_ctrl_i | When you press tab or ctrl+i, it comes through as a tab key event, but handlers for
tab and ctrl+i are both considered valid. | test_dispatch_key_valid_key_alias | python | Textualize/textual | tests/test_message_pump.py | https://github.com/Textualize/textual/blob/master/tests/test_message_pump.py | MIT |
async def test_dispatch_key_raises_when_conflicting_handler_aliases():
"""If you've got a handler for e.g. ctrl+i and a handler for tab, that's probably a mistake.
In the terminal, they're the same thing, so we fail fast via exception here."""
widget = DuplicateHandlersWidget()
with pytest.raises(DuplicateKeyHandlers):
await dispatch_key(widget, Key(key="tab", character="\t"))
assert widget.called_by == widget.key_tab | If you've got a handler for e.g. ctrl+i and a handler for tab, that's probably a mistake.
In the terminal, they're the same thing, so we fail fast via exception here. | test_dispatch_key_raises_when_conflicting_handler_aliases | python | Textualize/textual | tests/test_message_pump.py | https://github.com/Textualize/textual/blob/master/tests/test_message_pump.py | MIT |
async def test_message_queue_size():
"""Test message queue size property."""
app = App()
assert app.message_queue_size == 0
class TestMessage(Message):
pass
async with app.run_test() as pilot:
assert app.message_queue_size == 0
app.post_message(TestMessage())
assert app.message_queue_size == 1
app.post_message(TestMessage())
assert app.message_queue_size == 2
# A pause will process all the messages
await pilot.pause()
assert app.message_queue_size == 0 | Test message queue size property. | test_message_queue_size | python | Textualize/textual | tests/test_message_pump.py | https://github.com/Textualize/textual/blob/master/tests/test_message_pump.py | MIT |
async def test_prevent_with_call_next() -> None:
"""Test for https://github.com/Textualize/textual/issues/3166.
Does a callback scheduled with `call_next` respect messages that
were prevented when it was scheduled?
"""
hits = 0
class PreventTestApp(App[None]):
def compose(self) -> ComposeResult:
yield Input()
def change_input(self) -> None:
self.query_one(Input).value += "a"
def on_input_changed(self) -> None:
nonlocal hits
hits += 1
app = PreventTestApp()
async with app.run_test() as pilot:
app.call_next(app.change_input)
await pilot.pause()
assert hits == 1
with app.prevent(Input.Changed):
app.call_next(app.change_input)
await pilot.pause()
assert hits == 1
app.call_next(app.change_input)
await pilot.pause()
assert hits == 2 | Test for https://github.com/Textualize/textual/issues/3166.
Does a callback scheduled with `call_next` respect messages that
were prevented when it was scheduled? | test_prevent_with_call_next | python | Textualize/textual | tests/test_message_pump.py | https://github.com/Textualize/textual/blob/master/tests/test_message_pump.py | MIT |
async def test_prevent_default():
"""Test that prevent_default doesn't apply when a message is bubbled."""
app_button_pressed = False
class MyButton(Button):
def _on_button_pressed(self, event: Button.Pressed) -> None:
event.prevent_default()
class PreventApp(App[None]):
def compose(self) -> ComposeResult:
yield MyButton("Press me")
yield Label("No pressure")
def on_button_pressed(self, event: Button.Pressed) -> None:
nonlocal app_button_pressed
app_button_pressed = True
self.query_one(Label).update("Ouch!")
app = PreventApp()
async with app.run_test() as pilot:
await pilot.click(MyButton)
assert app_button_pressed | Test that prevent_default doesn't apply when a message is bubbled. | test_prevent_default | python | Textualize/textual | tests/test_message_pump.py | https://github.com/Textualize/textual/blob/master/tests/test_message_pump.py | MIT |
async def test_multiple_simultaneous_removals():
"""Regression test for https://github.com/Textualize/textual/issues/2854."""
# The app should run and finish without raising any errors.
async with RemoveOnTimerApp().run_test() as pilot:
# Sanity check to ensure labels were removed.
assert len(pilot.app.query(Label)) == 0 | Regression test for https://github.com/Textualize/textual/issues/2854. | test_multiple_simultaneous_removals | python | Textualize/textual | tests/test_await_remove.py | https://github.com/Textualize/textual/blob/master/tests/test_await_remove.py | MIT |
def test_width():
"""Test width settings."""
one = Fraction(1)
class TestWidget(Widget):
def get_content_width(self, container: Size, parent: Size) -> int:
return 10
def get_content_height(self, container: Size, parent: Size, width: int) -> int:
return 10
widget = TestWidget()
styles = widget.styles
box_model = widget._get_box_model(Size(60, 20), Size(80, 24), one, one)
assert box_model == BoxModel(Fraction(60), Fraction(20), Spacing(0, 0, 0, 0))
# Add a margin and check that it is reported
styles.margin = (1, 2, 3, 4)
box_model = widget._get_box_model(Size(60, 20), Size(80, 24), one, one)
assert box_model == BoxModel(Fraction(54), Fraction(16), Spacing(1, 2, 3, 4))
# Set width to auto-detect
styles.width = "auto"
box_model = widget._get_box_model(Size(60, 20), Size(80, 24), one, one)
# Setting width to auto should call get_auto_width
assert box_model == BoxModel(Fraction(10), Fraction(16), Spacing(1, 2, 3, 4))
# Set width to 100 vw which should make it the width of the parent
styles.width = "100vw"
box_model = widget._get_box_model(Size(60, 20), Size(80, 24), one, one)
assert box_model == BoxModel(Fraction(80), Fraction(16), Spacing(1, 2, 3, 4))
# Set the width to 100% should make it fill the container size
styles.width = "100%"
box_model = widget._get_box_model(Size(60, 20), Size(80, 24), one, one)
assert box_model == BoxModel(Fraction(54), Fraction(16), Spacing(1, 2, 3, 4))
styles.width = "100vw"
styles.max_width = "50%"
box_model = widget._get_box_model(Size(60, 20), Size(80, 24), one, one)
assert box_model == BoxModel(Fraction(27), Fraction(16), Spacing(1, 2, 3, 4)) | Test width settings. | test_width | python | Textualize/textual | tests/test_box_model.py | https://github.com/Textualize/textual/blob/master/tests/test_box_model.py | MIT |
def test_height():
"""Test height settings."""
one = Fraction(1)
class TestWidget(Widget):
def get_content_width(self, container: Size, parent: Size) -> int:
return 10
def get_content_height(self, container: Size, parent: Size, width: int) -> int:
return 10
widget = TestWidget()
styles = widget.styles
box_model = widget._get_box_model(Size(60, 20), Size(80, 24), one, one)
assert box_model == BoxModel(Fraction(60), Fraction(20), Spacing(0, 0, 0, 0))
# Add a margin and check that it is reported
styles.margin = (1, 2, 3, 4)
box_model = widget._get_box_model(Size(60, 20), Size(80, 24), one, one)
assert box_model == BoxModel(Fraction(54), Fraction(16), Spacing(1, 2, 3, 4))
# Set height to 100 vw which should make it the height of the parent
styles.height = "100vh"
box_model = widget._get_box_model(Size(60, 20), Size(80, 24), one, one)
assert box_model == BoxModel(Fraction(54), Fraction(24), Spacing(1, 2, 3, 4))
# Set the height to 100% should make it fill the container size
styles.height = "100%"
box_model = widget._get_box_model(Size(60, 20), Size(80, 24), one, one)
assert box_model == BoxModel(Fraction(54), Fraction(16), Spacing(1, 2, 3, 4))
styles.height = "auto"
styles.margin = 2
box_model = widget._get_box_model(Size(60, 20), Size(80, 24), one, one)
print(box_model)
assert box_model == BoxModel(Fraction(56), Fraction(10), Spacing(2, 2, 2, 2))
styles.margin = 1, 2, 3, 4
styles.height = "100vh"
styles.max_height = "50%"
box_model = widget._get_box_model(Size(60, 20), Size(80, 24), one, one)
assert box_model == BoxModel(Fraction(54), Fraction(8), Spacing(1, 2, 3, 4)) | Test height settings. | test_height | python | Textualize/textual | tests/test_box_model.py | https://github.com/Textualize/textual/blob/master/tests/test_box_model.py | MIT |
def test_max():
"""Check that max_width and max_height are respected."""
one = Fraction(1)
class TestWidget(Widget):
def get_content_width(self, container: Size, parent: Size) -> int:
assert False, "must not be called"
def get_content_height(self, container: Size, parent: Size, width: int) -> int:
assert False, "must not be called"
widget = TestWidget()
styles = widget.styles
styles.width = 100
styles.height = 80
styles.max_width = 40
styles.max_height = 30
box_model = widget._get_box_model(Size(40, 30), Size(80, 24), one, one)
assert box_model == BoxModel(Fraction(40), Fraction(30), Spacing(0, 0, 0, 0)) | Check that max_width and max_height are respected. | test_max | python | Textualize/textual | tests/test_box_model.py | https://github.com/Textualize/textual/blob/master/tests/test_box_model.py | MIT |
def test_min():
"""Check that min_width and min_height are respected."""
one = Fraction(1)
class TestWidget(Widget):
def get_content_width(self, container: Size, parent: Size) -> int:
assert False, "must not be called"
def get_content_height(self, container: Size, parent: Size, width: int) -> int:
assert False, "must not be called"
widget = TestWidget()
styles = widget.styles
styles.width = 10
styles.height = 5
styles.min_width = 40
styles.min_height = 30
box_model = widget._get_box_model(Size(40, 30), Size(80, 24), one, one)
assert box_model == BoxModel(Fraction(40), Fraction(30), Spacing(0, 0, 0, 0)) | Check that min_width and min_height are respected. | test_min | python | Textualize/textual | tests/test_box_model.py | https://github.com/Textualize/textual/blob/master/tests/test_box_model.py | MIT |
async def test_message_inheritance_namespace():
"""Inherited messages get their correct namespaces.
Regression test for https://github.com/Textualize/textual/issues/1814.
"""
class BaseWidget(Widget):
class Fired(Message):
pass
def trigger(self) -> None:
self.post_message(self.Fired())
class Left(BaseWidget):
class Fired(BaseWidget.Fired):
pass
class Right(BaseWidget):
class Fired(BaseWidget.Fired):
pass
class DummyWidget(Widget):
# ensure that referencing a message type in other class scopes
# doesn't break the namespace
_event = Left.Fired
handlers_called = []
class MessageInheritanceApp(App[None]):
def compose(self) -> ComposeResult:
yield Left()
yield Right()
def on_left_fired(self):
handlers_called.append("left")
def on_right_fired(self):
handlers_called.append("right")
app = MessageInheritanceApp()
async with app.run_test():
app.query_one(Left).trigger()
app.query_one(Right).trigger()
assert handlers_called == ["left", "right"] | Inherited messages get their correct namespaces.
Regression test for https://github.com/Textualize/textual/issues/1814. | test_message_inheritance_namespace | python | Textualize/textual | tests/test_message_handling.py | https://github.com/Textualize/textual/blob/master/tests/test_message_handling.py | MIT |
async def test_mount_via_app() -> None:
"""Perform mount tests via the app."""
# Make a background set of widgets.
widgets = [Static(id=f"starter-{n}") for n in range(10)]
async with App[None]().run_test() as pilot:
with pytest.raises(WidgetError):
await pilot.app.mount(SelfOwn())
async with App().run_test() as pilot:
# Mount the first one and make sure it's there.
await pilot.app.mount(widgets[0])
assert len(pilot.app.screen._nodes) == 1
assert pilot.app.screen._nodes[0] == widgets[0]
# Mount the next 2 widgets via mount.
await pilot.app.mount(*widgets[1:3])
assert list(pilot.app.screen._nodes) == widgets[0:3]
# Finally mount the rest of the widgets via mount_all.
await pilot.app.mount_all(widgets[3:])
assert list(pilot.app.screen._nodes) == widgets
async with App().run_test() as pilot:
# Mount a widget before -1, which is "before the end".
penultimate = Static(id="penultimate")
await pilot.app.mount_all(widgets)
await pilot.app.mount(penultimate, before=-1)
assert pilot.app.screen._nodes[-2] == penultimate
async with App().run_test() as pilot:
# Mount a widget after -1, which is "at the end".
ultimate = Static(id="ultimate")
await pilot.app.mount_all(widgets)
await pilot.app.mount(ultimate, after=-1)
assert pilot.app.screen._nodes[-1] == ultimate
async with App().run_test() as pilot:
# Mount a widget before -2, which is "before the penultimate".
penpenultimate = Static(id="penpenultimate")
await pilot.app.mount_all(widgets)
await pilot.app.mount(penpenultimate, before=-2)
assert pilot.app.screen._nodes[-3] == penpenultimate
async with App().run_test() as pilot:
# Mount a widget after -2, which is "before the end".
penultimate = Static(id="penultimate")
await pilot.app.mount_all(widgets)
await pilot.app.mount(penultimate, after=-2)
assert pilot.app.screen._nodes[-2] == penultimate
async with App().run_test() as pilot:
# Mount a widget before 0, which is "at the start".
start = Static(id="start")
await pilot.app.mount_all(widgets)
await pilot.app.mount(start, before=0)
assert pilot.app.screen._nodes[0] == start
async with App().run_test() as pilot:
# Mount a widget after 0. You get the idea...
second = Static(id="second")
await pilot.app.mount_all(widgets)
await pilot.app.mount(second, after=0)
assert pilot.app.screen._nodes[1] == second
async with App().run_test() as pilot:
# Mount a widget relative to another via query.
queue_jumper = Static(id="queue-jumper")
await pilot.app.mount_all(widgets)
await pilot.app.mount(queue_jumper, after="#starter-5")
assert pilot.app.screen._nodes[6] == queue_jumper
async with App().run_test() as pilot:
# Mount a widget relative to another via query.
queue_jumper = Static(id="queue-jumper")
await pilot.app.mount_all(widgets)
await pilot.app.mount(queue_jumper, after=widgets[5])
assert pilot.app.screen._nodes[6] == queue_jumper
async with App().run_test() as pilot:
# Make sure we get told off for trying to before and after.
await pilot.app.mount_all(widgets)
with pytest.raises(MountError):
await pilot.app.mount(Static(), before=2, after=2)
async with App().run_test() as pilot:
# Make sure we get told off trying to mount relative to something
# that isn't actually in the DOM.
await pilot.app.mount_all(widgets)
with pytest.raises(MountError):
await pilot.app.mount(Static(), before=Static())
with pytest.raises(MountError):
await pilot.app.mount(Static(), after=Static())
async with App().run_test() as pilot:
# Make sure we get an error if we try and mount with a selector that
# results in more than one hit.
await pilot.app.mount_all(widgets)
with pytest.raises(TooManyMatches):
await pilot.app.mount(Static(), before="Static") | Perform mount tests via the app. | test_mount_via_app | python | Textualize/textual | tests/test_widget_mounting.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_mounting.py | MIT |
async def test_mount_error() -> None:
"""Mounting a widget on an un-mounted widget should raise an error."""
app = App()
async with app.run_test():
with pytest.raises(MountError):
widget = Widget()
widget.mount(Static()) | Mounting a widget on an un-mounted widget should raise an error. | test_mount_error | python | Textualize/textual | tests/test_widget_mounting.py | https://github.com/Textualize/textual/blob/master/tests/test_widget_mounting.py | MIT |
def test_lru_cache_mapping():
"""Test cache values can be set and read back."""
cache = LRUCache(3)
cache["foo"] = 1
cache.set("bar", 2)
cache.set("baz", 3)
assert cache["foo"] == 1
assert cache["bar"] == 2
assert cache.get("baz") == 3 | Test cache values can be set and read back. | test_lru_cache_mapping | python | Textualize/textual | tests/test_cache.py | https://github.com/Textualize/textual/blob/master/tests/test_cache.py | MIT |
def test_lru_cache_evicts(keys: list[str], expected: list[str]):
"""Test adding adding additional values evicts oldest key"""
cache = LRUCache(3)
for value, key in enumerate(keys):
cache[key] = value
assert tuple(cache.keys()) == expected | Test adding adding additional values evicts oldest key | test_lru_cache_evicts | python | Textualize/textual | tests/test_cache.py | https://github.com/Textualize/textual/blob/master/tests/test_cache.py | MIT |
def test_lru_cache_len(keys: list[str], expected_len: int):
"""Test adding adding additional values evicts oldest key"""
cache = LRUCache(3)
for value, key in enumerate(keys):
cache[key] = value
assert len(cache) == expected_len | Test adding adding additional values evicts oldest key | test_lru_cache_len | python | Textualize/textual | tests/test_cache.py | https://github.com/Textualize/textual/blob/master/tests/test_cache.py | MIT |
def test_discard_regression():
"""Regression test for https://github.com/Textualize/textual/issues/3537"""
cache = LRUCache(maxsize=3)
cache[1] = "foo"
cache[2] = "bar"
cache[3] = "baz"
cache[4] = "egg"
assert cache.keys() == {2, 3, 4}
cache.discard(2)
assert cache.keys() == {3, 4}
cache[5] = "bob"
assert cache.keys() == {3, 4, 5}
cache.discard(5)
assert cache.keys() == {3, 4}
cache.discard(4)
cache.discard(3)
assert cache.keys() == set() | Regression test for https://github.com/Textualize/textual/issues/3537 | test_discard_regression | python | Textualize/textual | tests/test_cache.py | https://github.com/Textualize/textual/blob/master/tests/test_cache.py | MIT |
def check_quit(quit: bool | None) -> None:
"""Called when QuitScreen is dismissed."""
if quit:
self.exit() | Called when QuitScreen is dismissed. | action_request_quit.check_quit | python | Textualize/textual | tests/test_modal.py | https://github.com/Textualize/textual/blob/master/tests/test_modal.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."""
if quit:
self.exit()
self.push_screen(QuitScreen(), check_quit) | Action to display the quit dialog. | action_request_quit | python | Textualize/textual | tests/test_modal.py | https://github.com/Textualize/textual/blob/master/tests/test_modal.py | MIT |
def wrap(source: Sequence[int]) -> ImmutableSequenceView[int]:
"""Wrap a sequence of integers inside an immutable sequence view."""
return ImmutableSequenceView[int](source) | Wrap a sequence of integers inside an immutable sequence view. | wrap | python | Textualize/textual | tests/test_immutable_sequence_view.py | https://github.com/Textualize/textual/blob/master/tests/test_immutable_sequence_view.py | MIT |
def test_empty_immutable_sequence() -> None:
"""An empty immutable sequence should act as anticipated."""
assert len(wrap([])) == 0
assert bool(wrap([])) is False
assert list(wrap([])) == [] | An empty immutable sequence should act as anticipated. | test_empty_immutable_sequence | python | Textualize/textual | tests/test_immutable_sequence_view.py | https://github.com/Textualize/textual/blob/master/tests/test_immutable_sequence_view.py | MIT |
def test_non_empty_immutable_sequence() -> None:
"""A non-empty immutable sequence should act as anticipated."""
assert len(wrap([0])) == 1
assert bool(wrap([0])) is True
assert list(wrap([0])) == [0] | A non-empty immutable sequence should act as anticipated. | test_non_empty_immutable_sequence | python | Textualize/textual | tests/test_immutable_sequence_view.py | https://github.com/Textualize/textual/blob/master/tests/test_immutable_sequence_view.py | MIT |
def test_no_assign_to_immutable_sequence() -> None:
"""It should not be possible to assign into an immutable sequence."""
tester = wrap([1, 2, 3, 4, 5])
with pytest.raises(TypeError):
tester[0] = 23
with pytest.raises(TypeError):
tester[0:3] = 23 | It should not be possible to assign into an immutable sequence. | test_no_assign_to_immutable_sequence | python | Textualize/textual | tests/test_immutable_sequence_view.py | https://github.com/Textualize/textual/blob/master/tests/test_immutable_sequence_view.py | MIT |
def test_no_del_from_iummutable_sequence() -> None:
"""It should not be possible delete an item from an immutable sequence."""
tester = wrap([1, 2, 3, 4, 5])
with pytest.raises(TypeError):
del tester[0] | It should not be possible delete an item from an immutable sequence. | test_no_del_from_iummutable_sequence | python | Textualize/textual | tests/test_immutable_sequence_view.py | https://github.com/Textualize/textual/blob/master/tests/test_immutable_sequence_view.py | MIT |
def test_get_item_from_immutable_sequence() -> None:
"""It should be possible to get an item from an immutable sequence."""
assert wrap(range(10))[0] == 0
assert wrap(range(10))[-1] == 9 | It should be possible to get an item from an immutable sequence. | test_get_item_from_immutable_sequence | python | Textualize/textual | tests/test_immutable_sequence_view.py | https://github.com/Textualize/textual/blob/master/tests/test_immutable_sequence_view.py | MIT |
def test_get_slice_from_immutable_sequence() -> None:
"""It should be possible to get a slice from an immutable sequence."""
assert list(wrap(range(10))[0:2]) == [0, 1]
assert list(wrap(range(10))[0:-1]) == [0, 1, 2, 3, 4, 5, 6, 7, 8] | It should be possible to get a slice from an immutable sequence. | test_get_slice_from_immutable_sequence | python | Textualize/textual | tests/test_immutable_sequence_view.py | https://github.com/Textualize/textual/blob/master/tests/test_immutable_sequence_view.py | MIT |
def test_immutable_sequence_contains() -> None:
"""It should be possible to see if an immutable sequence contains a value."""
tester = wrap([1, 2, 3, 4, 5])
assert 1 in tester
assert 11 not in tester | It should be possible to see if an immutable sequence contains a value. | test_immutable_sequence_contains | python | Textualize/textual | tests/test_immutable_sequence_view.py | https://github.com/Textualize/textual/blob/master/tests/test_immutable_sequence_view.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.