From 01d8e982cc2ef8009a6b3e38d2b326d77e673c17 Mon Sep 17 00:00:00 2001 From: Umit Akkaya Date: Fri, 1 Sep 2017 17:12:34 +0200 Subject: [PATCH] tags querystring param to filter checks by tags --- hc/api/tests/test_list_checks.py | 36 ++++++++++++++++++++++++++++++++ hc/api/views.py | 5 +++++ 2 files changed, 41 insertions(+) diff --git a/hc/api/tests/test_list_checks.py b/hc/api/tests/test_list_checks.py index 1d7b4a41..6c167b03 100644 --- a/hc/api/tests/test_list_checks.py +++ b/hc/api/tests/test_list_checks.py @@ -20,6 +20,7 @@ class ListChecksTestCase(BaseTestCase): self.a1.last_ping = self.now self.a1.n_pings = 1 self.a1.status = "new" + self.a1.tags = "a1-tag a1-additional-tag" self.a1.save() self.a2 = Check(user=self.alice, name="Alice 2") @@ -27,6 +28,7 @@ class ListChecksTestCase(BaseTestCase): self.a2.grace = td(seconds=3600) self.a2.last_ping = self.now self.a2.status = "up" + self.a2.tags = "a2-tag" self.a2.save() def get(self): @@ -79,3 +81,37 @@ class ListChecksTestCase(BaseTestCase): self.assertEqual(r.status_code, 200) self.assertContains(r, "Alice") + + def test_it_works_with_tags_param(self): + r = self.client.get("/api/v1/checks/?tags=a2-tag", HTTP_X_API_KEY="abc") + self.assertEqual(r.status_code, 200) + + doc = r.json() + self.assertTrue("checks" in doc) + self.assertEqual(len(doc["checks"]), 1) + + check = doc["checks"][0] + + self.assertEqual(check["name"], "Alice 2") + self.assertEqual(check["tags"], "a2-tag") + + def test_it_filters_with_multiple_tags_param(self): + r = self.client.get("/api/v1/checks/?tags=a1-tag&tags=a1-additional-tag", HTTP_X_API_KEY="abc") + self.assertEqual(r.status_code, 200) + + doc = r.json() + self.assertTrue("checks" in doc) + self.assertEqual(len(doc["checks"]), 1) + + check = doc["checks"][0] + + self.assertEqual(check["name"], "Alice 1") + self.assertEqual(check["tags"], "a1-tag a1-additional-tag") + + def test_non_existing_tags_filter_returns_empty_result(self): + r = self.client.get("/api/v1/checks/?tags=non_existing_tag_with_no_checks", HTTP_X_API_KEY="abc") + self.assertEqual(r.status_code, 200) + + doc = r.json() + self.assertTrue("checks" in doc) + self.assertEqual(len(doc["checks"]), 0) diff --git a/hc/api/views.py b/hc/api/views.py index d351b867..6388c3ec 100644 --- a/hc/api/views.py +++ b/hc/api/views.py @@ -104,7 +104,12 @@ def _update(check, spec): @validate_json(schemas.check) def checks(request): if request.method == "GET": + tags = request.GET.getlist('tags', []) q = Check.objects.filter(user=request.user) + + for tag in tags: + q = q.filter(tags__icontains=tag.strip()) + doc = {"checks": [check.to_dict() for check in q]} return JsonResponse(doc)