Python rest_framework.test.APIClient() Examples

The following are 30 code examples of rest_framework.test.APIClient(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rest_framework.test , or try the search function .
Example #1
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 7 votes vote down vote up
def test_order_by_tag_w_tag_group(self):
        """Test that order by tags with a matching group-by tag works."""
        baseurl = reverse("reports-openshift-aws-instance-type")
        client = APIClient()

        tag_url = reverse("openshift-aws-tags")
        tag_url = tag_url + "?filter[time_scope_value]=-1&key_only=True"
        response = client.get(tag_url, **self.headers)
        tag_keys = response.data.get("data", [])

        for key in tag_keys:
            order_by_dict_key = f"order_by[tag:{key}]"
            group_by_dict_key = f"group_by[tag:{key}]"
            params = {
                "filter[resolution]": "monthly",
                "filter[time_scope_value]": "-1",
                "filter[time_scope_units]": "month",
                order_by_dict_key: random.choice(["asc", "desc"]),
                group_by_dict_key: random.choice(["asc", "desc"]),
            }

            url = baseurl + "?" + urlencode(params, quote_via=quote_plus)
            response = client.get(url, **self.headers)
            self.assertEqual(response.status_code, status.HTTP_200_OK) 
Example #2
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_costs_api_has_units(self):
        """Test that the costs API returns units."""
        url = reverse("reports-openshift-costs")
        client = APIClient()
        response = client.get(url, **self.headers)
        response_json = response.json()

        total = response_json.get("meta", {}).get("total", {})
        data = response_json.get("data", {})
        self.assertTrue("cost" in total)
        self.assertEqual(total.get("cost", {}).get("total", {}).get("units"), "USD")

        for item in data:
            if item.get("values"):
                values = item.get("values")[0]
                self.assertTrue("cost" in values)
                self.assertEqual(values.get("cost", {}).get("total").get("units"), "USD") 
Example #3
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_cpu_last_month(self):
        """Test that data is returned for the last month."""
        url = reverse("reports-openshift-cpu")
        client = APIClient()
        params = {
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-2",
            "filter[time_scope_units]": "month",
        }
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)

        expected_date = self.dh.last_month_start.strftime("%Y-%m")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()
        dates = sorted([item.get("date") for item in data.get("data")])
        self.assertEqual(dates[0], expected_date)

        values = data.get("data")[0].get("values")[0]
        self.assertTrue("limit" in values)
        self.assertTrue("usage" in values)
        self.assertTrue("request" in values) 
Example #4
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_cpu_with_delta_usage__capacity(self):
        """Test that usage v capacity deltas work."""
        delta = "usage__capacity"
        url = reverse("reports-openshift-cpu")
        client = APIClient()
        params = {"delta": delta}
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        delta_one, delta_two = delta.split("__")
        data = response.data
        data = [entry for entry in data.get("data", []) if entry.get("values")]
        self.assertNotEqual(len(data), 0)
        for entry in data:
            values = entry.get("values")[0]
            delta_percent = (
                (values.get(delta_one, {}).get("value") / values.get(delta_two, {}).get("value") * 100)  # noqa: W504
                if values.get(delta_two, {}).get("value")
                else 0
            )
            self.assertEqual(values.get("delta_percent"), delta_percent) 
Example #5
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_cpu_with_delta_usage__request(self):
        """Test that usage v request deltas work."""
        delta = "usage__request"
        url = reverse("reports-openshift-cpu")
        client = APIClient()
        params = {"delta": delta}
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        delta_one, delta_two = delta.split("__")
        data = response.data
        data = [entry for entry in data.get("data", []) if entry.get("values")]
        self.assertNotEqual(len(data), 0)
        for entry in data:
            values = entry.get("values")[0]
            delta_percent = (
                (values.get(delta_one, {}).get("value") / values.get(delta_two, {}).get("value") * 100)  # noqa: W504
                if values.get(delta_two, {}).get("value")
                else 0
            )
            self.assertEqual(values.get("delta_percent"), delta_percent) 
Example #6
Source File: test_html_renderer.py    From DjangoRestMultipleModels with MIT License 6 votes vote down vote up
def test_html_renderer(self):
        """
        Testing bug in which results dict failed to be passed into template context
        """
        client = APIClient()
        response = client.get('/template', format='html')

        # test the data is formatted properly and shows up in the template
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn('data', response.data)
        self.assertContains(response, "Tragedy")
        self.assertContains(response, "<html>")
        self.assertContains(response, "decrepit")

        # test that the JSONRenderer does NOT add the dictionary wrapper to the data
        response = client.get('/template?format=json')

        # test the data is formatted properly and shows up in the template
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertNotIn('data', response.data)
        self.assertNotIn('<html>', response) 
