Use Fairphone staff client instead of admin user for tests
authorMitja Nikolaus <mitja@fairphone.com>
Mon, 5 Nov 2018 09:00:53 +0000 (10:00 +0100)
committerMitja Nikolaus <mitja@fairphone.com>
Fri, 23 Nov 2018 14:48:02 +0000 (15:48 +0100)
Run tests against the REST API using a client that is related to a
Fairphone staff user instead of an admin user.

Issue: HIC-249
Change-Id: I33666235ff186fef566bdb0aa6e7a9c768856949

crashreport_stats/tests/test_rest_endpoints.py
crashreport_stats/tests/test_views.py
crashreport_stats/tests/utils.py
crashreports/tests/test_rest_api_devices.py
crashreports/tests/test_rest_api_heartbeats.py
crashreports/tests/test_rest_api_logfiles.py
crashreports/tests/utils.py

index bf35b6b..b24d71e 100644 (file)
@@ -36,10 +36,6 @@ class StatusTestCase(HiccupStatsAPITestCase):
         self.assertEqual(response.data["crashreports"], num_crashreports)
         self.assertEqual(response.data["heartbeats"], num_heartbeats)
 
-    def test_status_url_as_admin(self):
-        """Test that admin users can access the status URL."""
-        self._assert_get_as_admin_user_succeeds(self.status_url)
-
     def test_status_url_as_fp_staff(self):
         """Test that Fairphone staff users can access the status URL."""
         self._assert_get_as_fp_staff_succeeds(self.status_url)
@@ -88,7 +84,7 @@ class _VersionTestCase(HiccupStatsAPITestCase):
         return Dummy.create_dummy_version(**kwargs)
 
     def _get_with_params(self, url, params):
-        return self.admin.get("{}?{}".format(url, urlencode(params)))
+        return self.fp_staff_client.get("{}?{}".format(url, urlencode(params)))
 
     def _assert_result_length_is(self, response, count):
         self.assertEqual(response.status_code, status.HTTP_200_OK)
@@ -131,10 +127,6 @@ class VersionTestCase(_VersionTestCase):
         ]
         return versions
 
-    def test_endpoint_url_as_admin(self):
-        """Test that admin users can access the endpoint URL."""
-        self._assert_get_as_admin_user_succeeds(self.endpoint_url)
-
     def test_endpoint_url_as_fp_staff(self):
         """Test that Fairphone staff users can access the endpoint URL."""
         self._assert_get_as_fp_staff_succeeds(self.endpoint_url)
@@ -149,19 +141,19 @@ class VersionTestCase(_VersionTestCase):
 
     def test_list_versions_empty_database(self):
         """Test listing of versions on an empty database."""
-        response = self.admin.get(self.endpoint_url)
+        response = self.fp_staff_client.get(self.endpoint_url)
         self._assert_result_length_is(response, 0)
 
     def test_list_versions(self):
         """Test listing versions."""
         versions = self._create_version_entities()
-        response = self.admin.get(self.endpoint_url)
+        response = self.fp_staff_client.get(self.endpoint_url)
         self._assert_result_length_is(response, len(versions))
 
     def test_filter_versions_by_unique_entry_name(self):
         """Test filtering versions by their unique entry name."""
         versions = self._create_version_entities()
-        response = self.admin.get(self.endpoint_url)
+        response = self.fp_staff_client.get(self.endpoint_url)
 
         # Listing all entities should return the correct result length
         self._assert_result_length_is(response, len(versions))
@@ -196,7 +188,7 @@ class VersionTestCase(_VersionTestCase):
                 i += 1
 
         # # Listing all entities should return the correct result length
-        response = self.admin.get(self.endpoint_url)
+        response = self.fp_staff_client.get(self.endpoint_url)
         self._assert_result_length_is(response, len(versions))
 
         # List each of the entities with the matching filter params
