示例#1
0
class ClientNetworkTest(unittest.TestCase):
    """Tests for acme.client.ClientNetwork."""
    def setUp(self):
        self.verify_ssl = mock.MagicMock()
        self.wrap_in_jws = mock.MagicMock(return_value=mock.sentinel.wrapped)

        from acme.client import ClientNetwork
        self.net = ClientNetwork(key=KEY,
                                 alg=jose.RS256,
                                 verify_ssl=self.verify_ssl,
                                 user_agent='acme-python-test')

        self.response = mock.MagicMock(ok=True, status_code=http_client.OK)
        self.response.headers = {}
        self.response.links = {}

    def test_init(self):
        self.assertTrue(self.net.verify_ssl is self.verify_ssl)

    def test_wrap_in_jws(self):
        class MockJSONDeSerializable(jose.JSONDeSerializable):
            # pylint: disable=missing-docstring
            def __init__(self, value):
                self.value = value

            def to_partial_json(self):
                return {'foo': self.value}

            @classmethod
            def from_json(cls, value):
                pass  # pragma: no cover

        # pylint: disable=protected-access
        jws_dump = self.net._wrap_in_jws(MockJSONDeSerializable('foo'),
                                         nonce=b'Tg')
        jws = acme_jws.JWS.json_loads(jws_dump)
        self.assertEqual(json.loads(jws.payload.decode()), {'foo': 'foo'})
        self.assertEqual(jws.signature.combined.nonce, b'Tg')

    def test_check_response_not_ok_jobj_no_error(self):
        self.response.ok = False
        self.response.json.return_value = {}
        with mock.patch('acme.client.messages.Error.from_json') as from_json:
            from_json.side_effect = jose.DeserializationError
            # pylint: disable=protected-access
            self.assertRaises(errors.ClientError, self.net._check_response,
                              self.response)

    def test_check_response_not_ok_jobj_error(self):
        self.response.ok = False
        self.response.json.return_value = messages.Error(
            detail='foo', typ='serverInternal', title='some title').to_json()
        # pylint: disable=protected-access
        self.assertRaises(messages.Error, self.net._check_response,
                          self.response)

    def test_check_response_not_ok_no_jobj(self):
        self.response.ok = False
        self.response.json.side_effect = ValueError
        # pylint: disable=protected-access
        self.assertRaises(errors.ClientError, self.net._check_response,
                          self.response)

    def test_check_response_ok_no_jobj_ct_required(self):
        self.response.json.side_effect = ValueError
        for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:
            self.response.headers['Content-Type'] = response_ct
            # pylint: disable=protected-access
            self.assertRaises(errors.ClientError,
                              self.net._check_response,
                              self.response,
                              content_type=self.net.JSON_CONTENT_TYPE)

    def test_check_response_ok_no_jobj_no_ct(self):
        self.response.json.side_effect = ValueError
        for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:
            self.response.headers['Content-Type'] = response_ct
            # pylint: disable=protected-access,no-value-for-parameter
            self.assertEqual(self.response,
                             self.net._check_response(self.response))

    def test_check_response_jobj(self):
        self.response.json.return_value = {}
        for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:
            self.response.headers['Content-Type'] = response_ct
            # pylint: disable=protected-access,no-value-for-parameter
            self.assertEqual(self.response,
                             self.net._check_response(self.response))

    def test_send_request(self):
        self.net.session = mock.MagicMock()
        self.net.session.request.return_value = self.response
        # pylint: disable=protected-access
        self.assertEqual(
            self.response,
            self.net._send_request('HEAD',
                                   'http://example.com/',
                                   'foo',
                                   bar='baz'))
        self.net.session.request.assert_called_once_with('HEAD',
                                                         'http://example.com/',
                                                         'foo',
                                                         headers=mock.ANY,
                                                         verify=mock.ANY,
                                                         timeout=mock.ANY,
                                                         bar='baz')

    @mock.patch('acme.client.logger')
    def test_send_request_get_der(self, mock_logger):
        self.net.session = mock.MagicMock()
        self.net.session.request.return_value = mock.MagicMock(
            ok=True,
            status_code=http_client.OK,
            headers={"Content-Type": "application/pkix-cert"},
            content=b"hi")
        # pylint: disable=protected-access
        self.net._send_request('HEAD',
                               'http://example.com/',
                               'foo',
                               timeout=mock.ANY,
                               bar='baz')
        mock_logger.debug.assert_called_once_with(
            'Received response:\nHTTP %d\n%s\n\n%s', 200,
            'Content-Type: application/pkix-cert', b'aGk=')

    def test_send_request_post(self):
        self.net.session = mock.MagicMock()
        self.net.session.request.return_value = self.response
        # pylint: disable=protected-access
        self.assertEqual(
            self.response,
            self.net._send_request('POST',
                                   'http://example.com/',
                                   'foo',
                                   data='qux',
                                   bar='baz'))
        self.net.session.request.assert_called_once_with('POST',
                                                         'http://example.com/',
                                                         'foo',
                                                         headers=mock.ANY,
                                                         verify=mock.ANY,
                                                         timeout=mock.ANY,
                                                         data='qux',
                                                         bar='baz')

    def test_send_request_verify_ssl(self):
        # pylint: disable=protected-access
        for verify in True, False:
            self.net.session = mock.MagicMock()
            self.net.session.request.return_value = self.response
            self.net.verify_ssl = verify
            # pylint: disable=protected-access
            self.assertEqual(
                self.response,
                self.net._send_request('GET', 'http://example.com/'))
            self.net.session.request.assert_called_once_with(
                'GET',
                'http://example.com/',
                verify=verify,
                timeout=mock.ANY,
                headers=mock.ANY)

    def test_send_request_user_agent(self):
        self.net.session = mock.MagicMock()
        # pylint: disable=protected-access
        self.net._send_request('GET',
                               'http://example.com/',
                               headers={'bar': 'baz'})
        self.net.session.request.assert_called_once_with(
            'GET',
            'http://example.com/',
            verify=mock.ANY,
            timeout=mock.ANY,
            headers={
                'User-Agent': 'acme-python-test',
                'bar': 'baz'
            })

        self.net._send_request('GET',
                               'http://example.com/',
                               headers={'User-Agent': 'foo2'})
        self.net.session.request.assert_called_with(
            'GET',
            'http://example.com/',
            verify=mock.ANY,
            timeout=mock.ANY,
            headers={'User-Agent': 'foo2'})

    def test_send_request_timeout(self):
        self.net.session = mock.MagicMock()
        # pylint: disable=protected-access
        self.net._send_request('GET',
                               'http://example.com/',
                               headers={'bar': 'baz'})
        self.net.session.request.assert_called_once_with(mock.ANY,
                                                         mock.ANY,
                                                         verify=mock.ANY,
                                                         headers=mock.ANY,
                                                         timeout=45)

    def test_del(self):
        sess = mock.MagicMock()
        self.net.session = sess
        del self.net
        sess.close.assert_called_once_with()

    @mock.patch('acme.client.requests')
    def test_requests_error_passthrough(self, mock_requests):
        mock_requests.exceptions = requests.exceptions
        mock_requests.request.side_effect = requests.exceptions.RequestException
        # pylint: disable=protected-access
        self.assertRaises(requests.exceptions.RequestException,
                          self.net._send_request, 'GET', 'uri')
