From b50e697693d6afa0c761e3fdf48f5f0c18a0eca1 Mon Sep 17 00:00:00 2001 From: Charles Merriam Date: Mon, 15 Jul 2024 01:52:13 -0700 Subject: [PATCH] Fix #4722: DataTable add_rows gives incorrect error message (#4742) * Added fix and test case * Update CHANGELOG --------- Co-authored-by: Darren Burns --- CHANGELOG.md | 1 + src/textual/widgets/_data_table.py | 3 +++ tests/test_data_table.py | 8 ++++++++ 3 files changed, 12 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed46c3a9f2..70011f7fc5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Added - `TextArea.line_number_start` reactive attribute https://github.com/Textualize/textual/pull/4471 +- Raise `ValueError` with improved error message when number of cells inserted using `DataTable.add_row` doesn't match the number of columns in the table https://github.com/Textualize/textual/pull/4742 ### Fixed diff --git a/src/textual/widgets/_data_table.py b/src/textual/widgets/_data_table.py index 4d335fecaa..ee77bddbe1 100644 --- a/src/textual/widgets/_data_table.py +++ b/src/textual/widgets/_data_table.py @@ -1576,6 +1576,9 @@ def add_row( # If we don't do this, users will be required to call add_column(s) # Before they call add_row. + if len(cells) > len(self.ordered_columns): + raise ValueError("More values provided than there are columns.") + row_index = self.row_count # Map the key of this row to its current index self._row_locations[row_key] = row_index diff --git a/tests/test_data_table.py b/tests/test_data_table.py index 1320d853f0..63736e5194 100644 --- a/tests/test_data_table.py +++ b/tests/test_data_table.py @@ -254,6 +254,14 @@ async def test_add_row_duplicate_key(): with pytest.raises(DuplicateKey): table.add_row("2", key="1") # Duplicate row key +async def test_add_row_too_many_values(): + app = DataTableApp() + async with app.run_test(): + table = app.query_one(DataTable) + table.add_column("A") + table.add_row("1", key="1") + with pytest.raises(ValueError): + table.add_row("1", "2") async def test_add_column_duplicate_key(): app = DataTableApp()