@@ -221,7 +213,7 @@ class VersionTestCase(_VersionTestCase):
         versions[0].save()
 
         # Listing all entities should return the correct result length
-        response = self.admin.get(self.endpoint_url)
+        response = self.fp_staff_client.get(self.endpoint_url)
         self._assert_result_length_is(response, len(versions))
 
         # Expect the single matching result to be returned
@@ -269,10 +261,6 @@ class VersionDailyTestCase(_VersionTestCase):
         ]
         return versions_daily
 
-    def test_endpoint_url_as_admin(self):
-        """Test that admin users can access the endpoint URL."""
-        self._assert_get_as_admin_user_succeeds(self.endpoint_url)
-
     def test_endpoint_url_as_fp_staff(self):
         """Test that Fairphone staff users can access the endpoint URL."""
         self._assert_get_as_fp_staff_succeeds(self.endpoint_url)
@@ -287,13 +275,13 @@ class VersionDailyTestCase(_VersionTestCase):
 
     def test_list_daily_versions_empty_database(self):
         """Test listing of daily versions on an empty database."""
-        response = self.admin.get(self.endpoint_url)
+        response = self.fp_staff_client.get(self.endpoint_url)
         self._assert_result_length_is(response, 0)
 
     def test_list_daily_versions(self):
         """Test listing daily versions."""
         versions_daily = self._create_version_entities()
-        response = self.admin.get(self.endpoint_url)
+        response = self.fp_staff_client.get(self.endpoint_url)
         self._assert_result_length_is(response, len(versions_daily))
 
     def test_filter_daily_versions_by_version(self):
@@ -302,7 +290,7 @@ class VersionDailyTestCase(_VersionTestCase):
         versions = self._create_version_entities()
 
         # Listing all entities should return the correct result length
-        response = self.admin.get(self.endpoint_url)
+        response = self.fp_staff_client.get(self.endpoint_url)
         self._assert_result_length_is(response, len(versions))
 
         # List entities with filter
@@ -327,7 +315,7 @@ class VersionDailyTestCase(_VersionTestCase):
         versions[0].save()
 
         # Listing all entities should return the correct result length
-        response = self.admin.get(self.endpoint_url)
+        response = self.fp_staff_client.get(self.endpoint_url)
         self._assert_result_length_is(response, len(versions))
 
         # Expect the single matching result to be returned
@@ -402,15 +390,6 @@ class DeviceStatsTestCase(HiccupStatsAPITestCase):
         self.assertEqual(response.data["smpl_per_day"], smpl_per_day)
         self.assertEqual(response.data["last_active"], last_active)
 
-    def test_device_overview_url_as_admin(self):
-        """Test that admin users can access the URL."""
-        self._assert_get_as_admin_user_succeeds(
-            reverse(
-                self.device_overview_url,
-                kwargs={"uuid": self.device_owner_device.uuid},
-            )
-        )
-
     def test_device_overview_url_as_fp_staff(self):
         """Test that Fairphone staff users can access the URL."""
         self._assert_get_as_fp_staff_succeeds(
@@ -438,15 +417,6 @@ class DeviceStatsTestCase(HiccupStatsAPITestCase):
             )
         )
 
-    def test_device_report_history_url_as_admin(self):
-        """Test that admin users can access device report history URL."""
-        self._assert_get_as_admin_user_succeeds(
-            reverse(
-                self.device_report_history_url,
-                kwargs={"uuid": self.device_owner_device.uuid},
-            )
-        )
-
     def test_device_report_history_url_as_fp_staff(self):
         """Test that FP staff can access device report history URL."""
         self._assert_get_as_fp_staff_succeeds(
@@ -474,15 +444,6 @@ class DeviceStatsTestCase(HiccupStatsAPITestCase):
             )
         )
 
