From afe4ec6df8fad8f3181d9359152a35f32171235d Mon Sep 17 00:00:00 2001 From: Umit Akkaya Date: Thu, 7 Sep 2017 20:32:05 +0200 Subject: [PATCH] Ensure filter matches tag exactly --- hc/api/tests/test_list_checks.py | 14 +++++++++++--- hc/api/views.py | 18 ++++++++++++++---- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/hc/api/tests/test_list_checks.py b/hc/api/tests/test_list_checks.py index 6c167b03..db060379 100644 --- a/hc/api/tests/test_list_checks.py +++ b/hc/api/tests/test_list_checks.py @@ -83,7 +83,7 @@ class ListChecksTestCase(BaseTestCase): 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") + r = self.client.get("/api/v1/checks/?tag=a2-tag", HTTP_X_API_KEY="abc") self.assertEqual(r.status_code, 200) doc = r.json() @@ -96,7 +96,7 @@ class ListChecksTestCase(BaseTestCase): 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") + r = self.client.get("/api/v1/checks/?tag=a1-tag&tag=a1-additional-tag", HTTP_X_API_KEY="abc") self.assertEqual(r.status_code, 200) doc = r.json() @@ -108,8 +108,16 @@ class ListChecksTestCase(BaseTestCase): self.assertEqual(check["name"], "Alice 1") self.assertEqual(check["tags"], "a1-tag a1-additional-tag") + def test_it_does_not_match_tag_partially(self): + r = self.client.get("/api/v1/checks/?tag=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"]), 0) + 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") + r = self.client.get("/api/v1/checks/?tag=non_existing_tag_with_no_checks", HTTP_X_API_KEY="abc") self.assertEqual(r.status_code, 200) doc = r.json() diff --git a/hc/api/views.py b/hc/api/views.py index 6388c3ec..1f7aa27c 100644 --- a/hc/api/views.py +++ b/hc/api/views.py @@ -104,13 +104,23 @@ def _update(check, spec): @validate_json(schemas.check) def checks(request): if request.method == "GET": - tags = request.GET.getlist('tags', []) + tags = request.GET.getlist('tag', []) q = Check.objects.filter(user=request.user) - for tag in tags: - q = q.filter(tags__icontains=tag.strip()) + doc = {"checks": []} + + if len(tags) > 0: + for tag in tags: + q = q.filter(tags__contains=tag.strip()) + + tags_set = set(tags) + + for check in q: + if tags_set.issubset(set(check.tags_list())): + doc["checks"].append(check.to_dict()) + else: + doc["checks"] = [check.to_dict() for check in q] - doc = {"checks": [check.to_dict() for check in q]} return JsonResponse(doc) elif request.method == "POST":