Example #7
Source File: test_viewsets.py    From DjangoRestMultipleModels with MIT License 6 votes vote down vote up
def test_flat_viewset(self):
        """
        Tests the ObjectMutlipleModelAPIViewSet with the default settings
        """
        client = APIClient()
        response = client.get('/flat/', format='api')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(len(response.data), 6)
        self.assertEqual(response.data, [
            {'genre': 'Tragedy', 'title': 'Romeo And Juliet', 'year': 1597, 'type': 'Play'},
            {'genre': 'Comedy', 'title': 'A Midsummer Night\'s Dream', 'year': 1600, 'type': 'Play'},
            {'genre': 'Tragedy', 'title': 'Julius Caesar', 'year': 1623, 'type': 'Play'},
            {'genre': 'Comedy', 'title': 'As You Like It', 'year': 1623, 'type': 'Play'},
            {'title': "Shall I compare thee to a summer's day?", 'style': 'Sonnet', 'type': 'Poem'},
            {'title': "As a decrepit father takes delight", 'style': 'Sonnet', 'type': 'Poem'},
        ]) 
Example #8
Source File: test_viewsets.py    From DjangoRestMultipleModels with MIT License 6 votes vote down vote up
def test_object_viewset(self):
        """
        Tests the ObjectMutlipleModelAPIViewSet with the default settings
        """
        client = APIClient()
        response = client.get('/object/', format='api')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(len(response.data), 2)
        self.assertEqual(response.data, {
            'Play': [
                {'title': 'Romeo And Juliet', 'genre': 'Tragedy', 'year': 1597},
                {'title': "A Midsummer Night's Dream", 'genre': 'Comedy', 'year': 1600},
                {'title': 'Julius Caesar', 'genre': 'Tragedy', 'year': 1623},
                {'title': 'As You Like It', 'genre': 'Comedy', 'year': 1623},
            ],
            'Poem': [
                {'title': "Shall I compare thee to a summer's day?", 'style': 'Sonnet'},
                {'title': "As a decrepit father takes delight", 'style': 'Sonnet'}
            ]
        }) 
Example #9
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_cpu_with_delta_request__capacity(self):
        """Test that request v capacity deltas work."""
        delta = "request__capacity"
        url = reverse("reports-openshift-cpu")
        client = APIClient()
        params = {"delta": delta}
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        delta_one, delta_two = delta.split("__")
        data = response.json()
        data = [entry for entry in data.get("data", []) if entry.get("values")]
        self.assertNotEqual(len(data), 0)
        for entry in data:
            values = entry.get("values")[0]
            delta_percent = (
                (values.get(delta_one, {}).get("value") / values.get(delta_two, {}).get("value") * 100)  # noqa: W504
                if values.get(delta_two)
                else 0
            )
            self.assertAlmostEqual(values.get("delta_percent"), delta_percent) 
Example #10
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_group_by_project(self):
        """Test that grouping by project filters data."""
        with tenant_context(self.tenant):
            # Force Django to do GROUP BY to get nodes
            projects = (
                OCPUsageLineItemDailySummary.objects.filter(usage_start__gte=self.ten_days_ago.date())
                .values(*["namespace"])
                .annotate(project_count=Count("namespace"))
                .all()
            )
            project_of_interest = projects[0].get("namespace")

        url = reverse("reports-openshift-cpu")
        client = APIClient()
        params = {"group_by[project]": project_of_interest}

        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()
        for entry in data.get("data", []):
            for project in entry.get("projects", []):
                self.assertEqual(project.get("project"), project_of_interest) 
Example #11
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_filter_by_project_duplicate_projects(self):
        """Test that same-named projects across clusters are accounted for."""
        data_config = {"namespaces": ["project_one", "project_two"]}
        project_of_interest = data_config["namespaces"][0]

        url = reverse("reports-openshift-cpu")
        client = APIClient()
        params = {"filter[project]": project_of_interest}

        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()
        self.assertNotEqual(data.get("data", []), [])
        for entry in data.get("data", []):
            values = entry.get("values", [])
            if values:
                self.assertEqual(len(values), 1) 
Example #12
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_group_by_cluster(self):
        """Test that grouping by cluster filters data."""
        with tenant_context(self.tenant):
            # Force Django to do GROUP BY to get nodes
            clusters = (
                OCPUsageLineItemDailySummary.objects.filter(usage_start__gte=self.ten_days_ago.date())
                .values(*["cluster_id"])
                .annotate(cluster_count=Count("cluster_id"))
                .all()
            )
            cluster_of_interest = clusters[0].get("cluster_id")

        url = reverse("reports-openshift-cpu")
        client = APIClient()
        params = {"group_by[cluster]": cluster_of_interest}

        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()
        for entry in data.get("data", []):
            for cluster in entry.get("clusters", []):
                self.assertEqual(cluster.get("cluster"), cluster_of_interest) 
