class ConnectionTests(unittest.TestCase):
    def setUp(self):
        # Try to remove all environment variables to not influence unit test
        try:
            os.environ.pop('no_proxy')
            os.environ.pop('NO_PROXY')
            os.environ.pop('HTTPS_PROXY')
        except KeyError:
            pass
        # NOTE: this won't actually work, idea for this suite of unit tests
        # is to mock the actual server responses and just test logic in the
        # UEPConnection:
        self.cp = UEPConnection(username="******", password="******",
                handler="/Test/", insecure=True)
        self.temp_ent_dir = mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.temp_ent_dir)

    def test_accepts_a_timeout(self):
        self.cp = UEPConnection(username="******", password="******",
                handler="/Test/", insecure=True, timeout=3)

    def test_load_manager_capabilities(self):
        expected_capabilities = ['hypervisors_async', 'cores']
        proper_status = {'version': '1',
                         'result': True,
                         'managerCapabilities': expected_capabilities}
        improper_status = dict.copy(proper_status)
        # Remove the managerCapabilities key from the dict
        del improper_status['managerCapabilities']
        self.cp.conn = Mock()
        # The first call will return the proper_status, the second, the improper
        # status
        original_getStatus = self.cp.getStatus
        self.cp.getStatus = Mock(side_effect=[proper_status,
                                                     improper_status])
        actual_capabilities = self.cp._load_manager_capabilities()
        self.assertEqual(sorted(actual_capabilities),
                          sorted(expected_capabilities))
        self.assertEqual([], self.cp._load_manager_capabilities())
        self.cp.getStatus = original_getStatus

    def test_get_environment_by_name_requires_owner(self):
        self.assertRaises(Exception, self.cp.getEnvironment, None, {"name": "env name"})

    def test_get_environment_urlencoding(self):
        self.cp.conn = Mock()
        self.cp.conn.request_get = Mock(return_value=[])
        self.cp.getEnvironment(owner_key="myorg", name="env name__++=*&")
        self.cp.conn.request_get.assert_called_with(
                "/owners/myorg/environments?name=env+name__%2B%2B%3D%2A%26")

    def test_entitle_date(self):
        self.cp.conn = Mock()
        self.cp.conn.request_post = Mock(return_value=[])
        self.cp.bind("abcd", date(2011, 9, 2))
        self.cp.conn.request_post.assert_called_with(
                "/consumers/abcd/entitlements?entitle_date=2011-09-02")

    def test_no_entitle_date(self):
        self.cp.conn = Mock()
        self.cp.conn.request_post = Mock(return_value=[])
        self.cp.bind("abcd")
        self.cp.conn.request_post.assert_called_with("/consumers/abcd/entitlements")

    def test_clean_up_prefix(self):
        self.assertTrue(self.cp.handler == "/Test")

    def test_https_proxy_info_allcaps(self):
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host:4444'}):
            uep = UEPConnection(username="******", password="******",
                 handler="/Test/", insecure=True)
            self.assertEqual("u", uep.proxy_user)
            self.assertEqual("p", uep.proxy_password)
            self.assertEqual("host", uep.proxy_hostname)
            self.assertEqual(int("4444"), uep.proxy_port)

    def test_order(self):
        # should follow the order: HTTPS, https, HTTP, http
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host:4444',
                                       'http_proxy': 'http://*****:*****@host:2222'}):
            uep = UEPConnection(username="******", password="******",
                 handler="/Test/", insecure=True)
            self.assertEqual("u", uep.proxy_user)
            self.assertEqual("p", uep.proxy_password)
            self.assertEqual("host", uep.proxy_hostname)
            self.assertEqual(int("4444"), uep.proxy_port)

    def test_no_port(self):
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host'}):
            uep = UEPConnection(username="******", password="******",
                 handler="/Test/", insecure=True)
            self.assertEqual("u", uep.proxy_user)
            self.assertEqual("p", uep.proxy_password)
            self.assertEqual("host", uep.proxy_hostname)
            self.assertEqual(3128, uep.proxy_port)

    def test_no_user_or_password(self):
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host',
                                       'NO_PROXY': 'foo.example.com'}):
            with patch.object(connection.config, 'get', mock_config):
                uep = UEPConnection(username='******', password='******',
                                    handler='/test', insecure=True, no_proxy=host)
                self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_with_one_asterisk_via_api(self):
        """Test that API trumps env var with one asterisk and config."""
        host = self.cp.host
        port = self.cp.ssl_port

        def mock_config(section, name):
            if (section, name) == ('server', 'no_proxy'):
                return 'foo.example.com'
            if (section, name) == ('server', 'hostname'):
                return host
            if (section, name) == ('server', 'port'):
                return port
            return None

        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host',
                                       'NO_PROXY': '*'}):
            with patch.object(connection.config, 'get', mock_config):
                uep = UEPConnection(username='******', password='******',
                                    handler='/test', insecure=True, no_proxy=host)
                self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_with_asterisk_via_api(self):
        """Test that API trumps env var with asterisk and config."""
        host = self.cp.host
        port = self.cp.ssl_port

        def mock_config(section, name):
            if (section, name) == ('server', 'no_proxy'):
                return 'foo.example.com'
            if (section, name) == ('server', 'hostname'):
                return host
            if (section, name) == ('server', 'port'):
                return port
            return None

        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host',
                                       'NO_PROXY': '*.example.com'}):
            with patch.object(connection.config, 'get', mock_config):
                uep = UEPConnection(username='******', password='******',
                                    handler='/test', insecure=True, no_proxy=host)
                self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_via_environment_variable(self):
        """Test that env var no_proxy works."""
        host = self.cp.host
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host', 'NO_PROXY': host}):
            uep = UEPConnection(username='******', password='******',
                                handler='/test', insecure=True)
            self.assertEqual(None, uep.proxy_hostname)

    def test_NO_PROXY_with_one_asterisk_via_environment_variable(self):
        """Test that env var NO_PROXY with only one asterisk works."""
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host',
                                       'NO_PROXY': '*'}):
            uep = UEPConnection(username='******', password='******',
                                handler='/test', insecure=True)
            self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_with_one_asterisk_via_environment_variable(self):
        """Test that env var no_proxy with only one asterisk works."""
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host',
                                       'no_proxy': '*'}):
            uep = UEPConnection(username='******', password='******',
                                handler='/test', insecure=True)
            self.assertEqual(None, uep.proxy_hostname)

    def test_NO_PROXY_with_asterisk_via_environment_variable(self):
        """Test that env var NO_PROXY with asterisk works."""
        host = '*' + self.cp.host
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host',
                                       'NO_PROXY': host}):
            uep = UEPConnection(username='******', password='******',
                                handler='/test', insecure=True)
            self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_with_asterisk_via_environment_variable(self):
        """Test that env var no_proxy with asterisk works."""
        host = '*' + self.cp.host
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host',
                                       'no_proxy': host}):
            uep = UEPConnection(username='******', password='******',
                                handler='/test', insecure=True)
            self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_via_config(self):
        """Test that config trumps env var."""
        host = self.cp.host
        port = self.cp.ssl_port

        def mock_config(section, name):
            if (section, name) == ('server', 'no_proxy'):
                return host
            if (section, name) == ('server', 'hostname'):
                return host
            if (section, name) == ('server', 'port'):
                return port
            return None

        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host',
                                       'NO_PROXY': 'foo.example.com'}):
            with patch.object(connection.config, 'get', mock_config):
                uep = UEPConnection(username='******', password='******',
                                    handler='/test', insecure=True)
                self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_with_asterisk_via_config(self):
        """Test that config trumps env var."""
        host = self.cp.host
        port = self.cp.ssl_port

        def mock_config(section, name):
            if (section, name) == ('server', 'no_proxy'):
                return host
            if (section, name) == ('server', 'hostname'):
                return host
            if (section, name) == ('server', 'port'):
                return port
            return None

        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host',
                                       'NO_PROXY': '*.example.com'}):
            with patch.object(connection.config, 'get', mock_config):
                uep = UEPConnection(username='******', password='******',
                                    handler='/test', insecure=True)
                self.assertEqual(None, uep.proxy_hostname)

    def test_uep_connection_honors_no_proxy_setting(self):
        with patch.dict('os.environ', {'no_proxy': 'foobar'}):
            uep = UEPConnection(host="foobar", username="******", password="******", handler="/Test/", insecure=True,
                                proxy_hostname="proxyfoo", proxy_password="******", proxy_port=42, proxy_user="******")
            self.assertIs(None, uep.proxy_user)
            self.assertIs(None, uep.proxy_password)
            self.assertIs(None, uep.proxy_hostname)
            self.assertIs(None, uep.proxy_port)

    def test_content_connection_honors_no_proxy_setting(self):
        with patch.dict('os.environ', {'no_proxy': 'foobar'}):
            cont_conn = ContentConnection(host="foobar", username="******", password="******", insecure=True,
                                          proxy_hostname="proxyfoo", proxy_password="******", proxy_port=42,
                                          proxy_user="******")
            self.assertIs(None, cont_conn.proxy_user)
            self.assertIs(None, cont_conn.proxy_password)
            self.assertIs(None, cont_conn.proxy_hostname)
            self.assertIs(None, cont_conn.proxy_port)

    def test_sanitizeGuestIds_supports_strs(self):
        self.cp.supports_resource = Mock(return_value=True)
        guestIds = ['test' + str(i) for i in range(3)]
        resultGuestIds = self.cp.sanitizeGuestIds(guestIds)
        # When strings are given, they should always be unchanged
        self.assertEqual(guestIds, resultGuestIds)

    def test_sanitizeGuestIds_no_support_strs(self):
        self.cp.supports_resource = Mock(return_value=False)
        guestIds = ['test' + str(i) for i in range(3)]
        resultGuestIds = self.cp.sanitizeGuestIds(guestIds)
        # When strings are given, they should always be unchanged
        self.assertEqual(guestIds, resultGuestIds)

    def test_sanitizeGuestIds_supports_data(self):
        self.cp.supports_resource = Mock(return_value=True)
        guestIds = [{'guestId': 'test' + str(i)} for i in range(3)]
        resultGuestIds = self.cp.sanitizeGuestIds(guestIds)
        # The dictionary should be unchanged because the server supports guestIds
        self.assertEqual(guestIds, resultGuestIds)

    def test_sanitizeGuestIds_doesnt_support_data(self):
        self.cp.supports_resource = Mock(return_value=False)
        guestIds = [{'guestId': 'test' + str(i)} for i in range(3)]
        resultGuestIds = self.cp.sanitizeGuestIds(guestIds)
        # The result list should only be string ids because the server
        # doesn't support additional data
        expected_guestIds = [guestId['guestId'] for guestId in guestIds]
        self.assertEqual(expected_guestIds, resultGuestIds)

    def test_bad_ca_cert(self):
        f = open(os.path.join(self.temp_ent_dir, "foo.pem"), 'w+')
        f.write('xxxxxx\n')
        f.close()
        cont_conn = ContentConnection(host="foobar", username="******", password="******", insecure=True)
        cont_conn.ent_dir = self.temp_ent_dir
        with self.assertRaises(BadCertificateException):
            cont_conn._load_ca_certificates(ssl.SSLContext(ssl.PROTOCOL_SSLv23))
        restlib = Restlib("somehost", "123", "somehandler")
        restlib.ca_dir = self.temp_ent_dir
        with self.assertRaises(BadCertificateException):
            restlib._load_ca_certificates(ssl.SSLContext(ssl.PROTOCOL_SSLv23))
