PageRenderTime 68ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/pact_apps/pactpatient/tests/patient_caseupdates.py

https://github.com/dimagi/carehq
Python | 270 lines | 173 code | 55 blank | 42 comment | 15 complexity | f1bf0f8dd8e40704ff8bef81f41d6520 MD5 | raw file
  1. from StringIO import StringIO
  2. import pdb
  3. import random
  4. import uuid
  5. from django.contrib.sessions.backends.file import SessionStore
  6. from django.core.management import call_command
  7. import re
  8. from django.contrib.auth.models import User
  9. from django.core.urlresolvers import reverse
  10. from django.test import TestCase, Client
  11. from clinical_shared.tests.testcase import CareHQClinicalTestCase
  12. from clinical_shared.utils import generator
  13. from clinical_shared.utils.scrambler import make_random_cphone, make_random_caddress
  14. from couchforms.models import XFormInstance
  15. from casexml.apps.case.models import CommCareCase
  16. from pactpatient.models import PactPatient
  17. from pactpatient.views import new_patient
  18. from patient.models import Patient
  19. from .pactpatient_test_utils import delete_all
  20. from pactpatient.updater import generate_update_xml_old
  21. from django_digest.test import Client as DigestClient
  22. from permissions.models import Actor, Role, PrincipalRoleRelation
  23. from permissions.tests import RequestFactory
  24. from tenant.models import Tenant
  25. class patientCaseUpdateTests(CareHQClinicalTestCase):
  26. NUM_PHONES = 5
  27. NUM_ADDRESSES = 2
  28. def setUp(self):
  29. User.objects.all().delete()
  30. Actor.objects.all().delete()
  31. Role.objects.all().delete()
  32. PrincipalRoleRelation.objects.all().delete()
  33. delete_all(PactPatient, 'patient/all')
  34. call_command('carehq_init')
  35. self.tenant = Tenant.objects.all()[0]
  36. self._createUser()
  37. self.client = Client()
  38. def testOTARestore(self):
  39. """
  40. For a given patient created, ensure that it shows up in the OTA restore.
  41. Ensure also that changes in phone and addresses also show up in OTA restore.
  42. This test also uses django_digest to authenticate to the OTA restore URL.
  43. Verify all the phone and address information
  44. """
  45. patient_doc = self.test0CreatePatient()
  46. client = DigestClient()
  47. client.set_authorization(self.user.username, 'mockmock', 'Digest')
  48. restore_payload = client.get('/provider/caselist')
  49. case_id_re = re.compile('<case_id>(?P<case_id>\w+)<\/case_id>')
  50. case_id_xml = case_id_re.search(restore_payload.content).group('case_id')
  51. casedoc = CommCareCase.get(patient_doc.case_id)
  52. self.assertEqual(case_id_xml, casedoc._id)
  53. def test3PushPhonesIteratively(self):
  54. """
  55. Check to see if transactional single updates can do it vs. doing all each time
  56. """
  57. patient_doc = self.test0CreatePatient()
  58. allphones = []
  59. addresses = []
  60. for n in range(0, self.NUM_PHONES):
  61. newphone = make_random_cphone()
  62. newphone.description += "%s" % str(n + 1)
  63. allphones.append(newphone)
  64. to_send = [None for q in range(0, n)]
  65. to_send.append(newphone)
  66. #now, submit the xml.
  67. xml_body = generate_update_xml_old(User.objects.all()[0], patient_doc, to_send, addresses)
  68. xml_stream = StringIO(xml_body.encode('utf-8'))
  69. xml_stream.name = "xml_submission_file"
  70. uid_re = re.compile('<uid>(?P<doc_id>\w+)<\/uid>')
  71. submit_doc_id = uid_re.search(xml_body).group('doc_id')
  72. response = self.client.post(reverse('receiver.views.post'), {'xml_submission_file': xml_stream})
  73. #verify submission worked
  74. try:
  75. XFormInstance.get(submit_doc_id)
  76. except:
  77. self.fail("XForm submit failed")
  78. #verify casexml updated
  79. casedoc_updated = CommCareCase.get(patient_doc.case_id)
  80. for i, p in enumerate(allphones, start=1):
  81. self.assertTrue(hasattr(casedoc_updated, 'Phone%d' % i))
  82. self.assertEquals(p.number, getattr(casedoc_updated, 'Phone%d' % i))
  83. self.assertEquals(p.description, getattr(casedoc_updated, 'Phone%dType' % i))
  84. self.assertTrue(hasattr(casedoc_updated, 'Phone%dType' % i))
  85. def test2PushNewPhone(self):
  86. """
  87. Verify on the webform that the display is showing up on the patient view.
  88. """
  89. patient, phones, addresses = self.test1CreatePatientVerifyAddressAPI()
  90. response = self.client.post('/accounts/login/', {'username': 'mockmock@mockmock.com', 'password': 'mockmock'})
  91. response = self.client.get(reverse('view_pactpatient', kwargs={'patient_guid': patient._id}))
  92. content = response.content
  93. phone_indices = []
  94. for p in phones:
  95. #make sure the numbers are in the right order
  96. phone_indices.append(content.index(p.number))
  97. self.assertEquals(sorted(phone_indices), phone_indices)
  98. def test1CreatePatientVerifyAddressAPI(self):
  99. """
  100. Test create phone and addresses, submit via casexml and verify casexml gets updated with latest from patient model.
  101. This does it via API
  102. """
  103. patient_doc = self.test0CreatePatient()
  104. phones = []
  105. addresses = []
  106. for n in range(0, self.NUM_PHONES):
  107. newphone = make_random_cphone()
  108. newphone.description += "%s" % str(n + 1)
  109. phones.append(newphone)
  110. for n in range(0, self.NUM_ADDRESSES):
  111. newaddress = make_random_caddress()
  112. newaddress.description += "%s" % str(n + 1)
  113. addresses.append(newaddress)
  114. patient_doc.save()
  115. #first verify that the case got nothing
  116. casedoc_blank = CommCareCase.get(patient_doc.case_id)
  117. for n in range(1, self.NUM_PHONES + 1):
  118. self.assertFalse(hasattr(casedoc_blank, 'Phone%d' % n))
  119. self.assertFalse(hasattr(casedoc_blank, 'Phone%dType' % n))
  120. for n in range(1, self.NUM_ADDRESSES + 1):
  121. self.assertFalse(hasattr(casedoc_blank, 'address%d' % n))
  122. self.assertFalse(hasattr(casedoc_blank, 'address%dtype' % n))
  123. #now, submit the xml.
  124. xml_body = generate_update_xml_old(User.objects.all()[0], patient_doc, phones, addresses)
  125. xml_stream = StringIO(xml_body.encode('utf-8'))
  126. xml_stream.name = "xml_submission_file"
  127. uid_re = re.compile('<uid>(?P<doc_id>\w+)<\/uid>')
  128. submit_doc_id = uid_re.search(xml_body).group('doc_id')
  129. response = self.client.post(reverse('receiver.views.post'), {'xml_submission_file': xml_stream})
  130. #verify submission worked
  131. try:
  132. XFormInstance.get(submit_doc_id)
  133. except:
  134. self.fail("XForm submit failed")
  135. #verify casexml updated
  136. casedoc_updated = CommCareCase.get(patient_doc.case_id)
  137. for n in range(1, self.NUM_PHONES + 1):
  138. p = phones[n - 1]
  139. self.assertTrue(hasattr(casedoc_updated, 'Phone%d' % n))
  140. self.assertEquals(p.number, getattr(casedoc_updated, 'Phone%d' % n))
  141. self.assertEquals(p.description, getattr(casedoc_updated, 'Phone%dType' % n))
  142. self.assertTrue(hasattr(casedoc_updated, 'Phone%dType' % n))
  143. for n in range(1, self.NUM_ADDRESSES + 1):
  144. address = addresses[n - 1]
  145. self.assertTrue(hasattr(casedoc_updated, 'address%d' % n))
  146. self.assertTrue(hasattr(casedoc_updated, 'address%dtype' % n))
  147. self.assertEquals(address.description, getattr(casedoc_updated, 'address%dtype' % n))
  148. #next verify OTA restore
  149. client = DigestClient()
  150. client.set_authorization(self.user.username, 'mockmock', 'Digest')
  151. restore_payload = client.get('/provider/caselist')
  152. for n in range(1, self.NUM_PHONES + 1):
  153. phone = phones[n - 1]
  154. phone_re = re.compile('<Phone%d>(?P<phone>.*)<\/Phone%d>' % (n, n))
  155. phone_str = phone_re.search(restore_payload.content).group('phone')
  156. self.assertEquals(phone.number, phone_str)
  157. desc_re = re.compile('<Phone%dType>(?P<desc>.*)<\/Phone%dType>' % (n, n))
  158. desc_str = desc_re.search(restore_payload.content).group('desc')
  159. self.assertEquals(phone.description, desc_str)
  160. for n in range(1, self.NUM_ADDRESSES + 1):
  161. address = addresses[n - 1]
  162. address_re = re.compile('<address%d>(?P<address>.*)<\/address%d>' % (n, n))
  163. address_str = address_re.search(restore_payload.content).group('address')
  164. self.assertEquals(address.get_full_address(), address_str)
  165. desc_re = re.compile('<address%dtype>(?P<desc>.*)<\/address%dtype>' % (n, n))
  166. desc_str = desc_re.search(restore_payload.content).group('desc')
  167. self.assertEquals(address.description, desc_str)
  168. casedoc = CommCareCase.get(patient_doc.case_id)
  169. return patient_doc, phones, addresses
  170. def test0CreatePatient(self):
  171. """
  172. Test creates new patients and verify casexml is made alongside them
  173. Returns a patient couchdoc.
  174. """
  175. chws = []
  176. for x in range(0,5):
  177. chws.append(self._new_chw(self.tenant, generator.get_or_create_user()))
  178. response = self.client.post('/accounts/login/', {'username': 'mockmock@mockmock.com', 'password': 'mockmock'})
  179. response = self.client.post('/patient/new', {'first_name':'foo',
  180. 'last_name': 'bar',
  181. 'gender':'m',
  182. 'birthdate': '1/1/2000',
  183. 'pact_id': 'mockmock',
  184. 'arm': 'DOT',
  185. 'art_regimen': 'QD',
  186. 'non_art_regimen': 'BID',
  187. 'primary_hp': random.choice(chws).django_actor.user.username,
  188. 'patient_id': uuid.uuid4().hex,
  189. 'race': 'asian',
  190. 'is_latino': 'yes',
  191. 'mass_health_expiration': '1/1/2020',
  192. 'hiv_care_clinic': 'brigham_and_womens_hospital',
  193. 'ssn': '1112223333',
  194. 'preferred_language': 'english',
  195. })
  196. self.assertEquals(response.status_code, 302) #if it's successful, then it'll do a redirect.
  197. # rf = RequestFactory()
  198. # request = rf.get('/')
  199. # request.session = SessionStore()
  200. # request.user = self.user
  201. # request.POST = newpatient_data
  202. # request.method = "POST"
  203. # response = new_patient(request)
  204. self.assertEquals(response.status_code, 302) #if it's successful, then it'll do a redirect.
  205. self.assertEqual(1, Patient.objects.all().count())
  206. patient = Patient.objects.all()[0]
  207. casedoc = CommCareCase.get(patient.couchdoc.case_id)
  208. self.assertEquals(casedoc.external_id, patient.couchdoc.pact_id)
  209. return patient.couchdoc
  210. #start pushing xml submissions via form
  211. #verify that they get updated on casexml
  212. #verify on website that those phone numbers appear with client view..
  213. #setup phone numbers using old style