def test_simple_post():
    with patch.object(requests.Session, 'request') as request_mock, \
            patch.object(RequestLog, 'log') as log_mock:
        request_mock.return_value = Response()
        auth_manager = BasicAuthManager(TEST_API_USERNAME, TEST_API_PASSWORD)
        response = simple_post(
            domain=TEST_DOMAIN,
            url=TEST_API_URL,
            data='<payload id="abc123"><parrot status="déad" /></payload>',
            headers={'Content-Type': 'text/xml+parrot'},
            auth_manager=auth_manager,
            verify=True,
            payload_id=TEST_PAYLOAD_ID,
        )

        request_mock.assert_called_with(
            'POST',
            TEST_API_URL,
            data=b'<payload id="abc123"><parrot status="d\xc3\xa9ad" /></payload>',
            headers={
                'Content-Type': 'text/xml+parrot',
                'content-length': '56',
            },
            json=None,
            timeout=REQUEST_TIMEOUT,
        )
        ((__, (level, log_entry), ___),) = log_mock.mock_calls
        assert_equal(level, logging.INFO)
        assert_equal(log_entry.payload_id, TEST_PAYLOAD_ID)
        assert_equal(response.status_code, 200)
Exemple #2
0
 def get_auth_manager(self):
     if self.auth_type is None:
         return AuthManager()
     if self.auth_type == BASIC_AUTH:
         return BasicAuthManager(
             self.username,
             self.plaintext_password,
         )
     if self.auth_type == DIGEST_AUTH:
         return DigestAuthManager(
             self.username,
             self.plaintext_password,
         )
     if self.auth_type == OAUTH1:
         return OAuth1Manager(
             client_id=self.client_id,
             client_secret=self.plaintext_client_secret,
             api_endpoints=self._get_oauth1_api_endpoints(),
             connection_settings=self,
         )
     if self.auth_type == BEARER_AUTH:
         return BearerAuthManager(
             self.username,
             self.plaintext_password,
         )
     if self.auth_type == OAUTH2_PWD:
         return OAuth2PasswordGrantManager(
             self.url,
             self.username,
             self.plaintext_password,
             client_id=self.client_id,
             client_secret=self.plaintext_client_secret,
             api_settings=self._get_oauth2_api_settings(),
             connection_settings=self,
         )
def test_simple_request_DELETE():
    with patch.object(requests.Session, 'request') as request_mock, \
         patch.object(RequestLog, 'log'):
        request_mock.return_value = Response()
        auth_manager = BasicAuthManager(TEST_API_USERNAME, TEST_API_PASSWORD)
        simple_request(
            domain=TEST_DOMAIN,
            url=TEST_API_URL,
            data='<payload id="abc123"><parrot status="déad" /></payload>',
            headers={'Content-Type': 'text/xml+parrot'},
            auth_manager=auth_manager,
            verify=True,
            payload_id=TEST_PAYLOAD_ID,
            method="DELETE")

        request_mock.assert_called_with(
            'DELETE',
            TEST_API_URL,
            data=
            b'<payload id="abc123"><parrot status="d\xc3\xa9ad" /></payload>',
            headers={
                'Content-Type': 'text/xml+parrot',
                'content-length': '56',
            },
            timeout=REQUEST_TIMEOUT,
        )
Exemple #4
0
def test_generate_identifier():
    auth_manager = BasicAuthManager(USERNAME, PASSWORD)
    requests = Requests(
        DOMAIN,
        BASE_URL,
        verify=False,  # demo.mybahmni.org uses a self-issued cert
        auth_manager=auth_manager,
        logger=dummy_logger,
    )
    identifier = generate_identifier(requests, IDENTIFIER_TYPE)
    assert_regexp_matches(identifier, r'^BAH\d{6}$')  # e.g. BAH203001
Exemple #5
0
    def get_auth_manager(self):
        # Auth types that don't require a username:
        if self.auth_type is None:
            return AuthManager()
        if self.auth_type == OAUTH1:
            return OAuth1Manager(
                client_id=self.client_id,
                client_secret=self.plaintext_client_secret,
                api_endpoints=self._get_oauth1_api_endpoints(),
                connection_settings=self,
            )
        if self.auth_type == OAUTH2_CLIENT:
            return OAuth2ClientGrantManager(
                self.url,
                client_id=self.client_id,
                client_secret=self.plaintext_client_secret,
                token_url=self.token_url,
                refresh_url=self.refresh_url,
                connection_settings=self,
            )

        # Auth types that require a username:
        if not isinstance(self.username, str):
            return AuthManager()
        if self.auth_type == BASIC_AUTH:
            return BasicAuthManager(
                self.username,
                self.plaintext_password,
            )
        if self.auth_type == DIGEST_AUTH:
            return DigestAuthManager(
                self.username,
                self.plaintext_password,
            )
        if self.auth_type == BEARER_AUTH:
            return BearerAuthManager(
                self.username,
                self.plaintext_password,
            )
        if self.auth_type == OAUTH2_PWD:
            return OAuth2PasswordGrantManager(
                self.url,
                self.username,
                self.plaintext_password,
                client_id=self.client_id,
                client_secret=self.plaintext_client_secret,
                token_url=self.token_url,
                refresh_url=self.refresh_url,
                pass_credentials_in_header=self.pass_credentials_in_header,
                connection_settings=self,
            )
        raise ValueError(f'Unknown auth type {self.auth_type!r}')
def test_simple_post_400():
    with patch.object(requests.Session, 'request') as request_mock, \
            patch.object(Requests, 'notify_error') as notify_mock, \
            patch.object(RequestLog, 'log'):
        response = Response()
        response.status_code = 400
        response.content = b'Bad request'
        request_mock.return_value = response
        auth_manager = BasicAuthManager(TEST_API_USERNAME, TEST_API_PASSWORD)
        response = simple_post(
            domain=TEST_DOMAIN,
            url=TEST_API_URL,
            data='<payload id="abc123"><parrot status="déad" /></payload>',
            headers={'Content-Type': 'text/xml+parrot'},
            auth_manager=auth_manager,
            verify=True,
            payload_id=TEST_PAYLOAD_ID,
        )
        notify_mock.assert_called_with('HTTP status code 400: Bad request')
        assert_equal(response.status_code, 400)
Exemple #7
0
 def get_auth_manager(self):
     if self.auth_type is None:
         return AuthManager()
     if self.auth_type == BASIC_AUTH:
         return BasicAuthManager(
             self.username,
             self.plaintext_password,
         )
     if self.auth_type == DIGEST_AUTH:
         return DigestAuthManager(
             self.username,
             self.plaintext_password,
         )
     if self.auth_type == OAUTH1:
         raise NotImplementedError(
             _('OAuth1 authentication workflow not yet supported.'))
     if self.auth_type == BEARER_AUTH:
         return BearerAuthManager(
             self.username,
             self.plaintext_password,
         )
Exemple #8
0
 def test_basic_auth(self):
     auth_manager = BasicAuthManager(USERNAME, PASSWORD)
     auth = auth_manager.get_auth()
     self.assertEqual(auth.__class__.__name__, 'HTTPBasicAuth')
Exemple #9
0
def get_basic_requests(domain_name, base_url, username, password, **kwargs):
    """
    Returns a Requests instance with basic auth.
    """
    kwargs['auth_manager'] = BasicAuthManager(username, password)
    return Requests(domain_name, base_url, **kwargs)
Exemple #10
0
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',
        ))