예제 #2
0
class ConnectionTests(unittest.TestCase):

    def setUp(self):
        # NOTE: this won't actually work, idea for this suite of unit tests
        # is to mock the actual server responses and just test logic in the
        # UEPConnection:
        self.cp = UEPConnection(username="******", password="******",
                handler="/Test/", insecure=True)

    def test_load_manager_capabilities(self):
        expected_capabilities = ['hypervisors_async', 'cores']
        proper_status = {'version':'1',
                         'result':True,
                         'managerCapabilities':expected_capabilities}
        improper_status = dict.copy(proper_status)
        # Remove the managerCapabilities key from the dict
        del improper_status['managerCapabilities']
        self.cp.conn = Mock()
        # The first call will return the proper_status, the second, the improper
        # status
        original_getStatus = self.cp.getStatus
        self.cp.getStatus = Mock(side_effect=[proper_status,
                                                     improper_status])
        actual_capabilities = self.cp._load_manager_capabilities()
        self.assertEquals(sorted(actual_capabilities),
                          sorted(expected_capabilities))
        self.assertEquals([], self.cp._load_manager_capabilities())
        self.cp.getStatus = original_getStatus

    def test_get_environment_by_name_requires_owner(self):
        self.assertRaises(Exception, self.cp.getEnvironment, None, {"name": "env name"})

    def test_get_environment_urlencoding(self):
        self.cp.conn = Mock()
        self.cp.conn.request_get = Mock(return_value=[])
        self.cp.getEnvironment(owner_key="myorg", name="env name__++=*&")
        self.cp.conn.request_get.assert_called_with(
                "/owners/myorg/environments?name=env+name__%2B%2B%3D%2A%26")

    def test_entitle_date(self):
        self.cp.conn = Mock()
        self.cp.conn.request_post = Mock(return_value=[])
        self.cp.bind("abcd", date(2011, 9, 2))
        self.cp.conn.request_post.assert_called_with(
                "/consumers/abcd/entitlements?entitle_date=2011-09-02")

    def test_no_entitle_date(self):
        self.cp.conn = Mock()
        self.cp.conn.request_post = Mock(return_value=[])
        self.cp.bind("abcd")
        self.cp.conn.request_post.assert_called_with("/consumers/abcd/entitlements")

    def test_clean_up_prefix(self):
        self.assertTrue(self.cp.handler == "/Test")

    def test_https_proxy_info_allcaps(self):
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host:4444'}):
            uep = UEPConnection(username="******", password="******",
                 handler="/Test/", insecure=True)
            self.assertEquals("u", uep.proxy_user)
            self.assertEquals("p", uep.proxy_password)
            self.assertEquals("host", uep.proxy_hostname)
            self.assertEquals(int("4444"), uep.proxy_port)

    def test_order(self):
        # should follow the order: HTTPS, https, HTTP, http
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host:4444', 'http_proxy': 'http://*****:*****@host:2222'}):
            uep = UEPConnection(username="******", password="******",
                 handler="/Test/", insecure=True)
            self.assertEquals("u", uep.proxy_user)
            self.assertEquals("p", uep.proxy_password)
            self.assertEquals("host", uep.proxy_hostname)
            self.assertEquals(int("4444"), uep.proxy_port)

    def test_no_port(self):
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host'}):
            uep = UEPConnection(username="******", password="******",
                 handler="/Test/", insecure=True)
            self.assertEquals("u", uep.proxy_user)
            self.assertEquals("p", uep.proxy_password)
            self.assertEquals("host", uep.proxy_hostname)
            self.assertEquals(3128, uep.proxy_port)

    def test_no_user_or_password(self):
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://host:1111'}):
            uep = UEPConnection(username="******", password="******",
                 handler="/Test/", insecure=True)
            self.assertEquals(None, uep.proxy_user)
            self.assertEquals(None, uep.proxy_password)
            self.assertEquals("host", uep.proxy_hostname)
            self.assertEquals(int("1111"), uep.proxy_port)

    def test_sanitizeGuestIds_supports_strs(self):
        self.cp.supports_resource = Mock(return_value=True)
        guestIds = ['test' + str(i) for i in range(3)]
        resultGuestIds = self.cp.sanitizeGuestIds(guestIds)
        # When strings are given, they should always be unchanged
        self.assertEquals(guestIds, resultGuestIds)

    def test_sanitizeGuestIds_no_support_strs(self):
        self.cp.supports_resource = Mock(return_value=False)
        guestIds = ['test' + str(i) for i in range(3)]
        resultGuestIds = self.cp.sanitizeGuestIds(guestIds)
        # When strings are given, they should always be unchanged
        self.assertEquals(guestIds, resultGuestIds)

    def test_sanitizeGuestIds_supports_data(self):
        self.cp.supports_resource = Mock(return_value=True)
        guestIds = [{'guestId': 'test' + str(i)} for i in range(3)]
        resultGuestIds = self.cp.sanitizeGuestIds(guestIds)
        # The dictionary should be unchanged because the server supports guestIds
        self.assertEquals(guestIds, resultGuestIds)

    def test_sanitizeGuestIds_doesnt_support_data(self):
        self.cp.supports_resource = Mock(return_value=False)
        guestIds = [{'guestId': 'test' + str(i)} for i in range(3)]
        resultGuestIds = self.cp.sanitizeGuestIds(guestIds)
        # The result list should only be string ids because the server
        # doesn't support additional data
        expected_guestIds = [guestId['guestId'] for guestId in guestIds]
        self.assertEquals(expected_guestIds, resultGuestIds)