示例#2
0
class ClientNetworkTest(unittest.TestCase):
    """Tests for acme.client.ClientNetwork."""
    def setUp(self):
        self.verify_ssl = mock.MagicMock()
        self.wrap_in_jws = mock.MagicMock(return_value=mock.sentinel.wrapped)

        from acme.client import ClientNetwork
        self.net = ClientNetwork(key=KEY,
                                 alg=jose.RS256,
                                 verify_ssl=self.verify_ssl)

        self.response = mock.MagicMock(ok=True, status_code=http_client.OK)
        self.response.headers = {}
        self.response.links = {}

    def test_init(self):
        self.assertTrue(self.net.verify_ssl is self.verify_ssl)

    def test_wrap_in_jws(self):
        class MockJSONDeSerializable(jose.JSONDeSerializable):
            # pylint: disable=missing-docstring
            def __init__(self, value):
                self.value = value

            def to_partial_json(self):
                return {'foo': self.value}

            @classmethod
            def from_json(cls, value):
                pass  # pragma: no cover

        # pylint: disable=protected-access
        jws_dump = self.net._wrap_in_jws(MockJSONDeSerializable('foo'),
                                         nonce=b'Tg')
        jws = acme_jws.JWS.json_loads(jws_dump)
        self.assertEqual(json.loads(jws.payload.decode()), {'foo': 'foo'})
        self.assertEqual(jws.signature.combined.nonce, b'Tg')

    def test_check_response_not_ok_jobj_no_error(self):
        self.response.ok = False
        self.response.json.return_value = {}
        # pylint: disable=protected-access
        self.assertRaises(errors.ClientError, self.net._check_response,
                          self.response)

    def test_check_response_not_ok_jobj_error(self):
        self.response.ok = False
        self.response.json.return_value = messages.Error(
            detail='foo', typ='serverInternal', title='some title').to_json()
        # pylint: disable=protected-access
        self.assertRaises(messages.Error, self.net._check_response,
                          self.response)

    def test_check_response_not_ok_no_jobj(self):
        self.response.ok = False
        self.response.json.side_effect = ValueError
        # pylint: disable=protected-access
        self.assertRaises(errors.ClientError, self.net._check_response,
                          self.response)

    def test_check_response_ok_no_jobj_ct_required(self):
        self.response.json.side_effect = ValueError
        for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:
            self.response.headers['Content-Type'] = response_ct
            # pylint: disable=protected-access
            self.assertRaises(errors.ClientError,
                              self.net._check_response,
                              self.response,
                              content_type=self.net.JSON_CONTENT_TYPE)

    def test_check_response_ok_no_jobj_no_ct(self):
        self.response.json.side_effect = ValueError
        for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:
            self.response.headers['Content-Type'] = response_ct
            # pylint: disable=protected-access,no-value-for-parameter
            self.assertEqual(self.response,
                             self.net._check_response(self.response))

    def test_check_response_jobj(self):
        self.response.json.return_value = {}
        for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:
            self.response.headers['Content-Type'] = response_ct
            # pylint: disable=protected-access,no-value-for-parameter
            self.assertEqual(self.response,
                             self.net._check_response(self.response))

    @mock.patch('acme.client.requests')
    def test_send_request(self, mock_requests):
        mock_requests.request.return_value = self.response
        # pylint: disable=protected-access
        self.assertEqual(
            self.response,
            self.net._send_request('HEAD', 'url', 'foo', bar='baz'))
        mock_requests.request.assert_called_once_with('HEAD',
                                                      'url',
                                                      'foo',
                                                      verify=mock.ANY,
                                                      bar='baz')

    @mock.patch('acme.client.requests')
    def test_send_request_verify_ssl(self, mock_requests):
        # pylint: disable=protected-access
        for verify in True, False:
            mock_requests.request.reset_mock()
            mock_requests.request.return_value = self.response
            self.net.verify_ssl = verify
            # pylint: disable=protected-access
            self.assertEqual(self.response,
                             self.net._send_request('GET', 'url'))
            mock_requests.request.assert_called_once_with('GET',
                                                          'url',
                                                          verify=verify)

    @mock.patch('acme.client.requests')
    def test_requests_error_passthrough(self, mock_requests):
        mock_requests.exceptions = requests.exceptions
        mock_requests.request.side_effect = requests.exceptions.RequestException
        # pylint: disable=protected-access
        self.assertRaises(requests.exceptions.RequestException,
                          self.net._send_request, 'GET', 'uri')
