response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
A single  should be interpreted as a single press of the Escape key
def test_single_escape(parser): """A single \x1b should be interpreted as a single press of the Escape key""" events = parser.feed("\x1b") assert [event.key for event in events] == ["escape"]
Windows Terminal writes double ESC when the user presses the Escape key once.
def test_double_escape(parser): """Windows Terminal writes double ESC when the user presses the Escape key once.""" events = parser.feed("\x1b\x1b") assert [event.key for event in events] == ["escape"]
ANSI codes for mouse should be converted to Textual events
def test_mouse_click(parser, sequence, event_type, shift, meta): """ANSI codes for mouse should be converted to Textual events""" events = list(parser.feed(sequence)) assert len(events) == 1 event = events[0] assert isinstance(event, event_type) assert event.x == 49 assert event.y == 24 assert event.screen_x == 49 assert event.screen_y == 24 assert event.meta is meta assert event.shift is shift
Scrolling the mouse with and without modifiers held down. We don't currently capture modifier keys in scroll events.
def test_mouse_scroll_up(parser, sequence, shift, meta): """Scrolling the mouse with and without modifiers held down. We don't currently capture modifier keys in scroll events. """ events = list(parser.feed(sequence)) assert len(events) == 1 event = events[0] assert isinstance(event, MouseScrollUp) assert event.x == 17 assert event.y == 24 assert event.shift is shift assert event.meta is meta
Some sequences are interpreted as more than 1 keypress
def test_escape_sequence_resulting_in_multiple_keypresses(parser): """Some sequences are interpreted as more than 1 keypress""" events = list(parser.feed("\x1b[2;4~")) assert len(events) == 2 assert events[0].key == "escape" assert events[1].key == "shift+insert"
Test that we parse the correct values from the env variable.
def test__get_textual_animations(monkeypatch, env_variable, value): # type: ignore """Test that we parse the correct values from the env variable.""" monkeypatch.setenv("TEXTUAL_ANIMATIONS", env_variable) assert _get_textual_animations() == value
Test that the app gets the value of `show_animations` correctly.
def test_app_show_animations(monkeypatch, value): # type: ignore """Test that the app gets the value of `show_animations` correctly.""" monkeypatch.setattr(constants, "TEXTUAL_ANIMATIONS", value) app = App() assert app.animation_level == value
Ensure correct relative dimensions for programmatic assignments.
def test_grid_rows_columns_relative_units_are_correct(): """Ensure correct relative dimensions for programmatic assignments.""" styles = Styles() styles.grid_columns = "1fr 5%" fr, percent = styles.grid_columns assert fr.percent_unit == Unit.WIDTH assert percent.percent_unit == Unit.WIDTH styles.grid_rows = "1fr 5%" fr, percent = styles.grid_rows assert fr.percent_unit == Unit.HEIGHT assert percent.percent_unit == Unit.HEIGHT
Ensure correct relative dimensions for CSS parsed from files.
def test_styles_builder_uses_correct_relative_units_grid_rows_columns(): """Ensure correct relative dimensions for CSS parsed from files.""" CSS = "grid-rows: 1fr 5%; grid-columns: 1fr 5%;" styles = parse_declarations(CSS, "test") fr, percent = styles.grid_columns assert fr.percent_unit == Unit.WIDTH assert percent.percent_unit == Unit.WIDTH fr, percent = styles.grid_rows assert fr.percent_unit == Unit.HEIGHT assert percent.percent_unit == Unit.HEIGHT
Ensure that if the user is using CSS, they see CSS-specific examples and if they're using inline styles they see inline-specific examples.
def test_help_text_examples_are_contextualized(): """Ensure that if the user is using CSS, they see CSS-specific examples and if they're using inline styles they see inline-specific examples.""" rendered_inline = render(spacing_invalid_value_help_text("padding", "inline")) assert "widget.styles.padding" in rendered_inline rendered_css = render(spacing_invalid_value_help_text("padding", "css")) assert "padding:" in rendered_css
It should be possible to load a known-good stylesheet.
def test_mega_stylesheet() -> None: """It should be possible to load a known-good stylesheet.""" mega_stylesheet = Stylesheet() mega_stylesheet.read(Path(__file__).parent / "test_mega_stylesheet.tcss") mega_stylesheet.parse() assert ".---we-made-it-to-the-end---" in mega_stylesheet.css
Check some CSS which should fail.
def test_parse_errors(css: str, exception: type[Exception]) -> None: """Check some CSS which should fail.""" with pytest.raises(exception): list(parse("", css, ("foo", "")))
Check unknown selector raises a token error.
def test_parse_bad_pseudo_selector(): """Check unknown selector raises a token error.""" bad_selector = """\ Widget:foo{ border: red; } """ stylesheet = Stylesheet() stylesheet.add_source(bad_selector, None) with pytest.raises(TokenError) as error: stylesheet.parse() assert error.value.start == (1, 7)
Check unknown pseudo selector raises token error with correct position.
def test_parse_bad_pseudo_selector_with_suggestion(): """Check unknown pseudo selector raises token error with correct position.""" bad_selector = """ Widget:blu { border: red; } """ stylesheet = Stylesheet() stylesheet.add_source(bad_selector, None) with pytest.raises(TokenError) as error: stylesheet.parse() assert error.value.start == (2, 7)
Regression test for https://github.com/Textualize/textual/issues/3414
def test_opacity_set_allows_integer_value(): """Regression test for https://github.com/Textualize/textual/issues/3414""" styles = RenderStyles(DOMNode(), Styles(), Styles()) styles.text_opacity = 0 assert styles.text_opacity == 0.0
#ids have higher specificity than .classes
def test_stylesheet_apply_highest_specificity_wins(): """#ids have higher specificity than .classes""" css = "#id {color: red;} .class {color: blue;}" stylesheet = _make_user_stylesheet(css) node = DOMNode(classes="class", id="id") stylesheet.apply(node) assert node.styles.color == Color(255, 0, 0)
When we use two selectors containing only classes, then the selector `.b.c` has greater specificity than the selector `.a`
def test_stylesheet_apply_highest_specificity_wins_multiple_classes(): """When we use two selectors containing only classes, then the selector `.b.c` has greater specificity than the selector `.a`""" css = ".b.c {background: blue;} .a {background: red; color: lime;}" stylesheet = _make_user_stylesheet(css) node = DOMNode(classes="a b c") stylesheet.apply(node) assert node.styles.background == Color(0, 0, 255) assert node.styles.color == Color(0, 255, 0)
#id is further to the left in the specificity tuple than class, and a selector containing multiple classes cannot take priority over even a single class.
def test_stylesheet_many_classes_dont_overrule_id(): """#id is further to the left in the specificity tuple than class, and a selector containing multiple classes cannot take priority over even a single class.""" css = "#id {color: red;} .a.b.c.d {color: blue;}" stylesheet = _make_user_stylesheet(css) node = DOMNode(classes="a b c d", id="id") stylesheet.apply(node) assert node.styles.color == Color(255, 0, 0)
.a and .b both contain background and have same specificity, so .b wins since it was declared last - the background should be blue.
def test_stylesheet_apply_takes_final_rule_in_specificity_clash(): """.a and .b both contain background and have same specificity, so .b wins since it was declared last - the background should be blue.""" css = ".a {background: red; color: lime;} .b {background: blue;}" stylesheet = _make_user_stylesheet(css) node = DOMNode(classes="a b", id="c") stylesheet.apply(node) assert node.styles.color == Color(0, 255, 0) # color: lime assert node.styles.background == Color(0, 0, 255)
Ensure that we don't crash when working with empty rulesets
def test_stylesheet_apply_empty_rulesets(): """Ensure that we don't crash when working with empty rulesets""" css = ".a {} .b {}" stylesheet = _make_user_stylesheet(css) node = DOMNode(classes="a b") stylesheet.apply(node)
Test that we get nice errors with mistyped declaractions in nested CSS. When implementing pseudo-class support in nested TCSS (https://github.com/Textualize/textual/issues/4039), the first iterations didn't preserve this so we add these tests to make sure we don't take this feature away unintentionally.
def test_did_you_mean_for_property_names_in_nested_css( css_property_name: str, expected_property_name_suggestion: "str | None" ) -> None: """Test that we get nice errors with mistyped declaractions in nested CSS. When implementing pseudo-class support in nested TCSS (https://github.com/Textualize/textual/issues/4039), the first iterations didn't preserve this so we add these tests to make sure we don't take this feature away unintentionally. """ stylesheet = Stylesheet() css = """ Screen { * { border: blue; ${PROPERTY}: red; } } """.replace( "${PROPERTY}", css_property_name ) stylesheet.add_source(css) with pytest.raises(StylesheetParseError) as err: stylesheet.parse() _, help_text = err.value.errors.rules[1].errors[0] displayed_css_property_name = css_property_name.replace("_", "-") expected_summary = f"Invalid CSS property {displayed_css_property_name!r}" if expected_property_name_suggestion: expected_summary += f". Did you mean '{expected_property_name_suggestion}'?" assert help_text.summary == expected_summary
Make sure we get the correct suggestion for pseudo-classes with typos.
def test_did_you_mean_pseudo_classes(pseudo_class: str, expected: str) -> None: """Make sure we get the correct suggestion for pseudo-classes with typos.""" css = f""" Button:{pseudo_class} {{ background: red; }} """ with pytest.raises(TokenError) as err: list(tokenize(css, ("", ""))) assert f"unknown pseudo-class {pseudo_class!r}" in str(err.value) assert f"did you mean {expected!r}" in str(err.value)
Test that we get nice errors for pseudo-classes with typos in nested TCSS. When implementing pseudo-class support in nested TCSS (https://github.com/Textualize/textual/issues/4039), the first iterations didn't preserve this so we add these tests to make sure we don't take this feature away unintentionally.
def test_did_you_mean_pseudo_classes_in_nested_css( pseudo_class: str, expected: str ) -> None: """Test that we get nice errors for pseudo-classes with typos in nested TCSS. When implementing pseudo-class support in nested TCSS (https://github.com/Textualize/textual/issues/4039), the first iterations didn't preserve this so we add these tests to make sure we don't take this feature away unintentionally. """ css = f""" Screen {{ Button:{pseudo_class} {{ background: red; }} }} """ with pytest.raises(TokenError) as err: list(tokenize(css, ("", ""))) assert f"unknown pseudo-class {pseudo_class!r}" in str(err.value) assert f"did you mean {expected!r}" in str(err.value)
The text we put in is the text we get out.
def test_text(text): """The text we put in is the text we get out.""" document = Document(text) assert document.text == text
The location is always what we expect.
def test_document_end(text): """The location is always what we expect.""" document = Document(text) expected_line_number = ( len(text.splitlines()) if text.endswith("\n") else len(text.splitlines()) - 1 ) expected_pos = 0 if text.endswith("\n") else (len(text.splitlines()[-1])) assert document.end == (expected_line_number, expected_pos)
Testing deleting newline from right to left
def test_delete_single_newline(document): """Testing deleting newline from right to left""" replace_result = document.replace_range((1, 0), (0, 16), "") assert replace_result == EditResult(end_location=(0, 16), replaced_text="\n") assert document.lines == [ "I must not fear.Fear is the mind-killer.", "I forgot the rest of the quote.", "Sorry Will.", ]
Test deleting a range near the end of a document.
def test_delete_near_end_of_document(document): """Test deleting a range near the end of a document.""" replace_result = document.replace_range((1, 0), (3, 11), "") assert replace_result == EditResult( end_location=(1, 0), replaced_text="Fear is the mind-killer.\n" "I forgot the rest of the quote.\n" "Sorry Will.", ) assert document.lines == [ "I must not fear.", "", ]
Deleting a selection that partially spans the first and final lines of the selection.
def test_delete_multiple_lines_partially_spanned(document): """Deleting a selection that partially spans the first and final lines of the selection.""" replace_result = document.replace_range((0, 2), (2, 2), "") assert replace_result == EditResult( end_location=(0, 2), replaced_text="must not fear.\nFear is the mind-killer.\nI ", ) assert document.lines == [ "I forgot the rest of the quote.", "Sorry Will.", ]
Testing deleting newline from left to right
def test_delete_end_of_line(document): """Testing deleting newline from left to right""" replace_result = document.replace_range((0, 16), (1, 0), "") assert replace_result == EditResult( end_location=(0, 16), replaced_text="\n", ) assert document.lines == [ "I must not fear.Fear is the mind-killer.", "I forgot the rest of the quote.", "Sorry Will.", ]
Delete from the start to the end of the line.
def test_delete_single_line_excluding_newline(document): """Delete from the start to the end of the line.""" replace_result = document.replace_range((2, 0), (2, 31), "") assert replace_result == EditResult( end_location=(2, 0), replaced_text="I forgot the rest of the quote.", ) assert document.lines == [ "I must not fear.", "Fear is the mind-killer.", "", "Sorry Will.", ]
Delete from the start of a line to the start of the line below.
def test_delete_single_line_including_newline(document): """Delete from the start of a line to the start of the line below.""" replace_result = document.replace_range((2, 0), (3, 0), "") assert replace_result == EditResult( end_location=(2, 0), replaced_text="I forgot the rest of the quote.\n", ) assert document.lines == [ "I must not fear.", "Fear is the mind-killer.", "Sorry Will.", ]
Ensuring we can do a simple replacement of text.
def test_insert_range_text_no_newlines(): """Ensuring we can do a simple replacement of text.""" document = Document(TEXT) document.replace_range((0, 2), (0, 6), "MUST") assert document.lines == [ "I MUST not fear.", "Fear is the mind-killer.", ]
The post-edit content is not wrapped.
def test_refresh_range(): """The post-edit content is not wrapped.""" document = Document(SIMPLE_TEXT) wrapped_document = WrappedDocument(document, width=4) start_location = (1, 0) old_end_location = (3, 0) edit_result = document.replace_range(start_location, old_end_location, "123") # Inform the wrapped document about the range impacted by the edit wrapped_document.wrap_range( start_location, old_end_location, edit_result.end_location, ) # Now confirm the resulting wrapped version is as we would expect assert wrapped_document.lines == [["123 ", "4567"], ["123"]]
The post-edit content itself must be wrapped.
def test_refresh_range_new_text_wrapped(): """The post-edit content itself must be wrapped.""" document = Document(SIMPLE_TEXT) wrapped_document = WrappedDocument(document, width=4) start_location = (1, 0) old_end_location = (3, 0) edit_result = document.replace_range( start_location, old_end_location, "12 34567 8901" ) # Inform the wrapped document about the range impacted by the edit wrapped_document.wrap_range( start_location, old_end_location, edit_result.end_location ) # Now confirm the resulting wrapped version is as we would expect assert wrapped_document.lines == [ ["123 ", "4567"], ["12 ", "3456", "7 ", "8901"], ]
When we insert new content at the end of the document, ensure it wraps correctly.
def test_refresh_range_wrapping_at_previously_unavailable_range(): """When we insert new content at the end of the document, ensure it wraps correctly.""" document = Document(SIMPLE_TEXT) wrapped_document = WrappedDocument(document, width=4) edit_result = document.replace_range((3, 0), (3, 0), "012 3456\n78 90123\n45") wrapped_document.wrap_range((3, 0), (3, 0), edit_result.end_location) assert wrapped_document.lines == [ ["123 ", "4567"], ["1234", "5"], ["1234", "5678", "9"], ["012 ", "3456"], ["78 ", "9012", "3"], ["45"], ]
Test number type regex.
def test_input_number_type(): """Test number type regex.""" number = _RESTRICT_TYPES["number"] assert re.fullmatch(number, "0") assert re.fullmatch(number, "0.") assert re.fullmatch(number, ".") assert re.fullmatch(number, ".0") assert re.fullmatch(number, "1.1") assert re.fullmatch(number, "1e1") assert re.fullmatch(number, "1.2e") assert re.fullmatch(number, "1.2e10") assert re.fullmatch(number, "1.2E10") assert re.fullmatch(number, "1.2e-") assert re.fullmatch(number, "1.2e-10") assert not re.fullmatch(number, "1.2e10e") assert not re.fullmatch(number, "1f2") assert not re.fullmatch(number, "inf") assert not re.fullmatch(number, "nan")
Test input type regex
def test_input_integer_type(): """Test input type regex""" integer = _RESTRICT_TYPES["integer"] assert re.fullmatch(integer, "0") assert re.fullmatch(integer, "1") assert re.fullmatch(integer, "10") assert re.fullmatch(integer, "123456789") assert re.fullmatch(integer, "-") assert re.fullmatch(integer, "+") assert re.fullmatch(integer, "-1") assert re.fullmatch(integer, "+2") assert not re.fullmatch(integer, "+2e") assert not re.fullmatch(integer, "foo")
Test that an empty widget has height equal to 0.
def test_empty_widget_height(layout): """Test that an empty widget has height equal to 0.""" l = layout() # Make sure this measurement does not depend on the width. assert l.get_content_height(Widget(), Size(80, 24), Size(80, 24), 24) == 0 assert l.get_content_height(Widget(), Size(80, 24), Size(80, 24), 20) == 0 assert l.get_content_height(Widget(), Size(80, 24), Size(80, 24), 10) == 0 assert l.get_content_height(Widget(), Size(80, 24), Size(80, 24), 0) == 0
Test that an empty widget has width equal to 0.
def test_empty_widget_width(layout): """Test that an empty widget has width equal to 0.""" l = layout() assert l.get_content_width(Widget(), Size(80, 24), Size(80, 24)) == 0
A notification should not change the message.
def test_message() -> None: """A notification should not change the message.""" assert Notification("test").message == "test"
A notification with no title should have a empty title.
def test_default_title() -> None: """A notification with no title should have a empty title.""" assert Notification("test").title == ""
The default severity level should be as expected.
def test_default_severity_level() -> None: """The default severity level should be as expected.""" assert Notification("test").severity == "information"
The default timeout should be as expected.
def test_default_timeout() -> None: """The default timeout should be as expected.""" assert Notification("test").timeout == Notification.timeout
A collection of notifications should, by default, have unique IDs.
def test_identity_is_unique() -> None: """A collection of notifications should, by default, have unique IDs.""" notifications: set[str] = set() for _ in range(1000): notifications.add(Notification("test").identity) assert len(notifications) == 1000
We should have no notifications if we've not raised any.
def test_empty_to_start_with() -> None: """We should have no notifications if we've not raised any.""" assert len(Notifications()) == 0
Adding lots of long-timeout notifications should result in them being in the list.
def test_many_notifications() -> None: """Adding lots of long-timeout notifications should result in them being in the list.""" tester = Notifications() for _ in range(100): tester.add(Notification("test", timeout=60)) assert len(tester) == 100
Notifications should timeout from the list.
def test_timeout() -> None: """Notifications should timeout from the list.""" tester = Notifications() for n in range(100): tester.add(Notification("test", timeout=(0.5 if bool(n % 2) else 60))) assert len(tester) == 100 sleep(0.6) assert len(tester) == 50
It should be possible to test if a notification is in a collection.
def test_in() -> None: """It should be possible to test if a notification is in a collection.""" tester = Notifications() within = Notification("within", timeout=120) outwith = Notification("outwith", timeout=120) tester.add(within) assert within in tester assert outwith not in tester
It should be possible to remove a notification.
def test_remove_notification() -> None: """It should be possible to remove a notification.""" tester = Notifications() first = Notification("first", timeout=120) second = Notification("second", timeout=120) third = Notification("third", timeout=120) tester.add(first) tester.add(second) tester.add(third) assert list(tester) == [first, second, third] del tester[second] assert list(tester) == [first, third] del tester[first] assert list(tester) == [third] del tester[third] assert list(tester) == []
It should be possible to remove the same notification more than once without an error.
def test_remove_notification_multiple_times() -> None: """It should be possible to remove the same notification more than once without an error.""" tester = Notifications() alert = Notification("delete me") tester.add(alert) assert list(tester) == [alert] del tester[alert] assert list(tester) == [] del tester[alert] assert list(tester) == []
It should be possible to clear all notifications.
def test_clear() -> None: """It should be possible to clear all notifications.""" tester = Notifications() for _ in range(100): tester.add(Notification("test", timeout=120)) assert len(tester) == 100 tester.clear() assert len(tester) == 0
Sparkline should work with common Sequence types.
def test_sparkline_sequence_types(data: Sequence[int]): """Sparkline should work with common Sequence types.""" assert issubclass(type(data), Sequence) assert ( render(Sparkline(data, width=3)) == f"{GREEN}▁{STOP}{BLENDED}β–„{STOP}{RED}β–ˆ{STOP}" )
Tests switches but also acts a regression test for using width: auto in a Horizontal layout context.
def test_switches(snap_compare): """Tests switches but also acts a regression test for using width: auto in a Horizontal layout context.""" press = [ "shift+tab", "enter", # toggle off "shift+tab", "wait:20", "enter", # toggle on "wait:20", ] assert snap_compare(WIDGET_EXAMPLES_DIR / "switch.py", press=press)
Checking that invalid styling is applied. The snapshot app itself also adds styling for -valid which gives a green border.
def test_input_validation(snap_compare): """Checking that invalid styling is applied. The snapshot app itself also adds styling for -valid which gives a green border.""" press = [ *"-2", # -2 is invalid, so -invalid should be applied "tab", "3", # This is valid, so -valid should be applied "tab", *"-2", # -2 is invalid, so -invalid should be applied (and :focus, since we stop here) ] assert snap_compare(SNAPSHOT_APPS_DIR / "input_validation.py", press=press)
Make sure that the first value is selected by default if allow_blank=False.
def test_select_no_blank_has_default_value(snap_compare): """Make sure that the first value is selected by default if allow_blank=False.""" assert snap_compare(WIDGET_EXAMPLES_DIR / "select_widget_no_blank.py")
Test offsets of containers
def test_offsets(snap_compare): """Test offsets of containers""" assert snap_compare("snapshot_apps/offsets.py")
Test refreshing widget within a auto sized container
def test_nested_auto_heights(snap_compare): """Test refreshing widget within a auto sized container""" assert snap_compare("snapshot_apps/nested_auto_heights.py", press=["1", "2"])
Regression test for #1607 https://github.com/Textualize/textual/issues/1607 See also tests/css/test_programmatic_style_changes.py for other related regression tests.
def test_programmatic_scrollbar_gutter_change(snap_compare): """Regression test for #1607 https://github.com/Textualize/textual/issues/1607 See also tests/css/test_programmatic_style_changes.py for other related regression tests. """ assert snap_compare( "snapshot_apps/programmatic_scrollbar_gutter_change.py", press=["s"] )
Test the demo app (python -m textual)
def test_demo(snap_compare): """Test the demo app (python -m textual)""" assert snap_compare( Path("../../src/textual/demo.py"), terminal_size=(100, 30), )
Test renderable widths are calculate correctly.
def test_label_widths(snap_compare): """Test renderable widths are calculate correctly.""" assert snap_compare(SNAPSHOT_APPS_DIR / "label_widths.py")
Test setting a border alpha.
def test_border_alpha(snap_compare): """Test setting a border alpha.""" assert snap_compare(SNAPSHOT_APPS_DIR / "border_alpha.py")
Check that min_width applies in RichLog and that we can write to the RichLog when it's not visible, and it still renders as expected when made visible again.
def test_richlog_width(snap_compare): """Check that min_width applies in RichLog and that we can write to the RichLog when it's not visible, and it still renders as expected when made visible again.""" async def setup(pilot): from rich.text import Text rich_log: RichLog = pilot.app.query_one(RichLog) rich_log.write(Text("hello1", style="on red", justify="right"), expand=True) rich_log.visible = False rich_log.write(Text("world2", style="on green", justify="right"), expand=True) rich_log.visible = True rich_log.write(Text("hello3", style="on blue", justify="right"), expand=True) rich_log.display = False rich_log.write(Text("world4", style="on yellow", justify="right"), expand=True) rich_log.display = True assert snap_compare(SNAPSHOT_APPS_DIR / "richlog_width.py", run_before=setup)
Regression test for https://github.com/Textualize/textual/issues/2063.
def test_css_hot_reloading(snap_compare, monkeypatch): """Regression test for https://github.com/Textualize/textual/issues/2063.""" monkeypatch.setenv( "TEXTUAL", "debug" ) # This will make sure we create a file monitor. async def run_before(pilot): css_file = pilot.app.CSS_PATH with open(css_file, "w") as f: f.write("/* This file is purposefully empty. */\n") # Clear all the CSS. await pilot.app._on_css_change() assert snap_compare( SNAPSHOT_APPS_DIR / "hot_reloading_app.py", run_before=run_before )
Regression test for https://github.com/Textualize/textual/issues/3454.
def test_css_hot_reloading_on_screen(snap_compare, monkeypatch): """Regression test for https://github.com/Textualize/textual/issues/3454.""" monkeypatch.setenv( "TEXTUAL", "debug" ) # This will make sure we create a file monitor. async def run_before(pilot): css_file = pilot.app.screen.CSS_PATH with open(css_file, "w") as f: f.write("/* This file is purposefully empty. */\n") # Clear all the CSS. await pilot.app._on_css_change() assert snap_compare( SNAPSHOT_APPS_DIR / "hot_reloading_app_with_screen_css.py", run_before=run_before, )
Regression test for https://github.com/Textualize/textual/issues/3312.
def test_datatable_hot_reloading(snap_compare, monkeypatch): """Regression test for https://github.com/Textualize/textual/issues/3312.""" monkeypatch.setenv( "TEXTUAL", "debug" ) # This will make sure we create a file monitor. async def run_before(pilot): css_file = pilot.app.CSS_PATH with open(css_file, "w") as f: f.write("/* This file is purposefully empty. */\n") # Clear all the CSS. await pilot.app._on_css_change() assert snap_compare( SNAPSHOT_APPS_DIR / "datatable_hot_reloading.py", run_before=run_before )
Tests all markdown component classes reload correctly. See https://github.com/Textualize/textual/issues/3464.
def test_markdown_component_classes_reloading(snap_compare, monkeypatch): """Tests all markdown component classes reload correctly. See https://github.com/Textualize/textual/issues/3464.""" monkeypatch.setenv( "TEXTUAL", "debug" ) # This will make sure we create a file monitor. async def run_before(pilot): css_file = pilot.app.CSS_PATH with open(css_file, "w") as f: f.write("/* This file is purposefully empty. */\n") # Clear all the CSS. await pilot.app._on_css_change() assert snap_compare( SNAPSHOT_APPS_DIR / "markdown_component_classes_reloading.py", run_before=run_before, )
Each theme should have its own snapshot with at least some Python to check that the rendering is sensible. This also ensures that theme switching results in the display changing correctly.
def test_text_area_themes(snap_compare, theme_name): """Each theme should have its own snapshot with at least some Python to check that the rendering is sensible. This also ensures that theme switching results in the display changing correctly.""" text = """\ def hello(name): x = 123 while not False: print("hello " + name) continue """ def setup_theme(pilot): text_area = pilot.app.query_one(TextArea) text_area.load_text(text) text_area.language = "python" text_area.selection = Selection((0, 1), (1, 9)) text_area.theme = theme_name assert snap_compare( SNAPSHOT_APPS_DIR / "text_area.py", run_before=setup_theme, terminal_size=(48, text.count("\n") + 4), )
Outline style rendered incorrectly when applied to a `Button` widget. Regression test for https://github.com/Textualize/textual/issues/3628
def test_button_outline(snap_compare): """Outline style rendered incorrectly when applied to a `Button` widget. Regression test for https://github.com/Textualize/textual/issues/3628 """ assert snap_compare(SNAPSHOT_APPS_DIR / "button_outline.py")
Regression test for https://github.com/Textualize/textual/issues/3677. This tests that notifications stay on top of loading indicators and it also tests that loading a widget will remove its scrollbars.
def test_notifications_loading_overlap_order(snap_compare): """Regression test for https://github.com/Textualize/textual/issues/3677. This tests that notifications stay on top of loading indicators and it also tests that loading a widget will remove its scrollbars. """ assert snap_compare( SNAPSHOT_APPS_DIR / "notifications_above_loading.py", terminal_size=(80, 20) )
Regression test for https://github.com/Textualize/textual/issues/3687
def test_missing_vertical_scroll(snap_compare): """Regression test for https://github.com/Textualize/textual/issues/3687""" assert snap_compare(SNAPSHOT_APPS_DIR / "missing_vertical_scroll.py")
Test vertical min height takes border in to account.
def test_vertical_min_height(snap_compare): """Test vertical min height takes border in to account.""" assert snap_compare(SNAPSHOT_APPS_DIR / "vertical_min_height.py")
Test vertical max height takes border in to account.
def test_vertical_max_height(snap_compare): """Test vertical max height takes border in to account.""" assert snap_compare(SNAPSHOT_APPS_DIR / "vertical_max_height.py")
Test vertical max height takes border in to account.
def test_max_height_100(snap_compare): """Test vertical max height takes border in to account.""" assert snap_compare(SNAPSHOT_APPS_DIR / "max_height_100.py")
Test loading indicator.
def test_loading_indicator(snap_compare): """Test loading indicator.""" # https://github.com/Textualize/textual/pull/3816 assert snap_compare(SNAPSHOT_APPS_DIR / "loading.py", press=["space"])
Test loading indicator disabled widget.
def test_loading_indicator_disables_widget(snap_compare): """Test loading indicator disabled widget.""" # https://github.com/Textualize/textual/pull/3816 assert snap_compare( SNAPSHOT_APPS_DIR / "loading.py", press=["space", "down", "down", "space"] )
Regression test for broken style update on mount.
def test_mount_style_fix(snap_compare): """Regression test for broken style update on mount.""" # https://github.com/Textualize/textual/issues/3858 assert snap_compare(SNAPSHOT_APPS_DIR / "mount_style_fix.py")
Regression test for missing content with 0 sized scrollbars
def test_zero_scrollbar_size(snap_compare): """Regression test for missing content with 0 sized scrollbars""" # https://github.com/Textualize/textual/issues/3886 assert snap_compare(SNAPSHOT_APPS_DIR / "zero_scrollbar_size.py")
Test the Tree.root.is_expanded state after a Tree.clear
def test_tree_clearing_and_expansion(snap_compare): """Test the Tree.root.is_expanded state after a Tree.clear""" # https://github.com/Textualize/textual/issues/3557 assert snap_compare(SNAPSHOT_APPS_DIR / "tree_clearing.py")
Test specificity of nested rules is working.
def test_nested_specificity(snap_compare): """Test specificity of nested rules is working.""" # https://github.com/Textualize/textual/issues/3961 assert snap_compare(SNAPSHOT_APPS_DIR / "nested_specificity.py")
Test setting a new label for a tab amongst a TabbedContent.
def test_tab_rename(snap_compare): """Test setting a new label for a tab amongst a TabbedContent.""" assert snap_compare(SNAPSHOT_APPS_DIR / "tab_rename.py")
Check percentage widths work correctly.
def test_input_percentage_width(snap_compare): """Check percentage widths work correctly.""" # https://github.com/Textualize/textual/issues/3721 assert snap_compare(SNAPSHOT_APPS_DIR / "input_percentage_width.py")
Check recompose works.
def test_recompose(snap_compare): """Check recompose works.""" # https://github.com/Textualize/textual/pull/4206 assert snap_compare(SNAPSHOT_APPS_DIR / "recompose.py")
Test how ANSI colors in Rich renderables are mapped to hex colors.
def test_ansi_color_mapping(snap_compare, dark): """Test how ANSI colors in Rich renderables are mapped to hex colors.""" def setup(pilot): pilot.app.dark = dark assert snap_compare(SNAPSHOT_APPS_DIR / "ansi_mapping.py", run_before=setup)
Regression test for https://github.com/Textualize/textual/pull/4219.
def test_pretty_grid_gutter_interaction(snap_compare): """Regression test for https://github.com/Textualize/textual/pull/4219.""" assert snap_compare( SNAPSHOT_APPS_DIR / "pretty_grid_gutter_interaction.py", terminal_size=(81, 7) )
Test sort_children method.
def test_sort_children(snap_compare): """Test sort_children method.""" assert snap_compare(SNAPSHOT_APPS_DIR / "sort_children.py", terminal_size=(80, 25))
Test Styling after receiving an AppBlur message.
def test_app_blur(snap_compare): """Test Styling after receiving an AppBlur message.""" async def run_before(pilot) -> None: await pilot.pause() # Allow the AppBlur message to get processed. assert snap_compare(SNAPSHOT_APPS_DIR / "app_blur.py", run_before=run_before)
Test placeholder with diabled set to True.
def test_placeholder_disabled(snap_compare): """Test placeholder with diabled set to True.""" assert snap_compare(SNAPSHOT_APPS_DIR / "placeholder_disabled.py")
Tests that ListView scrolls correctly after updating its index.
def test_listview_index(snap_compare): """Tests that ListView scrolls correctly after updating its index.""" assert snap_compare(SNAPSHOT_APPS_DIR / "listview_index.py")
Test that button widths expand auto containers as expected.
def test_button_widths(snap_compare): """Test that button widths expand auto containers as expected.""" # https://github.com/Textualize/textual/issues/4024 assert snap_compare(SNAPSHOT_APPS_DIR / "button_widths.py")
Test the calculator example.
def test_example_calculator(snap_compare): """Test the calculator example.""" assert snap_compare(EXAMPLES_DIR / "calculator.py")
Test the color_command example.
def test_example_color_command(snap_compare): """Test the color_command example.""" assert snap_compare( EXAMPLES_DIR / "color_command.py", press=["ctrl+backslash", "r", "e", "d", "down", "down", "enter"], )
Test the dictionary example (basic layout test).
def test_example_dictionary(snap_compare): """Test the dictionary example (basic layout test).""" async def run_before(pilot): pilot.app.query(Input).first().cursor_blink = False assert snap_compare(EXAMPLES_DIR / "dictionary.py", run_before=run_before)
Test the five_by_five example.
def test_example_five_by_five(snap_compare): """Test the five_by_five example.""" assert snap_compare(EXAMPLES_DIR / "five_by_five.py")
Test the json_tree example.
def test_example_json_tree(snap_compare): """Test the json_tree example.""" assert snap_compare( EXAMPLES_DIR / "json_tree.py", press=["a", "down", "enter", "down", "down", "enter"], )
Test the markdown example.
def test_example_markdown(snap_compare): """Test the markdown example.""" assert snap_compare(EXAMPLES_DIR / "markdown.py")
Test the merlin example.
def test_example_merlin(snap_compare): """Test the merlin example.""" on_switches = {2, 3, 5, 8} async def run_before(pilot): pilot.app.query_one("Timer").running = False # This will freeze the clock. for switch in pilot.app.query("LabelSwitch"): switch.query_one("Switch").value = switch.switch_no in on_switches await pilot.pause() assert snap_compare(EXAMPLES_DIR / "merlin.py", run_before=run_before)
Test the pride example.
def test_example_pride(snap_compare): """Test the pride example.""" assert snap_compare(EXAMPLES_DIR / "pride.py")
Regression test for https://github.com/Textualize/textual/issues/4328
def test_button_with_console_markup(snap_compare): """Regression test for https://github.com/Textualize/textual/issues/4328""" assert snap_compare(SNAPSHOT_APPS_DIR / "button_markup.py")
Regression test for https://github.com/Textualize/textual/issues/4360
def test_width_100(snap_compare): """Regression test for https://github.com/Textualize/textual/issues/4360""" assert snap_compare(SNAPSHOT_APPS_DIR / "width_100.py")
Meta test to ensure the `TextArea.code_editor` convenience constructor is kept up to date with changes to the `TextArea.__init__` parameters.
def test_code_editor_parameters_kept_up_to_date(): """Meta test to ensure the `TextArea.code_editor` convenience constructor is kept up to date with changes to the `TextArea.__init__` parameters. """ text_area_params = inspect.signature(TextArea.__init__).parameters code_editor_params = inspect.signature(TextArea.code_editor).parameters expected_diffs = ["theme", "soft_wrap", "tab_behavior", "show_line_numbers"] for param in text_area_params: if param == "self": continue assert param in code_editor_params if param not in expected_diffs: assert code_editor_params[param] == text_area_params[param]