예제 #3
0
class ConnectionTests(unittest.TestCase):
    def setUp(self):
        # Try to remove all environment variables to not influence unit test
        try:
            os.environ.pop('no_proxy')
            os.environ.pop('NO_PROXY')
            os.environ.pop('HTTPS_PROXY')
        except KeyError:
            pass
        # NOTE: this won't actually work, idea for this suite of unit tests
        # is to mock the actual server responses and just test logic in the
        # UEPConnection:
        self.cp = UEPConnection(username="******",
                                password="******",
                                handler="/Test/",
                                insecure=True)
        self.temp_ent_dir = mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.temp_ent_dir)

    def test_accepts_a_timeout(self):
        self.cp = UEPConnection(username="******",
                                password="******",
                                handler="/Test/",
                                insecure=True,
                                timeout=3)

    def test_load_manager_capabilities(self):
        expected_capabilities = ['hypervisors_async', 'cores']
        proper_status = {
            'version': '1',
            'result': True,
            'managerCapabilities': expected_capabilities
        }
        improper_status = dict.copy(proper_status)
        # Remove the managerCapabilities key from the dict
        del improper_status['managerCapabilities']
        self.cp.conn = Mock()
        # The first call will return the proper_status, the second, the improper
        # status
        original_getStatus = self.cp.getStatus
        self.cp.getStatus = Mock(side_effect=[proper_status, improper_status])
        actual_capabilities = self.cp._load_manager_capabilities()
        self.assertEqual(sorted(actual_capabilities),
                         sorted(expected_capabilities))
        self.assertEqual([], self.cp._load_manager_capabilities())
        self.cp.getStatus = original_getStatus

    def test_get_environment_by_name_requires_owner(self):
        self.assertRaises(Exception, self.cp.getEnvironment, None,
                          {"name": "env name"})

    def test_get_environment_urlencoding(self):
        self.cp.conn = Mock()
        self.cp.conn.request_get = Mock(return_value=[])
        self.cp.getEnvironment(owner_key="myorg", name="env name__++=*&")
        self.cp.conn.request_get.assert_called_with(
            "/owners/myorg/environments?name=env+name__%2B%2B%3D%2A%26")

    def test_entitle_date(self):
        self.cp.conn = Mock()
        self.cp.conn.request_post = Mock(return_value=[])
        self.cp.bind("abcd", date(2011, 9, 2))
        self.cp.conn.request_post.assert_called_with(
            "/consumers/abcd/entitlements?entitle_date=2011-09-02")

    def test_no_entitle_date(self):
        self.cp.conn = Mock()
        self.cp.conn.request_post = Mock(return_value=[])
        self.cp.bind("abcd")
        self.cp.conn.request_post.assert_called_with(
            "/consumers/abcd/entitlements")

    def test_clean_up_prefix(self):
        self.assertTrue(self.cp.handler == "/Test")

    def test_https_proxy_info_allcaps(self):
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host:4444'}):
            uep = UEPConnection(username="******",
                                password="******",
                                handler="/Test/",
                                insecure=True)
            self.assertEqual("u", uep.proxy_user)
            self.assertEqual("p", uep.proxy_password)
            self.assertEqual("host", uep.proxy_hostname)
            self.assertEqual(int("4444"), uep.proxy_port)

    def test_order(self):
        # should follow the order: HTTPS, https, HTTP, http
        with patch.dict(
                'os.environ', {
                    'HTTPS_PROXY': 'http://*****:*****@host:4444',
                    'http_proxy': 'http://*****:*****@host:2222'
                }):
            uep = UEPConnection(username="******",
                                password="******",
                                handler="/Test/",
                                insecure=True)
            self.assertEqual("u", uep.proxy_user)
            self.assertEqual("p", uep.proxy_password)
            self.assertEqual("host", uep.proxy_hostname)
            self.assertEqual(int("4444"), uep.proxy_port)

    def test_no_port(self):
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host'}):
            uep = UEPConnection(username="******",
                                password="******",
                                handler="/Test/",
                                insecure=True)
            self.assertEqual("u", uep.proxy_user)
            self.assertEqual("p", uep.proxy_password)
            self.assertEqual("host", uep.proxy_hostname)
            self.assertEqual(3128, uep.proxy_port)

    def test_no_user_or_password(self):
        with patch.dict('os.environ', {'HTTPS_PROXY': 'http://*****:*****@host',
                'NO_PROXY': 'foo.example.com'
        }):
            with patch.object(connection.config, 'get', mock_config):
                uep = UEPConnection(username='******',
                                    password='******',
                                    handler='/test',
                                    insecure=True,
                                    no_proxy=host)
                self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_with_one_asterisk_via_api(self):
        """Test that API trumps env var with one asterisk and config."""
        host = self.cp.host
        port = self.cp.ssl_port

        def mock_config(section, name):
            if (section, name) == ('server', 'no_proxy'):
                return 'foo.example.com'
            if (section, name) == ('server', 'hostname'):
                return host
            if (section, name) == ('server', 'port'):
                return port
            return None

        with patch.dict('os.environ', {
                'HTTPS_PROXY': 'http://*****:*****@host',
                'NO_PROXY': '*'
        }):
            with patch.object(connection.config, 'get', mock_config):
                uep = UEPConnection(username='******',
                                    password='******',
                                    handler='/test',
                                    insecure=True,
                                    no_proxy=host)
                self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_with_asterisk_via_api(self):
        """Test that API trumps env var with asterisk and config."""
        host = self.cp.host
        port = self.cp.ssl_port

        def mock_config(section, name):
            if (section, name) == ('server', 'no_proxy'):
                return 'foo.example.com'
            if (section, name) == ('server', 'hostname'):
                return host
            if (section, name) == ('server', 'port'):
                return port
            return None

        with patch.dict('os.environ', {
                'HTTPS_PROXY': 'http://*****:*****@host',
                'NO_PROXY': '*.example.com'
        }):
            with patch.object(connection.config, 'get', mock_config):
                uep = UEPConnection(username='******',
                                    password='******',
                                    handler='/test',
                                    insecure=True,
                                    no_proxy=host)
                self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_via_environment_variable(self):
        """Test that env var no_proxy works."""
        host = self.cp.host
        with patch.dict('os.environ', {
                'HTTPS_PROXY': 'http://*****:*****@host',
                'NO_PROXY': host
        }):
            uep = UEPConnection(username='******',
                                password='******',
                                handler='/test',
                                insecure=True)
            self.assertEqual(None, uep.proxy_hostname)

    def test_NO_PROXY_with_one_asterisk_via_environment_variable(self):
        """Test that env var NO_PROXY with only one asterisk works."""
        with patch.dict('os.environ', {
                'HTTPS_PROXY': 'http://*****:*****@host',
                'NO_PROXY': '*'
        }):
            uep = UEPConnection(username='******',
                                password='******',
                                handler='/test',
                                insecure=True)
            self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_with_one_asterisk_via_environment_variable(self):
        """Test that env var no_proxy with only one asterisk works."""
        with patch.dict('os.environ', {
                'HTTPS_PROXY': 'http://*****:*****@host',
                'no_proxy': '*'
        }):
            uep = UEPConnection(username='******',
                                password='******',
                                handler='/test',
                                insecure=True)
            self.assertEqual(None, uep.proxy_hostname)

    def test_NO_PROXY_with_asterisk_via_environment_variable(self):
        """Test that env var NO_PROXY with asterisk works."""
        host = '*' + self.cp.host
        with patch.dict('os.environ', {
                'HTTPS_PROXY': 'http://*****:*****@host',
                'NO_PROXY': host
        }):
            uep = UEPConnection(username='******',
                                password='******',
                                handler='/test',
                                insecure=True)
            self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_with_asterisk_via_environment_variable(self):
        """Test that env var no_proxy with asterisk works."""
        host = '*' + self.cp.host
        with patch.dict('os.environ', {
                'HTTPS_PROXY': 'http://*****:*****@host',
                'no_proxy': host
        }):
            uep = UEPConnection(username='******',
                                password='******',
                                handler='/test',
                                insecure=True)
            self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_via_config(self):
        """Test that config trumps env var."""
        host = self.cp.host
        port = self.cp.ssl_port

        def mock_config(section, name):
            if (section, name) == ('server', 'no_proxy'):
                return host
            if (section, name) == ('server', 'hostname'):
                return host
            if (section, name) == ('server', 'port'):
                return port
            return None

        with patch.dict('os.environ', {
                'HTTPS_PROXY': 'http://*****:*****@host',
                'NO_PROXY': 'foo.example.com'
        }):
            with patch.object(connection.config, 'get', mock_config):
                uep = UEPConnection(username='******',
                                    password='******',
                                    handler='/test',
                                    insecure=True)
                self.assertEqual(None, uep.proxy_hostname)

    def test_no_proxy_with_asterisk_via_config(self):
        """Test that config trumps env var."""
        host = self.cp.host
        port = self.cp.ssl_port

        def mock_config(section, name):
            if (section, name) == ('server', 'no_proxy'):
                return host
            if (section, name) == ('server', 'hostname'):
                return host
            if (section, name) == ('server', 'port'):
                return port
            return None

        with patch.dict('os.environ', {
                'HTTPS_PROXY': 'http://*****:*****@host',
                'NO_PROXY': '*.example.com'
        }):
            with patch.object(connection.config, 'get', mock_config):
                uep = UEPConnection(username='******',
                                    password='******',
                                    handler='/test',
                                    insecure=True)
                self.assertEqual(None, uep.proxy_hostname)

    def test_uep_connection_honors_no_proxy_setting(self):
        with patch.dict('os.environ', {'no_proxy': 'foobar'}):
            uep = UEPConnection(host="foobar",
                                username="******",
                                password="******",
                                handler="/Test/",
                                insecure=True,
                                proxy_hostname="proxyfoo",
                                proxy_password="******",
                                proxy_port=42,
                                proxy_user="******")
            self.assertIs(None, uep.proxy_user)
            self.assertIs(None, uep.proxy_password)
            self.assertIs(None, uep.proxy_hostname)
            self.assertIs(None, uep.proxy_port)

    def test_content_connection_honors_no_proxy_setting(self):
        with patch.dict('os.environ', {'no_proxy': 'foobar'}):
            cont_conn = ContentConnection(host="foobar",
                                          username="******",
                                          password="******",
                                          insecure=True,
                                          proxy_hostname="proxyfoo",
                                          proxy_password="******",
                                          proxy_port=42,
                                          proxy_user="******")
            self.assertIs(None, cont_conn.proxy_user)
            self.assertIs(None, cont_conn.proxy_password)
            self.assertIs(None, cont_conn.proxy_hostname)
            self.assertIs(None, cont_conn.proxy_port)

    def test_sanitizeGuestIds_supports_strs(self):
        self.cp.supports_resource = Mock(return_value=True)
        guestIds = ['test' + str(i) for i in range(3)]
        resultGuestIds = self.cp.sanitizeGuestIds(guestIds)
        # When strings are given, they should always be unchanged
        self.assertEqual(guestIds, resultGuestIds)

    def test_sanitizeGuestIds_no_support_strs(self):
        self.cp.supports_resource = Mock(return_value=False)
        guestIds = ['test' + str(i) for i in range(3)]
        resultGuestIds = self.cp.sanitizeGuestIds(guestIds)
        # When strings are given, they should always be unchanged
        self.assertEqual(guestIds, resultGuestIds)

    def test_sanitizeGuestIds_supports_data(self):
        self.cp.supports_resource = Mock(return_value=True)
        guestIds = [{'guestId': 'test' + str(i)} for i in range(3)]
        resultGuestIds = self.cp.sanitizeGuestIds(guestIds)
        # The dictionary should be unchanged because the server supports guestIds
        self.assertEqual(guestIds, resultGuestIds)

    def test_sanitizeGuestIds_doesnt_support_data(self):
        self.cp.supports_resource = Mock(return_value=False)
        guestIds = [{'guestId': 'test' + str(i)} for i in range(3)]
        resultGuestIds = self.cp.sanitizeGuestIds(guestIds)
        # The result list should only be string ids because the server
        # doesn't support additional data
        expected_guestIds = [guestId['guestId'] for guestId in guestIds]
        self.assertEqual(expected_guestIds, resultGuestIds)

    def test_bad_ca_cert(self):
        with open(os.path.join(self.temp_ent_dir, "foo.pem"), 'w+') as cert:
            cert.write('xxxxxx\n')
        with open(os.path.join(self.temp_ent_dir, "foo-key.pem"), 'w+') as key:
            key.write('xxxxxx\n')
        cont_conn = ContentConnection(host="foobar",
                                      username="******",
                                      password="******",
                                      insecure=True)
        cont_conn.ent_dir = self.temp_ent_dir
        with self.assertRaises(BadCertificateException):
            cont_conn._load_ca_certificate(ssl.SSLContext(ssl.PROTOCOL_SSLv23),
                                           self.temp_ent_dir + '/foo.pem',
                                           self.temp_ent_dir + '/foo-key.pem')
        restlib = Restlib("somehost", "123", "somehandler")
        restlib.ca_dir = self.temp_ent_dir
        with self.assertRaises(BadCertificateException):
            restlib._load_ca_certificates(ssl.SSLContext(ssl.PROTOCOL_SSLv23))