this repo has no description
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

fix: cleanup and refactor tests (#1584)

it refactor tests

authored by

Aakash Singh and committed by
GitHub
c94f4642 ed4fcbee

+700 -963
+12 -24
care/facility/models/tests/test_patient.py
··· 1 - from care.facility.models import DiseaseStatusEnum, PatientRegistration 2 - from care.users.models import District, State 3 - from care.utils.tests.test_base import TestBase 1 + from rest_framework.test import APITestCase 4 2 3 + from care.facility.models import DiseaseStatusEnum 4 + from care.utils.tests.test_utils import TestUtils 5 5 6 - class PatientRegistrationTest(TestBase): 7 - @classmethod 8 - def setUpTestData(cls): 9 - super().setUpTestData() 10 - cls.state = State.objects.create(name="tripura") 11 - cls.district = District.objects.create(state=cls.state, name="agartala") 12 - cls.patient_data = cls.get_patient_data(district=cls.district, state=cls.state) 13 - cls.patient = cls._create_patient(cls.patient_data) 14 6 7 + class PatientRegistrationTest(TestUtils, APITestCase): 15 8 @classmethod 16 - def _create_patient(cls, data): 17 - data = data.copy() 18 - data.pop("medical_history", []) 19 - data.pop("state", "") 20 - data.pop("district", "") 21 - data.pop("disease_status", 0) 22 - data.update( 23 - { 24 - "state_id": cls.state.id, 25 - "district_id": cls.district.id, 26 - } 27 - ) 28 - return PatientRegistration.objects.create(**data) 9 + def setUpTestData(cls): 10 + cls.state = cls.create_state() 11 + cls.district = cls.create_district(cls.state) 12 + cls.local_body = cls.create_local_body(cls.district) 13 + cls.super_user = cls.create_super_user("su", cls.district) 14 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 15 + cls.user = cls.create_user("staff1", cls.district, home_facility=cls.facility) 16 + cls.patient = cls.create_patient(cls.district, cls.facility) 29 17 30 18 def test_disease_state_recovery_is_aliased_to_recovered(self): 31 19 patient = self.patient
-48
care/facility/tests/mixins.py
··· 1 - from django.test import TestCase 2 - from rest_framework.test import APIRequestFactory, force_authenticate 3 - 4 - from care.users.models import District, LocalBody, State, User, Ward 5 - 6 - 7 - class TestClassMixin(TestCase): 8 - def setUp(self): 9 - self.factory = APIRequestFactory() 10 - state = State.objects.create(name="Kerala") 11 - district = District.objects.create(state=state, name="Ernakulam") 12 - local_body = LocalBody.objects.create( 13 - district=district, name="Test Local Body", body_type=20, localbody_code="T1" 14 - ) 15 - ward = Ward.objects.create(local_body=local_body, name="Test Ward", number=1) 16 - self.users = [ 17 - User.objects.create_user( 18 - username="distAdmin", 19 - user_type=30, 20 - phone_number="+919898989898", 21 - gender=1, 22 - age=18, 23 - ward=ward, 24 - district=district, 25 - local_body=local_body, 26 - state=state, 27 - verified=True, 28 - ), 29 - ] 30 - 31 - def new_request(self, params, method, viewset, authenticate=False, pk=None): 32 - if pk is None: 33 - pk = {} 34 - 35 - request_methods = { 36 - "get": self.factory.get, 37 - "post": self.factory.post, 38 - "patch": self.factory.patch, 39 - "put": self.factory.put, 40 - "delete": self.factory.delete, 41 - } 42 - 43 - method_type = list(method.keys())[0] 44 - request = request_methods[method_type](*params) 45 - view = viewset.as_view(method) 46 - if authenticate: 47 - force_authenticate(request, user=authenticate) 48 - return view(request, **pk)
+33 -34
care/facility/tests/test_asset_api.py
··· 1 - from django.utils.timezone import datetime, make_aware 1 + from django.utils.timezone import datetime 2 2 from rest_framework import status 3 - from rest_framework.test import APIRequestFactory, APITestCase 3 + from rest_framework.test import APITestCase 4 4 5 - from care.facility.models import Asset, AssetLocation, Bed, User 6 - from care.utils.tests.test_base import TestBase 5 + from care.facility.models import Asset, Bed 6 + from care.utils.tests.test_utils import TestUtils 7 7 8 8 9 - class AssetViewSetTestCase(TestBase, APITestCase): 10 - asset_id = None 11 - 9 + class AssetViewSetTestCase(TestUtils, APITestCase): 12 10 @classmethod 13 - def setUpClass(cls): 14 - super().setUpClass() 15 - cls.factory = APIRequestFactory() 16 - state = cls.create_state() 17 - district = cls.create_district(state=state) 18 - cls.user = cls.create_user(district=district, username="test user") 19 - cls.facility = cls.create_facility(district=district, user=cls.user) 20 - cls.asset1_location = AssetLocation.objects.create( 21 - name="asset1 location", location_type=1, facility=cls.facility 11 + def setUpTestData(cls) -> None: 12 + cls.state = cls.create_state() 13 + cls.district = cls.create_district(cls.state) 14 + cls.local_body = cls.create_local_body(cls.district) 15 + cls.super_user = cls.create_super_user("su", cls.district) 16 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 17 + cls.asset_location = cls.create_asset_location(cls.facility) 18 + cls.user = cls.create_user("staff", cls.district, home_facility=cls.facility) 19 + cls.patient = cls.create_patient( 20 + cls.district, cls.facility, local_body=cls.local_body 22 21 ) 23 - cls.asset = Asset.objects.create( 24 - name="Test Asset", 25 - current_location=cls.asset1_location, 26 - asset_type=50, 27 - warranty_amc_end_of_validity=make_aware(datetime(2021, 4, 1)), 28 - ) 22 + 23 + def setUp(self) -> None: 24 + super().setUp() 25 + self.asset = self.create_asset(self.asset_location) 29 26 30 27 def test_list_assets(self): 31 28 response = self.client.get("/api/v1/asset/") ··· 34 31 def test_create_asset(self): 35 32 sample_data = { 36 33 "name": "Test Asset", 37 - "current_location": self.asset1_location.pk, 34 + "current_location": self.asset_location.pk, 38 35 "asset_type": 50, 39 - "location": self.asset1_location.external_id, 36 + "location": self.asset_location.external_id, 40 37 } 41 38 response = self.client.post("/api/v1/asset/", sample_data) 42 39 self.assertEqual(response.status_code, status.HTTP_201_CREATED) ··· 44 41 def test_create_asset_with_warranty_past(self): 45 42 sample_data = { 46 43 "name": "Test Asset", 47 - "current_location": self.asset1_location.pk, 44 + "current_location": self.asset_location.pk, 48 45 "asset_type": 50, 49 - "location": self.asset1_location.external_id, 46 + "location": self.asset_location.external_id, 50 47 "warranty_amc_end_of_validity": "2000-04-01", 51 48 } 52 49 response = self.client.post("/api/v1/asset/", sample_data) ··· 59 56 def test_update_asset(self): 60 57 sample_data = { 61 58 "name": "Updated Test Asset", 62 - "current_location": self.asset1_location.pk, 59 + "current_location": self.asset_location.pk, 63 60 "asset_type": 50, 64 - "location": self.asset1_location.external_id, 61 + "location": self.asset_location.external_id, 65 62 } 66 63 response = self.client.patch( 67 64 f"/api/v1/asset/{self.asset.external_id}/", sample_data ··· 95 92 self.assertEqual(Asset.objects.filter(pk=self.asset.pk).exists(), True) 96 93 97 94 def test_delete_asset(self): 98 - self.user.user_type = User.TYPE_VALUE_MAP["DistrictAdmin"] 99 - self.user.save() 95 + user = self.create_user( 96 + "distadmin", self.district, home_facility=self.facility, user_type=30 97 + ) 98 + self.client.force_authenticate(user=user) 100 99 response = self.client.delete( 101 100 f"/api/v1/asset/{self.asset.external_id}/", 102 101 ) ··· 105 104 106 105 def test_asset_filter_in_use_by_consultation(self): 107 106 asset1 = Asset.objects.create( 108 - name="asset1", current_location=self.asset1_location 107 + name="asset1", current_location=self.asset_location 109 108 ) 110 109 asset2 = Asset.objects.create( 111 - name="asset2", current_location=self.asset1_location 110 + name="asset2", current_location=self.asset_location 112 111 ) 113 112 114 - consultation = self.create_consultation() 113 + consultation = self.create_consultation(self.patient, self.facility) 115 114 bed = Bed.objects.create( 116 - name="bed1", location=self.asset1_location, facility=self.facility 115 + name="bed1", location=self.asset_location, facility=self.facility 117 116 ) 118 117 self.client.post( 119 118 "/api/v1/consultationbed/",
+16 -34
care/facility/tests/test_asset_availability_api.py
··· 1 1 from django.utils import timezone 2 2 from rest_framework import status 3 - from rest_framework.test import APIRequestFactory, APITestCase 3 + from rest_framework.test import APITestCase 4 4 5 - from care.facility.api.viewsets.asset import AssetAvailabilityViewSet 6 - from care.facility.models import Asset, AssetAvailabilityRecord, AssetLocation 5 + from care.facility.models import AssetAvailabilityRecord 7 6 from care.facility.models.asset import AvailabilityStatus 8 - from care.facility.tests.mixins import TestClassMixin 9 - from care.utils.tests.test_base import TestBase 7 + from care.utils.tests.test_utils import TestUtils 10 8 11 9 12 - class AssetAvailabilityViewSetTestCase(TestBase, TestClassMixin, APITestCase): 10 + class AssetAvailabilityViewSetTestCase(TestUtils, APITestCase): 13 11 @classmethod 14 - def setUp(cls): 15 - cls.factory = APIRequestFactory() 16 - state = cls.create_state() 17 - district = cls.create_district(state=state) 18 - cls.user = cls.create_user(district=district, username="test user") 19 - facility = cls.create_facility(district=district, user=cls.user) 20 - cls.asset_from_location = AssetLocation.objects.create( 21 - name="asset from location", location_type=1, facility=facility 22 - ) 23 - cls.asset_to_location = AssetLocation.objects.create( 24 - name="asset to location", location_type=1, facility=facility 25 - ) 26 - cls.asset = Asset.objects.create( 27 - name="Test Asset", current_location=cls.asset_from_location, asset_type=50 28 - ) 29 - 12 + def setUpTestData(cls) -> None: 13 + cls.state = cls.create_state() 14 + cls.district = cls.create_district(cls.state) 15 + cls.local_body = cls.create_local_body(cls.district) 16 + cls.super_user = cls.create_super_user("su", cls.district) 17 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 18 + cls.user = cls.create_user("staff1", cls.district, home_facility=cls.facility) 19 + cls.asset_location = cls.create_asset_location(cls.facility) 20 + cls.asset = cls.create_asset(cls.asset_location) 30 21 cls.asset_availability = AssetAvailabilityRecord.objects.create( 31 22 asset=cls.asset, 32 23 status=AvailabilityStatus.OPERATIONAL.value, ··· 34 25 ) 35 26 36 27 def test_list_asset_availability(self): 37 - response = self.new_request( 38 - ("/api/v1/asset_availability/",), 39 - {"get": "list"}, 40 - AssetAvailabilityViewSet, 41 - True, 42 - ) 28 + response = self.client.get("/api/v1/asset_availability/") 43 29 self.assertEqual(response.status_code, status.HTTP_200_OK) 44 30 self.assertEqual( 45 31 response.data["results"][0]["status"], AvailabilityStatus.OPERATIONAL.value 46 32 ) 47 33 48 34 def test_retrieve_asset_availability(self): 49 - response = self.new_request( 50 - (f"/api/v1/asset_availability/{self.asset_availability.id}/",), 51 - {"get": "retrieve"}, 52 - AssetAvailabilityViewSet, 53 - True, 54 - {"pk": self.asset_availability.id}, 35 + response = self.client.get( 36 + f"/api/v1/asset_availability/{self.asset_availability.id}/" 55 37 ) 56 38 self.assertEqual(response.status_code, status.HTTP_200_OK) 57 39 self.assertEqual(response.data["status"], AvailabilityStatus.OPERATIONAL.value)
+22 -53
care/facility/tests/test_asset_location_api.py
··· 1 1 from rest_framework import status 2 - from rest_framework.test import APIRequestFactory, APITestCase 2 + from rest_framework.test import APITestCase 3 3 4 - from care.facility.api.viewsets.asset import AssetLocationViewSet 5 - from care.facility.models import AssetLocation 6 - from care.facility.tests.mixins import TestClassMixin 7 - from care.utils.tests.test_base import TestBase 4 + from care.utils.tests.test_utils import TestUtils 8 5 9 6 10 - class AssetLocationViewSetTestCase(TestBase, TestClassMixin, APITestCase): 11 - def setUp(self): 12 - self.factory = APIRequestFactory() 13 - state = self.create_state() 14 - district = self.create_district(state=state) 15 - self.user = self.create_user(district=district, username="test user") 16 - self.facility = self.create_facility(district=district, user=self.user) 17 - self.asset_location = AssetLocation.objects.create( 18 - name="asset location", location_type=1, facility=self.facility 19 - ) 7 + class AssetLocationViewSetTestCase(TestUtils, APITestCase): 8 + @classmethod 9 + def setUpTestData(cls) -> None: 10 + cls.state = cls.create_state() 11 + cls.district = cls.create_district(cls.state) 12 + cls.local_body = cls.create_local_body(cls.district) 13 + cls.super_user = cls.create_super_user("su", cls.district) 14 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 15 + cls.asset_location = cls.create_asset_location(cls.facility) 16 + cls.user = cls.create_user("staff", cls.district, home_facility=cls.facility) 20 17 21 18 def test_list_asset_locations(self): 22 - response = self.new_request( 23 - (f"/api/v1/asset_location/{self.facility.external_id}",), 24 - {"get": "list"}, 25 - AssetLocationViewSet, 26 - self.user, 27 - {"facility_external_id": self.facility.external_id}, 19 + response = self.client.get( 20 + f"/api/v1/facility/{self.facility.external_id}/asset_location/" 28 21 ) 29 22 self.assertEqual(response.status_code, status.HTTP_200_OK) 30 23 self.assertContains(response, self.asset_location.external_id) 31 24 32 25 def test_retrieve_asset_location(self): 33 - response = self.new_request( 34 - ("/api/v1/asset_location/{self.facility.external_id}/",), 35 - {"get": "retrieve"}, 36 - AssetLocationViewSet, 37 - self.user, 38 - { 39 - "facility_external_id": self.facility.external_id, 40 - "external_id": self.asset_location.external_id, 41 - }, 26 + response = self.client.get( 27 + f"/api/v1/facility/{self.facility.external_id}/asset_location/{self.asset_location.external_id}/" 42 28 ) 43 29 self.assertEqual(response.status_code, status.HTTP_200_OK) 44 30 self.assertContains(response, self.asset_location.external_id) 45 31 46 32 def test_create_asset_location(self): 47 33 sample_data = {"name": "Test Asset Location"} 48 - response = self.new_request( 49 - ( 50 - "/api/v1/asset-location/{self.facility.external_id}/", 51 - sample_data, 52 - "json", 53 - ), 54 - {"post": "create"}, 55 - AssetLocationViewSet, 56 - self.user, 57 - {"facility_external_id": self.facility.external_id}, 34 + response = self.client.post( 35 + f"/api/v1/facility/{self.facility.external_id}/asset_location/", 36 + sample_data, 58 37 ) 59 38 self.assertEqual(response.status_code, status.HTTP_201_CREATED) 60 39 61 40 def test_update_asset_location(self): 62 41 sample_data = {"name": "Updated Test Asset Location"} 63 - response = self.new_request( 64 - ( 65 - "/api/v1/asset-location/{self.facility.external_id}/", 66 - sample_data, 67 - "json", 68 - ), 69 - {"patch": "partial_update"}, 70 - AssetLocationViewSet, 71 - self.user, 72 - { 73 - "facility_external_id": self.facility.external_id, 74 - "external_id": self.asset_location.external_id, 75 - }, 42 + response = self.client.patch( 43 + f"/api/v1/facility/{self.facility.external_id}/asset_location/{self.asset_location.external_id}/", 44 + sample_data, 76 45 ) 77 46 self.assertEqual(response.status_code, status.HTTP_200_OK) 78 47 self.assertEqual(response.data["name"], sample_data["name"])
+15 -47
care/facility/tests/test_asset_public_api.py
··· 1 - from django.core.cache import cache 2 1 from rest_framework import status 3 - from rest_framework.test import APIRequestFactory, APITestCase 2 + from rest_framework.test import APITestCase 4 3 5 - from care.facility.api.viewsets.asset import AssetPublicViewSet 6 - from care.facility.models import Asset, AssetLocation 7 - from care.facility.tests.mixins import TestClassMixin 8 - from care.utils.tests.test_base import TestBase 4 + from care.utils.tests.test_utils import TestUtils 9 5 10 6 11 - class AssetPublicViewSetTestCase(TestBase, TestClassMixin, APITestCase): 12 - def setUp(self): 13 - self.factory = APIRequestFactory() 14 - state = self.create_state() 15 - district = self.create_district(state=state) 16 - self.user = self.create_user(district=district, username="test user") 17 - facility = self.create_facility(district=district, user=self.user) 18 - self.asset_location = AssetLocation.objects.create( 19 - name="asset1 location", location_type=1, facility=facility 20 - ) 21 - self.asset = Asset.objects.create( 22 - name="Test Asset", current_location=self.asset_location, asset_type=50 23 - ) 7 + class AssetPublicViewSetTestCase(TestUtils, APITestCase): 8 + @classmethod 9 + def setUpTestData(cls) -> None: 10 + cls.state = cls.create_state() 11 + cls.district = cls.create_district(cls.state) 12 + cls.local_body = cls.create_local_body(cls.district) 13 + cls.super_user = cls.create_super_user("su", cls.district) 14 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 15 + cls.asset_location = cls.create_asset_location(cls.facility) 16 + cls.asset = cls.create_asset(cls.asset_location) 17 + cls.user = cls.create_user("staff1", cls.district, home_facility=cls.facility) 24 18 25 19 def test_retrieve_asset(self): 26 - response = self.new_request( 27 - (f"/api/v1/public/asset/{self.asset.external_id}/",), 28 - {"get": "retrieve"}, 29 - AssetPublicViewSet, 30 - self.user, 31 - {"external_id": str(self.asset.external_id)}, 32 - ) 20 + response = self.client.get(f"/api/v1/public/asset/{self.asset.external_id}/") 33 21 self.assertEqual(response.status_code, status.HTTP_200_OK) 34 22 35 - def test_retrieve_cached_asset(self): 36 - key = "asset:" + str(self.asset.external_id) 37 - cache.set(key, {"name": "Cached Asset"}, 60 * 60 * 24) 38 - 39 - response = self.new_request( 40 - (f"/api/v1/public/asset/{self.asset.external_id}/",), 41 - {"get": "retrieve"}, 42 - AssetPublicViewSet, 43 - self.user, 44 - {"external_id": str(self.asset.external_id)}, 45 - ) 46 - self.assertEqual(response.status_code, status.HTTP_200_OK) 47 - self.assertEqual(response.data["name"], "Cached Asset") 48 - 49 23 def test_retrieve_nonexistent_asset(self): 50 - response = self.new_request( 51 - ("/api/v1/public/asset/nonexistent/",), 52 - {"get": "retrieve"}, 53 - AssetPublicViewSet, 54 - self.user, 55 - {"external_id": "nonexistent"}, 56 - ) 24 + response = self.client.get("/api/v1/public/asset/nonexistent/") 57 25 self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+36 -83
care/facility/tests/test_asset_service_history_api.py
··· 2 2 3 3 from django.utils.timezone import now 4 4 from rest_framework import status 5 - from rest_framework.test import APIRequestFactory, APITestCase 5 + from rest_framework.test import APITestCase 6 6 7 - from care.facility.api.viewsets.asset import AssetServiceViewSet, AssetViewSet 8 - from care.facility.models import Asset, AssetLocation, AssetService 7 + from care.facility.models import AssetService 9 8 from care.facility.models.asset import AssetServiceEdit 10 - from care.facility.tests.mixins import TestClassMixin 11 - from care.utils.tests.test_base import TestBase 9 + from care.utils.tests.test_utils import TestUtils 12 10 13 11 14 - class AssetServiceViewSetTestCase(TestBase, TestClassMixin, APITestCase): 15 - def setUp(self): 16 - self.today = datetime.today().strftime("%Y-%m-%d") 17 - self.yesterday = (datetime.today() - timedelta(days=1)).strftime("%Y-%m-%d") 18 - self.factory = APIRequestFactory() 19 - state = self.create_state() 20 - district = self.create_district(state=state) 21 - self.user = self.create_user(district=district, username="test user") 22 - facility = self.create_facility(district=district, user=self.user) 23 - self.asset_location = AssetLocation.objects.create( 24 - name="asset from location", location_type=1, facility=facility 25 - ) 26 - self.asset = Asset.objects.create( 27 - name="Test Asset", current_location=self.asset_location, asset_type=50 28 - ) 29 - self.asset_service = AssetService.objects.create( 30 - asset=self.asset, 31 - serviced_on=self.today, 12 + class AssetServiceViewSetTestCase(TestUtils, APITestCase): 13 + @classmethod 14 + def setUpTestData(cls): 15 + cls.state = cls.create_state() 16 + cls.district = cls.create_district(cls.state) 17 + cls.local_body = cls.create_local_body(cls.district) 18 + cls.super_user = cls.create_super_user("su", cls.district) 19 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 20 + cls.asset_location = cls.create_asset_location(cls.facility) 21 + cls.asset = cls.create_asset(cls.asset_location) 22 + cls.user = cls.create_user("staff", cls.district, home_facility=cls.facility) 23 + cls.today = datetime.today().strftime("%Y-%m-%d") 24 + cls.yesterday = (datetime.today() - timedelta(days=1)).strftime("%Y-%m-%d") 25 + cls.asset_service = AssetService.objects.create( 26 + asset=cls.asset, 27 + serviced_on=cls.today, 32 28 note="Test Note", 33 29 ) 34 - self.asset_service_initital_edit = AssetServiceEdit.objects.create( 35 - asset_service=self.asset_service, 36 - serviced_on=self.today, 30 + cls.asset_service_initital_edit = AssetServiceEdit.objects.create( 31 + asset_service=cls.asset_service, 32 + serviced_on=cls.today, 37 33 note="Test Note", 38 34 edited_on=now(), 39 - edited_by=self.user, 35 + edited_by=cls.user, 40 36 ) 41 37 42 38 def test_list_asset_service(self): 43 - response = self.new_request( 44 - (f"/api/v1/asset/{self.asset.external_id}/service_records/",), 45 - {"get": "list"}, 46 - AssetServiceViewSet, 47 - self.user, 48 - {"asset_external_id": self.asset.external_id}, 39 + response = self.client.get( 40 + f"/api/v1/asset/{self.asset.external_id}/service_records/" 49 41 ) 50 42 self.assertEqual(response.status_code, status.HTTP_200_OK) 51 43 52 44 def test_retrieve_asset_service(self): 53 - response = self.new_request( 54 - ( 55 - f"/api/v1/asset/{self.asset.external_id}/service_records/{self.asset_service.id}/", 56 - ), 57 - {"get": "retrieve"}, 58 - AssetServiceViewSet, 59 - self.user, 60 - { 61 - "external_id": self.asset_service.external_id, 62 - "asset_external_id": self.asset.external_id, 63 - }, 45 + response = self.client.get( 46 + f"/api/v1/asset/{self.asset.external_id}/service_records/{self.asset_service.external_id}/" 64 47 ) 65 48 self.assertEqual(response.status_code, status.HTTP_200_OK) 66 49 67 50 def test_add_asset_service_record(self): 68 - response = self.new_request( 69 - (f"/api/v1/asset/{self.asset.external_id}",), 70 - {"get": "retrieve"}, 71 - AssetViewSet, 72 - self.user, 73 - { 74 - "external_id": self.asset.external_id, 75 - }, 76 - ) 77 - self.assertEqual(response.data["last_service"], None) 51 + response = self.client.get(f"/api/v1/asset/{self.asset.external_id}/") 52 + self.assertEqual(response.data.get("last_service"), None) 78 53 79 54 sample_data = {"last_serviced_on": self.today, "note": "Hello"} 80 - response = self.new_request( 81 - (f"/api/v1/asset/{self.asset.external_id}", sample_data, "json"), 82 - {"patch": "partial_update"}, 83 - AssetViewSet, 84 - self.user, 85 - { 86 - "external_id": self.asset.external_id, 87 - }, 55 + response = self.client.patch( 56 + f"/api/v1/asset/{self.asset.external_id}/", sample_data 88 57 ) 89 58 self.assertEqual(response.status_code, status.HTTP_200_OK) 90 59 self.assertEqual(response.data["last_service"]["serviced_on"], self.today) ··· 92 61 93 62 def test_update_asset_service_record(self): 94 63 sample_data = {"last_serviced_on": self.today, "note": "Hello 2"} 95 - response = self.new_request( 96 - (f"/api/v1/asset/{self.asset.external_id}", sample_data, "json"), 97 - {"patch": "partial_update"}, 98 - AssetViewSet, 99 - self.user, 100 - { 101 - "external_id": self.asset.external_id, 102 - }, 64 + response = self.client.patch( 65 + f"/api/v1/asset/{self.asset.external_id}/", sample_data 103 66 ) 104 67 self.assertEqual(response.status_code, status.HTTP_200_OK) 105 68 self.assertEqual(response.data["last_service"]["serviced_on"], self.today) ··· 107 70 108 71 def test_edit_asset_service_record(self): 109 72 sample_data = {"serviced_on": self.yesterday, "note": "Hello 3"} 110 - response = self.new_request( 111 - ( 112 - f"/api/v1/asset/{self.asset.external_id}/service_records/{self.asset_service.external_id}", 113 - sample_data, 114 - "json", 115 - ), 116 - {"patch": "partial_update"}, 117 - AssetServiceViewSet, 118 - self.user, 119 - { 120 - "external_id": self.asset_service.external_id, 121 - "asset_external_id": self.asset.external_id, 122 - }, 73 + response = self.client.patch( 74 + f"/api/v1/asset/{self.asset.external_id}/service_records/{self.asset_service.external_id}/", 75 + sample_data, 123 76 ) 124 77 self.assertEqual(response.status_code, status.HTTP_200_OK) 125 78 self.assertEqual(response.data["serviced_on"], self.yesterday)
+27 -35
care/facility/tests/test_asset_transaction_api.py
··· 1 1 from rest_framework import status 2 - from rest_framework.test import APIRequestFactory, APITestCase 2 + from rest_framework.test import APITestCase 3 3 4 - from care.facility.api.viewsets.asset import AssetTransactionViewSet 5 - from care.facility.models import Asset, AssetLocation, AssetTransaction 6 - from care.facility.tests.mixins import TestClassMixin 7 - from care.utils.tests.test_base import TestBase 4 + from care.facility.models import AssetTransaction 5 + from care.utils.tests.test_utils import TestUtils 8 6 9 7 10 - class AssetTransactionViewSetTestCase(TestBase, TestClassMixin, APITestCase): 11 - def setUp(self): 12 - self.factory = APIRequestFactory() 13 - state = self.create_state() 14 - district = self.create_district(state=state) 15 - self.user = self.create_user(district=district, username="test user") 16 - facility = self.create_facility(district=district, user=self.user) 17 - self.asset_from_location = AssetLocation.objects.create( 18 - name="asset from location", location_type=1, facility=facility 8 + class AssetTransactionViewSetTestCase(TestUtils, APITestCase): 9 + @classmethod 10 + def setUpTestData(cls): 11 + cls.state = cls.create_state() 12 + cls.district = cls.create_district(cls.state) 13 + cls.local_body = cls.create_local_body(cls.district) 14 + cls.super_user = cls.create_super_user("su", cls.district) 15 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 16 + cls.user = cls.create_user("staff", cls.district, home_facility=cls.facility) 17 + 18 + cls.asset_from_location = cls.create_asset_location( 19 + cls.facility, name="asset from location" 19 20 ) 20 - self.asset_to_location = AssetLocation.objects.create( 21 - name="asset to location", location_type=1, facility=facility 21 + cls.asset_to_location = cls.create_asset_location( 22 + cls.facility, name="asset to location" 22 23 ) 23 - self.asset = Asset.objects.create( 24 - name="Test Asset", current_location=self.asset_from_location, asset_type=50 24 + cls.asset = cls.create_asset( 25 + cls.asset_from_location, name="Test Asset", asset_type=50 25 26 ) 26 - self.asset_transaction = AssetTransaction.objects.create( 27 - asset=self.asset, 28 - from_location=self.asset_from_location, 29 - to_location=self.asset_to_location, 30 - performed_by=self.user, 27 + cls.asset_transaction = AssetTransaction.objects.create( 28 + asset=cls.asset, 29 + from_location=cls.asset_from_location, 30 + to_location=cls.asset_to_location, 31 + performed_by=cls.user, 31 32 ) 32 33 33 34 def test_list_asset_transactions(self): 34 - response = self.new_request( 35 - ("/api/v1/asset_transaction/",), 36 - {"get": "list"}, 37 - AssetTransactionViewSet, 38 - self.user, 39 - ) 35 + response = self.client.get("/api/v1/asset_transaction/") 40 36 self.assertEqual(response.status_code, status.HTTP_200_OK) 41 37 42 38 def test_retrieve_asset_transaction(self): 43 - response = self.new_request( 44 - (f"/api/v1/asset_transaction/{self.asset_transaction.id}/",), 45 - {"get": "retrieve"}, 46 - AssetTransactionViewSet, 47 - self.user, 48 - {"pk": self.asset_transaction.id}, 39 + response = self.client.get( 40 + f"/api/v1/asset_transaction/{self.asset_transaction.id}/" 49 41 ) 50 42 self.assertEqual(response.status_code, status.HTTP_200_OK)
+26 -21
care/facility/tests/test_bed_create.py
··· 1 1 from rest_framework import status 2 + from rest_framework.test import APITestCase 2 3 3 - from care.facility.models import AssetLocation, Bed 4 - from care.utils.tests.test_base import TestBase 4 + from care.facility.models import Bed 5 + from care.utils.tests.test_utils import TestUtils 5 6 6 7 7 - class SingleBedTest(TestBase): 8 - def setUp(self) -> None: 9 - super().setUp() 10 - self.asset_location: AssetLocation = AssetLocation.objects.create( 11 - name="asset location", location_type=1, facility=self.facility 12 - ) 13 - 14 - def tearDown(self) -> None: 15 - Bed._default_manager.filter(facility=self.facility).delete() 16 - AssetLocation._default_manager.filter(id=self.asset_location.id).delete() 8 + class SingleBedTest(TestUtils, APITestCase): 9 + @classmethod 10 + def setUpTestData(cls) -> None: 11 + cls.state = cls.create_state() 12 + cls.district = cls.create_district(cls.state) 13 + cls.local_body = cls.create_local_body(cls.district) 14 + cls.super_user = cls.create_super_user("su", cls.district) 15 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 16 + cls.asset_location = cls.create_asset_location(cls.facility) 17 + cls.asset = cls.create_asset(cls.asset_location) 18 + cls.user = cls.create_user("staff", cls.district, home_facility=cls.facility) 17 19 18 20 def test_create(self): 19 21 sample_data = { ··· 32 34 ) 33 35 34 36 35 - class MultipleBedTest(TestBase): 36 - def setUp(self) -> None: 37 - super().setUp() 38 - self.asset_location: AssetLocation = AssetLocation.objects.create( 39 - name="asset location", location_type=1, facility=self.facility 37 + class MultipleBedTest(TestUtils, APITestCase): 38 + @classmethod 39 + def setUpTestData(cls) -> None: 40 + cls.state = cls.create_state() 41 + cls.district = cls.create_district(cls.state) 42 + cls.local_body = cls.create_local_body(cls.district) 43 + cls.super_user = cls.create_super_user("su", cls.district) 44 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 45 + cls.asset_location = cls.create_asset_location(cls.facility) 46 + cls.asset = cls.create_asset(cls.asset_location) 47 + cls.user = cls.create_user( 48 + "distadmin", cls.district, home_facility=cls.facility, user_type=30 40 49 ) 41 - 42 - def tearDown(self) -> None: 43 - Bed._default_manager.filter(facility=self.facility).delete() 44 - AssetLocation._default_manager.filter(id=self.asset_location.id).delete() 45 50 46 51 def test_create(self): 47 52 sample_data = {
+21 -9
care/facility/tests/test_consultation_bed_asset_api.py
··· 1 1 from datetime import datetime 2 2 3 3 from rest_framework import status 4 + from rest_framework.test import APITestCase 4 5 5 - from care.facility.models import Asset, AssetLocation, Bed, ConsultationBedAsset 6 - from care.utils.tests.test_base import TestBase 6 + from care.facility.models import Asset, Bed, ConsultationBedAsset 7 + from care.utils.tests.test_utils import TestUtils 7 8 8 9 9 - class ConsultationBedAssetApiTestCase(TestBase): 10 + class ConsultationBedAssetApiTestCase(TestUtils, APITestCase): 11 + @classmethod 12 + def setUpTestData(cls) -> None: 13 + cls.state = cls.create_state() 14 + cls.district = cls.create_district(cls.state) 15 + cls.local_body = cls.create_local_body(cls.district) 16 + cls.super_user = cls.create_super_user("su", cls.district) 17 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 18 + cls.asset_location = cls.create_asset_location(cls.facility) 19 + cls.asset = cls.create_asset(cls.asset_location) 20 + cls.user = cls.create_user("staff", cls.district, home_facility=cls.facility) 21 + cls.patient = cls.create_patient( 22 + cls.district, cls.facility, local_body=cls.local_body 23 + ) 24 + 10 25 def setUp(self) -> None: 11 26 super().setUp() 12 - self.asset_location: AssetLocation = AssetLocation.objects.create( 13 - name="asset location", location_type=1, facility=self.facility 14 - ) 15 27 self.bed1 = Bed.objects.create( 16 28 name="bed1", location=self.asset_location, facility=self.facility 17 29 ) ··· 29 41 ) 30 42 31 43 def test_link_asset_to_consultation_bed(self): 32 - consultation = self.create_consultation() 44 + consultation = self.create_consultation(self.patient, self.facility) 33 45 response = self.client.post( 34 46 "/api/v1/consultationbed/", 35 47 { ··· 43 55 self.assertEqual(ConsultationBedAsset.objects.count(), 2) 44 56 45 57 def test_link_asset_to_consultation_bed_with_asset_already_in_use(self): 46 - consultation = self.create_consultation() 58 + consultation = self.create_consultation(self.patient, self.facility) 47 59 self.client.post( 48 60 "/api/v1/consultationbed/", 49 61 { ··· 53 65 "assets": [self.asset1.external_id, self.asset2.external_id], 54 66 }, 55 67 ) 56 - consultation2 = self.create_consultation() 68 + consultation2 = self.create_consultation(self.patient, self.facility) 57 69 response = self.client.post( 58 70 "/api/v1/consultationbed/", 59 71 {
+24 -41
care/facility/tests/test_facility_api.py
··· 1 - from django.test import TestCase 2 1 from rest_framework import status 2 + from rest_framework.test import APITestCase 3 3 4 - from care.facility.api.viewsets.facility import AllFacilityViewSet, FacilityViewSet 5 - from care.facility.tests.mixins import TestClassMixin 4 + from care.utils.tests.test_utils import TestUtils 6 5 7 6 8 - class FacilityTests(TestClassMixin, TestCase): 7 + class FacilityTests(TestUtils, APITestCase): 8 + @classmethod 9 + def setUpTestData(cls) -> None: 10 + cls.state = cls.create_state() 11 + cls.district = cls.create_district(cls.state) 12 + cls.local_body = cls.create_local_body(cls.district) 13 + cls.super_user = cls.create_super_user("su", cls.district) 14 + cls.user = cls.create_user("staff", cls.district) 15 + 9 16 def test_all_listing(self): 10 - response = self.new_request( 11 - ("/api/v1/getallfacilitiess/",), {"get": "list"}, AllFacilityViewSet 12 - ) 17 + response = self.client.get("/api/v1/getallfacilities/") 13 18 self.assertIs(response.status_code, status.HTTP_200_OK) 14 19 15 20 def test_listing(self): 16 - response = self.new_request( 17 - ("/api/v1/facility/",), {"get": "list"}, FacilityViewSet, self.users[0] 18 - ) 21 + response = self.client.get("/api/v1/facility/") 19 22 self.assertIs(response.status_code, status.HTTP_200_OK) 20 23 21 24 def test_create(self): 22 - user = self.users[0] 25 + dist_admin = self.create_user("dist_admin", self.district, user_type=30) 23 26 sample_data = { 24 27 "name": "Hospital X", 25 - "ward": user.ward.pk, 26 - "local_body": user.local_body.pk, 27 - "district": user.district.pk, 28 - "state": user.state.pk, 28 + "district": self.district.pk, 29 + "state": self.state.pk, 30 + "local_body": self.local_body.pk, 29 31 "facility_type": "Educational Inst", 30 32 "address": "Nearby", 31 33 "pincode": 390024, 32 34 "features": [], 33 35 } 34 - response = self.new_request( 35 - ("/api/v1/facility/", sample_data, "json"), 36 - {"post": "create"}, 37 - FacilityViewSet, 38 - user, 39 - ) 40 - fac_id = response.data["id"] 36 + self.client.force_authenticate(user=dist_admin) 37 + response = self.client.post("/api/v1/facility/", sample_data) 41 38 self.assertIs(response.status_code, status.HTTP_201_CREATED) 42 - 43 - retrieve_response = self.new_request( 44 - (f"/api/v1/facility/{fac_id}",), 45 - {"get": "retrieve"}, 46 - FacilityViewSet, 47 - user, 48 - {"external_id": fac_id}, 49 - ) 50 - 39 + fac_id = response.data["id"] 40 + retrieve_response = self.client.get(f"/api/v1/facility/{fac_id}/") 51 41 self.assertIs(retrieve_response.status_code, status.HTTP_200_OK) 52 42 53 43 def test_no_auth(self): 54 - response = self.new_request( 55 - ("/api/v1/facility/",), 56 - {"get": "list"}, 57 - FacilityViewSet, 58 - ) 44 + self.client.force_authenticate(user=None) 45 + response = self.client.get("/api/v1/facility/") 59 46 self.assertIs(response.status_code, status.HTTP_403_FORBIDDEN) 60 47 61 48 sample_data = {} 62 - create_response = self.new_request( 63 - ("/api/v1/facility/", sample_data, "json"), 64 - {"post": "create"}, 65 - FacilityViewSet, 66 - ) 49 + create_response = self.client.post("/api/v1/facility/", sample_data) 67 50 self.assertIs(create_response.status_code, status.HTTP_403_FORBIDDEN)
care/facility/tests/test_facility_patient_history_api.py

This is a binary file and will not be displayed.

+16 -36
care/facility/tests/test_facilityuser_api.py
··· 1 - from django.test import TestCase 2 1 from rest_framework import status 2 + from rest_framework.test import APITestCase 3 3 4 - from care.facility.api.viewsets.facility_users import FacilityUserViewSet 5 - from care.facility.models.facility import Facility 6 - from care.facility.tests.mixins import TestClassMixin 7 4 from care.users.models import Skill 8 - 9 - 10 - class FacilityUserTest(TestClassMixin, TestCase): 11 - def setUp(self): 12 - super().setUp() 13 - self.creator = self.users[0] 14 - 15 - sample_data = { 16 - "name": "Hospital X", 17 - "ward": self.creator.ward, 18 - "local_body": self.creator.local_body, 19 - "district": self.creator.district, 20 - "state": self.creator.state, 21 - "facility_type": 1, 22 - "address": "Nearby", 23 - "pincode": 390024, 24 - "features": [], 25 - } 26 - self.facility = Facility.objects.create( 27 - external_id="550e8400-e29b-41d4-a716-446655440000", 28 - created_by=self.creator, 29 - **sample_data, 30 - ) 5 + from care.utils.tests.test_utils import TestUtils 31 6 32 - self.skill1 = Skill.objects.create(name="Skill 1") 33 - self.skill2 = Skill.objects.create(name="Skill 2") 34 7 35 - self.users[0].skills.add(self.skill1, self.skill2) 8 + class FacilityUserTest(TestUtils, APITestCase): 9 + @classmethod 10 + def setUpTestData(cls) -> None: 11 + cls.state = cls.create_state() 12 + cls.district = cls.create_district(cls.state) 13 + cls.local_body = cls.create_local_body(cls.district) 14 + cls.super_user = cls.create_super_user("su", cls.district) 15 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 16 + cls.user = cls.create_user("staff", cls.district, home_facility=cls.facility) 17 + cls.skill1 = Skill.objects.create(name="Skill 1") 18 + cls.skill2 = Skill.objects.create(name="Skill 2") 19 + cls.user.skills.add(cls.skill1, cls.skill2) 36 20 37 21 def test_get_queryset_with_prefetching(self): 38 - response = self.new_request( 39 - (f"/api/v1/facility/{self.facility.external_id}/get_users/",), 40 - {"get": "list"}, 41 - FacilityUserViewSet, 42 - self.users[0], 43 - {"facility_external_id": self.facility.external_id}, 22 + response = self.client.get( 23 + f"/api/v1/facility/{self.facility.external_id}/get_users/" 44 24 ) 45 25 46 26 self.assertEqual(response.status_code, status.HTTP_200_OK)
+9 -2
care/facility/tests/test_medibase_api.py
··· 1 1 from rest_framework import status 2 + from rest_framework.test import APITestCase 2 3 3 - from care.utils.tests.test_base import TestBase 4 + from care.utils.tests.test_utils import TestUtils 4 5 5 6 6 - class TestMedibaseApi(TestBase): 7 + class TestMedibaseApi(TestUtils, APITestCase): 8 + @classmethod 9 + def setUpTestData(cls) -> None: 10 + cls.state = cls.create_state() 11 + cls.district = cls.create_district(state=cls.state) 12 + cls.user = cls.create_user("staff1", cls.district) 13 + 7 14 def get_url(self, query=None): 8 15 return f"/api/v1/medibase/?query={query}" 9 16
+16 -3
care/facility/tests/test_medicine_administrations_api.py
··· 1 1 from django.utils import timezone 2 2 from rest_framework import status 3 + from rest_framework.test import APITestCase 3 4 4 5 from care.facility.models import MedibaseMedicine, Prescription 5 - from care.utils.tests.test_base import TestBase 6 + from care.utils.tests.test_utils import TestUtils 6 7 7 8 8 - class MedicineAdministrationsApiTestCase(TestBase): 9 + class MedicineAdministrationsApiTestCase(TestUtils, APITestCase): 10 + @classmethod 11 + def setUpTestData(cls) -> None: 12 + cls.state = cls.create_state() 13 + cls.district = cls.create_district(cls.state) 14 + cls.local_body = cls.create_local_body(cls.district) 15 + cls.super_user = cls.create_super_user("su", cls.district) 16 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 17 + cls.user = cls.create_user("staff1", cls.district, home_facility=cls.facility) 18 + cls.patient = cls.create_patient( 19 + cls.district, cls.facility, local_body=cls.local_body 20 + ) 21 + 9 22 def setUp(self) -> None: 10 23 super().setUp() 11 24 self.normal_prescription = self.create_prescription() 12 25 13 26 def create_prescription(self, **kwargs): 14 27 data = { 15 - "consultation": self.create_consultation(), 28 + "consultation": self.create_consultation(self.patient, self.facility), 16 29 "medicine": MedibaseMedicine.objects.first(), 17 30 "prescription_type": "REGULAR", 18 31 "dosage": "1 mg",
care/facility/tests/test_migrations.py

This is a binary file and will not be displayed.

+58 -63
care/facility/tests/test_patient_api.py
··· 1 - from datetime import datetime 2 1 from enum import Enum 3 2 4 - from django.utils.timezone import make_aware 3 + from django.utils.timezone import now 5 4 from rest_framework import status 6 - from rest_framework.test import APIRequestFactory, APITestCase 7 - from rest_framework_simplejwt.tokens import RefreshToken 5 + from rest_framework.test import APITestCase 8 6 9 - from care.facility.models import User 10 - from care.facility.tests.mixins import TestClassMixin 11 - from care.utils.tests.test_base import TestBase 7 + from care.utils.tests.test_utils import TestUtils 12 8 13 9 14 10 class ExpectedPatientNoteKeys(Enum): ··· 77 73 LAST_LOGIN = "last_login" 78 74 79 75 80 - class PatientNotesTestCase(TestBase, TestClassMixin, APITestCase): 81 - asset_id = None 82 - 83 - def setUp(self): 84 - self.factory = APIRequestFactory() 85 - state = self.create_state() 86 - district = self.create_district(state=state) 76 + class PatientNotesTestCase(TestUtils, APITestCase): 77 + @classmethod 78 + def setUpTestData(cls) -> None: 79 + cls.state = cls.create_state() 80 + cls.district = cls.create_district(cls.state) 81 + cls.local_body = cls.create_local_body(cls.district) 82 + cls.super_user = cls.create_super_user("su", cls.district) 83 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 84 + cls.user = cls.create_user( 85 + "doctor1", cls.district, home_facility=cls.facility, user_type=15 86 + ) 87 + cls.asset_location = cls.create_asset_location(cls.facility) 88 + cls.asset = cls.create_asset(cls.asset_location) 89 + cls.state_admin = cls.create_user( 90 + "state-admin", cls.district, home_facility=cls.facility, user_type=40 91 + ) 87 92 88 - # Create users and facility 89 - self.user = self.create_user( 90 - district=district, 91 - username="test user", 92 - user_type=User.TYPE_VALUE_MAP["Doctor"], 93 + cls.facility2 = cls.create_facility( 94 + cls.super_user, cls.district, cls.local_body 93 95 ) 94 - facility = self.create_facility(district=district) 95 - self.user.home_facility = facility 96 - self.user.save() 97 - 98 - # Create another user from different facility 99 - self.user2 = self.create_user( 100 - district=district, 101 - username="test user 2", 102 - user_type=User.TYPE_VALUE_MAP["Doctor"], 96 + cls.user2 = cls.create_user( 97 + "doctor2", cls.district, home_facility=cls.facility2, user_type=15 103 98 ) 104 - facility2 = self.create_facility(district=district) 105 - self.user2.home_facility = facility2 106 - self.user2.save() 107 - 108 - self.patient = self.create_patient(district=district.id, facility=facility) 99 + cls.patient = cls.create_patient(cls.district, cls.facility) 109 100 101 + def setUp(self): 102 + super().setUp() 110 103 self.create_patient_note( 111 - patient=self.patient, facility=facility, created_by=self.user 104 + patient=self.patient, facility=self.facility, created_by=self.user 112 105 ) 113 - 114 106 self.create_patient_note( 115 - patient=self.patient, facility=facility, created_by=self.user2 107 + patient=self.patient, facility=self.facility, created_by=self.user2 116 108 ) 117 109 118 - refresh_token = RefreshToken.for_user(self.user) 119 - self.client.credentials( 120 - HTTP_AUTHORIZATION=f"Bearer {refresh_token.access_token}" 121 - ) 110 + def create_patient_note( 111 + self, patient=None, note="Patient is doing find", created_by=None, **kwargs 112 + ): 113 + data = { 114 + "facility": patient.facility or self.facility, 115 + "note": note, 116 + } 117 + data.update(kwargs) 118 + self.client.force_authenticate(user=created_by) 119 + self.client.post(f"/api/v1/patient/{patient.external_id}/notes/", data=data) 122 120 123 121 def test_patient_notes(self): 124 122 patientId = self.patient.external_id ··· 199 197 ) 200 198 201 199 202 - class PatientFilterTestCase(TestBase, TestClassMixin, APITestCase): 203 - def setUp(self): 204 - self.factory = APIRequestFactory() 205 - state = self.create_state() 206 - district = self.create_district(state=state) 207 - 208 - self.user = self.create_super_user(district=district, username="test user") 209 - facility = self.create_facility(district=district, user=self.user) 210 - self.user.home_facility = facility 211 - self.user.save() 212 - 213 - self.patient = self.create_patient(district=district.id, created_by=self.user) 214 - self.consultation = self.create_consultation( 200 + class PatientFilterTestCase(TestUtils, APITestCase): 201 + @classmethod 202 + def setUpTestData(cls): 203 + cls.state = cls.create_state() 204 + cls.district = cls.create_district(cls.state) 205 + cls.local_body = cls.create_local_body(cls.district) 206 + cls.super_user = cls.create_super_user("su", cls.district) 207 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 208 + cls.user = cls.create_user( 209 + "doctor1", cls.district, home_facility=cls.facility, user_type=15 210 + ) 211 + cls.patient = cls.create_patient(cls.district, cls.facility) 212 + cls.consultation = cls.create_consultation( 215 213 patient_no="IP5678", 216 - patient=self.patient, 217 - facility=facility, 218 - created_by=self.user, 214 + patient=cls.patient, 215 + facility=cls.facility, 216 + created_by=cls.user, 219 217 suggestion="A", 220 - admission_date=make_aware(datetime(2020, 4, 1, 15, 30, 00)), 218 + admission_date=now(), 221 219 ) 222 - self.patient.last_consultation = self.consultation 223 - self.patient.save() 224 - refresh_token = RefreshToken.for_user(self.user) 225 - self.client.credentials( 226 - HTTP_AUTHORIZATION=f"Bearer {refresh_token.access_token}" 227 - ) 220 + cls.patient.last_consultation = cls.consultation 221 + cls.patient.save() 228 222 229 223 def test_filter_by_patient_no(self): 224 + self.client.force_authenticate(user=self.user) 230 225 response = self.client.get("/api/v1/patient/?patient_no=IP5678") 231 226 self.assertEqual(response.status_code, 200) 232 227 self.assertEqual(response.data["count"], 1)
+28 -87
care/facility/tests/test_patient_consultation_api.py
··· 1 1 import datetime 2 2 3 - from django.test import TestCase 4 3 from django.utils.timezone import make_aware 5 4 from rest_framework import status 6 - from rest_framework.test import APIRequestFactory, APITestCase 5 + from rest_framework.test import APITestCase 7 6 8 - from care.facility.api.viewsets.facility_users import FacilityUserViewSet 9 - from care.facility.api.viewsets.patient_consultation import PatientConsultationViewSet 10 - from care.facility.models import Facility, User 11 7 from care.facility.models.patient_consultation import ( 12 8 CATEGORY_CHOICES, 13 9 PatientConsultation, 14 10 ) 15 - from care.facility.tests.mixins import TestClassMixin 16 - from care.users.models import Skill 17 - from care.utils.tests.test_base import TestBase 18 - 19 - 20 - class FacilityUserTest(TestClassMixin, TestCase): 21 - def setUp(self): 22 - super().setUp() 23 - self.creator = self.users[0] 24 - 25 - sample_data = { 26 - "name": "Hospital X", 27 - "ward": self.creator.ward, 28 - "local_body": self.creator.local_body, 29 - "district": self.creator.district, 30 - "state": self.creator.state, 31 - "facility_type": 1, 32 - "address": "Nearby", 33 - "pincode": 390024, 34 - "features": [], 35 - } 36 - self.facility = Facility.objects.create( 37 - external_id="550e8400-e29b-41d4-a716-446655440000", 38 - created_by=self.creator, 39 - **sample_data, 40 - ) 11 + from care.utils.tests.test_utils import TestUtils 41 12 42 - self.skill1 = Skill.objects.create(name="Skill 1") 43 - self.skill2 = Skill.objects.create(name="Skill 2") 44 13 45 - self.users[0].skills.add(self.skill1, self.skill2) 46 - 47 - def test_get_queryset_with_prefetching(self): 48 - response = self.new_request( 49 - (f"/api/v1/facility/{self.facility.external_id}/get_users/",), 50 - {"get": "list"}, 51 - FacilityUserViewSet, 52 - self.users[0], 53 - {"facility_external_id": self.facility.external_id}, 14 + class TestPatientConsultation(TestUtils, APITestCase): 15 + @classmethod 16 + def setUpTestData(cls) -> None: 17 + cls.state = cls.create_state() 18 + cls.district = cls.create_district(cls.state) 19 + cls.local_body = cls.create_local_body(cls.district) 20 + cls.super_user = cls.create_super_user("su", cls.district) 21 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 22 + cls.user = cls.create_user("staff1", cls.district, home_facility=cls.facility) 23 + cls.doctor = cls.create_user( 24 + "doctor", cls.district, home_facility=cls.facility, user_type=15 54 25 ) 55 26 56 - self.assertEqual(response.status_code, status.HTTP_200_OK) 57 - self.assertNumQueries(2) 58 - 59 - 60 - class TestPatientConsultation(TestBase, TestClassMixin, APITestCase): 61 27 def get_default_data(self): 62 28 return { 63 29 "symptoms": [1], ··· 69 35 "verified_by": self.doctor.id, 70 36 } 71 37 72 - def setUp(self): 73 - self.factory = APIRequestFactory() 74 - self.doctor = self.create_user( 75 - username="doctor1", 76 - district=self.district, 77 - user_type=User.TYPE_VALUE_MAP["Doctor"], 78 - ) 79 - 80 - self.consultation = self.create_consultation( 81 - suggestion="A", 82 - admission_date=make_aware(datetime.datetime(2020, 4, 1, 15, 30, 00)), 83 - ) 38 + def get_url(self, consultation=None): 39 + if consultation: 40 + return f"/api/v1/consultation/{consultation.external_id}/" 41 + return "/api/v1/consultation/" 84 42 85 43 def create_admission_consultation(self, patient=None, **kwargs): 86 - patient = patient or self.create_patient(facility_id=self.facility.id) 87 - data = self.get_default_data() 44 + patient = patient or self.create_patient(self.district, self.facility) 45 + data = self.get_default_data().copy() 88 46 kwargs.update( 89 47 { 90 48 "patient": patient.external_id, ··· 92 50 } 93 51 ) 94 52 data.update(kwargs) 95 - res = self.new_request( 96 - (self.get_url(), data, "json"), 97 - {"post": "create"}, 98 - PatientConsultationViewSet, 99 - self.state_admin, 100 - {}, 101 - ) 53 + res = self.client.post(self.get_url(), data) 102 54 return PatientConsultation.objects.get(external_id=res.data["id"]) 103 55 104 56 def update_consultation(self, consultation, **kwargs): 105 - return self.new_request( 106 - (self.get_url(consultation), kwargs, "json"), 107 - {"patch": "partial_update"}, 108 - PatientConsultationViewSet, 109 - self.state_admin, 110 - {"external_id": consultation.external_id}, 111 - ) 112 - 113 - def get_url(self, consultation=None): 114 - if consultation: 115 - return f"/api/v1/consultation/{consultation.external_id}" 116 - return "/api/v1/consultation" 57 + return self.client.patch(self.get_url(consultation), kwargs, "json") 117 58 118 59 def discharge(self, consultation, **kwargs): 119 - return self.new_request( 120 - (f"{self.get_url(consultation)}/discharge_patient", kwargs, "json"), 121 - {"post": "discharge_patient"}, 122 - PatientConsultationViewSet, 123 - self.state_admin, 124 - {"external_id": consultation.external_id}, 60 + return self.client.post( 61 + f"{self.get_url(consultation)}discharge_patient/", kwargs, "json" 125 62 ) 126 63 127 64 def test_create_consultation_verified_by_invalid_user(self): 65 + consultation = self.create_admission_consultation( 66 + suggestion="A", 67 + admission_date=make_aware(datetime.datetime(2020, 4, 1, 15, 30, 00)), 68 + ) 128 69 res = self.update_consultation( 129 - self.consultation, verified_by=self.state_admin.id, suggestion="A" 70 + consultation, verified_by=self.doctor.id, suggestion="A" 130 71 ) 131 72 self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) 132 73
+12 -2
care/facility/tests/test_patient_daily_rounds_api.py
··· 1 1 from rest_framework import status 2 + from rest_framework.test import APITestCase 2 3 3 - from care.utils.tests.test_base import TestBase 4 + from care.utils.tests.test_utils import TestUtils 4 5 5 6 6 - class TestDailyRoundApi(TestBase): 7 + class TestDailyRoundApi(TestUtils, APITestCase): 8 + @classmethod 9 + def setUpTestData(cls) -> None: 10 + cls.state = cls.create_state() 11 + cls.district = cls.create_district(cls.state) 12 + cls.local_body = cls.create_local_body(cls.district) 13 + cls.super_user = cls.create_super_user("su", cls.district) 14 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 15 + cls.user = cls.create_user("staff1", cls.district, home_facility=cls.facility) 16 + 7 17 def get_url(self, external_consultation_id=None): 8 18 return f"/api/v1/consultation/{external_consultation_id}/daily_rounds/analyse/" 9 19
care/facility/tests/test_patient_sample_api.py

This is a binary file and will not be displayed.

+19 -9
care/facility/tests/test_prescriptions_api.py
··· 1 1 from rest_framework import status 2 + from rest_framework.test import APITestCase 2 3 3 4 from care.facility.models import MedibaseMedicine 4 - from care.utils.tests.test_base import TestBase 5 + from care.utils.tests.test_utils import TestUtils 5 6 6 7 7 - class PrescriptionsApiTestCase(TestBase): 8 + class PrescriptionsApiTestCase(TestUtils, APITestCase): 9 + @classmethod 10 + def setUpTestData(cls) -> None: 11 + cls.state = cls.create_state() 12 + cls.district = cls.create_district(cls.state) 13 + cls.local_body = cls.create_local_body(cls.district) 14 + cls.super_user = cls.create_super_user("su", cls.district) 15 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 16 + cls.user = cls.create_user("staff1", cls.district, home_facility=cls.facility) 17 + cls.patient = cls.create_patient(cls.district, cls.facility) 18 + 8 19 def setUp(self) -> None: 9 20 super().setUp() 21 + self.consultation = self.create_consultation(self.patient, self.facility) 10 22 self.medicine = MedibaseMedicine.objects.first() 11 23 12 24 self.normal_prescription_data = { ··· 18 30 } 19 31 20 32 def test_create_normal_prescription(self): 21 - consultation = self.create_consultation() 22 33 response = self.client.post( 23 - f"/api/v1/consultation/{consultation.external_id}/prescriptions/", 34 + f"/api/v1/consultation/{self.consultation.external_id}/prescriptions/", 24 35 self.normal_prescription_data, 25 36 ) 26 37 self.assertEqual(response.status_code, status.HTTP_201_CREATED) ··· 32 43 3. Discontinues the first prescription 33 44 4. Re-attempts to create another prescription with Medicine A (expecting success) 34 45 """ 35 - consultation = self.create_consultation() 36 46 res = self.client.post( 37 - f"/api/v1/consultation/{consultation.external_id}/prescriptions/", 47 + f"/api/v1/consultation/{self.consultation.external_id}/prescriptions/", 38 48 self.normal_prescription_data, 39 49 ) 40 50 self.assertEqual(res.status_code, status.HTTP_201_CREATED) 41 51 discontinue_prescription_id = res.data["id"] 42 52 43 53 res = self.client.post( 44 - f"/api/v1/consultation/{consultation.external_id}/prescriptions/", 54 + f"/api/v1/consultation/{self.consultation.external_id}/prescriptions/", 45 55 self.normal_prescription_data, 46 56 ) 47 57 self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) 48 58 49 59 res = self.client.post( 50 - f"/api/v1/consultation/{consultation.external_id}/prescriptions/{discontinue_prescription_id}/discontinue/", 60 + f"/api/v1/consultation/{self.consultation.external_id}/prescriptions/{discontinue_prescription_id}/discontinue/", 51 61 { 52 62 "discontinued_reason": "Test Reason", 53 63 }, ··· 55 65 self.assertEqual(res.status_code, status.HTTP_200_OK) 56 66 57 67 res = self.client.post( 58 - f"/api/v1/consultation/{consultation.external_id}/prescriptions/", 68 + f"/api/v1/consultation/{self.consultation.external_id}/prescriptions/", 59 69 self.normal_prescription_data, 60 70 ) 61 71 self.assertEqual(res.status_code, status.HTTP_201_CREATED)
+24 -26
care/users/tests/test_api.py
··· 1 1 from rest_framework import status 2 + from rest_framework.test import APITestCase 2 3 3 4 from care.users.models import GENDER_CHOICES, User 4 - from care.utils.tests.test_base import TestBase 5 + from care.utils.tests.test_utils import TestUtils 5 6 6 7 7 - class TestSuperUser(TestBase): 8 + class TestSuperUser(TestUtils, APITestCase): 9 + @classmethod 10 + def setUpTestData(cls) -> None: 11 + cls.state = cls.create_state() 12 + cls.district = cls.create_district(cls.state) 13 + cls.local_body = cls.create_local_body(cls.district) 14 + cls.super_user = cls.create_super_user("su", cls.district) 15 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 16 + cls.user = cls.create_user("staff1", cls.district) 17 + cls.user_data = cls.get_user_data(cls.district, 40) 18 + 8 19 def setUp(self): 9 - """ 10 - Run once before every test 11 - - login the super user 12 - """ 13 20 self.client.force_authenticate(self.super_user) 14 21 15 22 def get_detail_representation(self, obj=None) -> dict: ··· 89 96 ) 90 97 91 98 92 - class TestUser(TestBase): 99 + class TestUser(TestUtils, APITestCase): 93 100 def get_detail_representation(self, obj=None) -> dict: 94 101 return { 95 102 "username": obj.username, ··· 105 112 } 106 113 107 114 @classmethod 108 - def setUpClass(cls) -> None: 109 - """ 110 - Runs once per class method 111 - 112 - Create 3 users 113 - - 2 users initialized by setUpClass of TestBase 114 - - 1 will be used to check if they can tinker attributes of the other 115 - """ 116 - super(TestUser, cls).setUpClass() 117 - cls.data_2 = cls.get_user_data() 115 + def setUpTestData(cls) -> None: 116 + cls.state = cls.create_state() 117 + cls.district = cls.create_district(cls.state) 118 + cls.local_body = cls.create_local_body(cls.district) 119 + cls.super_user = cls.create_super_user("su", cls.district) 120 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 121 + cls.user = cls.create_user("staff1", cls.district, home_facility=cls.facility) 122 + cls.data_2 = cls.get_user_data(cls.district) 118 123 cls.data_2.update({"username": "user_2", "password": "password"}) 119 - cls.user_2 = cls.create_user(district=cls.district, username="user_2") 120 - 121 - def setUp(self): 122 - """ 123 - Run once before every test 124 - - login the super user 125 - """ 126 - self.client.force_login(self.user) 124 + cls.user_2 = cls.create_user(**cls.data_2) 127 125 128 126 def test_user_can_access_url(self): 129 127 """Test user can access the url by location""" ··· 138 136 self.assertEqual(response.status_code, status.HTTP_200_OK) 139 137 res_data_json = response.json() 140 138 # test total user count 141 - self.assertEqual(res_data_json["count"], 3) # 3 existing, plus the new one 139 + self.assertEqual(res_data_json["count"], 2) 142 140 results = res_data_json["results"] 143 141 # test presence of usernames 144 142 self.assertIn(self.user.id, {r["id"] for r in results})
+32 -10
care/users/tests/test_auth.py
··· 1 - from django.conf import settings 1 + from datetime import timedelta 2 + 3 + from django.test import override_settings 4 + from django.utils.timezone import now 2 5 from django_rest_passwordreset.models import ResetPasswordToken 3 6 from rest_framework import status 7 + from rest_framework.test import APITestCase 4 8 5 - from care.utils.tests.test_base import TestBase 9 + from care.users.models import User 10 + from care.utils.tests.test_utils import TestUtils 6 11 7 12 8 - class TestAuthTokens(TestBase): 13 + @override_settings(DISABLE_RATELIMIT=True) 14 + class TestAuthTokens(TestUtils, APITestCase): 9 15 @classmethod 10 - def setUpClass(cls) -> None: 11 - super().setUpClass() 12 - settings.DISABLE_RATELIMIT = True 16 + def setUpTestData(cls) -> None: 17 + cls.state = cls.create_state() 18 + cls.district = cls.create_district(cls.state) 19 + cls.local_body = cls.create_local_body(cls.district) 20 + cls.super_user = cls.create_super_user("su", cls.district) 21 + cls.user = cls.create_user("user", cls.district) 13 22 14 23 def test_login_with_valid_credentials(self): 15 24 response = self.client.post( ··· 90 99 self.assertEqual(response.data["detail"], "Token is invalid or expired") 91 100 92 101 93 - class TestPasswordReset(TestBase): 102 + @override_settings(DISABLE_RATELIMIT=True) 103 + class TestPasswordReset(TestUtils, APITestCase): 94 104 @classmethod 95 - def setUpClass(cls) -> None: 96 - super().setUpClass() 97 - settings.DISABLE_RATELIMIT = True 105 + def setUpTestData(cls) -> None: 106 + cls.state = cls.create_state() 107 + cls.district = cls.create_district(cls.state) 108 + cls.local_body = cls.create_local_body(cls.district) 109 + cls.super_user = cls.create_super_user("su", cls.district) 110 + cls.user = cls.create_user("user", cls.district) 111 + 112 + def create_reset_password_token( 113 + self, user: User, expired: bool = False 114 + ) -> ResetPasswordToken: 115 + token = ResetPasswordToken.objects.create(user=user) 116 + if expired: 117 + token.created_at = now() - timedelta(hours=2) 118 + token.save() 119 + return token 98 120 99 121 def test_forgot_password_with_valid_input(self): 100 122 response = self.client.post(
+15 -7
care/users/tests/test_facility_user_create.py
··· 1 1 from rest_framework import status 2 + from rest_framework.test import APITestCase 2 3 3 4 from care.users.models import User 4 - from care.utils.tests.test_base import TestBase 5 + from care.utils.tests.test_utils import TestUtils 5 6 6 7 7 - class TestFacilityUserApi(TestBase): 8 + class TestFacilityUserApi(TestUtils, APITestCase): 9 + @classmethod 10 + def setUpTestData(cls) -> None: 11 + cls.state = cls.create_state() 12 + cls.district = cls.create_district(cls.state) 13 + cls.local_body = cls.create_local_body(cls.district) 14 + cls.super_user = cls.create_super_user("su", cls.district) 15 + cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body) 16 + cls.user = cls.create_user("staff1", cls.district, home_facility=cls.facility) 17 + 8 18 def get_base_url(self): 9 - return "/api/v1/users/add_user" 19 + return "/api/v1/users/add_user/" 10 20 11 21 def get_list_representation(self, obj) -> dict: 12 22 raise NotImplementedError ··· 53 63 data = self.get_new_user_data().copy() 54 64 data.update({"user_type": "DistrictAdmin"}) 55 65 56 - response = self.client.post(self.get_url(), data=data, format="json") 57 - # Test Creation 66 + response = self.client.post(self.get_base_url(), data=data, format="json") 58 67 self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) 59 68 60 69 def test_create_facility_user__should_fail__when_different_location(self): ··· 62 71 data = self.get_new_user_data().copy() 63 72 data.update({"district": new_district.id}) 64 73 65 - response = self.client.post(self.get_url(), data=data, format="json") 66 - # Test Creation 74 + response = self.client.post(self.get_base_url(), data=data, format="json") 67 75 self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
-11
care/users/tests/test_models.py
··· 118 118 user = self.user 119 119 max_length = user._meta.get_field("phone_number").max_length 120 120 self.assertEqual(max_length, 14) 121 - 122 - def test_get_absolute_url(self): 123 - """Test whether model returns correct url for detail view of a user""" 124 - # This is part of django-cookie cutter and isn't used right now 125 - # Reference link for the slack thread: 126 - # https://rebuildearth.slack.com/archives/C010GQBMFJ9/p1585218577029200?thread_ts=1585218248.028800&cid=C010GQBMFJ9 127 - pass 128 - # user = self.user 129 - # url_absolute = reverse('users:detail', kwargs={'username': user.username}) 130 - # response = self.client.get(url_absolute) 131 - # self.assertEqual(response.status_code, 200)
+225 -204
care/utils/tests/test_base.py care/utils/tests/test_utils.py
··· 1 - import abc 2 - import datetime 1 + import uuid 3 2 from collections import OrderedDict 3 + from datetime import UTC, date, datetime 4 + from typing import Any 4 5 from uuid import uuid4 5 6 7 + from django.test import override_settings 6 8 from django.utils.timezone import make_aware, now 7 - from django_rest_passwordreset.models import ResetPasswordToken 8 9 from pytz import unicode 9 10 from rest_framework import status 10 - from rest_framework.test import APITestCase 11 - from rest_framework_simplejwt.tokens import RefreshToken 12 11 13 12 from care.facility.models import ( 14 13 CATEGORY_CHOICES, ··· 23 22 PatientRegistration, 24 23 User, 25 24 ) 25 + from care.facility.models.asset import Asset, AssetLocation 26 + from care.facility.models.facility import FacilityUser 26 27 from care.users.models import District, State 27 - from config.tests.helper import EverythingEquals, mock_equal 28 28 29 29 30 - class TestBase(APITestCase): 30 + class override_cache(override_settings): 31 + """ 32 + Overrides the cache settings for the test to use a 33 + local memory cache instead of the redis cache 34 + """ 35 + 36 + def __init__(self, decorated): 37 + self.decorated = decorated 38 + super().__init__( 39 + CACHES={ 40 + "default": { 41 + "BACKEND": "django.core.cache.backends.locmem.LocMemCache", 42 + "LOCATION": f"care-test-{uuid.uuid4()}", 43 + } 44 + }, 45 + ) 46 + 47 + def __call__(self) -> Any: 48 + return super().__call__(self.decorated) 49 + 50 + 51 + class EverythingEquals: 52 + def __eq__(self, other): 53 + return True 54 + 55 + 56 + mock_equal = EverythingEquals() 57 + 58 + 59 + def assert_equal_dicts(d1, d2, ignore_keys=[]): 60 + def check_equal(): 61 + ignored = set(ignore_keys) 62 + for k1, v1 in d1.items(): 63 + if k1 not in ignored and (k1 not in d2 or d2[k1] != v1): 64 + print(k1, v1, d2[k1]) 65 + return False 66 + for k2, v2 in d2.items(): 67 + if k2 not in ignored and k2 not in d1: 68 + print(k2, v2) 69 + return False 70 + return True 71 + 72 + return check_equal() 73 + 74 + 75 + class TestUtils: 31 76 """ 32 77 Base class for tests, handles most of the test setup and tools for setting up data 33 78 """ 34 79 35 80 maxDiff = None 36 81 37 - @classmethod 38 - def create_user(cls, district: District, username: str = "user", **kwargs) -> User: 39 - data = { 40 - "email": f"{username}@somedomain.com", 41 - "phone_number": "5554446667", 42 - "age": 30, 43 - "gender": 2, 44 - "verified": True, 45 - "username": username, 46 - "password": "bar", 47 - "district": district, 48 - "user_type": User.TYPE_VALUE_MAP["Staff"], 49 - } 50 - data.update(kwargs) 51 - return User.objects.create_user(**data) 82 + def setUp(self) -> None: 83 + self.client.force_login(self.user) 52 84 53 - @classmethod 54 - def create_super_user(cls, district: District, username: str = "superuser") -> User: 55 - user = cls.create_user( 56 - district=district, 57 - username=username, 58 - user_type=User.TYPE_VALUE_MAP["StateAdmin"], 59 - ) 60 - user.is_superuser = True 61 - user.save() 62 - return user 85 + def get_base_url(self) -> str: 86 + """ 87 + Should return the base url of the testing viewset 88 + eg: return "api/v1/facility/" 89 + """ 90 + raise NotImplementedError() 63 91 64 92 @classmethod 65 - def create_reset_password_token( 66 - cls, user: User, expired: bool = False 67 - ) -> ResetPasswordToken: 68 - token = ResetPasswordToken.objects.create(user=user) 69 - if expired: 70 - token.created_at = now() - datetime.timedelta(hours=2) 71 - token.save() 72 - return token 93 + def create_state(cls) -> State: 94 + return State.objects.create(name=f"State{now().timestamp()}") 73 95 74 96 @classmethod 75 97 def create_district(cls, state: State) -> District: 76 - return District.objects.create( 77 - state=state, name=f"District{datetime.datetime.now().timestamp()}" 78 - ) 98 + return District.objects.create(state=state, name=f"District{now().timestamp()}") 79 99 80 100 @classmethod 81 - def create_state(cls) -> State: 82 - return State.objects.create(name=f"State{datetime.datetime.now().timestamp()}") 83 - 84 - @classmethod 85 - def create_facility( 86 - cls, district: District, user: User = None, **kwargs 87 - ) -> Facility: 88 - user = user or cls.user 101 + def create_local_body(cls, district: District, **kwargs) -> LocalBody: 89 102 data = { 90 - "name": "Foo", 103 + "name": f"LocalBody{now().timestamp()}", 91 104 "district": district, 92 - "facility_type": 1, 93 - "address": "8/88, 1st Cross, 1st Main, Boo Layout", 94 - "pincode": 123456, 95 - "oxygen_capacity": 10, 96 - "phone_number": "9998887776", 97 - "created_by": user, 105 + "body_type": 10, 106 + "localbody_code": "d123456", 98 107 } 99 108 data.update(kwargs) 100 - f = Facility(**data) 101 - f.save() 102 - return f 109 + return LocalBody.objects.create(**data) 103 110 104 111 @classmethod 105 - def create_patient(cls, facility=None, **kwargs): 106 - patient_data = cls.get_patient_data().copy() 107 - patient_data.update(kwargs) 108 - 109 - medical_history = patient_data.pop("medical_history", []) 110 - district_id = patient_data.pop("district", None) 111 - state_id = patient_data.pop("state", None) 112 - 113 - patient_data.update( 114 - { 115 - "facility": facility or cls.facility, 116 - "district_id": district_id, 117 - "state_id": state_id, 118 - "disease_status": getattr( 119 - DiseaseStatusEnum, patient_data["disease_status"] 120 - ).value, 121 - } 122 - ) 123 - 124 - patient = PatientRegistration.objects.create(**patient_data) 125 - diseases = [ 126 - Disease.objects.create( 127 - patient=patient, 128 - disease=DISEASE_CHOICES_MAP[mh["disease"]], 129 - details=mh["details"], 130 - ) 131 - for mh in medical_history 132 - ] 133 - patient.medical_history.set(diseases) 134 - 135 - return patient 136 - 137 - @classmethod 138 - def get_user_data(cls, district: District = None, user_type: str = None): 112 + def get_user_data(cls, district: District, user_type: str = None): 139 113 """ 140 114 Returns the data to be used for API testing 141 115 ··· 144 118 145 119 Params: 146 120 district: District 147 - user_type: str(A valid mapping for the integer types mentioned inside the models) 121 + user_type: str(A valid mapping for the integer types mentioned 122 + inside the models) 148 123 """ 149 - district = district or cls.district 150 - user_type = user_type or User.TYPE_VALUE_MAP["Staff"] 151 124 152 125 return { 153 - "user_type": user_type, 126 + "user_type": user_type or User.TYPE_VALUE_MAP["Staff"], 154 127 "district": district, 155 128 "state": district.state, 156 129 "phone_number": "8887776665", ··· 162 135 } 163 136 164 137 @classmethod 138 + def link_user_with_facility(cls, user: User, facility: Facility, created_by: User): 139 + FacilityUser.objects.create(user=user, facility=facility, created_by=created_by) 140 + 141 + @classmethod 142 + def create_user( 143 + cls, 144 + username: str = None, 145 + district: District = None, 146 + local_body: LocalBody = None, 147 + **kwargs, 148 + ) -> User: 149 + if username is None: 150 + username = f"user{now().timestamp()}" 151 + 152 + data = { 153 + "email": f"{username}@somedomain.com", 154 + "phone_number": "5554446667", 155 + "age": 30, 156 + "gender": 2, 157 + "verified": True, 158 + "username": username, 159 + "password": "bar", 160 + "state": district.state, 161 + "district": district, 162 + "local_body": local_body, 163 + "user_type": User.TYPE_VALUE_MAP["Staff"], 164 + } 165 + data.update(kwargs) 166 + user = User.objects.create_user(**data) 167 + if home_facility := kwargs.get("home_facility"): 168 + cls.link_user_with_facility(user, home_facility, user) 169 + return user 170 + 171 + @classmethod 172 + def create_super_user(cls, *args, **kwargs) -> User: 173 + return cls.create_user( 174 + *args, 175 + is_superuser=True, 176 + user_type=User.TYPE_VALUE_MAP["StateAdmin"], 177 + **kwargs, 178 + ) 179 + 180 + @classmethod 165 181 def get_facility_data(cls, district): 166 182 """ 167 183 Returns the data to be used for API testing ··· 179 195 "name": "Foo", 180 196 "district": (district or cls.district).id, 181 197 "facility_type": 1, 182 - "address": f"Address {datetime.datetime.now().timestamp}", 198 + "address": f"Address {now().timestamp}", 183 199 "location": {"latitude": 49.878248, "longitude": 24.452545}, 184 200 "pincode": 123456, 185 201 "oxygen_capacity": 10, ··· 188 204 } 189 205 190 206 @classmethod 191 - def get_patient_data(cls, district=None, state=None): 207 + def create_facility( 208 + cls, user: User, district: District, local_body: LocalBody, **kwargs 209 + ) -> Facility: 210 + data = { 211 + "name": "Foo", 212 + "district": district, 213 + "state": district.state, 214 + "local_body": local_body, 215 + "facility_type": 1, 216 + "address": "8/88, 1st Cross, 1st Main, Boo Layout", 217 + "pincode": 123456, 218 + "oxygen_capacity": 10, 219 + "phone_number": "9998887776", 220 + "created_by": user, 221 + } 222 + data.update(kwargs) 223 + return Facility.objects.create(**data) 224 + 225 + @classmethod 226 + def get_patient_data(cls, district, state) -> dict: 192 227 return { 193 228 "name": "Foo", 194 229 "age": 32, 195 - "date_of_birth": datetime.date(1992, 4, 1), 230 + "date_of_birth": date(1992, 4, 1), 196 231 "gender": 2, 197 232 "is_medical_worker": True, 198 233 "is_antenatal": False, ··· 200 235 "allow_transfer": True, 201 236 "blood_group": "O+", 202 237 "ongoing_medication": "", 203 - "date_of_return": make_aware(datetime.datetime(2020, 4, 1, 15, 30, 00)), 238 + "date_of_return": make_aware(datetime(2020, 4, 1, 15, 30, 00)), 204 239 "disease_status": "SUSPECTED", 205 240 "phone_number": "+918888888888", 206 241 "address": "Global citizen", ··· 212 247 "present_health": "Fine", 213 248 "has_SARI": False, 214 249 "is_active": True, 215 - "state": (state or cls.state).id, 216 - "district": (district or cls.district).id, 250 + "state_id": state.id, 251 + "district_id": district.id, 217 252 "local_body": None, 218 253 "number_of_aged_dependents": 2, 219 254 "number_of_chronic_diseased_dependents": 1, 220 255 "medical_history": [{"disease": "Diabetes", "details": "150 count"}], 221 256 "date_of_receipt_of_information": make_aware( 222 - datetime.datetime(2020, 4, 1, 15, 30, 00) 257 + datetime(2020, 4, 1, 15, 30, 00) 223 258 ), 224 259 } 225 260 226 261 @classmethod 227 - def setUpClass(cls) -> None: 228 - super(TestBase, cls).setUpClass() 229 - cls.state = cls.create_state() 230 - cls.district = cls.create_district(cls.state) 231 - cls.user_type = User.TYPE_VALUE_MAP["Staff"] 232 - cls.user = cls.create_user(cls.district) 233 - cls.super_user = cls.create_super_user(district=cls.district) 234 - cls.facility = cls.create_facility(cls.district) 235 - cls.patient = cls.create_patient() 236 - cls.state_admin = cls.create_user( 237 - cls.district, 238 - username="state-admin", 239 - user_type=User.TYPE_VALUE_MAP["StateAdmin"], 240 - home_facility=cls.facility, 262 + def create_patient(cls, district: District, facility: Facility, **kwargs): 263 + patient_data = cls.get_patient_data(district, district.state).copy() 264 + medical_history = patient_data.pop("medical_history", []) 265 + 266 + patient_data.update( 267 + { 268 + "facility": facility, 269 + "disease_status": getattr( 270 + DiseaseStatusEnum, patient_data["disease_status"] 271 + ).value, 272 + } 241 273 ) 242 274 243 - cls.user_data = cls.get_user_data(cls.district, cls.user_type) 244 - cls.facility_data = cls.get_facility_data(cls.district) 245 - cls.patient_data = cls.get_patient_data(cls.district) 275 + patient_data.update(kwargs) 276 + patient = PatientRegistration.objects.create(**patient_data) 277 + diseases = [ 278 + Disease.objects.create( 279 + patient=patient, 280 + disease=DISEASE_CHOICES_MAP[mh["disease"]], 281 + details=mh["details"], 282 + ) 283 + for mh in medical_history 284 + ] 285 + patient.medical_history.set(diseases) 246 286 247 - def setUp(self) -> None: 248 - self.client.force_login(self.user) 287 + return patient 249 288 250 - @abc.abstractmethod 251 - def get_base_url(self): 252 - """ 253 - Should return the base url of the testing viewset 254 - WITHOUT trailing slash 289 + @classmethod 290 + def get_consultation_data(cls): 291 + return { 292 + "patient": cls.patient, 293 + "facility": cls.facility, 294 + "symptoms": [SYMPTOM_CHOICES[0][0], SYMPTOM_CHOICES[1][0]], 295 + "other_symptoms": "No other symptoms", 296 + "symptoms_onset_date": make_aware(datetime(2020, 4, 7, 15, 30)), 297 + "deprecated_covid_category": COVID_CATEGORY_CHOICES[0][0], 298 + "category": CATEGORY_CHOICES[0][0], 299 + "examination_details": "examination_details", 300 + "history_of_present_illness": "history_of_present_illness", 301 + "treatment_plan": "treatment_plan", 302 + "suggestion": PatientConsultation.SUGGESTION_CHOICES[0][0], 303 + "referred_to": None, 304 + "admission_date": None, 305 + "discharge_date": None, 306 + "consultation_notes": "", 307 + "course_in_facility": "", 308 + "created_date": mock_equal, 309 + "modified_date": mock_equal, 310 + } 255 311 256 - eg: return "api/v1/facility" 257 - :return: str 258 - """ 259 - raise NotImplementedError() 312 + @classmethod 313 + def create_consultation( 314 + cls, 315 + patient: PatientRegistration, 316 + facility: Facility, 317 + referred_to=None, 318 + **kwargs, 319 + ) -> PatientConsultation: 320 + data = cls.get_consultation_data().copy() 321 + kwargs.update( 322 + { 323 + "patient": patient, 324 + "facility": facility, 325 + "referred_to": referred_to, 326 + } 327 + ) 328 + data.update(kwargs) 329 + return PatientConsultation.objects.create(**data) 260 330 261 - def get_url(self, entry_id=None, action=None, *args, **kwargs): 262 - url = self.get_base_url(*args, **kwargs) 263 - if entry_id is not None: 264 - url = f"{url}/{entry_id}" 265 - if action is not None: 266 - url = f"{url}/{action}" 267 - return f"{url}/" 331 + @classmethod 332 + def create_asset_location(cls, facility: Facility, **kwargs) -> AssetLocation: 333 + data = {"name": "asset1 location", "location_type": 1, "facility": facility} 334 + data.update(kwargs) 335 + return AssetLocation.objects.create(**data) 336 + 337 + @classmethod 338 + def create_asset(cls, location: AssetLocation, **kwargs) -> Asset: 339 + data = { 340 + "name": "Test Asset", 341 + "current_location": location, 342 + "asset_type": 50, 343 + "warranty_amc_end_of_validity": make_aware(datetime(2030, 4, 1)), 344 + } 345 + data.update(kwargs) 346 + return Asset.objects.create(**data) 268 347 269 348 @classmethod 270 349 def clone_object(cls, obj, save=True): ··· 279 358 new_obj.save() 280 359 return new_obj 281 360 282 - @abc.abstractmethod 283 361 def get_list_representation(self, obj) -> dict: 284 362 """ 285 363 Returns the dict representation of the obj in list API ··· 288 366 """ 289 367 raise NotImplementedError() 290 368 291 - @abc.abstractmethod 292 369 def get_detail_representation(self, obj=None) -> dict: 293 370 """ 294 371 Returns the dict representation of the obj in detail/retrieve API ··· 327 404 "id": local_body.id, 328 405 "name": local_body.name, 329 406 "district": local_body.district.id, 407 + "localbody_code": local_body.localbody_code, 408 + "body_type": local_body.body_type, 330 409 }, 331 410 } 332 411 ··· 367 446 unicode, 368 447 ), 369 448 ): 370 - return_value = datetime.datetime.strptime( 371 - value, "%Y-%m-%dT%H:%M:%S.%fZ" 372 - ) 449 + return_value = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%fZ") 373 450 return ( 374 - return_value.astimezone(tz=datetime.timezone.utc) 375 - if isinstance(return_value, datetime.datetime) 451 + return_value.astimezone(tz=UTC) 452 + if isinstance(return_value, datetime) 376 453 else return_value 377 454 ) 378 455 return value ··· 399 476 }, 400 477 **self.get_local_body_district_state_representation(facility), 401 478 } 402 - 403 - @classmethod 404 - def get_consultation_data(cls): 405 - return { 406 - "patient": cls.patient, 407 - "facility": cls.facility, 408 - "symptoms": [SYMPTOM_CHOICES[0][0], SYMPTOM_CHOICES[1][0]], 409 - "other_symptoms": "No other symptoms", 410 - "symptoms_onset_date": make_aware(datetime.datetime(2020, 4, 7, 15, 30)), 411 - "deprecated_covid_category": COVID_CATEGORY_CHOICES[0][0], 412 - "category": CATEGORY_CHOICES[0][0], 413 - "examination_details": "examination_details", 414 - "history_of_present_illness": "history_of_present_illness", 415 - "treatment_plan": "treatment_plan", 416 - "suggestion": PatientConsultation.SUGGESTION_CHOICES[0][0], 417 - "referred_to": None, 418 - "admission_date": None, 419 - "discharge_date": None, 420 - "consultation_notes": "", 421 - "course_in_facility": "", 422 - "created_date": mock_equal, 423 - "modified_date": mock_equal, 424 - } 425 - 426 - @classmethod 427 - def create_consultation( 428 - cls, patient=None, facility=None, referred_to=None, **kwargs 429 - ) -> PatientConsultation: 430 - data = cls.get_consultation_data() 431 - kwargs.update( 432 - { 433 - "patient": patient or cls.patient, 434 - "facility": facility or cls.facility, 435 - "referred_to": referred_to, 436 - } 437 - ) 438 - data.update(kwargs) 439 - return PatientConsultation.objects.create(**data) 440 - 441 - def create_patient_note( 442 - self, patient=None, note="Patient is doing find", created_by=None, **kwargs 443 - ): 444 - data = { 445 - "facility": patient.facility or self.facility, 446 - "note": note, 447 - } 448 - data.update(kwargs) 449 - 450 - patientId = patient.external_id 451 - 452 - refresh_token = RefreshToken.for_user(created_by) 453 - self.client.credentials( 454 - HTTP_AUTHORIZATION=f"Bearer {refresh_token.access_token}" 455 - ) 456 - 457 - self.client.post(f"/api/v1/patient/{patientId}/notes/", data=data)
+9 -1
config/settings/test.py
··· 35 35 # ------------------------------------------------------------------------------ 36 36 37 37 DATABASES = {"default": env.db("DATABASE_URL", default="postgres:///care-test")} 38 - DATABASES["default"]["ATOMIC_REQUESTS"] = True 38 + 39 + # test in peace 40 + CACHES = { 41 + "default": { 42 + "BACKEND": "django.core.cache.backends.dummy.DummyCache", 43 + } 44 + } 45 + # for testing retelimit use override_settings decorator 46 + SILENCED_SYSTEM_CHECKS = ["django_ratelimit.E003", "django_ratelimit.W001"] 39 47 40 48 # https://whitenoise.evans.io/en/stable/django.html#whitenoise-makes-my-tests-run-slow 41 49 WHITENOISE_AUTOREFRESH = True
-68
config/tests/helper.py
··· 1 - """Use this module for tests in only users api""" 2 - from care.users.models import District, State, User 3 - 4 - # will be fixed later 5 - 6 - 7 - class TestHelper: 8 - """Initialize objects that will be useful for all other tests""" 9 - 10 - @classmethod 11 - def setup_data(cls): 12 - """Initialize the data objects to be used for other function""" 13 - cls.state = State.objects.create(name="KL") 14 - cls.district = District.objects.create(name="Kannur", state=cls.state) 15 - cls.user = User.objects.create( 16 - user_type=10, 17 - district=cls.district, 18 - phone_number="8887776665", 19 - gender=2, 20 - age=30, 21 - email="foo@foobar.com", 22 - username="user", 23 - ) 24 - cls.user.set_password("bar") 25 - cls.user.save() 26 - 27 - cls.user_creds = { 28 - "username": "user", 29 - "password": "bar", 30 - } 31 - 32 - cls.user_data = { 33 - "user_type": 10, 34 - "phone_number": "8887776665", 35 - "gender": 2, 36 - "age": 30, 37 - "email": "foo@foobar.com", 38 - "username": "user", 39 - "password": "bar", 40 - } 41 - 42 - # # this is weird but it is what it is, this data will be used when using the request API 43 - cls.user_data_client = cls.user_data.copy() 44 - cls.user_data_client["user_type"] = "Staff" 45 - 46 - 47 - class EverythingEquals: 48 - def __eq__(self, other): 49 - return True 50 - 51 - 52 - mock_equal = EverythingEquals() 53 - 54 - 55 - def assert_equal_dicts(d1, d2, ignore_keys=[]): 56 - def check_equal(): 57 - ignored = set(ignore_keys) 58 - for k1, v1 in d1.items(): 59 - if k1 not in ignored and (k1 not in d2 or d2[k1] != v1): 60 - print(k1, v1, d2[k1]) 61 - return False 62 - for k2, v2 in d2.items(): 63 - if k2 not in ignored and k2 not in d1: 64 - print(k2, v2) 65 - return False 66 - return True 67 - 68 - return check_equal()
+5 -5
pyproject.toml
··· 1 1 [tool.coverage.run] 2 2 branch = true 3 - source = ["care", "config"] 3 + source = ["care"] 4 4 parallel = true 5 5 concurrency = ["multiprocessing"] 6 - 7 - 8 - [tool.coverage.report] 6 + relative_files = true 9 7 omit = [ 10 8 "*/tests/*", 11 - "*/migrations/*", 9 + "*/migrations*/*", 12 10 "*/asgi.py", 13 11 "*/wsgi.py", 14 12 "manage.py", 15 13 ".venv/*" 16 14 ] 15 + 16 + [tool.coverage.report] 17 17 exclude_lines = [ 18 18 "pragma: no cover", 19 19 "raise NotImplementedError"