示例#3
0
class ClientNetworkTest(unittest.TestCase):
    """Tests for acme.client.ClientNetwork."""

    # pylint: disable=too-many-public-methods

    def setUp(self):
        self.verify_ssl = mock.MagicMock()
        self.wrap_in_jws = mock.MagicMock(return_value=mock.sentinel.wrapped)

        from acme.client import ClientNetwork
        self.net = ClientNetwork(key=KEY,
                                 alg=jose.RS256,
                                 verify_ssl=self.verify_ssl,
                                 user_agent='acme-python-test')

        self.response = mock.MagicMock(ok=True, status_code=http_client.OK)
        self.response.headers = {}
        self.response.links = {}

    def test_init(self):
        self.assertTrue(self.net.verify_ssl is self.verify_ssl)

    def test_wrap_in_jws(self):
        # pylint: disable=protected-access
        jws_dump = self.net._wrap_in_jws(MockJSONDeSerializable('foo'),
                                         nonce=b'Tg',
                                         url="url",
                                         acme_version=1)
        jws = acme_jws.JWS.json_loads(jws_dump)
        self.assertEqual(json.loads(jws.payload.decode()), {'foo': 'foo'})
        self.assertEqual(jws.signature.combined.nonce, b'Tg')

    def test_wrap_in_jws_v2(self):
        self.net.account = {'uri': 'acct-uri'}
        # pylint: disable=protected-access
        jws_dump = self.net._wrap_in_jws(MockJSONDeSerializable('foo'),
                                         nonce=b'Tg',
                                         url="url",
                                         acme_version=2)
        jws = acme_jws.JWS.json_loads(jws_dump)
        self.assertEqual(json.loads(jws.payload.decode()), {'foo': 'foo'})
        self.assertEqual(jws.signature.combined.nonce, b'Tg')
        self.assertEqual(jws.signature.combined.kid, u'acct-uri')
        self.assertEqual(jws.signature.combined.url, u'url')

    def test_check_response_not_ok_jobj_no_error(self):
        self.response.ok = False
        self.response.json.return_value = {}
        with mock.patch('acme.client.messages.Error.from_json') as from_json:
            from_json.side_effect = jose.DeserializationError
            # pylint: disable=protected-access
            self.assertRaises(errors.ClientError, self.net._check_response,
                              self.response)

    def test_check_response_not_ok_jobj_error(self):
        self.response.ok = False
        self.response.json.return_value = messages.Error(
            detail='foo', typ='serverInternal', title='some title').to_json()
        # pylint: disable=protected-access
        self.assertRaises(messages.Error, self.net._check_response,
                          self.response)

    def test_check_response_not_ok_no_jobj(self):
        self.response.ok = False
        self.response.json.side_effect = ValueError
        # pylint: disable=protected-access
        self.assertRaises(errors.ClientError, self.net._check_response,
                          self.response)

    def test_check_response_ok_no_jobj_ct_required(self):
        self.response.json.side_effect = ValueError
        for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:
            self.response.headers['Content-Type'] = response_ct
            # pylint: disable=protected-access
            self.assertRaises(errors.ClientError,
                              self.net._check_response,
                              self.response,
                              content_type=self.net.JSON_CONTENT_TYPE)

    def test_check_response_ok_no_jobj_no_ct(self):
        self.response.json.side_effect = ValueError
        for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:
            self.response.headers['Content-Type'] = response_ct
            # pylint: disable=protected-access,no-value-for-parameter
            self.assertEqual(self.response,
                             self.net._check_response(self.response))

    def test_check_response_conflict(self):
        self.response.ok = False
        self.response.status_code = 409
        # pylint: disable=protected-access
        self.assertRaises(errors.ConflictError, self.net._check_response,
                          self.response)

    def test_check_response_jobj(self):
        self.response.json.return_value = {}
        for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:
            self.response.headers['Content-Type'] = response_ct
            # pylint: disable=protected-access,no-value-for-parameter
            self.assertEqual(self.response,
                             self.net._check_response(self.response))

    def test_send_request(self):
        self.net.session = mock.MagicMock()
        self.net.session.request.return_value = self.response
        # pylint: disable=protected-access
        self.assertEqual(
            self.response,
            self.net._send_request('HEAD',
                                   'http://example.com/',
                                   'foo',
                                   bar='baz'))
        self.net.session.request.assert_called_once_with('HEAD',
                                                         'http://example.com/',
                                                         'foo',
                                                         headers=mock.ANY,
                                                         verify=mock.ANY,
                                                         timeout=mock.ANY,
                                                         bar='baz')

    @mock.patch('acme.client.logger')
    def test_send_request_get_der(self, mock_logger):
        self.net.session = mock.MagicMock()
        self.net.session.request.return_value = mock.MagicMock(
            ok=True,
            status_code=http_client.OK,
            headers={"Content-Type": "application/pkix-cert"},
            content=b"hi")
        # pylint: disable=protected-access
        self.net._send_request('HEAD',
                               'http://example.com/',
                               'foo',
                               timeout=mock.ANY,
                               bar='baz')
        mock_logger.debug.assert_called_with(
            'Received response:\nHTTP %d\n%s\n\n%s', 200,
            'Content-Type: application/pkix-cert', b'aGk=')

    def test_send_request_post(self):
        self.net.session = mock.MagicMock()
        self.net.session.request.return_value = self.response
        # pylint: disable=protected-access
        self.assertEqual(
            self.response,
            self.net._send_request('POST',
                                   'http://example.com/',
                                   'foo',
                                   data='qux',
                                   bar='baz'))
        self.net.session.request.assert_called_once_with('POST',
                                                         'http://example.com/',
                                                         'foo',
                                                         headers=mock.ANY,
                                                         verify=mock.ANY,
                                                         timeout=mock.ANY,
                                                         data='qux',
                                                         bar='baz')

    def test_send_request_verify_ssl(self):
        # pylint: disable=protected-access
        for verify in True, False:
            self.net.session = mock.MagicMock()
            self.net.session.request.return_value = self.response
            self.net.verify_ssl = verify
            # pylint: disable=protected-access
            self.assertEqual(
                self.response,
                self.net._send_request('GET', 'http://example.com/'))
            self.net.session.request.assert_called_once_with(
                'GET',
                'http://example.com/',
                verify=verify,
                timeout=mock.ANY,
                headers=mock.ANY)

    def test_send_request_user_agent(self):
        self.net.session = mock.MagicMock()
        # pylint: disable=protected-access
        self.net._send_request('GET',
                               'http://example.com/',
                               headers={'bar': 'baz'})
        self.net.session.request.assert_called_once_with(
            'GET',
            'http://example.com/',
            verify=mock.ANY,
            timeout=mock.ANY,
            headers={
                'User-Agent': 'acme-python-test',
                'bar': 'baz'
            })

        self.net._send_request('GET',
                               'http://example.com/',
                               headers={'User-Agent': 'foo2'})
        self.net.session.request.assert_called_with(
            'GET',
            'http://example.com/',
            verify=mock.ANY,
            timeout=mock.ANY,
            headers={'User-Agent': 'foo2'})

    def test_send_request_timeout(self):
        self.net.session = mock.MagicMock()
        # pylint: disable=protected-access
        self.net._send_request('GET',
                               'http://example.com/',
                               headers={'bar': 'baz'})
        self.net.session.request.assert_called_once_with(mock.ANY,
                                                         mock.ANY,
                                                         verify=mock.ANY,
                                                         headers=mock.ANY,
                                                         timeout=45)

    def test_del(self, close_exception=None):
        sess = mock.MagicMock()

        if close_exception is not None:
            sess.close.side_effect = close_exception

        self.net.session = sess
        del self.net
        sess.close.assert_called_once_with()

    def test_del_error(self):
        self.test_del(ReferenceError)

    @mock.patch('acme.client.requests')
    def test_requests_error_passthrough(self, mock_requests):
        mock_requests.exceptions = requests.exceptions
        mock_requests.request.side_effect = requests.exceptions.RequestException
        # pylint: disable=protected-access
        self.assertRaises(requests.exceptions.RequestException,
                          self.net._send_request, 'GET', 'uri')

    def test_urllib_error(self):
        # Using a connection error to test a properly formatted error message
        try:
            # pylint: disable=protected-access
            self.net._send_request('GET',
                                   "http://localhost:19123/nonexistent.txt")

        # Value Error Generated Exceptions
        except ValueError as y:
            self.assertEqual(
                "Requesting localhost/nonexistent: "
                "Connection refused", str(y))

        # Requests Library Exceptions
        except requests.exceptions.ConnectionError as z:  #pragma: no cover
            self.assertEqual(
                "('Connection aborted.', "
                "error(111, 'Connection refused'))", str(z))
