def test_http_auth(self):
     con = Urllib3HttpConnection(http_auth="username:secret")
     self.assertEquals(
         {
             "authorization": "Basic dXNlcm5hbWU6c2VjcmV0",
             "connection": "keep-alive",
             "content-type": "application/json",
             "user-agent": con._get_default_user_agent(),
         },
         con.headers,
     )
예제 #2
0
    def test_content_length_gets_set(self):
        con = Urllib3HttpConnection()
        m = con.pool.urlopen = Mock()
        m.return_value.status = 200

        con.perform_request('PUT', '/', body='0123456789'.encode('utf-8'))
        m.assert_called_once_with('PUT',
                                  '/',
                                  '0123456789'.encode('utf-8'),
                                  headers={'content-length': '10'},
                                  retries=False)
예제 #3
0
    def test_cloud_id_http_compress_override(self):
        # 'http_compress' will be 'True' by default for connections with
        # 'cloud_id' set but should prioritize user-defined values.
        con = Urllib3HttpConnection(
            cloud_id=
            "foobar:ZXhhbXBsZS5jbG91ZC5jb20kMGZkNTBmNjIzMjBlZDY1MzlmNmNiNDhlMWI2OCRhYzUzOTVhODgz\nNDU2NmM5ZjE1Y2Q4ZTQ5MGE=\n",
        )
        self.assertEquals(con.http_compress, True)

        con = Urllib3HttpConnection(
            cloud_id=
            "foobar:ZXhhbXBsZS5jbG91ZC5jb20kMGZkNTBmNjIzMjBlZDY1MzlmNmNiNDhlMWI2OCRhYzUzOTVhODgz\nNDU2NmM5ZjE1Y2Q4ZTQ5MGE=\n",
            http_compress=False)
        self.assertEquals(con.http_compress, False)

        con = Urllib3HttpConnection(
            cloud_id=
            "foobar:ZXhhbXBsZS5jbG91ZC5jb20kMGZkNTBmNjIzMjBlZDY1MzlmNmNiNDhlMWI2OCRhYzUzOTVhODgz\nNDU2NmM5ZjE1Y2Q4ZTQ5MGE=\n",
            http_compress=True)
        self.assertEquals(con.http_compress, True)
예제 #4
0
    def test_cloud_id_http_compress_override(self):
        # 'http_compress' will be 'True' by default for connections with
        # 'cloud_id' set but should prioritize user-defined values.
        con = Urllib3HttpConnection(
            cloud_id=
            "cluster:dXMtZWFzdC0xLmF3cy5mb3VuZC5pbyQ0ZmE4ODIxZTc1NjM0MDMyYmVkMWNmMjIxMTBlMmY5NyQ0ZmE4ODIxZTc1NjM0MDMyYmVkMWNmMjIxMTBlMmY5Ng==",
        )
        self.assertEqual(con.http_compress, True)

        con = Urllib3HttpConnection(
            cloud_id=
            "cluster:dXMtZWFzdC0xLmF3cy5mb3VuZC5pbyQ0ZmE4ODIxZTc1NjM0MDMyYmVkMWNmMjIxMTBlMmY5NyQ0ZmE4ODIxZTc1NjM0MDMyYmVkMWNmMjIxMTBlMmY5Ng==",
            http_compress=False,
        )
        self.assertEqual(con.http_compress, False)

        con = Urllib3HttpConnection(
            cloud_id=
            "cluster:dXMtZWFzdC0xLmF3cy5mb3VuZC5pbyQ0ZmE4ODIxZTc1NjM0MDMyYmVkMWNmMjIxMTBlMmY5NyQ0ZmE4ODIxZTc1NjM0MDMyYmVkMWNmMjIxMTBlMmY5Ng==",
            http_compress=True,
        )
        self.assertEqual(con.http_compress, True)
예제 #5
0
    def test_uses_https_if_verify_certs_is_off(self):
        if (
            sys.version_info >= (3,0) and sys.version_info <= (3,4)
            ) or (
            sys.version_info >= (2,6) and sys.version_info <= (2,7)
        ):
            raise SkipTest("SSL Context not supported in this version of python")
        with warnings.catch_warnings(record=True) as w:
            con = Urllib3HttpConnection(use_ssl=True, verify_certs=False)
            self.assertEquals(1, len(w))
            self.assertEquals('Connecting to localhost using SSL with verify_certs=False is insecure.', str(w[0].message))

        self.assertIsInstance(con.pool, urllib3.HTTPSConnectionPool)
예제 #6
0
    def _get_mock_connection(self, connection_params={}, response_body=b"{}"):
        con = Urllib3HttpConnection(**connection_params)

        def _dummy_urlopen(*args, **kwargs):
            dummy_response = Mock()
            dummy_response.headers = {}
            dummy_response.status = 200
            dummy_response.data = response_body
            _dummy_urlopen.call_args = (args, kwargs)
            return dummy_response

        con.pool.urlopen = _dummy_urlopen
        return con