Example #13
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_cpu_last_month_daily(self):
        """Test that data is returned for the full month."""
        url = reverse("reports-openshift-cpu")
        client = APIClient()
        params = {"filter[resolution]": "daily", "filter[time_scope_value]": "-2", "filter[time_scope_units]": "month"}
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)

        expected_start_date = self.dh.last_month_start.strftime("%Y-%m-%d")
        expected_end_date = self.dh.last_month_end.strftime("%Y-%m-%d")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()
        dates = sorted([item.get("date") for item in data.get("data")])
        self.assertEqual(dates[0], expected_start_date)
        self.assertEqual(dates[-1], expected_end_date)

        for item in data.get("data"):
            if item.get("values"):
                values = item.get("values")[0]
                self.assertTrue("limit" in values)
                self.assertTrue("usage" in values)
                self.assertTrue("request" in values) 
Example #14
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_cpu_this_month_daily(self):
        """Test that data is returned for the full month."""
        url = reverse("reports-openshift-cpu")
        client = APIClient()
        params = {"filter[resolution]": "daily", "filter[time_scope_value]": "-1", "filter[time_scope_units]": "month"}
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)

        expected_start_date = self.dh.this_month_start.strftime("%Y-%m-%d")
        expected_end_date = self.dh.today.strftime("%Y-%m-%d")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()
        dates = sorted([item.get("date") for item in data.get("data")])
        self.assertEqual(dates[0], expected_start_date)
        self.assertEqual(dates[-1], expected_end_date)

        for item in data.get("data"):
            if item.get("values"):
                values = item.get("values")[0]
                self.assertTrue("limit" in values)
                self.assertTrue("usage" in values)
                self.assertTrue("request" in values) 
Example #15
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_cpu_this_month(self):
        """Test that data is returned for the full month."""
        url = reverse("reports-openshift-cpu")
        client = APIClient()
        params = {
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-1",
            "filter[time_scope_units]": "month",
        }
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)

        expected_date = self.dh.today.strftime("%Y-%m")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()
        dates = sorted([item.get("date") for item in data.get("data")])
        self.assertEqual(dates[0], expected_date)

        values = data.get("data")[0].get("values")[0]
        self.assertTrue("limit" in values)
        self.assertTrue("usage" in values)
        self.assertTrue("request" in values) 
Example #16
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_memory_api_has_units(self):
        """Test that the memory API returns units."""
        url = reverse("reports-openshift-memory")
        client = APIClient()
        response = client.get(url, **self.headers)
        response_json = response.json()

        total = response_json.get("meta", {}).get("total", {})
        data = response_json.get("data", {})
        self.assertTrue("usage" in total)
        self.assertEqual(total.get("usage", {}).get("units"), "GB-Hours")

        for item in data:
            if item.get("values"):
                values = item.get("values")[0]
                self.assertTrue("usage" in values)
                self.assertEqual(values.get("usage", {}).get("units"), "GB-Hours") 
Example #17
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_cpu_api_has_units(self):
        """Test that the CPU API returns units."""
        url = reverse("reports-openshift-cpu")
        client = APIClient()
        response = client.get(url, **self.headers)
        response_json = response.json()

        total = response_json.get("meta", {}).get("total", {})
        data = response_json.get("data", {})
        self.assertTrue("usage" in total)
        self.assertEqual(total.get("usage", {}).get("units"), "Core-Hours")

        for item in data:
            if item.get("values"):
                values = item.get("values")[0]
                self.assertTrue("usage" in values)
                self.assertEqual(values.get("usage", {}).get("units"), "Core-Hours") 
Example #18
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_cpu(self):
        """Test that OCP CPU endpoint works."""
        url = reverse("reports-openshift-cpu")
        client = APIClient()
        response = client.get(url, **self.headers)

        expected_end_date = self.dh.today.date().strftime("%Y-%m-%d")
        expected_start_date = self.ten_days_ago.strftime("%Y-%m-%d")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()
        dates = sorted([item.get("date") for item in data.get("data")])
        self.assertEqual(dates[0], expected_start_date)
        self.assertEqual(dates[-1], expected_end_date)

        for item in data.get("data"):
            if item.get("values"):
                values = item.get("values")[0]
                self.assertTrue("limit" in values)
                self.assertTrue("usage" in values)
                self.assertTrue("request" in values) 