-    def test_device_update_history_url_as_admin(self):
-        """Test that admin users can access device update history URL."""
-        self._assert_get_as_admin_user_succeeds(
-            reverse(
-                self.device_update_history_url,
-                kwargs={"uuid": self.device_owner_device.uuid},
-            )
-        )
-
     def test_device_update_history_url_as_fp_staff(self):
         """Test that FP staff can access device update history URL."""
         self._assert_get_as_fp_staff_succeeds(
@@ -510,20 +471,6 @@ class DeviceStatsTestCase(HiccupStatsAPITestCase):
             )
         )
 
-    def test_logfile_download_url_as_admin(self):
-        """Test that admin users can access the logfile download URL."""
-        non_existent_logfile_id = 0
-        self.assertFalse(
-            LogFile.objects.filter(id=non_existent_logfile_id).exists()
-        )
-        self._assert_get_as_admin_user_succeeds(
-            reverse(
-                self.device_logfile_download_url,
-                kwargs={"id_logfile": non_existent_logfile_id},
-            ),
-            expected_status=status.HTTP_404_NOT_FOUND,
-        )
-
     def tes_logfile_download_url_as_fp_staff(self):
         """Test that FP staff can access the logfile download URL."""
         non_existent_logfile_id = 0
index 0965f75..adcec7d 100644 (file)
@@ -31,10 +31,6 @@ class ViewsTestCase(HiccupStatsAPITestCase):
     def _get_with_params(self, url, params):
         return self.fp_staff_client.get(self._url_with_params(url, params))
 
-    def test_home_view_as_admin(self):
-        """Test that admin users can access the home view."""
-        self._assert_get_as_admin_user_succeeds(self.home_url)
-
     def test_home_view_as_fp_staff(self):
         """Test that Fairphone staff users can access the home view."""
         self._assert_get_as_fp_staff_succeeds(self.home_url)
@@ -53,14 +49,6 @@ class ViewsTestCase(HiccupStatsAPITestCase):
             self.home_url, expected_status=status.HTTP_302_FOUND
         )
 
-    def test_device_view_as_admin(self):
-        """Test that admin users can access the device view."""
-        self._assert_get_as_admin_user_succeeds(
-            self._url_with_params(
-                self.device_url, {"uuid": self.device_owner_device.uuid}
-            )
-        )
-
     def test_device_view_as_fp_staff(self):
         """Test that Fairphone staff users can access the device view."""
         self._assert_get_as_fp_staff_succeeds(
@@ -89,10 +77,6 @@ class ViewsTestCase(HiccupStatsAPITestCase):
             expected_status=status.HTTP_302_FOUND,
         )
 
-    def test_versions_view_as_admin(self):
-        """Test that admin users can access the versions view."""
-        self._assert_get_as_admin_user_succeeds(self.versions_url)
-
     def test_versions_view_as_fp_staff(self):
         """Test that Fairphone staff users can access the versions view."""
         self._assert_get_as_fp_staff_succeeds(self.versions_url)
@@ -111,10 +95,6 @@ class ViewsTestCase(HiccupStatsAPITestCase):
             self.versions_url, expected_status=status.HTTP_302_FOUND
         )
 
-    def test_versions_all_view_as_admin(self):
-        """Test that admin users can access the versions all view."""
-        self._assert_get_as_admin_user_succeeds(self.versions_all_url)
-
     def test_versions_all_view_as_fp_staff(self):
         """Test that Fairphone staff users can access the versions all view."""
         self._assert_get_as_fp_staff_succeeds(self.versions_all_url)
@@ -133,20 +113,6 @@ class ViewsTestCase(HiccupStatsAPITestCase):
             self.versions_all_url, expected_status=status.HTTP_302_FOUND
         )
 
