response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Locate the leftmost item in the sequence equal to value via bisection.
Args:
sequence: The sequence to search in.
value: The value to find.
Returns:
The index of the value, or -1 if the value is not found in the sequence. | def index(sequence: Sequence, value: Any) -> int:
"""Locate the leftmost item in the sequence equal to value via bisection.
Args:
sequence: The sequence to search in.
value: The value to find.
Returns:
The index of the value, or -1 if the value is not found in the sequence.
"""
insert_index = bisect_left(sequence, value)
if insert_index != len(sequence) and sequence[insert_index] == value:
return insert_index
return -1 |
Set the console mode for a given file (stdout or stdin).
Args:
file: A file like object.
mode: New mode.
Returns:
True on success, otherwise False. | def set_console_mode(file: IO, mode: int) -> bool:
"""Set the console mode for a given file (stdout or stdin).
Args:
file: A file like object.
mode: New mode.
Returns:
True on success, otherwise False.
"""
windows_filehandle = msvcrt.get_osfhandle(file.fileno()) # type: ignore
success = KERNEL32.SetConsoleMode(windows_filehandle, mode)
return success |
Get the console mode for a given file (stdout or stdin)
Args:
file: A file-like object.
Returns:
The current console mode. | def get_console_mode(file: IO) -> int:
"""Get the console mode for a given file (stdout or stdin)
Args:
file: A file-like object.
Returns:
The current console mode.
"""
windows_filehandle = msvcrt.get_osfhandle(file.fileno()) # type: ignore
mode = wintypes.DWORD()
KERNEL32.GetConsoleMode(windows_filehandle, ctypes.byref(mode))
return mode.value |
Enable application mode.
Returns:
A callable that will restore terminal to previous state. | def enable_application_mode() -> Callable[[], None]:
"""Enable application mode.
Returns:
A callable that will restore terminal to previous state.
"""
terminal_in = sys.__stdin__
terminal_out = sys.__stdout__
current_console_mode_in = get_console_mode(terminal_in)
current_console_mode_out = get_console_mode(terminal_out)
def restore() -> None:
"""Restore console mode to previous settings"""
set_console_mode(terminal_in, current_console_mode_in)
set_console_mode(terminal_out, current_console_mode_out)
set_console_mode(
terminal_out, current_console_mode_out | ENABLE_VIRTUAL_TERMINAL_PROCESSING
)
set_console_mode(terminal_in, ENABLE_VIRTUAL_TERMINAL_INPUT)
return restore |
Waits for multiple handles. (Similar to 'select') Returns the handle which is ready.
Returns `None` on timeout.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx
Note that handles should be a list of `HANDLE` objects, not integers. See
this comment in the patch by @quark-zju for the reason why:
''' Make sure HANDLE on Windows has a correct size
Previously, the type of various HANDLEs are native Python integer
types. The ctypes library will treat them as 4-byte integer when used
in function arguments. On 64-bit Windows, HANDLE is 8-byte and usually
a small integer. Depending on whether the extra 4 bytes are zero-ed out
or not, things can happen to work, or break. '''
This function returns either `None` or one of the given `HANDLE` objects.
(The return value can be tested with the `is` operator.) | def wait_for_handles(handles: List[HANDLE], timeout: int = -1) -> Optional[HANDLE]:
"""
Waits for multiple handles. (Similar to 'select') Returns the handle which is ready.
Returns `None` on timeout.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx
Note that handles should be a list of `HANDLE` objects, not integers. See
this comment in the patch by @quark-zju for the reason why:
''' Make sure HANDLE on Windows has a correct size
Previously, the type of various HANDLEs are native Python integer
types. The ctypes library will treat them as 4-byte integer when used
in function arguments. On 64-bit Windows, HANDLE is 8-byte and usually
a small integer. Depending on whether the extra 4 bytes are zero-ed out
or not, things can happen to work, or break. '''
This function returns either `None` or one of the given `HANDLE` objects.
(The return value can be tested with the `is` operator.)
"""
arrtype = HANDLE * len(handles)
handle_array = arrtype(*handles)
ret: int = KERNEL32.WaitForMultipleObjects(
len(handle_array), handle_array, BOOL(False), DWORD(timeout)
)
if ret == WAIT_TIMEOUT:
return None
else:
return handles[ret] |
Get a named layout object.
Args:
name: Name of the layout.
Raises:
MissingLayout: If the named layout doesn't exist.
Returns:
A layout object. | def get_layout(name: str) -> Layout:
"""Get a named layout object.
Args:
name: Name of the layout.
Raises:
MissingLayout: If the named layout doesn't exist.
Returns:
A layout object.
"""
layout_class = LAYOUT_MAP.get(name)
if layout_class is None:
raise MissingLayout(f"no layout called {name!r}, valid layouts")
return layout_class() |
Blend from one color to another.
Cached because when a UI is static the opacity will be constant.
Args:
bg_color: Background color.
fg_color: Foreground color.
opacity: Opacity.
Returns:
Resulting style. | def _get_blended_style_cached(
bg_color: Color, fg_color: Color, opacity: float
) -> Style:
"""Blend from one color to another.
Cached because when a UI is static the opacity will be constant.
Args:
bg_color: Background color.
fg_color: Foreground color.
opacity: Opacity.
Returns:
Resulting style.
"""
return Style.from_color(
color=blend_colors(bg_color, fg_color, ratio=opacity),
bgcolor=bg_color,
) |
Given two RGB colors, return a color that sits some distance between
them in RGB color space.
Args:
color1: The first color.
color2: The second color.
ratio: The ratio of color1 to color2.
Returns:
A Color representing the blending of the two supplied colors. | def blend_colors(color1: Color, color2: Color, ratio: float) -> Color:
"""Given two RGB colors, return a color that sits some distance between
them in RGB color space.
Args:
color1: The first color.
color2: The second color.
ratio: The ratio of color1 to color2.
Returns:
A Color representing the blending of the two supplied colors.
"""
assert color1.triplet is not None
assert color2.triplet is not None
r1, g1, b1 = color1.triplet
r2, g2, b2 = color2.triplet
return Color.from_rgb(
r1 + (r2 - r1) * ratio,
g1 + (g2 - g1) * ratio,
b1 + (b2 - b1) * ratio,
) |
Blend two colors given as a tuple of 3 values for red, green, and blue.
Args:
color1: The first color.
color2: The second color.
ratio: The ratio of color1 to color2.
Returns:
A Color representing the blending of the two supplied colors. | def blend_colors_rgb(
color1: tuple[int, int, int], color2: tuple[int, int, int], ratio: float
) -> Color:
"""Blend two colors given as a tuple of 3 values for red, green, and blue.
Args:
color1: The first color.
color2: The second color.
ratio: The ratio of color1 to color2.
Returns:
A Color representing the blending of the two supplied colors.
"""
r1, g1, b1 = color1
r2, g2, b2 = color2
return Color.from_rgb(
r1 + (r2 - r1) * ratio,
g1 + (g2 - g1) * ratio,
b1 + (b2 - b1) * ratio,
) |
Convert a cell into a Rich renderable for display.
Args:
obj: Data for a cell.
Returns:
A renderable to be displayed which represents the data. | def default_cell_formatter(obj: object) -> RenderableType:
"""Convert a cell into a Rich renderable for display.
Args:
obj: Data for a cell.
Returns:
A renderable to be displayed which represents the data.
"""
if isinstance(obj, str):
return Text.from_markup(obj)
if isinstance(obj, float):
return f"{obj:.2f}"
if not is_renderable(obj):
return str(obj)
return cast(RenderableType, obj) |
Callable that returns the built-in max to initialise a reactive. | def _max_factory() -> Callable[[Sequence[float]], float]:
"""Callable that returns the built-in max to initialise a reactive."""
return max |
Check if a renderable conforms to the Rich Console protocol
(https://rich.readthedocs.io/en/latest/protocol.html)
Args:
renderable: A potentially renderable object.
Raises:
RenderError: If the object can not be rendered. | def _check_renderable(renderable: object):
"""Check if a renderable conforms to the Rich Console protocol
(https://rich.readthedocs.io/en/latest/protocol.html)
Args:
renderable: A potentially renderable object.
Raises:
RenderError: If the object can not be rendered.
"""
if not is_renderable(renderable):
raise RenderError(
f"unable to render {renderable!r}; a string, Text, or other Rich renderable is required"
) |
Build a mapping of utf-8 byte offsets to codepoint offsets for the given data.
Args:
data: utf-8 bytes.
Returns:
A `dict[int, int]` mapping byte indices to codepoint indices within `data`. | def build_byte_to_codepoint_dict(data: bytes) -> dict[int, int]:
"""Build a mapping of utf-8 byte offsets to codepoint offsets for the given data.
Args:
data: utf-8 bytes.
Returns:
A `dict[int, int]` mapping byte indices to codepoint indices within `data`.
"""
byte_to_codepoint: dict[int, int] = {}
current_byte_offset = 0
code_point_offset = 0
while current_byte_offset < len(data):
byte_to_codepoint[current_byte_offset] = code_point_offset
first_byte = data[current_byte_offset]
# Single-byte character
if (first_byte & 0b10000000) == 0:
current_byte_offset += 1
# 2-byte character
elif (first_byte & 0b11100000) == 0b11000000:
current_byte_offset += 2
# 3-byte character
elif (first_byte & 0b11110000) == 0b11100000:
current_byte_offset += 3
# 4-byte character
elif (first_byte & 0b11111000) == 0b11110000:
current_byte_offset += 4
else:
raise ValueError(f"Invalid UTF-8 byte: {first_byte}")
code_point_offset += 1
# Mapping for the end of the string
byte_to_codepoint[current_byte_offset] = code_point_offset
return byte_to_codepoint |
Test that tuple arguments are parsed correctly. | 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 special characters nested in strings are handled correctly.
See also: https://github.com/Textualize/textual/issues/2088 | 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 an animation from one float to another. | def test_simple_animation():
"""Test an animation from one float to another."""
# Thing that may be animated
animate_test = AnimateTest()
# Fake wall-clock time
time = 100.0
# Object that does the animation
animation = SimpleAnimation(
animate_test,
"foo",
time,
3.0,
start_value=20.0,
end_value=50.0,
final_value=None,
easing=lambda x: x,
)
assert animate_test.foo == 0.0
assert animation(time) is False
assert animate_test.foo == 20.0
assert animation(time + 1.0) is False
assert animate_test.foo == 30.0
assert animation(time + 2.0) is False
assert animate_test.foo == 40.0
assert animation(time + 2.9) is False # Not quite final value
assert animate_test.foo == pytest.approx(49.0)
assert animation(time + 3.0) is True # True to indicate animation is complete
assert animate_test.foo is None # This is final_value
assert animation(time + 3.0) is True
assert animate_test.foo is None |
Test animation handles duration of 0. | def test_simple_animation_duration_zero():
"""Test animation handles duration of 0."""
# Thing that may be animated
animatable = AnimateTest()
# Fake wall-clock time
time = 100.0
# Object that does the animation
animation = SimpleAnimation(
animatable,
"foo",
time,
0.0,
start_value=20.0,
end_value=50.0,
final_value=50.0,
easing=lambda x: x,
)
assert animation(time) is True # Duration is 0, so this is last value
assert animatable.foo == 50.0
assert animation(time + 1.0) is True
assert animatable.foo == 50.0 |
Test an animation from one float to another, where the end value is less than the start. | def test_simple_animation_reverse():
"""Test an animation from one float to another, where the end value is less than the start."""
# Thing that may be animated
animate_Test = AnimateTest()
# Fake wall-clock time
time = 100.0
# Object that does the animation
animation = SimpleAnimation(
animate_Test,
"foo",
time,
3.0,
start_value=50.0,
end_value=20.0,
final_value=20.0,
easing=lambda x: x,
)
assert animation(time) is False
assert animate_Test.foo == 50.0
assert animation(time + 1.0) is False
assert animate_Test.foo == 40.0
assert animation(time + 2.0) is False
assert animate_Test.foo == 30.0
assert animation(time + 3.0) is True
assert animate_Test.foo == 20.0 |
Test SimpleAnimation works with the Animatable protocol | def test_animatable():
"""Test SimpleAnimation works with the Animatable protocol"""
animate_test = AnimateTest()
# Fake wall-clock time
time = 100.0
# Object that does the animation
animation = SimpleAnimation(
animate_test,
"bar",
time,
3.0,
start_value=Animatable(20.0),
end_value=Animatable(50.0),
final_value=Animatable(50.0),
easing=lambda x: x,
)
assert animation(time) is False
assert animate_test.bar.value == 20.0
assert animation(time + 1.0) is False
assert animate_test.bar.value == 30.0
assert animation(time + 2.0) is False
assert animate_test.bar.value == 40.0
assert animation(time + 2.9) is False
assert animate_test.bar.value == pytest.approx(49.0)
assert animation(time + 3.0) is True # True to indicate animation is complete
assert animate_test.bar.value == 50.0 |
Test `batch_update` context manager | def test_batch_update():
"""Test `batch_update` context manager"""
app = App()
assert app._batch_count == 0 # Start at zero
with app.batch_update():
assert app._batch_count == 1 # Increments in context manager
with app.batch_update():
assert app._batch_count == 2 # Nested updates
assert app._batch_count == 1 # Exiting decrements
assert app._batch_count == 0 |
The border_title gets set to a single line even when multiple lines are provided. | def test_border_title_single_line():
"""The border_title gets set to a single line even when multiple lines are provided."""
widget = Widget()
assert widget.border_title is None
widget.border_title = None
assert widget.border_title is None
widget.border_title = ""
assert widget.border_title == ""
widget.border_title = "How is life\ngoing for you?"
assert widget.border_title == "How is life"
widget.border_title = "How is life\n\rgoing for you?"
assert widget.border_title == "How is life"
widget.border_title = "Sorry you \r\n have to \n read this."
assert widget.border_title == "Sorry you "
widget.border_title = "[red]This also \n works with markup \n involved.[/]"
assert widget.border_title == "[red]This also [/red]"
widget.border_title = Text.from_markup("[bold]Hello World")
assert widget.border_title == "[bold]Hello World[/bold]" |
The border_subtitle gets set to a single line even when multiple lines are provided. | def test_border_subtitle_single_line():
"""The border_subtitle gets set to a single line even when multiple lines are provided."""
widget = Widget()
widget.border_subtitle = ""
assert widget.border_subtitle == ""
widget.border_subtitle = "How is life\ngoing for you?"
assert widget.border_subtitle == "How is life"
widget.border_subtitle = "How is life\n\rgoing for you?"
assert widget.border_subtitle == "How is life"
widget.border_subtitle = "Sorry you \r\n have to \n read this."
assert widget.border_subtitle == "Sorry you "
widget.border_subtitle = "[red]This also \n works with markup \n involved.[/]"
assert widget.border_subtitle == "[red]This also [/red]"
widget.border_subtitle = Text.from_markup("[bold]Hello World")
assert widget.border_subtitle == "[bold]Hello World[/bold]" |
Test that we get an empty list of segments if there is no label to display. | def test_render_border_label_empty_label_skipped(
width: int, has_left_corner: bool, has_right_corner: bool
):
"""Test that we get an empty list of segments if there is no label to display."""
assert [] == list(
render_border_label(
(Text(""), Style()),
True,
"round",
width,
_EMPTY_STYLE,
_EMPTY_STYLE,
_EMPTY_STYLE,
_WIDE_CONSOLE,
has_left_corner,
has_right_corner,
)
) |
Test that we skip rendering a label when we do not have space for it.
In order for us to have enough space for the label, we need to have space for the
corners that we need (none, just one, or both) and we need to be able to have two
blank spaces around the label (one on each side).
If we don't have space for all of these, we skip the label altogether. | def test_render_border_label_skipped_if_narrow(
label: str, width: int, has_left_corner: bool, has_right_corner: bool
):
"""Test that we skip rendering a label when we do not have space for it.
In order for us to have enough space for the label, we need to have space for the
corners that we need (none, just one, or both) and we need to be able to have two
blank spaces around the label (one on each side).
If we don't have space for all of these, we skip the label altogether.
"""
assert [] == list(
render_border_label(
(Text.from_markup(label), Style()),
True,
"round",
width,
_EMPTY_STYLE,
_EMPTY_STYLE,
_EMPTY_STYLE,
_WIDE_CONSOLE,
has_left_corner,
has_right_corner,
)
) |
Test label rendering in a wide area with no styling. | def test_render_border_label_wide_plain(label: str):
"""Test label rendering in a wide area with no styling."""
BIG_NUM = 9999
args = (
True,
"round",
BIG_NUM,
_EMPTY_STYLE,
_EMPTY_STYLE,
_EMPTY_STYLE,
_WIDE_CONSOLE,
True,
True,
)
segments = render_border_label((Text.from_markup(label), Style()), *args)
(segment,) = segments
assert segment == Segment(f" {label} ", None) |
Test label rendering if there is no text but some markup. | def test_render_border_empty_text_with_markup(label: str):
"""Test label rendering if there is no text but some markup."""
assert [] == list(
render_border_label(
(Text.from_markup(label), Style()),
True,
"round",
999,
_EMPTY_STYLE,
_EMPTY_STYLE,
_EMPTY_STYLE,
_WIDE_CONSOLE,
True,
True,
)
) |
Test label rendering with styling, with and without overflow. | def test_render_border_label():
"""Test label rendering with styling, with and without overflow."""
label = "[b][on red]What [i]is up[/on red] with you?[/]"
border_style = Style.parse("green on blue")
# Implicit test on the number of segments returned:
blank1, what, is_up, with_you, blank2 = render_border_label(
(Text.from_markup(label), Style()),
True,
"round",
9999,
_EMPTY_STYLE,
_EMPTY_STYLE,
border_style,
_WIDE_CONSOLE,
True,
True,
)
expected_blank = Segment(" ", border_style)
assert blank1 == expected_blank
assert blank2 == expected_blank
what_style = Style.parse("b on red")
expected_what = Segment("What ", border_style + what_style)
assert what == expected_what
is_up_style = Style.parse("b on red i")
expected_is_up = Segment("is up", border_style + is_up_style)
assert is_up == expected_is_up
with_you_style = Style.parse("b i")
expected_with_you = Segment(" with you?", border_style + with_you_style)
assert with_you == expected_with_you
blank1, what, blank2 = render_border_label(
(Text.from_markup(label), Style()),
True,
"round",
5 + 4, # 5 where "Whatβ¦" fits + 2 for the blank spaces + 2 for the corners.
_EMPTY_STYLE,
_EMPTY_STYLE,
border_style,
_WIDE_CONSOLE,
True, # This corner costs 2 cells.
True, # This corner costs 2 cells.
)
assert blank1 == expected_blank
assert blank2 == expected_blank
expected_what = Segment("Whatβ¦", border_style + what_style)
assert what == expected_what |
Test width settings. | 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 height settings. | 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)) |
Check that max_width and max_height are respected. | 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 min_width and min_height are respected. | 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)) |
Test cache values can be set and read back. | 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 adding adding additional values evicts oldest key | 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 | 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 |
Regression test for https://github.com/Textualize/textual/issues/3537 | 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() |
Check conversion to Rich color. | def test_rich_color():
"""Check conversion to Rich color."""
assert Color(10, 20, 30, 1.0).rich_color == RichColor.from_rgb(10, 20, 30)
assert Color.from_rich_color(RichColor.from_rgb(10, 20, 30)) == Color(
10, 20, 30, 1.0
) |
Check conversion to CSS style | def test_css():
"""Check conversion to CSS style"""
assert Color(10, 20, 30, 1.0).css == "rgb(10,20,30)"
assert Color(10, 20, 30, 0.5).css == "rgba(10,20,30,0.5)" |
Test conversion from the RGB color space to CIE-L*ab. | def test_rgb_to_lab(r, g, b, L_, a_, b_):
"""Test conversion from the RGB color space to CIE-L*ab."""
rgb = Color(r, g, b)
lab = rgb_to_lab(rgb)
assert lab.L == pytest.approx(L_, abs=0.1)
assert lab.a == pytest.approx(a_, abs=0.1)
assert lab.b == pytest.approx(b_, abs=0.1) |
Test conversion from the CIE-L*ab color space to RGB. | def test_lab_to_rgb(r, g, b, L_, a_, b_):
"""Test conversion from the CIE-L*ab color space to RGB."""
lab = Lab(L_, a_, b_)
rgb = lab_to_rgb(lab)
assert rgb.r == pytest.approx(r, abs=1)
assert rgb.g == pytest.approx(g, abs=1)
assert rgb.b == pytest.approx(b, abs=1) |
Test RGB -> CIE-L*ab -> RGB color conversion roundtripping. | def test_rgb_lab_rgb_roundtrip():
"""Test RGB -> CIE-L*ab -> RGB color conversion roundtripping."""
for r in range(0, 256, 32):
for g in range(0, 256, 32):
for b in range(0, 256, 32):
c_ = lab_to_rgb(rgb_to_lab(Color(r, g, b)))
assert c_.r == pytest.approx(r, abs=1)
assert c_.g == pytest.approx(g, abs=1)
assert c_.b == pytest.approx(b, abs=1) |
Test the call_from_thread method. | def test_call_from_thread():
"""Test the call_from_thread method."""
class BackgroundThread(Thread):
"""A background thread which will modify app in some way."""
def __init__(self, app: App[object]) -> None:
self.app = app
super().__init__()
def run(self) -> None:
def write_stuff(text: str) -> None:
"""Write stuff to a widget."""
self.app.query_one(RichLog).write(text)
self.app.call_from_thread(write_stuff, "Hello")
# Exit the app with a code we can assert
self.app.call_from_thread(self.app.exit, 123)
class ThreadTestApp(App[object]):
"""Trivial app with a single widget."""
def compose(self) -> ComposeResult:
yield RichLog()
def on_ready(self) -> None:
"""Launch a thread which will modify the app."""
try:
self.call_from_thread(print)
except RuntimeError as error:
# Calling this from the same thread as the app is an error
self._runtime_error = error
BackgroundThread(self).start()
app = ThreadTestApp()
result = app.run(headless=True, size=(80, 24))
assert isinstance(app._runtime_error, RuntimeError)
assert result == 123 |
Test if binding merging is done correctly when (not) inheriting bindings. | def test_inherited_bindings():
"""Test if binding merging is done correctly when (not) inheriting bindings."""
class A(DOMNode):
BINDINGS = [("a", "a", "a")]
class B(A):
BINDINGS = [("b", "b", "b")]
class C(B, inherit_bindings=False):
BINDINGS = [("c", "c", "c")]
class D(C, inherit_bindings=False):
pass
class E(D):
BINDINGS = [("e", "e", "e")]
a = A()
assert list(a._bindings.keys.keys()) == ["a"]
b = B()
assert list(b._bindings.keys.keys()) == ["a", "b"]
c = C()
assert list(c._bindings.keys.keys()) == ["c"]
d = D()
assert not list(d._bindings.keys.keys())
e = E()
assert list(e._bindings.keys.keys()) == ["e"] |
Test if component classes are inherited properly. | def test_component_classes_inheritance():
"""Test if component classes are inherited properly."""
class A(DOMNode):
COMPONENT_CLASSES = {"a-1", "a-2"}
class B(A, inherit_component_classes=False):
COMPONENT_CLASSES = {"b-1"}
class C(B):
COMPONENT_CLASSES = {"c-1", "c-2"}
class D(C):
pass
class E(D):
COMPONENT_CLASSES = {"e-1"}
class F(E, inherit_component_classes=False):
COMPONENT_CLASSES = {"f-1"}
node = DOMNode()
node_cc = node._get_component_classes()
a = A()
a_cc = a._get_component_classes()
b = B()
b_cc = b._get_component_classes()
c = C()
c_cc = c._get_component_classes()
d = D()
d_cc = d._get_component_classes()
e = E()
e_cc = e._get_component_classes()
f = F()
f_cc = f._get_component_classes()
assert node_cc == frozenset()
assert a_cc == {"a-1", "a-2"}
assert b_cc == {"b-1"}
assert c_cc == {"b-1", "c-1", "c-2"}
assert d_cc == c_cc
assert e_cc == {"b-1", "c-1", "c-2", "e-1"}
assert f_cc == {"f-1"} |
a
/ b c
/ / d e f | def search():
"""
a
/ \
b c
/ / \
d e f
"""
a = DOMNode(id="a")
b = DOMNode(id="b")
c = DOMNode(id="c")
d = DOMNode(id="d")
e = DOMNode(id="e")
f = DOMNode(id="f")
a._add_child(b)
a._add_child(c)
b._add_child(d)
c._add_child(e)
c._add_child(f)
yield a |
Regression tests for https://github.com/Textualize/textual/issues/3954. | def test_id_validation(identifier: str):
"""Regression tests for https://github.com/Textualize/textual/issues/3954."""
with pytest.raises(BadIdentifier):
DOMNode(id=identifier) |
Test allow_focus and allow_focus_children are called and the result used. | def test_allow_focus():
"""Test allow_focus and allow_focus_children are called and the result used."""
focusable_allow_focus_called = False
non_focusable_allow_focus_called = False
class Focusable(Widget, can_focus=False):
def allow_focus(self) -> bool:
nonlocal focusable_allow_focus_called
focusable_allow_focus_called = True
return True
class NonFocusable(Container, can_focus=True):
def allow_focus(self) -> bool:
nonlocal non_focusable_allow_focus_called
non_focusable_allow_focus_called = True
return False
class FocusableContainer(Container, can_focus_children=False):
def allow_focus_children(self) -> bool:
return True
class NonFocusableContainer(Container, can_focus_children=True):
def allow_focus_children(self) -> bool:
return False
app = App()
app._set_active()
app.push_screen(Screen())
app.screen._add_children(
Focusable(id="foo"),
NonFocusable(id="bar"),
FocusableContainer(Button("egg", id="egg")),
NonFocusableContainer(Button("EGG", id="qux")),
)
assert [widget.id for widget in app.screen.focus_chain] == ["foo", "egg"]
assert focusable_allow_focus_called
assert non_focusable_allow_focus_called |
Ensure focusing the next widget wraps around the focus chain. | def test_focus_next_wrap_around(screen: Screen):
"""Ensure focusing the next widget wraps around the focus chain."""
screen.set_focus(screen.query_one("#child"))
assert screen.focused.id == "child"
assert screen.focus_next().id == "foo" |
Ensure focusing the previous widget wraps around the focus chain. | def test_focus_previous_wrap_around(screen: Screen):
"""Ensure focusing the previous widget wraps around the focus chain."""
screen.set_focus(screen.query_one("#foo"))
assert screen.focused.id == "foo"
assert screen.focus_previous().id == "child" |
Ensure moving focus in both directions wraps around the focus chain. | def test_wrap_around_selector(screen: Screen):
"""Ensure moving focus in both directions wraps around the focus chain."""
screen.set_focus(screen.query_one("#foo"))
assert screen.focused.id == "foo"
assert screen.focus_previous("#Paul").id == "Paul"
assert screen.focus_next("#foo").id == "foo" |
Ensure focus is cleared when selector matches nothing. | def test_no_focus_empty_selector(screen: Screen):
"""Ensure focus is cleared when selector matches nothing."""
assert screen.focus_next("#bananas") is None
assert screen.focus_previous("#bananas") is None
screen.set_focus(screen.query_one("#foo"))
assert screen.focused is not None
assert screen.focus_next("#bananas") is None
assert screen.focused is None
screen.set_focus(screen.query_one("#foo"))
assert screen.focused is not None
assert screen.focus_previous("#bananas") is None
assert screen.focused is None |
Move focus with a selector that matches the currently focused node. | def test_focus_next_and_previous_with_type_selector(screen: Screen):
"""Move focus with a selector that matches the currently focused node."""
screen.set_focus(screen.query_one("#Paul"))
assert screen.focused.id == "Paul"
assert screen.focus_next(Focusable).id == "baz"
assert screen.focus_next(Focusable).id == "child"
assert screen.focus_previous(Focusable).id == "baz"
assert screen.focus_previous(Focusable).id == "Paul"
assert screen.focus_previous(Focusable).id == "container1"
assert screen.focus_previous(Focusable).id == "foo" |
Move focus with a selector that matches the currently focused node. | def test_focus_next_and_previous_with_str_selector(screen: Screen):
"""Move focus with a selector that matches the currently focused node."""
screen.set_focus(screen.query_one("#foo"))
assert screen.focused.id == "foo"
assert screen.focus_next(".a").id == "foo"
assert screen.focus_next(".c").id == "Paul"
assert screen.focus_next(".c").id == "child"
assert screen.focus_previous(".c").id == "Paul"
assert screen.focus_previous(".a").id == "foo" |
Test moving the focus with a selector that does not match the currently focused node. | def test_focus_next_and_previous_with_type_selector_without_self():
"""Test moving the focus with a selector that does not match the currently focused node."""
app = App()
app._set_active()
app.push_screen(Screen())
screen = app.screen
from textual.containers import Horizontal, VerticalScroll
from textual.widgets import Button, Input, Switch
screen._add_children(
VerticalScroll(
Horizontal(
Input(id="w3"),
Switch(id="w4"),
Input(id="w5"),
Button(id="w6"),
Switch(id="w7"),
id="w2",
),
Horizontal(
Button(id="w9"),
Switch(id="w10"),
Button(id="w11"),
Input(id="w12"),
Input(id="w13"),
id="w8",
),
id="w1",
)
)
screen.set_focus(screen.query_one("#w3"))
assert screen.focused.id == "w3"
assert screen.focus_next(Button).id == "w6"
assert screen.focus_next(Switch).id == "w7"
assert screen.focus_next(Input).id == "w12"
assert screen.focus_previous(Button).id == "w11"
assert screen.focus_previous(Switch).id == "w10"
assert screen.focus_previous(Button).id == "w9"
assert screen.focus_previous(Input).id == "w5" |
Test moving the focus with a selector that does not match the currently focused node. | def test_focus_next_and_previous_with_str_selector_without_self(screen: Screen):
"""Test moving the focus with a selector that does not match the currently focused node."""
screen.set_focus(screen.query_one("#foo"))
assert screen.focused.id == "foo"
assert screen.focus_next(".c").id == "Paul"
assert screen.focus_next(".b").id == "baz"
assert screen.focus_next(".c").id == "child"
assert screen.focus_previous(".a").id == "foo"
assert screen.focus_previous(".a").id == "foo"
assert screen.focus_previous(".b").id == "baz" |
Test Size.with_height | def test_size_with_height():
"""Test Size.with_height"""
assert Size(1, 2).with_height(10) == Size(1, 10) |
Test Size.with_width | def test_size_with_width():
"""Test Size.with_width"""
assert Size(1, 2).with_width(10) == Size(10, 2) |
Wrap a sequence of integers inside an immutable sequence view. | def wrap(source: Sequence[int]) -> ImmutableSequenceView[int]:
"""Wrap a sequence of integers inside an immutable sequence view."""
return ImmutableSequenceView[int](source) |
An empty immutable sequence should act as anticipated. | 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([])) == [] |
A non-empty immutable sequence should act as anticipated. | 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] |
It should not be possible to assign into an immutable sequence. | 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 delete an item from an immutable sequence. | 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 be possible to get an item from an immutable sequence. | 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 a slice from an immutable sequence. | 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 see if an immutable sequence contains a value. | 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 |
Test a key display is the same if used in conjunction with another key.
For example, "ctrl+right_square_bracket" should display the bracket as "]",
the same as it would without the ctrl modifier.
Regression test for #3035 https://github.com/Textualize/textual/issues/3035 | def test_get_key_display_when_used_in_conjunction():
"""Test a key display is the same if used in conjunction with another key.
For example, "ctrl+right_square_bracket" should display the bracket as "]",
the same as it would without the ctrl modifier.
Regression test for #3035 https://github.com/Textualize/textual/issues/3035
"""
right_square_bracket = _get_key_display("right_square_bracket")
ctrl_right_square_bracket = _get_key_display("ctrl+right_square_bracket")
assert ctrl_right_square_bracket == f"CTRL+{right_square_bracket}"
left = _get_key_display("left")
ctrl_left = _get_key_display("ctrl+left")
assert ctrl_left == f"CTRL+{left}" |
Check dim filter changes color and resets dim attribute. | def test_dim_apply():
"""Check dim filter changes color and resets dim attribute."""
dim_filter = DimFilter()
segments = [Segment("Hello, World!", Style.parse("dim #ffffff on #0000ff"))]
dimmed_segments = dim_filter.apply(segments, Color(0, 0, 0))
expected = [Segment("Hello, World!", Style.parse("not dim #7f7fff on #0000ff"))]
assert dimmed_segments == expected |
Does an empty node list report as being empty? | def test_empty_list():
"""Does an empty node list report as being empty?"""
assert len(NodeList()) == 0 |
Does adding a node to the node list report as having one item? | def test_add_one():
"""Does adding a node to the node list report as having one item?"""
nodes = NodeList()
nodes._append(Widget())
assert len(nodes) == 1 |
Does adding the same item to the node list ignore the additional adds? | def test_repeat_add_one():
"""Does adding the same item to the node list ignore the additional adds?"""
nodes = NodeList()
widget = Widget()
for _ in range(1000):
nodes._append(widget)
assert len(nodes) == 1 |
Does a node list act as a truthy object? | def test_truthy():
"""Does a node list act as a truthy object?"""
nodes = NodeList()
assert not bool(nodes)
nodes._append(Widget())
assert bool(nodes) |
Can we check if a widget is (not) within the list? | def test_contains():
"""Can we check if a widget is (not) within the list?"""
widget = Widget()
nodes = NodeList()
assert widget not in nodes
nodes._append(widget)
assert widget in nodes
assert Widget() not in nodes |
Can we get the index of a widget in the list? | def test_index():
"""Can we get the index of a widget in the list?"""
widget = Widget()
nodes = NodeList()
with pytest.raises(ValueError):
_ = nodes.index(widget)
nodes._append(widget)
assert nodes.index(widget) == 0 |
Can we remove a widget we've added? | def test_remove():
"""Can we remove a widget we've added?"""
widget = Widget()
nodes = NodeList()
nodes._append(widget)
assert widget in nodes
nodes._remove(widget)
assert widget not in nodes |
Can we clear the list? | def test_clear():
"""Can we clear the list?"""
nodes = NodeList()
assert len(nodes) == 0
widgets = [Widget() for _ in range(1000)]
for widget in widgets:
nodes._append(widget)
assert len(nodes) == 1000
for widget in widgets:
assert widget in nodes
nodes._clear()
assert len(nodes) == 0
for widget in widgets:
assert widget not in nodes |
Check bad selectors raise an error. | def test_on_bad_selector() -> None:
"""Check bad selectors raise an error."""
with pytest.raises(OnDecoratorError):
@on(Button.Pressed, "@")
def foo():
pass |
Check messages with no 'control' attribute raise an error. | def test_on_no_control() -> None:
"""Check messages with no 'control' attribute raise an error."""
class CustomMessage(Message):
pass
with pytest.raises(OnDecoratorError):
@on(CustomMessage, "#foo")
def foo():
pass |
Check `on` checks if the attribute is in ALLOW_SELECTOR_MATCH. | def test_on_attribute_not_listed() -> None:
"""Check `on` checks if the attribute is in ALLOW_SELECTOR_MATCH."""
class CustomMessage(Message):
pass
with pytest.raises(OnDecoratorError):
@on(CustomMessage, foo="bar")
def foo():
pass |
Test resolving fraction units in combination with minimum widths. | def test_resolve_fraction_unit():
"""Test resolving fraction units in combination with minimum widths."""
widget1 = Widget()
widget2 = Widget()
widget3 = Widget()
widget1.styles.width = "1fr"
widget1.styles.min_width = 20
widget2.styles.width = "2fr"
widget2.styles.min_width = 10
widget3.styles.width = "1fr"
styles = (widget1.styles, widget2.styles, widget3.styles)
# Try with width 80.
# Fraction unit should one fourth of width
assert resolve_fraction_unit(
styles,
Size(80, 24),
Size(80, 24),
Fraction(80),
resolve_dimension="width",
) == Fraction(20)
# Try with width 50
# First widget is fixed at 20
# Remaining three widgets have 30 to play with
# Fraction is 10
assert resolve_fraction_unit(
styles,
Size(80, 24),
Size(80, 24),
Fraction(50),
resolve_dimension="width",
) == Fraction(10)
# Try with width 35
# First widget fixed at 20
# Fraction is 5
assert resolve_fraction_unit(
styles,
Size(80, 24),
Size(80, 24),
Fraction(35),
resolve_dimension="width",
) == Fraction(5)
# Try with width 32
# First widget fixed at 20
# Second widget is fixed at 10
# Remaining widget has all the space
# Fraction is 2
assert resolve_fraction_unit(
styles,
Size(80, 24),
Size(80, 24),
Fraction(32),
resolve_dimension="width",
) == Fraction(2) |
Check for zero division errors. | def test_resolve_fraction_unit_stress_test():
"""Check for zero division errors."""
# https://github.com/Textualize/textual/issues/2673
widget = Widget()
styles = widget.styles
styles.width = "1fr"
# We're mainly checking for the absence of zero division errors,
# which is a reoccurring theme for this code.
for remaining_space in range(1, 101, 10):
for max_width in range(1, remaining_space):
styles.max_width = max_width
for width in range(1, remaining_space):
resolved_unit = resolve_fraction_unit(
[styles, styles, styles],
Size(width, 24),
Size(width, 24),
Fraction(remaining_space),
"width",
)
assert resolved_unit <= remaining_space |
Test https://github.com/Textualize/textual/issues/2502 | def test_resolve_issue_2502():
"""Test https://github.com/Textualize/textual/issues/2502"""
widget = Widget()
widget.styles.width = "1fr"
widget.styles.min_width = 11
assert isinstance(
resolve_fraction_unit(
(widget.styles,),
Size(80, 24),
Size(80, 24),
Fraction(10),
resolve_dimension="width",
),
Fraction,
) |
Regression test for an issue found while working on
https://github.com/Textualize/textual/issues/3628 - an extra vertical line
was being produced when aligning. If you passed in a Size of height=1 to
`align_lines`, it was producing a result containing 2 lines instead of 1. | def test_align_lines_vertical_middle():
"""Regression test for an issue found while working on
https://github.com/Textualize/textual/issues/3628 - an extra vertical line
was being produced when aligning. If you passed in a Size of height=1 to
`align_lines`, it was producing a result containing 2 lines instead of 1."""
lines = [[Segment(" "), Segment("hello"), Segment(" ")]]
result = align_lines(
lines, Style(), size=Size(10, 3), horizontal="center", vertical="middle"
)
assert list(result) == [
[Segment(" ", Style())],
[Segment(" "), Segment("hello"), Segment(" ")],
[Segment(" ", Style())],
] |
When the content perfectly fits the available horizontal space,
no empty segments should be produced. This is a regression test for
the issue https://github.com/Textualize/textual/issues/3628. | def test_align_lines_perfect_fit_horizontal_center():
"""When the content perfectly fits the available horizontal space,
no empty segments should be produced. This is a regression test for
the issue https://github.com/Textualize/textual/issues/3628."""
lines = [[Segment(" "), Segment("hello"), Segment(" ")]] # 10 cells of content
result = align_lines(
lines, Style(), size=Size(10, 1), horizontal="center", vertical="middle"
)
assert list(result) == [[Segment(" "), Segment("hello"), Segment(" ")]] |
When the content perfectly fits the available horizontal space,
no empty segments should be produced. This is a regression test for
the issue https://github.com/Textualize/textual/issues/3628. | def test_align_lines_perfect_fit_horizontal_right():
"""When the content perfectly fits the available horizontal space,
no empty segments should be produced. This is a regression test for
the issue https://github.com/Textualize/textual/issues/3628."""
lines = [[Segment(" "), Segment("hello"), Segment(" ")]] # 10 cells of content
result = align_lines(
lines, Style(), size=Size(10, 1), horizontal="right", vertical="middle"
)
assert list(result) == [[Segment(" "), Segment("hello"), Segment(" ")]] |
Check exceptions raised by Signal class. | 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 the repr doesn't break. | def test_repr():
"""Check the repr doesn't break."""
app = App()
test_signal = Signal(app, "test")
assert isinstance(repr(test_signal), str) |
The simple slug function should produce the expected slug. | def test_simple_slug(text: str, expected: str) -> None:
"""The simple slug function should produce the expected slug."""
assert slug(text) == expected |
The tracked slugging class should produce the expected slugs. | def test_tracked_slugs(tracker: TrackedSlugs, text: str, expected: str) -> None:
"""The tracked slugging class should produce the expected slugs."""
assert tracker.slug(text) == expected |
Extract the text content from lines. | 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 |
Test that empty style returns the content un-altered | 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__,
Console(),
"",
"",
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),
]
assert lines == expected |
Check that we only render content once or if it has been marked as dirty. | 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,
Console(),
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,
Console(),
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,
Console(),
None,
None,
content_size=Size(3, 3),
)
assert rendered_lines == [0, 1]
text_content = _extract_content(lines)
assert text_content == expected_text |
Check that none or hidden is normalized to empty string. | def test_box_normalization():
"""Check that none or hidden is normalized to empty string."""
styles = Styles()
styles.border_left = ("none", "red")
assert styles.border_left == ("", Color.parse("red")) |
Style "none" mixed with others should give custom Textual exception. | def test_text_style_none_with_others(style_attr):
"""Style "none" mixed with others should give custom Textual exception."""
styles = Styles()
with pytest.raises(StyleValueError):
setattr(styles, style_attr, "bold none underline italic") |
Setting text style to "none" should clear the styles. | def test_text_style_set_to_none(style_attr):
"""Setting text style to "none" should clear the styles."""
styles = Styles()
setattr(styles, style_attr, "bold underline italic")
assert getattr(styles, style_attr) != Style.null()
setattr(styles, style_attr, "none")
assert getattr(styles, style_attr) == Style.null() |
Regression test for https://github.com/Textualize/textual/issues/4413 | def test_Integer_failure_description_when_NotANumber():
"""Regression test for https://github.com/Textualize/textual/issues/4413"""
validator = Integer()
result = validator.validate("x")
assert result.is_valid is False
assert result.failure_descriptions[0] == "Must be a valid integer." |
Ensure error is raised when bad class names are used for widgets. | 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 |
Regression test for https://github.com/Textualize/textual/issues/2711.
When we exit an app with a "long" timer, everything asyncio-related
should shutdown quickly. So, we create an app with a timer that triggers
every SLEEP_FOR seconds and we shut the app down immediately after creating
it. `asyncio` should be done quickly (i.e., the timer was cancelled) and
thus the total time this takes should be considerably lesser than the time
we originally set the timer for. | def test_win_sleep_timer_is_cancellable():
"""Regression test for https://github.com/Textualize/textual/issues/2711.
When we exit an app with a "long" timer, everything asyncio-related
should shutdown quickly. So, we create an app with a timer that triggers
every SLEEP_FOR seconds and we shut the app down immediately after creating
it. `asyncio` should be done quickly (i.e., the timer was cancelled) and
thus the total time this takes should be considerably lesser than the time
we originally set the timer for.
"""
SLEEP_FOR = 10
class WindowsIntervalBugApp(App[None]):
def on_mount(self) -> None:
self.set_interval(SLEEP_FOR, lambda: None)
def key_e(self):
self.exit()
async def actual_test():
async with WindowsIntervalBugApp().run_test() as pilot:
await pilot.press("e")
start = time.perf_counter()
asyncio.run(actual_test())
end = time.perf_counter()
assert end - start < 1 |
When bracketed paste mode is enabled in the terminal emulator and
the user pastes in some text, it will surround the pasted input
with the escape codes "[200~" and "[201~". The text between
these codes corresponds to a single `Paste` event in Textual. | def test_bracketed_paste(parser):
"""When bracketed paste mode is enabled in the terminal emulator and
the user pastes in some text, it will surround the pasted input
with the escape codes "\x1b[200~" and "\x1b[201~". The text between
these codes corresponds to a single `Paste` event in Textual.
"""
pasted_text = "PASTED"
events = list(parser.feed(f"\x1b[200~{pasted_text}\x1b[201~"))
assert len(events) == 1
assert isinstance(events[0], Paste)
assert events[0].text == pasted_text |
When performing a bracketed paste, if the pasted content contains
supported ANSI escape sequences, it should not interfere with the paste,
and no escape sequences within the bracketed paste should be converted
into Textual events. | def test_bracketed_paste_content_contains_escape_codes(parser):
"""When performing a bracketed paste, if the pasted content contains
supported ANSI escape sequences, it should not interfere with the paste,
and no escape sequences within the bracketed paste should be converted
into Textual events.
"""
pasted_text = "PAS\x0fTED"
events = list(parser.feed(f"\x1b[200~{pasted_text}\x1b[201~"))
assert len(events) == 1
assert events[0].text == pasted_text |
The sequence did not match, and we hit the maximum sequence search
length threshold, so each character should be issued as a key-press instead. | def test_cant_match_escape_sequence_too_long(parser):
"""The sequence did not match, and we hit the maximum sequence search
length threshold, so each character should be issued as a key-press instead.
"""
sequence = "\x1b[123456789123456789123"
events = list(parser.feed(sequence))
# Every character in the sequence is converted to a key press
assert len(events) == len(sequence)
assert all(isinstance(event, Key) for event in events)
# When we backtrack '\x1b' is translated to '^'
assert events[0].key == "circumflex_accent"
# The rest of the characters correspond to the expected key presses
events = events[1:]
for index, character in enumerate(sequence[1:]):
assert events[index].character == character |
When we feed the parser an unknown sequence followed by a known
sequence. The characters in the unknown sequence are delivered as keys,
and the known escape sequence that follows is delivered as expected. | def test_unknown_sequence_followed_by_known_sequence(parser, chunk_size):
"""When we feed the parser an unknown sequence followed by a known
sequence. The characters in the unknown sequence are delivered as keys,
and the known escape sequence that follows is delivered as expected.
"""
unknown_sequence = "\x1b[?"
known_sequence = "\x1b[8~" # key = 'end'
sequence = unknown_sequence + known_sequence
events = []
parser.more_data = lambda: True
for chunk in chunks(sequence, chunk_size):
events.append(parser.feed(chunk))
events = list(itertools.chain.from_iterable(list(event) for event in events))
assert [event.key for event in events] == [
"circumflex_accent",
"left_square_bracket",
"question_mark",
"end",
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.