From ac34c57574679b3039d38e966535b4923313f23b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89lie=20Bouttier?= Date: Tue, 8 Oct 2024 14:42:59 +0200 Subject: [PATCH] feat(taxref): taxons comparison through path --- apptax/taxonomie/models.py | 8 +++++++ apptax/tests/test_models.py | 46 +++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 apptax/tests/test_models.py diff --git a/apptax/taxonomie/models.py b/apptax/taxonomie/models.py index 9b16f9cc..090bf105 100644 --- a/apptax/taxonomie/models.py +++ b/apptax/taxonomie/models.py @@ -230,6 +230,9 @@ def where_params(cls, filters=None, *, query): query = query.filter(col.ilike(value + "%")) return query + def __le__(self, other): + return self.tree <= other.tree + @serializable class BibListes(db.Model): @@ -546,6 +549,11 @@ class TaxrefTree(db.Model): taxref = db.relationship(Taxref, backref=backref("tree", uselist=False)) path = db.Column(db.String, nullable=False) + def __le__(self, other): + # self <= other means taxon other is the same or a parent of self + p1, p2 = self.path.split("."), other.path.split(".") + return len(p1) >= len(p2) and p1[: len(p2)] == p2 + # Taxref deffered properties diff --git a/apptax/tests/test_models.py b/apptax/tests/test_models.py new file mode 100644 index 00000000..b59ab1e1 --- /dev/null +++ b/apptax/tests/test_models.py @@ -0,0 +1,46 @@ +import pytest +import sqlalchemy as sa + +from .fixtures import * +from apptax.taxonomie.models import Taxref, TaxrefTree + + +@pytest.mark.usefixtures("client_class", "temporary_transaction") +class TestModels: + def test_taxref_tree_comparison(self): + animalia = db.session.execute( + sa.select(TaxrefTree).where(TaxrefTree.cd_nom == 183716) + ).scalar_one() + capra_ibex = db.session.execute( + sa.select(TaxrefTree).where(TaxrefTree.cd_nom == 61098) + ).scalar_one() + cinnamon = db.session.execute( + sa.select(TaxrefTree).where(TaxrefTree.cd_nom == 706584) + ).scalar_one() + + assert animalia <= animalia + assert capra_ibex <= animalia + assert not animalia <= capra_ibex + assert not cinnamon <= animalia + assert not animalia <= cinnamon + assert not cinnamon <= capra_ibex + assert not capra_ibex <= cinnamon + + def test_taxref_comparison(self): + animalia = db.session.execute( + sa.select(Taxref).where(Taxref.cd_nom == 183716) + ).scalar_one() + capra_ibex = db.session.execute( + sa.select(Taxref).where(Taxref.cd_nom == 61098) + ).scalar_one() + cinnamon = db.session.execute( + sa.select(Taxref).where(Taxref.cd_nom == 706584) + ).scalar_one() + + assert animalia <= animalia + assert capra_ibex <= animalia + assert not animalia <= capra_ibex + assert not cinnamon <= animalia + assert not animalia <= cinnamon + assert not cinnamon <= capra_ibex + assert not capra_ibex <= cinnamon