Add tests around DataTable key generation

This commit is contained in:
Darren Burns
2023-01-19 14:58:14 +00:00
parent 57863cd6cd
commit 501952abd5
2 changed files with 31 additions and 1 deletions

View File

@@ -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.

View File

@@ -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"