mirror of
https://github.com/Textualize/textual.git
synced 2025-10-17 02:38:12 +03:00
Add tests around DataTable key generation
This commit is contained in:
@@ -35,15 +35,20 @@ class CellDoesNotExist(Exception):
|
||||
pass
|
||||
|
||||
|
||||
# TODO: Revisit?
|
||||
class Key(NamedTuple):
|
||||
value: str | None
|
||||
|
||||
def __hash__(self):
|
||||
# TODO: Revisit
|
||||
# If a string is supplied, we use the hash of the string.
|
||||
# If no string was supplied, we use the default hash to ensure uniqueness amongst instances.
|
||||
return hash(self.value) if self.value is not None else super().__hash__(self)
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
# Strings will match Keys containing the same string value.
|
||||
# Otherwise, you'll need to supply the exact same key object.
|
||||
return hash(self) == hash(other)
|
||||
|
||||
|
||||
def default_cell_formatter(obj: object) -> RenderableType | None:
|
||||
"""Format a cell in to a renderable.
|
||||
|
||||
@@ -2,6 +2,7 @@ from textual.app import App
|
||||
from textual.coordinate import Coordinate
|
||||
from textual.message import Message
|
||||
from textual.widgets import DataTable
|
||||
from textual.widgets._data_table import Key
|
||||
|
||||
|
||||
class DataTableApp(App):
|
||||
@@ -147,3 +148,27 @@ async def test_clear():
|
||||
# Clearing the columns too
|
||||
table.clear(columns=True)
|
||||
assert len(table.columns) == 0
|
||||
|
||||
|
||||
def test_key_equals_equivalent_string():
|
||||
text = "Hello"
|
||||
key = Key(text)
|
||||
assert key == text
|
||||
assert hash(key) == hash(text)
|
||||
|
||||
|
||||
def test_key_doesnt_match_non_equal_string():
|
||||
key = Key("123")
|
||||
text = "laksjdlaskjd"
|
||||
assert key != text
|
||||
assert hash(key) != hash(text)
|
||||
|
||||
|
||||
def test_key_string_lookup():
|
||||
# Indirectly covered by other tests, but let's explicitly show how
|
||||
# we intend for the keys to work for cache lookups.
|
||||
dictionary = {
|
||||
"hello": "world",
|
||||
}
|
||||
assert dictionary["hello"] == "world"
|
||||
assert dictionary[Key("hello")] == "world"
|
||||
|
||||
Reference in New Issue
Block a user