示例#4
0
class ClientNetworkTest(unittest.TestCase):
    """Tests for acme.client.ClientNetwork."""

    def setUp(self):
        self.verify_ssl = mock.MagicMock()
        self.wrap_in_jws = mock.MagicMock(return_value=mock.sentinel.wrapped)

        from acme.client import ClientNetwork
        self.net = ClientNetwork(
            key=KEY, alg=jose.RS256, verify_ssl=self.verify_ssl,
            user_agent='acme-python-test')

        self.response = mock.MagicMock(ok=True, status_code=http_client.OK)
        self.response.headers = {}
        self.response.links = {}

    def test_init(self):
        self.assertTrue(self.net.verify_ssl is self.verify_ssl)

    def test_wrap_in_jws(self):
        class MockJSONDeSerializable(jose.JSONDeSerializable):
            # pylint: disable=missing-docstring
            def __init__(self, value):
                self.value = value

            def to_partial_json(self):
                return {'foo': self.value}

            @classmethod
            def from_json(cls, value):
                pass  # pragma: no cover

        # pylint: disable=protected-access
        jws_dump = self.net._wrap_in_jws(
            MockJSONDeSerializable('foo'), nonce=b'Tg')
        jws = acme_jws.JWS.json_loads(jws_dump)
        self.assertEqual(json.loads(jws.payload.decode()), {'foo': 'foo'})
        self.assertEqual(jws.signature.combined.nonce, b'Tg')

    def test_check_response_not_ok_jobj_no_error(self):
        self.response.ok = False
        self.response.json.return_value = {}
        with mock.patch('acme.client.messages.Error.from_json') as from_json:
            from_json.side_effect = jose.DeserializationError
            # pylint: disable=protected-access
            self.assertRaises(
                errors.ClientError, self.net._check_response, self.response)

    def test_check_response_not_ok_jobj_error(self):
        self.response.ok = False
        self.response.json.return_value = messages.Error(
            detail='foo', typ='serverInternal', title='some title').to_json()
        # pylint: disable=protected-access
        self.assertRaises(
            messages.Error, self.net._check_response, self.response)

    def test_check_response_not_ok_no_jobj(self):
        self.response.ok = False
        self.response.json.side_effect = ValueError
        # pylint: disable=protected-access
        self.assertRaises(
            errors.ClientError, self.net._check_response, self.response)

    def test_check_response_ok_no_jobj_ct_required(self):
        self.response.json.side_effect = ValueError
        for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:
            self.response.headers['Content-Type'] = response_ct
            # pylint: disable=protected-access
            self.assertRaises(
                errors.ClientError, self.net._check_response, self.response,
                content_type=self.net.JSON_CONTENT_TYPE)

    def test_check_response_ok_no_jobj_no_ct(self):
        self.response.json.side_effect = ValueError
        for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:
            self.response.headers['Content-Type'] = response_ct
            # pylint: disable=protected-access,no-value-for-parameter
            self.assertEqual(
                self.response, self.net._check_response(self.response))

    def test_check_response_jobj(self):
        self.response.json.return_value = {}
        for response_ct in [self.net.JSON_CONTENT_TYPE, 'foo']:
            self.response.headers['Content-Type'] = response_ct
            # pylint: disable=protected-access,no-value-for-parameter
            self.assertEqual(
                self.response, self.net._check_response(self.response))

    @mock.patch('acme.client.requests')
    def test_send_request(self, mock_requests):
        mock_requests.request.return_value = self.response
        # pylint: disable=protected-access
        self.assertEqual(self.response, self.net._send_request(
            'HEAD', 'url', 'foo', bar='baz'))
        mock_requests.request.assert_called_once_with(
            'HEAD', 'url', 'foo', verify=mock.ANY, bar='baz', headers=mock.ANY)

    @mock.patch('acme.client.requests')
    def test_send_request_verify_ssl(self, mock_requests):
        # pylint: disable=protected-access
        for verify in True, False:
            mock_requests.request.reset_mock()
            mock_requests.request.return_value = self.response
            self.net.verify_ssl = verify
            # pylint: disable=protected-access
            self.assertEqual(
                self.response, self.net._send_request('GET', 'url'))
            mock_requests.request.assert_called_once_with(
                'GET', 'url', verify=verify, headers=mock.ANY)

    @mock.patch('acme.client.requests')
    def test_send_request_user_agent(self, mock_requests):
        mock_requests.request.return_value = self.response
        # pylint: disable=protected-access
        self.net._send_request('GET', 'url', headers={'bar': 'baz'})
        mock_requests.request.assert_called_once_with(
            'GET', 'url', verify=mock.ANY,
            headers={'User-Agent': 'acme-python-test', 'bar': 'baz'})

        self.net._send_request('GET', 'url', headers={'User-Agent': 'foo2'})
        mock_requests.request.assert_called_with(
            'GET', 'url', verify=mock.ANY, headers={'User-Agent': 'foo2'})

    @mock.patch('acme.client.requests')
    def test_requests_error_passthrough(self, mock_requests):
        mock_requests.exceptions = requests.exceptions
        mock_requests.request.side_effect = requests.exceptions.RequestException
        # pylint: disable=protected-access
        self.assertRaises(requests.exceptions.RequestException,
                          self.net._send_request, 'GET', 'uri')