예제 #7
0
 def test_http_cloud_id(self):
     con = Urllib3HttpConnection(
         cloud_id=
         "foobar:ZXhhbXBsZS5jbG91ZC5jb20kMGZkNTBmNjIzMjBlZDY1MzlmNmNiNDhlMWI2OCRhYzUzOTVhODgz\nNDU2NmM5ZjE1Y2Q4ZTQ5MGE=\n"
     )
     self.assertTrue(con.use_ssl)
     self.assertEquals(
         con.host,
         "https://0fd50f62320ed6539f6cb48e1b68.example.cloud.com:9243")
     self.assertEquals(con.port, 9243)
     self.assertEquals(con.hostname,
                       "0fd50f62320ed6539f6cb48e1b68.example.cloud.com")
     self.assertTrue(con.http_compress)
예제 #8
0
    def test_api_key_auth(self):
        # test with tuple
        con = Urllib3HttpConnection(
            cloud_id=
            "foobar:ZXhhbXBsZS5jbG91ZC5jb20kMGZkNTBmNjIzMjBlZDY1MzlmNmNiNDhlMWI2OCRhYzUzOTVhODgz\nNDU2NmM5ZjE1Y2Q4ZTQ5MGE=\n",
            api_key=("elastic", "changeme1"),
        )
        self.assertEquals(con.headers["authorization"],
                          "ApiKey ZWxhc3RpYzpjaGFuZ2VtZTE=")
        self.assertEquals(
            con.host,
            "https://0fd50f62320ed6539f6cb48e1b68.example.cloud.com:9243")

        # test with base64 encoded string
        con = Urllib3HttpConnection(
            cloud_id=
            "foobar:ZXhhbXBsZS5jbG91ZC5jb20kMGZkNTBmNjIzMjBlZDY1MzlmNmNiNDhlMWI2OCRhYzUzOTVhODgz\nNDU2NmM5ZjE1Y2Q4ZTQ5MGE=\n",
            api_key="ZWxhc3RpYzpjaGFuZ2VtZTI=",
        )
        self.assertEquals(con.headers["authorization"],
                          "ApiKey ZWxhc3RpYzpjaGFuZ2VtZTI=")
        self.assertEquals(
            con.host,
            "https://0fd50f62320ed6539f6cb48e1b68.example.cloud.com:9243")
예제 #9
0
    def test_ssl_context(self):
        try:
            context = ssl.create_default_context()
        except AttributeError:
            # if create_default_context raises an AttributeError Exception
            # it means SSLContext is not available for that version of python
            # and we should skip this test.
            raise SkipTest(
                "Test test_ssl_context is skipped cause SSLContext is not available for this version of ptyhon"
            )

        con = Urllib3HttpConnection(use_ssl=True, ssl_context=context)
        self.assertEqual(len(con.pool.conn_kw.keys()), 1)
        self.assertIsInstance(con.pool.conn_kw["ssl_context"], ssl.SSLContext)
        self.assertTrue(con.use_ssl)
예제 #10
0
    def test_api_key_auth(self):
        # test with tuple
        con = Urllib3HttpConnection(
            cloud_id=
            "cluster:dXMtZWFzdC0xLmF3cy5mb3VuZC5pbyQ0ZmE4ODIxZTc1NjM0MDMyYmVkMWNmMjIxMTBlMmY5NyQ0ZmE4ODIxZTc1NjM0MDMyYmVkMWNmMjIxMTBlMmY5Ng==",
            api_key=("elastic", "changeme1"),
        )
        self.assertEqual(con.headers["authorization"],
                         "ApiKey ZWxhc3RpYzpjaGFuZ2VtZTE=")
        self.assertEqual(
            con.host,
            "https://4fa8821e75634032bed1cf22110e2f97.us-east-1.aws.found.io")

        # test with base64 encoded string
        con = Urllib3HttpConnection(
            cloud_id=
            "cluster:dXMtZWFzdC0xLmF3cy5mb3VuZC5pbyQ0ZmE4ODIxZTc1NjM0MDMyYmVkMWNmMjIxMTBlMmY5NyQ0ZmE4ODIxZTc1NjM0MDMyYmVkMWNmMjIxMTBlMmY5Ng==",
            api_key="ZWxhc3RpYzpjaGFuZ2VtZTI=",
        )
        self.assertEqual(con.headers["authorization"],
                         "ApiKey ZWxhc3RpYzpjaGFuZ2VtZTI=")
        self.assertEqual(
            con.host,
            "https://4fa8821e75634032bed1cf22110e2f97.us-east-1.aws.found.io")
예제 #11
0
    def test_warns_if_using_non_default_ssl_kwargs_with_ssl_context(self):
        for kwargs in (
            {"ssl_show_warn": False},
            {"ssl_show_warn": True},
            {"verify_certs": True},
            {"verify_certs": False},
            {"ca_certs": "/path/to/certs"},
            {"ssl_show_warn": True, "ca_certs": "/path/to/certs"},
        ):
            kwargs["ssl_context"] = ssl.create_default_context()

            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter("always")

                Urllib3HttpConnection(**kwargs)

                self.assertEqual(1, len(w))
                self.assertEqual(
                    "When using `ssl_context`, all other SSL related kwargs are ignored",
                    str(w[0].message),
                )
