diff --git a/mreg/api/v1/tests/test_filtering.py b/mreg/api/v1/tests/test_filtering.py new file mode 100644 index 00000000..7ad0ee25 --- /dev/null +++ b/mreg/api/v1/tests/test_filtering.py @@ -0,0 +1,67 @@ + +from typing import List + +from mreg.models.host import Host +from mreg.models.resource_records import Cname + +from .tests import MregAPITestCase + +from unittest_parametrize import param +from unittest_parametrize import parametrize +from unittest_parametrize import ParametrizedTestCase + + +class FilterTestCase(ParametrizedTestCase, MregAPITestCase): + """Test filtering.""" + + # endpoint, query_key, target, expected_hits + # + # NOTE: The generated hostnames are UNIQUE across every test case! + # The format is: f"{endpoint}{query_key}{i}.example.com".replace("_", "") + # where i is the index of the hostname (and we make three for each test). + @parametrize( + ("endpoint", "query_key", "target", "expected_hits"), + [ + param("hosts", "name", "hostsname0.example.com", 1, id="hosts_name"), + param("cnames", "host__name", "cnameshostname1.example.com", 1, id="cnames_host__name"), + param("cnames", "host__name__icontains", "cnameshostnameicontains", 3, id="cnames_host__icontains"), + ], + + ) + def test_filtering_for_host(self, endpoint: str, query_key: str, target: str, expected_hits: str) -> None: + """Test filtering on host.""" + + generate_count = 3 + msg_prefix = f"{endpoint} : {query_key} -> {target} => " + + hosts: List[Host] = [] + cnames: List[Cname] = [] + for i in range(generate_count): + hostname = f"{endpoint}{query_key}{i}.example.com".replace("_", "") + hosts.append(Host.objects.create( + name=hostname, + contact="admin@example.com", + ttl=3600, + comment="Test host", + )) + + for i in range(generate_count): + cname = f"cname.{endpoint}{query_key}{i}.example.com".replace("_", "") + cnames.append(Cname.objects.create( + host=hosts[i], + name=cname, + ttl=3600 + )) + + hostname = hosts[0].name + response = self.client.get(f"/api/v1/{endpoint}/?{query_key}={target}") + self.assertEqual(response.status_code, 200) + data = response.json() + self.assertEqual(data["count"], expected_hits, msg=f"{msg_prefix} {data}") + + for host in hosts: + host.delete() + + for cname in cnames: + cname.delete() + diff --git a/requirements-test.txt b/requirements-test.txt index 33462432..e4ddd128 100644 --- a/requirements-test.txt +++ b/requirements-test.txt @@ -16,6 +16,7 @@ tzdata==2024.1 tox pytest pytest-django +unittest_parametrize # These are currently not used, but should be... pylint