def test_verify_ssl(self): with patch('corehq.motech.requests.RequestLog', Mock()), \ patch('corehq.motech.requests.requests') as requests_mock: requests = Requests(TEST_DOMAIN, TEST_API_URL, TEST_API_USERNAME, TEST_API_PASSWORD, verify=False) requests.get('me') requests_mock.get.assert_called_with( TEST_API_URL + 'me', headers={'Accept': 'application/json'}, auth=(TEST_API_USERNAME, TEST_API_PASSWORD), verify=False )
def test_verify_ssl(self): with patch('corehq.motech.requests.RequestLog', Mock()), \ patch('corehq.motech.requests.requests') as requests_mock: requests = Requests(TEST_DOMAIN, TEST_API_URL, TEST_API_USERNAME, TEST_API_PASSWORD, verify=False) requests.get('me') requests_mock.get.assert_called_with( TEST_API_URL + 'me', headers={'Accept': 'application/json'}, auth=(TEST_API_USERNAME, TEST_API_PASSWORD), verify=False)
def test_verify_ssl(self): with patch.object(requests.Session, 'request') as request_mock: req = Requests(TEST_DOMAIN, TEST_API_URL, TEST_API_USERNAME, TEST_API_PASSWORD, verify=False, logger=noop_logger) req.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, verify=False)
def openmrs_raw_api(request, domain, repeater_id, rest_uri): get_params = dict(request.GET) no_links = get_params.pop('links', None) is None repeater = OpenmrsRepeater.get(repeater_id) assert repeater.domain == domain requests = Requests(repeater.domain, repeater.url, repeater.username, repeater.password) raw_json = requests.get('/ws/rest/v1' + rest_uri, get_params).json() if no_links: return JsonResponse(_filter_out_links(raw_json)) return JsonResponse(raw_json)
class JsonApiRequestTests(SimpleTestCase): def setUp(self): self.requests = Requests(TEST_DOMAIN, TEST_API_URL, TEST_API_USERNAME, TEST_API_PASSWORD) self.org_unit_id = 'abc' self.data_element_id = '123' def test_authentication(self): with patch('corehq.motech.requests.RequestLog', Mock()), \ patch('corehq.motech.requests.requests') as requests_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 requests_mock.get.return_value = response_mock response = self.requests.get('me') requests_mock.get.assert_called_with( TEST_API_URL + 'me', headers={'Accept': 'application/json'}, auth=(TEST_API_USERNAME, TEST_API_PASSWORD) ) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['code'], TEST_API_USERNAME) def test_send_data_value_set(self): with patch('corehq.motech.requests.RequestLog', Mock()), \ patch('corehq.motech.requests.requests') as requests_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 requests_mock.post.return_value = response_mock response = self.requests.post('dataValueSets', json=payload) requests_mock.post.assert_called_with( 'http://localhost:9080/api/dataValueSets', json=payload, headers={'Content-type': 'application/json', 'Accept': 'application/json'}, auth=(TEST_API_USERNAME, TEST_API_PASSWORD) ) self.assertEqual(response.status_code, 201) self.assertEqual(response.json()['status'], 'SUCCESS') self.assertEqual(response.json()['importCount']['imported'], 2)
class RequestsTests(SimpleTestCase): def setUp(self): self.requests = Requests(TEST_DOMAIN, TEST_API_URL, TEST_API_USERNAME, TEST_API_PASSWORD) self.org_unit_id = 'abc' self.data_element_id = '123' def test_authentication(self): with patch('corehq.motech.requests.RequestLog', Mock()), \ 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)) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['code'], TEST_API_USERNAME) def test_send_data_value_set(self): with patch('corehq.motech.requests.RequestLog', Mock()), \ 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://localhost:9080/api/dataValueSets', data=None, json=payload, headers={ 'Content-type': 'application/json', 'Accept': 'application/json' }, auth=(TEST_API_USERNAME, TEST_API_PASSWORD)) self.assertEqual(response.status_code, 201) self.assertEqual(response.json()['status'], 'SUCCESS') self.assertEqual(response.json()['importCount']['imported'], 2) def test_verify_ssl(self): with patch('corehq.motech.requests.RequestLog', Mock()), \ patch.object(requests.Session, 'request') as request_mock: self.requests = Requests(TEST_DOMAIN, TEST_API_URL, TEST_API_USERNAME, TEST_API_PASSWORD, verify=False) 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), verify=False) def test_with_session(self): with patch('corehq.motech.requests.RequestLog', Mock()), \ patch.object(requests.Session, 'request'), \ patch.object(requests.Session, 'close') as close_mock: with Requests(TEST_DOMAIN, TEST_API_URL, TEST_API_USERNAME, TEST_API_PASSWORD) as self.requests: self.requests.get('me') self.requests.get('me') self.requests.get('me') self.assertEqual(close_mock.call_count, 1) def test_without_session(self): with patch('corehq.motech.requests.RequestLog', Mock()), \ patch.object(requests.Session, 'request'), \ patch.object(requests.Session, 'close') as close_mock: self.requests.get('me') self.requests.get('me') self.requests.get('me') self.assertEqual(close_mock.call_count, 3) def test_with_and_without_session(self): with patch('corehq.motech.requests.RequestLog', Mock()), \ patch.object(requests.Session, 'request'), \ patch.object(requests.Session, 'close') as close_mock: with Requests(TEST_DOMAIN, TEST_API_URL, TEST_API_USERNAME, TEST_API_PASSWORD) as self.requests: self.requests.get('me') self.requests.get('me') self.requests.get('me') self.requests.get('me') self.assertEqual(close_mock.call_count, 2)
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=['*****@*****.**', '*****@*****.**'])
class UnpackRequestArgsTests(SimpleTestCase): def setUp(self): self.requests = Requests(TEST_DOMAIN, TEST_API_URL, TEST_API_USERNAME, TEST_API_PASSWORD) content = {'status': 'Created'} self.content_json = json.dumps(content) self.request_method = 'POST' self.request_headers = { 'Content-type': 'application/json', 'Accept': 'application/json' } self.status_code = 201 self.error_message = '' self.uri = 'person/' self.json_data = {'name': 'Alice'} self.data = json.dumps(self.json_data) self.response_mock = Mock() self.response_mock.status_code = self.status_code self.response_mock.content = self.content_json self.response_mock.json.return_value = content def assert_create_called_with_request_body_and_params( self, create_mock, request_body, request_params=None): create_mock.assert_called_with( domain=TEST_DOMAIN, log_level=logging.INFO, request_body=request_body, request_error=self.error_message, request_headers=self.request_headers, request_method=self.request_method, request_params=request_params, request_url='http://localhost:9080/api/person/', response_body=self.content_json, response_status=self.status_code, ) def test_post_with_no_args(self): with patch.object(requests.Session, 'request') as request_mock, \ patch.object(RequestLog.objects, 'create') as create_mock: request_mock.return_value = self.response_mock self.requests.post(self.uri) self.assert_create_called_with_request_body_and_params( create_mock, None) def test_post_with_data_kwarg(self): with patch.object(requests.Session, 'request') as request_mock, \ patch.object(RequestLog.objects, 'create') as create_mock: request_mock.return_value = self.response_mock self.requests.post(self.uri, data=self.data) self.assert_create_called_with_request_body_and_params( create_mock, self.data) def test_post_with_json_kwarg(self): with patch.object(requests.Session, 'request') as request_mock, \ patch.object(RequestLog.objects, 'create') as create_mock: request_mock.return_value = self.response_mock self.requests.post(self.uri, json=self.json_data) self.assert_create_called_with_request_body_and_params( create_mock, self.json_data) def test_post_with_data_arg(self): with patch.object(requests.Session, 'request') as request_mock, \ patch.object(RequestLog.objects, 'create') as create_mock: request_mock.return_value = self.response_mock self.requests.post(self.uri, self.data) self.assert_create_called_with_request_body_and_params( create_mock, self.data) def test_post_with_json_arg(self): with patch.object(requests.Session, 'request') as request_mock, \ patch.object(RequestLog.objects, 'create') as create_mock: request_mock.return_value = self.response_mock self.requests.post(self.uri, None, self.json_data) self.assert_create_called_with_request_body_and_params( create_mock, self.json_data) def test_post_with_data_and_json(self): with patch.object(requests.Session, 'request') as request_mock, \ patch.object(RequestLog.objects, 'create') as create_mock: request_mock.return_value = self.response_mock self.requests.post(self.uri, self.data, self.json_data) self.assert_create_called_with_request_body_and_params( create_mock, self.data) def test_get_with_params(self): content = {'code': TEST_API_USERNAME} self.content_json = json.dumps(content) self.request_method = 'GET' request_params = {'v': 'full'} self.request_headers = {'Accept': 'application/json'} self.status_code = 200 self.response_mock.status_code = self.status_code self.response_mock.content = self.content_json self.response_mock.json.return_value = content with patch.object(requests.Session, 'request') as request_mock, \ patch.object(RequestLog.objects, 'create') as create_mock: request_mock.return_value = self.response_mock self.requests.get(self.uri, request_params) self.assert_create_called_with_request_body_and_params( create_mock, None, request_params) def test_delete(self): content = {'status': 'Deleted'} self.content_json = json.dumps(content) self.request_method = 'DELETE' self.request_headers = {'Accept': 'application/json'} self.status_code = 200 self.response_mock.status_code = self.status_code self.response_mock.content = self.content_json self.response_mock.json.return_value = content with patch.object(requests.Session, 'request') as request_mock, \ patch.object(RequestLog.objects, 'create') as create_mock: request_mock.return_value = self.response_mock self.requests.delete(self.uri) self.assert_create_called_with_request_body_and_params( create_mock, None)
class Dhis2ApiTests(SimpleTestCase): """ These tests are for reference. They demonstrate the DHIS2 API calls relevant to Tracked Entity integration. """ def setUp(self): self.requests = Requests(domain_name, base_url, username, password) @patch('corehq.motech.requests.RequestLog', Mock()) def test_get_index(self): endpoint = f"/api/{api_version}/trackedEntityInstances" params = {"ou": allen_town_health_post_ou} response = self.requests.get(endpoint, params=params) _assert_status_2xx(response) instances = response.json()["trackedEntityInstances"] assert_true(instances) @patch('corehq.motech.requests.RequestLog', Mock()) def test_query(self): last_name = "Pierce" endpoint = f"/api/{api_version}/trackedEntityInstances" params = { "ou": allen_town_health_post_ou, "filter": f"{last_name_attr_id}:EQ:{last_name}", } response = self.requests.get(endpoint, params=params) _assert_status_2xx(response) instances = response.json()["trackedEntityInstances"] assert_true(instances) assert_true( all( _is_attr_equal(te, last_name_attr_id, last_name) for te in instances), "Query results do not match query filter.") @patch('corehq.motech.requests.RequestLog', Mock()) def test_grid_query(self): city = "Johannesburg" endpoint = f"/api/{api_version}/trackedEntityInstances/query" params = { "ou": allen_town_health_post_ou, "filter": f"{city_attr_id}:EQ:{city}", "attribute": [first_name_attr_id, last_name_attr_id], "skipPaging": 1, } response = self.requests.get(endpoint, params=params) _assert_status_2xx(response) @patch('corehq.motech.requests.RequestLog', Mock()) def test_create(self): endpoint = f"/api/{api_version}/trackedEntityInstances" json_data = { "trackedEntityType": person_te_type_id, "orgUnit": allen_town_health_post_ou, "attributes": [ { "attribute": first_name_attr_id, "value": "Nelson" }, { "attribute": last_name_attr_id, "value": "Mandela" }, { "attribute": address_attr_id, "value": "De Tuynhuys" }, { "attribute": city_attr_id, "value": "Cape Town" }, { "attribute": gender_attr_id, "value": "Male" }, ] } response = self.requests.post(endpoint, json=json_data) _assert_status_2xx(response) result = response.json() assert_equal(result["response"]["imported"], 1) tei_id = result["response"]["importSummaries"][0]["reference"] assert_true( re.match(dhis2_id_pattern, tei_id), f'Instance ID "{tei_id}" does not look like a DHIS2 ID', ) tei_url = result["response"]["importSummaries"][0]["href"] assert_true(tei_url.startswith(base_url)) @patch('corehq.motech.requests.RequestLog', Mock()) def test_update(self): tei_id = "wrqfV2SkucE" with get_tracked_entity(self.requests, tei_id) as person: _update_attr(person, first_name_attr_id, "Nelson") _update_attr(person, last_name_attr_id, "Mandela") endpoint = f"/api/{api_version}/trackedEntityInstances/{tei_id}" response = self.requests.put(endpoint, json=person) _assert_status_2xx(response)
class RequestsTests(SimpleTestCase): def setUp(self): self.requests = Requests(TEST_DOMAIN, TEST_API_URL, TEST_API_USERNAME, TEST_API_PASSWORD) self.org_unit_id = 'abc' self.data_element_id = '123' def test_authentication(self): with patch('corehq.motech.requests.RequestLog', Mock()), \ patch('corehq.motech.requests.requests') as requests_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 requests_mock.get.return_value = response_mock response = self.requests.get('me') requests_mock.get.assert_called_with( TEST_API_URL + 'me', headers={'Accept': 'application/json'}, auth=(TEST_API_USERNAME, TEST_API_PASSWORD) ) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['code'], TEST_API_USERNAME) def test_send_data_value_set(self): with patch('corehq.motech.requests.RequestLog', Mock()), \ patch('corehq.motech.requests.requests') as requests_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 requests_mock.post.return_value = response_mock response = self.requests.post('dataValueSets', json=payload) requests_mock.post.assert_called_with( 'http://localhost:9080/api/dataValueSets', json=payload, headers={'Content-type': 'application/json', 'Accept': 'application/json'}, auth=(TEST_API_USERNAME, TEST_API_PASSWORD) ) self.assertEqual(response.status_code, 201) self.assertEqual(response.json()['status'], 'SUCCESS') self.assertEqual(response.json()['importCount']['imported'], 2) def test_verify_ssl(self): with patch('corehq.motech.requests.RequestLog', Mock()), \ patch('corehq.motech.requests.requests') as requests_mock: requests = Requests(TEST_DOMAIN, TEST_API_URL, TEST_API_USERNAME, TEST_API_PASSWORD, verify=False) requests.get('me') requests_mock.get.assert_called_with( TEST_API_URL + 'me', headers={'Accept': 'application/json'}, auth=(TEST_API_USERNAME, TEST_API_PASSWORD), verify=False )
def test_paginated_bundle(): @attr.s(auto_attribs=True) class Response: data: dict def json(self): return self.data fane_jonda = { 'resourceType': 'Patient', 'name': [{ 'given': ['Fane'], 'family': 'Jonda' }], } jone_fanda = { 'resourceType': 'Patient', 'name': [{ 'given': ['Jone'], 'family': 'Fanda' }], } jane_fonda = { 'resourceType': 'Patient', 'name': [{ 'given': ['Jane'], 'family': 'Fonda' }], } base_url = 'https://example.com/api/' requests = Requests('test-domain', base_url, auth_manager=BasicAuthManager('user', 'pass')) # First requests.get should be called with a search endpoint requests.get = Mock(return_value=Response({ 'resourceType': 'bundle', 'link': [ { 'relation': 'self', 'url': base_url + 'Patient/page/1' }, # Page 1 { 'relation': 'next', 'url': base_url + 'Patient/page/2' }, ], 'entry': [ { 'resource': fane_jonda }, { 'resource': jone_fanda }, ], })) # requests.send_request should be called with urls for subsequent pages requests.send_request = Mock(return_value=Response({ 'resourceType': 'bundle', 'link': [ { 'relation': 'self', 'url': base_url + 'Patient/page/2' }, # Page 2 { 'relation': 'previous', 'url': base_url + 'Patient/page/1' }, ], 'entry': [{ 'resource': jane_fonda }], })) resource = { 'resourceType': 'Patient', 'name': [{ 'given': ['Jane', 'Seymour'], 'family': 'Fonda' }], 'gender': 'female', 'birthDate': '1937-12-21', 'address': [{ 'country': 'United States of America' }], } search_params = PatientSearcher.search_search_params[1] search = Search(requests, resource, search_params) candidates = search.iter_candidates() assert_equal(next(candidates), fane_jonda) assert_equal(next(candidates), jone_fanda) assert_equal(next(candidates), jane_fonda) # The first request searched the Patient endpoint assert_true( requests.get.called_with('Patient/', params={ 'given': 'Jane Seymour', 'family': 'Fonda', 'gender': 'female', 'birthdate': '1937-12-21', 'address-country': 'United States of America', })) # The next request called the "next" URL assert_true( requests.get.called_with( 'GET', 'https://example.com/api/Patient/page/2', ))