From 18d07b5398fac4c92d6677199a06621ef1781e83 Mon Sep 17 00:00:00 2001 From: Colin Maudry Date: Sun, 19 Apr 2026 22:36:55 +0200 Subject: [PATCH] feat: add normalize_sort_by hashable cache-key helper (#72) Add normalize_sort_by function to convert Dash DataTable's sort_by list (unhashable) into a tuple representation (hashable) for use in cache keys. Includes TDD-driven tests for empty inputs, hashability, and order preservation. Co-Authored-By: Claude Sonnet 4.6 --- src/utils/table.py | 6 ++++++ tests/test_table.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/utils/table.py b/src/utils/table.py index 07f832d..871f89b 100644 --- a/src/utils/table.py +++ b/src/utils/table.py @@ -146,6 +146,12 @@ def dates_to_strings(lff: pl.LazyFrame, column: str) -> pl.LazyFrame: return lff +def normalize_sort_by(sort_by) -> tuple: + if not sort_by: + return () + return tuple((entry["column_id"], entry["direction"]) for entry in sort_by) + + def format_number(number) -> str: number = "{:,}".format(number).replace(",", " ") return number diff --git a/tests/test_table.py b/tests/test_table.py index aced802..a633332 100644 --- a/tests/test_table.py +++ b/tests/test_table.py @@ -44,3 +44,37 @@ def test_filter_table_data_does_not_call_track_search(monkeypatch, sample_lff): assert calls == [] assert result.height == 1 + + +def test_normalize_sort_by_handles_empty(): + from src.utils.table import normalize_sort_by + + assert normalize_sort_by(None) == () + assert normalize_sort_by([]) == () + + +def test_normalize_sort_by_returns_hashable_tuple(): + from src.utils.table import normalize_sort_by + + sort_by = [ + {"column_id": "montant", "direction": "desc"}, + {"column_id": "dateNotification", "direction": "asc"}, + ] + key = normalize_sort_by(sort_by) + + assert key == (("montant", "desc"), ("dateNotification", "asc")) + # Must be hashable so that flask-caching can build a cache key from it + hash(key) + + +def test_normalize_sort_by_preserves_order(): + """Order matters for sort: [A, B] != [B, A].""" + from src.utils.table import normalize_sort_by + + a_then_b = normalize_sort_by( + [{"column_id": "a", "direction": "asc"}, {"column_id": "b", "direction": "asc"}] + ) + b_then_a = normalize_sort_by( + [{"column_id": "b", "direction": "asc"}, {"column_id": "a", "direction": "asc"}] + ) + assert a_then_b != b_then_a