示例#5
0
class ClientNetworkTest(unittest.TestCase):
    """Tests for acme.client.ClientNetwork."""

    def setUp(self):
        self.verify_ssl = mock.MagicMock()
        self.wrap_in_jws = mock.MagicMock(return_value=mock.sentinel.wrapped)

        from acme.client import ClientNetwork

        self.net = ClientNetwork(key=KEY, alg=jose.RS256, verify_ssl=self.verify_ssl)

        self.response = mock.MagicMock(ok=True, status_code=http_client.OK)
        self.response.headers = {}
        self.response.links = {}

    def test_init(self):
        self.assertTrue(self.net.verify_ssl is self.verify_ssl)

    def test_wrap_in_jws(self):
        class MockClientRequestableResource(jose.JSONDeSerializable):
            # pylint: disable=missing-docstring
            resource_type = "mock"

            def __init__(self, value):
                self.value = value

            def to_partial_json(self):
                return {"foo": self.value}

            @classmethod
            def from_json(cls, value):
                pass  # pragma: no cover

        # pylint: disable=protected-access
        jws_dump = self.net._wrap_in_jws(MockClientRequestableResource("foo"), nonce=b"Tg")
        jws = acme_jws.JWS.json_loads(jws_dump)
        self.assertEqual(json.loads(jws.payload.decode()), {"foo": "foo", "resource": "mock"})
        self.assertEqual(jws.signature.combined.nonce, b"Tg")

    def test_check_response_not_ok_jobj_no_error(self):
        self.response.ok = False
        self.response.json.return_value = {}
        # pylint: disable=protected-access
        self.assertRaises(errors.ClientError, self.net._check_response, self.response)

    def test_check_response_not_ok_jobj_error(self):
        self.response.ok = False
        self.response.json.return_value = messages.Error(
            detail="foo", typ="serverInternal", title="some title"
        ).to_json()
        # pylint: disable=protected-access
        self.assertRaises(messages.Error, self.net._check_response, self.response)

    def test_check_response_not_ok_no_jobj(self):
        self.response.ok = False
        self.response.json.side_effect = ValueError
        # pylint: disable=protected-access
        self.assertRaises(errors.ClientError, self.net._check_response, self.response)

    def test_check_response_ok_no_jobj_ct_required(self):
        self.response.json.side_effect = ValueError
        for response_ct in [self.net.JSON_CONTENT_TYPE, "foo"]:
            self.response.headers["Content-Type"] = response_ct
            # pylint: disable=protected-access
            self.assertRaises(
                errors.ClientError, self.net._check_response, self.response, content_type=self.net.JSON_CONTENT_TYPE
            )

    def test_check_response_ok_no_jobj_no_ct(self):
        self.response.json.side_effect = ValueError
        for response_ct in [self.net.JSON_CONTENT_TYPE, "foo"]:
            self.response.headers["Content-Type"] = response_ct
            # pylint: disable=protected-access,no-value-for-parameter
            self.assertEqual(self.response, self.net._check_response(self.response))

    def test_check_response_jobj(self):
        self.response.json.return_value = {}
        for response_ct in [self.net.JSON_CONTENT_TYPE, "foo"]:
            self.response.headers["Content-Type"] = response_ct
            # pylint: disable=protected-access,no-value-for-parameter
            self.assertEqual(self.response, self.net._check_response(self.response))

    @mock.patch("acme.client.requests")
    def test_send_request(self, mock_requests):
        mock_requests.request.return_value = self.response
        # pylint: disable=protected-access
        self.assertEqual(self.response, self.net._send_request("HEAD", "url", "foo", bar="baz"))
        mock_requests.request.assert_called_once_with("HEAD", "url", "foo", verify=mock.ANY, bar="baz")

    @mock.patch("acme.client.requests")
    def test_send_request_verify_ssl(self, mock_requests):
        # pylint: disable=protected-access
        for verify in True, False:
            mock_requests.request.reset_mock()
            mock_requests.request.return_value = self.response
            self.net.verify_ssl = verify
            # pylint: disable=protected-access
            self.assertEqual(self.response, self.net._send_request("GET", "url"))
            mock_requests.request.assert_called_once_with("GET", "url", verify=verify)

    @mock.patch("acme.client.requests")
    def test_requests_error_passthrough(self, mock_requests):
        mock_requests.exceptions = requests.exceptions
        mock_requests.request.side_effect = requests.exceptions.RequestException
        # pylint: disable=protected-access
        self.assertRaises(requests.exceptions.RequestException, self.net._send_request, "GET", "uri")