-    def test_home_view_post_as_admin_user(self):
-        """Test HTTP POST method to home view as admin user."""
-        response = self.admin.post(
-            self.home_url, data={"uuid": str(self.device_owner_device.uuid)}
-        )
-
-        # Assert that the response is a redirect to the device page
-        self.assertRedirects(
-            response,
-            self._url_with_params(
-                self.device_url, {"uuid": self.device_owner_device.uuid}
-            ),
-        )
-
     def test_home_view_post_as_fp_staff(self):
         """Test HTTP POST method to home view as Fairphone staff user."""
         response = self.fp_staff_client.post(
index 279320b..8db1d0f 100644 (file)
@@ -322,20 +322,13 @@ class HiccupStatsAPITestCase(APITestCase):
 
     @classmethod
     def setUpTestData(cls):  # noqa: N802
-        """Create an admin and two client users for accessing the API.
+        """Create client users for accessing the API.
 
         The APIClient that can be used to make authenticated requests as
-        admin user is stored in self.admin. A client which is related to a
-        user that is part of the Fairphone staff group is stored in
-        self.fp_staff_client. A client which is related to a device owner
-        user is stored in self.device_owner_client.
+        Fairphone staff user is stored in self.fp_staff_client. Additionally, a
+        client which is related to a device owner user is stored in
+        self.device_owner_client.
         """
-        admin_user = User.objects.create_superuser(
-            "somebody", "somebody@example.com", "thepassword"
-        )
-        cls.admin = APIClient()
-        cls.admin.force_login(admin_user)
-
         fp_staff_group = Group.objects.get(name=FP_STAFF_GROUP_NAME)
         fp_staff_user = User.objects.create_user(
             "fp_staff", "somebody@fairphone.com", "thepassword"
@@ -356,12 +349,6 @@ class HiccupStatsAPITestCase(APITestCase):
             HTTP_AUTHORIZATION="Token " + cls.device_owner_user.auth_token.key
         )
 
-    def _assert_get_as_admin_user_succeeds(
-        self, url, expected_status=status.HTTP_200_OK
-    ):
-        response = self.admin.get(url)
-        self.assertEqual(response.status_code, expected_status)
-
     def _assert_get_as_fp_staff_succeeds(
         self, url, expected_status=status.HTTP_200_OK
     ):
index d023ce5..512a56a 100644 (file)
@@ -89,7 +89,7 @@ class ListDevicesTestCase(HiccupCrashreportsAPITestCase):
             str(self._register_device()[0]) for _ in range(number_of_devices)
         ]
 
-        response = self.admin.get(reverse(self.LIST_CREATE_URL), {})
+        response = self.fp_staff_client.get(reverse(self.LIST_CREATE_URL), {})
         self.assertEqual(response.status_code, status.HTTP_200_OK)
         self.assertEqual(len(response.data["results"]), number_of_devices)
         for result in response.data["results"]:
@@ -101,9 +101,11 @@ class ListDevicesTestCase(HiccupCrashreportsAPITestCase):
         self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
 
     def test_retrieve_device_auth(self):
-        """Test retrieval of devices as admin user."""
+        """Test retrieval of devices as Fairphone staff user."""
         uuid, _, token = self._register_device()
-        response = self.admin.get(reverse(self.RETRIEVE_URL, args=[uuid]), {})
+        response = self.fp_staff_client.get(
+            reverse(self.RETRIEVE_URL, args=[uuid]), {}
+        )
         self.assertEqual(response.status_code, status.HTTP_200_OK)
         self.assertEqual(response.data["uuid"], str(uuid))
         self.assertEqual(response.data["token"], token)
@@ -115,10 +117,10 @@ class ListDevicesTestCase(HiccupCrashreportsAPITestCase):
         self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
 
     def test_delete_device_auth(self):
-        """Test deletion of devices as admin user."""
+        """Test deletion of devices as Fairphone staff user."""
         uuid, _, _ = self._register_device()
         url = reverse(self.RETRIEVE_URL, args=[uuid])
-        response = self.admin.delete(url, {})
+        response = self.fp_staff_client.delete(url, {})
         self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
-        response = self.admin.delete(url, {})
+        response = self.fp_staff_client.delete(url, {})
         self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
index 04b7477..c4e72d3 100644 (file)
@@ -28,7 +28,7 @@ class HeartbeatsTestCase(HiccupCrashreportsAPITestCase):
 
     def _retrieve_single(self, user):
         count = 5
-        response = self._post_multiple(self.admin, self.data, count)
+        response = self._post_multiple(self.fp_staff_client, self.data, count)
         self.assertEqual(len(response), count)
         self.assertEqual(response[0].status_code, status.HTTP_201_CREATED)
         url = reverse(self.RETRIEVE_URL, args=[response[0].data["id"]])
@@ -59,15 +59,17 @@ class HeartbeatsTestCase(HiccupCrashreportsAPITestCase):
         response = noauth_client.post(reverse(self.LIST_CREATE_URL), self.data)
         self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
 
-    def test_create_as_admin(self):
-        """Test creation as admin."""
-        response = self.admin.post(reverse(self.LIST_CREATE_URL), self.data)
+    def test_create_as_fp_staff(self):
+        """Test creation as Fairphone staff."""
+        response = self.fp_staff_client.post(
+            reverse(self.LIST_CREATE_URL), self.data
+        )
         self.assertEqual(response.status_code, status.HTTP_201_CREATED)
         self.assertTrue(response.data["id"] > 0)
 
-    def test_create_as_admin_not_existing_device(self):
+    def test_create_as_fp_staff_not_existing_device(self):
         """Test creation of heartbeat on non-existing device."""
-        response = self.admin.post(
+        response = self.fp_staff_client.post(
             reverse(self.LIST_CREATE_URL), self._create_dummy_data()
         )
         self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
@@ -93,13 +95,15 @@ class HeartbeatsTestCase(HiccupCrashreportsAPITestCase):
         """Test listing of heartbeats."""
         count = 5
         self._post_multiple(self.user, self.data, count)
-        response = self.admin.get(reverse(self.LIST_CREATE_URL))
+        response = self.fp_staff_client.get(reverse(self.LIST_CREATE_URL))
         self.assertEqual(response.status_code, status.HTTP_200_OK)
         self.assertEqual(len(response.data["results"]), count)
 
-    def test_retrieve_single_admin(self):
-        """Test retrieval as admin."""
-        self.assertEqual(self._retrieve_single(self.admin), status.HTTP_200_OK)
+    def test_retrieve_single_fp_staff(self):
+        """Test retrieval as Fairphone staff."""
+        self.assertEqual(
+            self._retrieve_single(self.fp_staff_client), status.HTTP_200_OK
+        )
 
     def test_retrieve_single_device_owner(self):
         """Test retrieval as device owner."""
@@ -114,10 +118,11 @@ class HeartbeatsTestCase(HiccupCrashreportsAPITestCase):
             self._retrieve_single(noauth_client), status.HTTP_401_UNAUTHORIZED
         )
 
-    def test_retrieve_single_by_device_admin(self):
-        """Test retrieval by device as admin."""
+    def test_retrieve_single_by_device_fp_staff(self):
+        """Test retrieval by device as Fairphone staff."""
         self.assertEqual(
-            self._retrieve_single_by_device(self.admin), status.HTTP_200_OK
+            self._retrieve_single_by_device(self.fp_staff_client),
+            status.HTTP_200_OK,
         )
 
     def test_retrieve_single_by_device_device_owner(self):
@@ -141,10 +146,10 @@ class HeartbeatsTestCase(HiccupCrashreportsAPITestCase):
         uuid, _, _ = self._register_device()
         self._post_multiple(self.user, self.data, count)
         self._post_multiple(
-            self.admin, self._create_dummy_data(uuid=uuid), count
+            self.fp_staff_client, self._create_dummy_data(uuid=uuid), count
         )
         url = reverse(self.LIST_CREATE_BY_UUID_URL, args=[self.uuid])
-        response = self.admin.get(url)
+        response = self.fp_staff_client.get(url)
         self.assertEqual(response.status_code, status.HTTP_200_OK)
         self.assertEqual(len(response.data["results"]), count)
 
@@ -170,7 +175,7 @@ class HeartbeatsTestCase(HiccupCrashreportsAPITestCase):
         response = self.user.post(reverse(self.LIST_CREATE_URL), data)
         self.assertEqual(response.status_code, status.HTTP_201_CREATED)
         url = reverse(self.LIST_CREATE_BY_UUID_URL, args=[self.uuid])
-        response = self.admin.get(url)
+        response = self.fp_staff_client.get(url)
         self.assertEqual(response.status_code, status.HTTP_200_OK)
         self.assertEqual(len(response.data["results"]), 1)
         self.assertIsNone(response.data["results"][0]["radio_version"])
@@ -180,7 +185,7 @@ class HeartbeatsTestCase(HiccupCrashreportsAPITestCase):
         response = self.user.post(reverse(self.LIST_CREATE_URL), self.data)
         self.assertEqual(response.status_code, status.HTTP_201_CREATED)
         url = reverse(self.LIST_CREATE_BY_UUID_URL, args=[self.uuid])
-        response = self.admin.get(url)
+        response = self.fp_staff_client.get(url)
         self.assertEqual(response.status_code, status.HTTP_200_OK)
         self.assertEqual(len(response.data["results"]), 1)
         self.assertEqual(
index 56c6f1c..afe8abb 100644 (file)
@@ -98,9 +98,9 @@ class LogfileUploadTest(HiccupCrashreportsAPITestCase):
         """Test upload of logfiles as device owner."""
         self._test_logfile_upload(self.user, self.device_uuid)
 
-    def test_logfile_upload_as_admin(self):
-        """Test upload of logfiles as admin user."""
-        self._test_logfile_upload(self.admin, self.device_uuid)
+    def test_logfile_upload_as_fp_staff(self):
+        """Test upload of logfiles as Fairphone staff user."""
+        self._test_logfile_upload(self.fp_staff_client, self.device_uuid)
 
     def tearDown(self):
         """Remove the file and directories that were created for the test."""
index 15ace6b..1202fce 100644 (file)
@@ -3,12 +3,13 @@
 import os
 from typing import Optional
 
-from django.contrib.auth.models import User
+from django.contrib.auth.models import User, Group
 from django.urls import reverse
 from rest_framework import status
 from rest_framework.test import APITestCase, APIClient
 
 from crashreports.models import Crashreport
+from hiccup.allauth_adapters import FP_STAFF_GROUP_NAME
 
 DEFAULT_DUMMY_LOG_FILE_DIRECTORY = os.path.join("resources", "test")
 
@@ -137,16 +138,18 @@ class HiccupCrashreportsAPITestCase(APITestCase):
     REGISTER_DEVICE_URL = "api_v1_register_device"
 
     def setUp(self):
-        """Create an admin user for accessing the API.
+        """Create a Fairphone staff user for accessing the API.
 
         The APIClient that can be used to make authenticated requests to the
-        server is stored in self.admin.
+        server is stored in self.fp_staff_client.
         """
-        admin_user = User.objects.create_superuser(
-            "somebody", "somebody@example.com", "thepassword"
+        fp_staff_group = Group.objects.get(name=FP_STAFF_GROUP_NAME)
+        fp_staff_user = User.objects.create_user(
+            "fp_staff", "somebody@fairphone.com", "thepassword"
         )
-        self.admin = APIClient()
-        self.admin.force_authenticate(admin_user)
+        fp_staff_user.groups.add(fp_staff_group)
+        self.fp_staff_client = APIClient()
+        self.fp_staff_client.force_login(fp_staff_user)
 
     def _register_device(self, **kwargs):
         """Register a new device.