From 1059449f93ab5783c18d87a78776ee76d771dfe7 Mon Sep 17 00:00:00 2001 From: Nathan McDougall Date: Tue, 13 Aug 2024 23:22:37 +1200 Subject: [PATCH] Fix bug in pin_versions_prune for days arg --- pins/boards.py | 3 ++- pins/tests/test_boards.py | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/pins/boards.py b/pins/boards.py index 7ad07bb..e985d48 100644 --- a/pins/boards.py +++ b/pins/boards.py @@ -473,7 +473,8 @@ def pin_versions_prune(self, name, n: "int | None" = None, days: "int | None" = raise ValueError("Argument days is {days}, but must be greater than 0.") date_cutoff = datetime.today() - timedelta(days=days) - to_delete = [v for v in versions if v.created < date_cutoff] + # Avoid deleting the most recent version + to_delete = [v for v in versions[:-1] if v.created < date_cutoff] # message user about deletions ---- # TODO(question): how to pin_inform? Log or warning? diff --git a/pins/tests/test_boards.py b/pins/tests/test_boards.py index a693a82..ef28f84 100644 --- a/pins/tests/test_boards.py +++ b/pins/tests/test_boards.py @@ -437,6 +437,33 @@ def test_board_pin_versions_prune_days(board, pin_prune, pin_name, days): assert len(new_versions) == days +def test_board_pin_versions_prune_days_protect_most_recent(board, pin_name): + """To address https://github.com/rstudio/pins-python/issues/297""" + # RStudio cannot handle days, since it involves pulling metadata + if board.fs.protocol == "rsc": + with pytest.raises(NotImplementedError): + board.pin_versions_prune(pin_name, days=5) + return + + today = datetime.now() + two_days_ago = today - timedelta(days=2, minutes=1) + three_days_ago = today - timedelta(days=3, minutes=1) + + # Note, we are _not_ going to write a pin for today, otherwise we wouldn't be + # properly testing the protection of the most recent version - it would be trivially + # protected because it would always lie in the last day / fraction of a day. + board.pin_write({"a": 1}, pin_name, type="json", created=two_days_ago) + assert len(board.pin_versions(pin_name, as_df=False)) == 1 + board.pin_write({"a": 2}, pin_name, type="json", created=three_days_ago) + + # prune the versions, keeping only the most recent + board.pin_versions_prune(pin_name, days=1) + + # check that only the most recent version remains + versions = board.pin_versions(pin_name, as_df=False) + assert len(versions) == 1 + + # pin_search ==================================================================