Example #19
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_process_multiple_tag_query_params(self):
        """Test that grouping by multiple tag keys returns a valid response."""
        with tenant_context(self.tenant):
            labels = (
                OCPAWSCostLineItemDailySummary.objects.filter(usage_start__gte=self.ten_days_ago)
                .values(*["tags"])
                .first()
            )
            self.assertIsNotNone(labels)
            tags = labels.get("tags")

        qstr = "filter[limit]=2"

        # pick a random subset of tags
        kval = len(tags.keys())
        if kval > 2:
            kval = random.randint(2, len(tags.keys()))
        selected_tags = random.choices(list(tags.keys()), k=kval)
        for tag in selected_tags:
            qstr += f"&group_by[tag:{tag}]=*"

        url = reverse("reports-openshift-aws-costs") + "?" + qstr
        client = APIClient()
        response = client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_200_OK) 
Example #20
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_aws_storage(self):
        """Test that OCP on AWS Storage endpoint works."""
        url = reverse("reports-openshift-aws-storage")
        client = APIClient()
        response = client.get(url, **self.headers)

        expected_end_date = self.dh.today.date().strftime("%Y-%m-%d")
        expected_start_date = self.ten_days_ago.strftime("%Y-%m-%d")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()
        dates = sorted([item.get("date") for item in data.get("data")])
        self.assertEqual(dates[0], expected_start_date)
        self.assertEqual(dates[-1], expected_end_date)

        for item in data.get("data"):
            if item.get("values"):
                values = item.get("values")[0]
                self.assertTrue("usage" in values)
                self.assertTrue("cost" in values) 
Example #21
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_aws_storage_last_thirty_days(self):
        """Test that OCP CPU endpoint works."""
        url = reverse("reports-openshift-aws-storage")
        client = APIClient()
        params = {"filter[time_scope_value]": "-30", "filter[time_scope_units]": "day", "filter[resolution]": "daily"}
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)

        expected_end_date = self.dh.today
        expected_start_date = self.dh.n_days_ago(expected_end_date, 29)
        expected_end_date = str(expected_end_date.date())
        expected_start_date = str(expected_start_date.date())
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()
        dates = sorted([item.get("date") for item in data.get("data")])
        self.assertEqual(dates[0], expected_start_date)
        self.assertEqual(dates[-1], expected_end_date)

        for item in data.get("data"):
            if item.get("values"):
                values = item.get("values")[0]
                self.assertTrue("usage" in values)
                self.assertTrue("cost" in values) 
Example #22
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_aws_storage_this_month(self):
        """Test that data is returned for the full month."""
        url = reverse("reports-openshift-aws-storage")
        client = APIClient()
        params = {
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-1",
            "filter[time_scope_units]": "month",
        }
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)

        expected_date = self.dh.today.strftime("%Y-%m")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()
        dates = sorted([item.get("date") for item in data.get("data")])
        self.assertEqual(dates[0], expected_date)
        self.assertNotEqual(data.get("data")[0].get("values", []), [])
        values = data.get("data")[0].get("values")[0]
        self.assertTrue("usage" in values)
        self.assertTrue("cost" in values) 
Example #23
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_aws_storage_this_month_daily(self):
        """Test that data is returned for the full month."""
        url = reverse("reports-openshift-aws-storage")
        client = APIClient()
        params = {"filter[resolution]": "daily", "filter[time_scope_value]": "-1", "filter[time_scope_units]": "month"}
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)

        expected_start_date = self.dh.this_month_start.strftime("%Y-%m-%d")
        expected_end_date = self.dh.today.strftime("%Y-%m-%d")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()
        dates = sorted([item.get("date") for item in data.get("data")])
        self.assertEqual(dates[0], expected_start_date)
        self.assertEqual(dates[-1], expected_end_date)

        for item in data.get("data"):
            if item.get("values"):
                values = item.get("values")[0]
                self.assertTrue("usage" in values)
                self.assertTrue("cost" in values) 
Example #24
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_aws_storage_last_month_daily(self):
        """Test that data is returned for the full month."""
        url = reverse("reports-openshift-aws-storage")
        client = APIClient()
        params = {"filter[resolution]": "daily", "filter[time_scope_value]": "-2", "filter[time_scope_units]": "month"}
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)

        expected_start_date = self.dh.last_month_start.strftime("%Y-%m-%d")
        expected_end_date = self.dh.last_month_end.strftime("%Y-%m-%d")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()
        dates = sorted([item.get("date") for item in data.get("data")])
        self.assertEqual(dates[0], expected_start_date)
        self.assertEqual(dates[-1], expected_end_date)

        for item in data.get("data"):
            if item.get("values"):
                values = item.get("values")[0]
                self.assertTrue("usage" in values)
                self.assertTrue("cost" in values) 
