From 501952abd50ca13ce0635b4eb64bd098c9e23fb4 Mon Sep 17 00:00:00 2001 From: Darren Burns Date: Thu, 19 Jan 2023 14:58:14 +0000 Subject: [PATCH] Add tests around DataTable key generation --- src/textual/widgets/_data_table.py | 7 ++++++- tests/test_data_table.py | 25 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/textual/widgets/_data_table.py b/src/textual/widgets/_data_table.py index 482faa405..b8f208eb3 100644 --- a/src/textual/widgets/_data_table.py +++ b/src/textual/widgets/_data_table.py @@ -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. diff --git a/tests/test_data_table.py b/tests/test_data_table.py index 6ff0192b9..322cc9de4 100644 --- a/tests/test_data_table.py +++ b/tests/test_data_table.py @@ -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"