From: Christian Heller Date: Thu, 2 May 2024 00:14:53 +0000 (+0200) Subject: Always check if item is saved before removal attempt. X-Git-Url: https://plomlompom.com/repos/%7B%7Bprefix%7D%7D/static/templates?a=commitdiff_plain;h=9c68e4b443a695652f2ba3acae126ad02e3f6ffa;p=plomtask Always check if item is saved before removal attempt. --- diff --git a/plomtask/db.py b/plomtask/db.py index 3a661d3..0509492 100644 --- a/plomtask/db.py +++ b/plomtask/db.py @@ -261,6 +261,7 @@ class BaseModel(Generic[BaseModelId]): def remove(self, db_conn: DatabaseConnection) -> None: """Remove from DB and cache.""" - assert isinstance(self.id_, int | str) + if self.id_ is None or self.__class__.get_cached(self.id_) is None: + raise HandledException('cannot remove unsaved item') self.uncache() db_conn.delete_where(self.table_name, 'id', self.id_) diff --git a/tests/days.py b/tests/days.py index f67c80a..ffc2ab2 100644 --- a/tests/days.py +++ b/tests/days.py @@ -3,7 +3,8 @@ from unittest import TestCase from datetime import datetime from tests.utils import TestCaseWithDB, TestCaseWithServer from plomtask.days import Day, todays_date -from plomtask.exceptions import BadFormatException, NotFoundException +from plomtask.exceptions import (BadFormatException, NotFoundException, + HandledException) class TestsSansDB(TestCase): @@ -67,6 +68,16 @@ class TestsWithDB(TestCaseWithDB): self.assertEqual(day.id_, date) self.assertEqual(day.comment, comment) + def test_Day_from_table_row(self) -> None: + """Test .from_table_row() properly reads in class from DB""" + day = Day('2024-01-01') + day.save(self.db_conn) + assert isinstance(day.id_, str) + for row in self.db_conn.row_where(Day.table_name, 'id', day.id_): + retrieved = Day.from_table_row(self.db_conn, row) + self.assertEqual(day, retrieved) + self.assertEqual({day.id_: day}, Day.get_cache()) + def test_Day_by_id(self) -> None: """Test .by_id().""" date1 = '2024-01-01' @@ -91,9 +102,11 @@ class TestsWithDB(TestCaseWithDB): day1 = Day(date1) day2 = Day(date2) day3 = Day(date3) + # check pre-save .all() returns empty list + self.assertEqual(Day.all(self.db_conn), []) + # check that all() shows all saved, but no unsaved items day1.save(self.db_conn) day3.save(self.db_conn) - # check that all() shows all saved, but no unsaved items self.assertEqual(Day.all(self.db_conn), [day1, day3]) day2.save(self.db_conn) @@ -135,6 +148,8 @@ class TestsWithDB(TestCaseWithDB): """Test .remove() effects on DB and cache.""" date = '2024-01-01' day = Day(date) + with self.assertRaises(HandledException): + day.remove(self.db_conn) day.save(self.db_conn) day.remove(self.db_conn) self.check_storage([]) diff --git a/tests/processes.py b/tests/processes.py index 3d861b7..ce7f857 100644 --- a/tests/processes.py +++ b/tests/processes.py @@ -23,7 +23,7 @@ class TestsSansDB(TestCase): class TestsWithDB(TestCaseWithDB): - """Mdule tests not requiring DB setup.""" + """Module tests requiring DB setup.""" def setUp(self) -> None: super().setUp()