From 597dca7c2825ee4ca9e36ef31c5c11a524b0ec80 Mon Sep 17 00:00:00 2001 From: Donkie Date: Wed, 20 Sep 2023 21:02:49 +0200 Subject: [PATCH] Fixed combining empty and non-empty filter Previously it would then act as a wildcard filter --- spoolman/database/utils.py | 25 +++++++++++++++------- tests_integration/tests/spool/test_find.py | 13 +++++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/spoolman/database/utils.py b/spoolman/database/utils.py index 93d0525d6..c9b95273e 100644 --- a/spoolman/database/utils.py +++ b/spoolman/database/utils.py @@ -45,10 +45,15 @@ def add_where_clause_str_opt( ) -> Select: """Add a where clause to a select statement for an optional string field.""" if value is not None: - if len(value) == 0: - stmt = stmt.where(sqlalchemy.or_(field.is_(None), field == "")) - else: - stmt = stmt.where(sqlalchemy.or_(*(field.ilike(f"%{value}%") for value in value.split(",")))) + conditions = [] + for value_part in value.split(","): + if len(value_part) == 0: + conditions.append(field.is_(None)) + conditions.append(field == "") + else: + conditions.append(field.ilike(f"%{value_part}%")) + + stmt = stmt.where(sqlalchemy.or_(*conditions)) return stmt @@ -59,10 +64,14 @@ def add_where_clause_str( ) -> Select: """Add a where clause to a select statement for a string field.""" if value is not None: - if len(value) == 0: - stmt = stmt.where(field == "") - else: - stmt = stmt.where(sqlalchemy.or_(*(field.ilike(f"%{value}%") for value in value.split(",")))) + conditions = [] + for value_part in value.split(","): + if len(value_part) == 0: + conditions.append(field == "") + else: + conditions.append(field.ilike(f"%{value_part}%")) + + stmt = stmt.where(sqlalchemy.or_(*conditions)) return stmt diff --git a/tests_integration/tests/spool/test_find.py b/tests_integration/tests/spool/test_find.py index 7ddf553a1..436869572 100644 --- a/tests_integration/tests/spool/test_find.py +++ b/tests_integration/tests/spool/test_find.py @@ -445,6 +445,19 @@ def test_find_spools_by_empty_location(spools: Fixture): assert spool_lists_equal(spools_result, (spools.spools[3], spools.spools[4])) +def test_find_spools_by_empty_and_filled_location(spools: Fixture): + # Execute + result = httpx.get( + f"{URL}/api/v1/spool", + params={"location": "The Pantry,"}, + ) + result.raise_for_status() + + # Verify + spools_result = result.json() + assert spool_lists_equal(spools_result, (spools.spools[0], spools.spools[3], spools.spools[4])) + + def test_find_spools_by_lot_nr(spools: Fixture): # Execute result = httpx.get(