def send_request(self, repeat_record, payload): """ Sends API request and returns response if ``payload`` is a form that is configured to be forwarded to DHIS2. If ``payload`` is a form that isn't configured to be forwarded, returns True. """ requests = Requests( self.domain, self.url, self.username, self.plaintext_password, verify=self.verify, notify_addresses=self.notify_addresses, payload_id=repeat_record.payload_id, ) for form_config in self.dhis2_config.form_configs: if form_config.xmlns == payload['form']['@xmlns']: try: return send_dhis2_event( requests, form_config, payload, ) except (RequestException, HTTPError, ConfigurationError) as err: requests.notify_error(f"Error sending Events to {self}: {err}") raise return True
class RequestsTests(SimpleTestCase): def setUp(self): self.requests = Requests(TEST_DOMAIN, TEST_API_URL, TEST_API_USERNAME, TEST_API_PASSWORD, logger=noop_logger) self.org_unit_id = 'abc' self.data_element_id = '123' def test_authentication(self): with patch.object(requests.Session, 'request') as request_mock: content = {'code': TEST_API_USERNAME} content_json = json.dumps(content) response_mock = Mock() response_mock.status_code = 200 response_mock.content = content_json response_mock.json.return_value = content request_mock.return_value = response_mock response = self.requests.get('me') request_mock.assert_called_with( 'GET', TEST_API_URL + 'me', allow_redirects=True, headers={'Accept': 'application/json'}, auth=(TEST_API_USERNAME, TEST_API_PASSWORD), timeout=REQUEST_TIMEOUT, ) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['code'], TEST_API_USERNAME) def test_send_data_value_set(self): with patch.object(requests.Session, 'request') as request_mock: payload = { 'dataValues': [ { 'dataElement': self.data_element_id, 'period': "201701", 'orgUnit': self.org_unit_id, 'value': "180" }, { 'dataElement': self.data_element_id, 'period': "201702", 'orgUnit': self.org_unit_id, 'value': "200" }, ] } content = {'status': 'SUCCESS', 'importCount': {'imported': 2}} content_json = json.dumps(content) response_mock = Mock() response_mock.status_code = 201 response_mock.content = content_json response_mock.json.return_value = content request_mock.return_value = response_mock response = self.requests.post('dataValueSets', json=payload) request_mock.assert_called_with( 'POST', 'http://*****:*****@example.com', '*****@*****.**']) with patch('corehq.motech.requests.send_mail_async') as send_mail_mock: requests.notify_error('foo') send_mail_mock.delay.assert_called_with( 'MOTECH Error', ('foo\r\n' 'Project space: test-domain\r\n' 'Remote API base URL: http://localhost:9080/api/\r\n' 'Remote API username: admin'), from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=['*****@*****.**', '*****@*****.**'])
def import_patients_with_importer(importer_json): importer = OpenmrsImporter.wrap(importer_json) password = b64_aes_decrypt(importer.password) requests = Requests(importer.domain, importer.server_url, importer.username, password, notify_addresses=importer.notify_addresses) if importer.location_type_name: try: location_type = LocationType.objects.get( domain=importer.domain, name=importer.location_type_name) except LocationType.DoesNotExist: requests.notify_error( f'No organization level named "{importer.location_type_name}" ' f'found in project space "{importer.domain}".') return if importer.location_id: location = SQLLocation.objects.filter(domain=importer.domain).get( importer.location_id) locations = location.get_descendants.filter( location_type=location_type) else: locations = SQLLocation.objects.filter(domain=importer.domain, location_type=location_type) for location in locations: # Assign cases to the first user in the location, not to the location itself owner = get_one_commcare_user_at_location(importer.domain, location.location_id) if not owner: requests.notify_error( f'Project space "{importer.domain}" at location ' f'"{location.name}" has no user to own cases imported ' f'from OpenMRS Importer "{importer}"') continue # The same report is fetched for each location. WE DO THIS # ASSUMING THAT THE LOCATION IS USED IN THE REPORT # PARAMETERS. If not, OpenMRS will return THE SAME PATIENTS # multiple times and they will be assigned to a different # user each time. try: import_patients_of_owner(requests, importer, importer.domain, owner.user_id, location) except ConfigurationError as err: requests.notify_error(str(err)) elif importer.owner_id: if not is_valid_owner(importer.owner_id): requests.notify_error( f'Error importing patients for project space "{importer.domain}" ' f'from OpenMRS Importer "{importer}": owner_id "{importer.owner_id}" ' 'is invalid.') return try: import_patients_of_owner(requests, importer, importer.domain, importer.owner_id) except ConfigurationError as err: requests.notify_error(str(err)) else: requests.notify_error( f'Error importing patients for project space "{importer.domain}" from ' f'OpenMRS Importer "{importer}": Unable to determine the owner of ' 'imported cases without either owner_id or location_type_name')