Example #25
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_order_by_tag_w_wrong_group(self):
        """Test that order by tags with a non-matching group-by fails."""
        baseurl = reverse("reports-openshift-aws-instance-type")
        client = APIClient()

        tag_url = reverse("openshift-aws-tags")
        tag_url = tag_url + "?filter[time_scope_value]=-1&key_only=True"
        response = client.get(tag_url, **self.headers)
        tag_keys = response.data.get("data", [])

        for key in tag_keys:
            order_by_dict_key = f"order_by[tag:{key}]"
            params = {
                "filter[resolution]": "monthly",
                "filter[time_scope_value]": "-1",
                "filter[time_scope_units]": "month",
                order_by_dict_key: random.choice(["asc", "desc"]),
                "group_by[usage]": random.choice(["asc", "desc"]),
            }

            url = baseurl + "?" + urlencode(params, quote_via=quote_plus)
            response = client.get(url, **self.headers)
            self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) 
Example #26
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_order_by_tag_wo_group(self):
        """Test that order by tags without a group-by fails."""
        baseurl = reverse("reports-openshift-aws-instance-type")
        client = APIClient()

        tag_url = reverse("openshift-aws-tags")
        tag_url = tag_url + "?filter[time_scope_value]=-1&key_only=True"
        response = client.get(tag_url, **self.headers)
        tag_keys = response.data.get("data", [])

        for key in tag_keys:
            order_by_dict_key = f"order_by[tag:{key}]"
            params = {
                "filter[resolution]": "monthly",
                "filter[time_scope_value]": "-1",
                "filter[time_scope_units]": "month",
                order_by_dict_key: random.choice(["asc", "desc"]),
            }

            url = baseurl + "?" + urlencode(params, quote_via=quote_plus)
            response = client.get(url, **self.headers)
            self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) 
Example #27
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_default_pagination(self):
        """Test that the default pagination works."""
        url = reverse("reports-openshift-aws-instance-type")
        client = APIClient()
        params = {
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-1",
            "filter[time_scope_units]": "month",
        }
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        response_data = response.json()
        data = response_data.get("data", [])
        meta = response_data.get("meta", {})
        count = meta.get("count", 0)

        self.assertIn("total", meta)
        self.assertIn("filter", meta)
        self.assertIn("count", meta)

        self.assertEqual(len(data), count) 
Example #28
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_aws_storage_with_group_by_and_limit(self):
        """Test that data is grouped by and limited."""
        url = reverse("reports-openshift-aws-storage")
        client = APIClient()
        params = {
            "group_by[node]": "*",
            "filter[limit]": 1,
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-2",
            "filter[time_scope_units]": "month",
        }
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()
        data = data.get("data", [])
        for entry in data:
            other = entry.get("nodes", [])[-1:]
            self.assertNotEqual(other, [])
            self.assertIn("Other", other[0].get("node")) 
Example #29
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_aws_instance_type(self):
        """Test that the instance type API runs."""
        url = reverse("reports-openshift-aws-instance-type")
        client = APIClient()
        response = client.get(url, **self.headers)

        expected_end_date = self.dh.today.date().strftime("%Y-%m-%d")
        expected_start_date = self.ten_days_ago.strftime("%Y-%m-%d")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()
        dates = sorted([item.get("date") for item in data.get("data")])
        self.assertEqual(dates[0], expected_start_date)
        self.assertEqual(dates[-1], expected_end_date)

        for item in data.get("data"):
            if item.get("values"):
                values = item.get("values")[0]
                self.assertTrue("usage" in values)
                self.assertTrue("cost" in values)
                self.assertTrue("count" in values) 
Example #30
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_execute_query_ocp_aws_costs_group_by_project(self):
        """Test that grouping by project filters data."""
        with tenant_context(self.tenant):
            # Force Django to do GROUP BY to get nodes
            projects = (
                OCPAWSCostLineItemDailySummary.objects.filter(usage_start__gte=self.ten_days_ago)
                .values(*["namespace"])
                .annotate(project_count=Count("namespace"))
                .all()
            )
            project_of_interest = projects[0].get("namespace")

        url = reverse("reports-openshift-aws-costs")
        client = APIClient()
        params = {"group_by[project]": project_of_interest}

        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()
        for entry in data.get("data", []):
            for project in entry.get("projects", []):
                self.assertEqual(project.get("project"), project_of_interest)