From 1b66888bd7aeb170932eaedfa2fbeece85da26ba Mon Sep 17 00:00:00 2001 From: Xavier Bustamante Talavera Date: Fri, 10 Aug 2018 00:52:01 +0200 Subject: [PATCH] Add roots() method in lots --- ereuse_devicehub/resources/inventory.py | 3 ++- ereuse_devicehub/resources/lot/models.py | 5 +++++ tests/test_lot.py | 13 +++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/ereuse_devicehub/resources/inventory.py b/ereuse_devicehub/resources/inventory.py index 087e56c6..10171804 100644 --- a/ereuse_devicehub/resources/inventory.py +++ b/ereuse_devicehub/resources/inventory.py @@ -7,6 +7,7 @@ from sqlalchemy import Column from ereuse_devicehub.resources.device.models import Device from ereuse_devicehub.resources.event.models import Rate +from ereuse_devicehub.resources.lot.models import Lot from ereuse_devicehub.resources.schemas import Thing from ereuse_devicehub.resources.tag import Tag from teal.query import Between, FullTextSearch, ILike, Join, Or, Query, Sort, SortField @@ -97,7 +98,7 @@ class InventoryView(View): .paginate(page=args['page'], per_page=30) # type: Pagination inventory = { 'devices': app.resources[Device.t].schema.dump(devices.items, many=True, nested=1), - 'groups': [], + 'lots': Lot.roots(), 'widgets': {}, 'pagination': { 'page': devices.page, diff --git a/ereuse_devicehub/resources/lot/models.py b/ereuse_devicehub/resources/lot/models.py index c442be42..a264183c 100644 --- a/ereuse_devicehub/resources/lot/models.py +++ b/ereuse_devicehub/resources/lot/models.py @@ -48,6 +48,11 @@ class Lot(Thing): def __contains__(self, child: 'Lot'): return Edge.has_lot(self.id, child.id) + @classmethod + def roots(cls): + """Gets the lots that are not under any other lot.""" + return set(cls.query.join(cls.edges).filter(db.func.nlevel(Edge.path) == 1).all()) + def __repr__(self) -> str: return ''.format(self) diff --git a/tests/test_lot.py b/tests/test_lot.py index e6b9a4d7..97edb752 100644 --- a/tests/test_lot.py +++ b/tests/test_lot.py @@ -168,3 +168,16 @@ def test_lot_unite_graphs(): l2.remove_child(l4) assert l4 not in l2 and l5 not in l2 and l6 not in l2 and l7 not in l2 and l8 not in l2 assert l4 not in l3 and l5 not in l3 and l6 not in l3 and l7 not in l3 and l8 not in l3 + + +@pytest.mark.usefixtures(conftest.auth_app_context.__name__) +def test_lot_roots(): + """Tests getting the method Lot.roots.""" + lots = Lot('1'), Lot('2'), Lot('3') + l1, l2, l3 = lots + db.session.add_all(lots) + db.session.flush() + + assert Lot.roots() == {l1, l2, l3} + l1.add_child(l2) + assert Lot.roots() == {l1, l3}