From 319d6c8b81554effbea4d5fb6ee0ea2eda3ea8ce Mon Sep 17 00:00:00 2001 From: Charlie Denton Date: Sun, 21 Jan 2018 18:18:05 +0000 Subject: [PATCH] Add Route.level property --- conman/routes/models.py | 10 ++++++++++ tests/routes/test_models.py | 12 ++++++++++++ 2 files changed, 22 insertions(+) diff --git a/conman/routes/models.py b/conman/routes/models.py index 3d618e0..f62649e 100644 --- a/conman/routes/models.py +++ b/conman/routes/models.py @@ -136,6 +136,16 @@ def handle(self, request, path): # Deal with the request return handler.handle(request, path) + @property + def level(self): + """Fetch the one-indexed 'level' of this item in the URL tree.""" + return self.url.count('/') + + @level.setter + def level(self, new_value): + """Silently fails to allow queryset annotation to work.""" + pass + def move_to(self, new_url, *, move_children): """ Move this Route to a new url. diff --git a/tests/routes/test_models.py b/tests/routes/test_models.py index 10e109f..03915e2 100644 --- a/tests/routes/test_models.py +++ b/tests/routes/test_models.py @@ -47,6 +47,18 @@ def test_url_form_widget(self): widget = Route._meta.get_field('url').formfield().widget self.assertIsInstance(widget, forms.TextInput) + def test_level(self): + """Route.level is based on the url field.""" + urls = ( + (1, '/'), + (2, '/branch/'), + (3, '/branch/leaf/'), + ) + for level, url in urls: + with self.subTest(url=url): + route = RouteFactory.build(url=url) + self.assertEqual(route.level, level) + class RouteUniquenessTest(TestCase): """Check uniqueness conditions on Route are enforced in the DB."""