예제 #12
0
 def test_default_user_agent(self):
     con = Urllib3HttpConnection()
     self.assertEquals(
         con._get_default_user_agent(), "elasticsearch-py/%s (Python %s)" %
         (__versionstr__, python_version()))
예제 #13
0
 def test_keep_alive_is_on_by_default(self):
     con = Urllib3HttpConnection()
     self.assertEquals({'connection': 'keep-alive',
         'content-type': 'application/json'}, con.headers)
예제 #14
0
 def test_http_auth_list(self):
     con = Urllib3HttpConnection(http_auth=['username', 'secret'])
     self.assertEquals({'authorization': 'Basic dXNlcm5hbWU6c2VjcmV0',
         'content-type': 'application/json',
         'connection': 'keep-alive'}, con.headers)
예제 #15
0
 def test_no_warning_when_using_ssl_context(self):
     ctx = ssl.create_default_context()
     with warnings.catch_warnings(record=True) as w:
         Urllib3HttpConnection(ssl_context=ctx)
         self.assertEquals(0, len(w))
예제 #16
0
 def test_doesnt_use_https_if_not_specified(self):
     con = Urllib3HttpConnection()
     self.assertIsInstance(con.pool, urllib3.HTTPConnectionPool)
예제 #17
0
 def test_timeout_set(self):
     con = Urllib3HttpConnection(timeout=42)
     self.assertEquals(42, con.timeout)
예제 #18
0
    def test_urllib3_connection(self):
        # Defaults
        conn = Urllib3HttpConnection("httpbin.org", port=443, use_ssl=True)
        user_agent = conn._get_default_user_agent()
        status, data = self.httpbin_anything(conn)
        assert status == 200
        assert data["method"] == "GET"
        assert data["headers"] == {
            "Accept-Encoding": "identity",
            "Content-Type": "application/json",
            "Host": "httpbin.org",
            "User-Agent": user_agent,
        }

        # http_compress=False
        conn = Urllib3HttpConnection("httpbin.org",
                                     port=443,
                                     use_ssl=True,
                                     http_compress=False)
        status, data = self.httpbin_anything(conn)
        assert status == 200
        assert data["method"] == "GET"
        assert data["headers"] == {
            "Accept-Encoding": "identity",
            "Content-Type": "application/json",
            "Host": "httpbin.org",
            "User-Agent": user_agent,
        }

        # http_compress=True
        conn = Urllib3HttpConnection("httpbin.org",
                                     port=443,
                                     use_ssl=True,
                                     http_compress=True)
        status, data = self.httpbin_anything(conn)
        assert status == 200
        assert data["headers"] == {
            "Accept-Encoding": "gzip,deflate",
            "Content-Type": "application/json",
            "Host": "httpbin.org",
            "User-Agent": user_agent,
        }

        # Headers
        conn = Urllib3HttpConnection(
            "httpbin.org",
            port=443,
            use_ssl=True,
            http_compress=True,
            headers={"header1": "value1"},
        )
        status, data = self.httpbin_anything(conn,
                                             headers={
                                                 "header2": "value2",
                                                 "header1": "override!"
                                             })
        assert status == 200
        assert data["headers"] == {
            "Accept-Encoding": "gzip,deflate",
            "Content-Type": "application/json",
            "Host": "httpbin.org",
            "Header1": "override!",
            "Header2": "value2",
            "User-Agent": user_agent,
        }
예제 #19
0
 def test_http_auth(self):
     con = Urllib3HttpConnection(http_auth='username:secret')
     self.assertEquals({'authorization': 'Basic dXNlcm5hbWU6c2VjcmV0'},
                       con.headers)
예제 #20
0
 def test_opaque_id(self):
     con = Urllib3HttpConnection(opaque_id="app-1")
     self.assertEqual(con.headers["x-opaque-id"], "app-1")
예제 #21
0
 def test_http_compression(self):
     con = Urllib3HttpConnection(http_compress=True)
     self.assertTrue(con.http_compress)
     self.assertEquals(con.headers["content-encoding"], "gzip")
예제 #22
0
 def test_uses_https_if_specified(self):
     con = Urllib3HttpConnection(use_ssl=True)
     self.assertIsInstance(con.pool, urllib3.HTTPSConnectionPool)
예제 #23
0
 def test_http_auth_list(self):
     con = Urllib3HttpConnection(http_auth=['username', 'secret'])
     self.assertEquals({'authorization': 'Basic dXNlcm5hbWU6c2VjcmV0'},
                       con.pool.headers)
예제 #24
0
 def test_keep_alive_is_on_by_default(self):
     con = Urllib3HttpConnection()
     self.assertEquals({'connection': 'keep-alive'}, con.headers)