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="******", insecure=True) 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")
class BindRequestTests(unittest.TestCase): def setUp(self): self.cp = UEPConnection(username="******", password="******", insecure=True) consumerInfo = self.cp.registerConsumer("test-consumer", "system", owner="admin") self.consumer_uuid = consumerInfo['uuid'] @patch.object(Restlib, 'validateResponse') @patch('rhsm.connection.drift_check', return_value=False) @patch('httplib.HTTPSConnection', auto_spec=True) def test_bind_no_args(self, mock_conn, mock_drift, mock_validate): self.cp.bind(self.consumer_uuid) # verify we called request() with kwargs that include 'body' as None # Specifically, we are checking that passing in "" to post_request, as # it does by default, results in None here. bin() passes no args there # so we use the default, "". See bz #907536 for (name, args, kwargs) in mock_conn.mock_calls: if name == '().request': self.assertEqual(None, kwargs['body']) @patch.object(Restlib, 'validateResponse') @patch('rhsm.connection.drift_check', return_value=False) @patch('httplib.HTTPSConnection', auto_spec=True) def test_bind_by_pool(self, mock_conn, mock_drift, mock_validate): # this test is just to verify we make the httplib connection with # right args, we don't validate the bind here self.cp.bindByEntitlementPool(self.consumer_uuid, '123121111', '1') for (name, args, kwargs) in mock_conn.mock_calls: if name == '().request': self.assertEqual(None, kwargs['body'])
class CandlepinConnection(): def getOwners(self): return self.cp.getOwnerList(self.username) def __init__(self): self.conn_username = "******" self.owner = "admin" self.cp = UEPConnection(username=self.conn_username, password="******", host="localhost", ssl_port=8443, handler="/candlepin", insecure=True) def createConsumer(self, name, facts, installed_products): consumer = self.cp.registerConsumer(name=name, facts=facts, owner=self.owner, installed_products=installed_products) print "created consumer with uuid %s. binding.." % consumer['uuid'] self.cp.bind(consumer['uuid'], entitle_date=datetime.now()) print "bind complete" self.cp.checkin(consumer['uuid']) return consumer['uuid'] def updateConsumer(self, uuid, facts, installed_products): self.cp.updateConsumer(uuid, facts=facts, installed_products=installed_products) self.cp.checkin(uuid)
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_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")
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) 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.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', '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_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_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_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) 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'}): connection = ContentConnection(host="foobar", username="******", password="******", insecure=True, proxy_hostname="proxyfoo", proxy_password="******", proxy_port=42, proxy_user="******") self.assertIs(None, connection.proxy_user) self.assertIs(None, connection.proxy_password) self.assertIs(None, connection.proxy_hostname) self.assertIs(None, connection.proxy_port) def test_bad_ca_cert(self): f = open(os.path.join(self.temp_ent_dir, "foo.pem"), 'w+') f.write('xxxxxx\n') f.close() connection = ContentConnection(host="foobar", username="******", password="******", insecure=True) connection.ent_dir = self.temp_ent_dir with self.assertRaises(BadCertificateException) as e: connection._load_ca_certificates( ssl.SSLContext(ssl.PROTOCOL_SSLv23)) restlib = Restlib("somehost", "123", "somehandler") restlib.ca_dir = self.temp_ent_dir with self.assertRaises(BadCertificateException) as e: restlib._load_ca_certificates(ssl.SSLContext(ssl.PROTOCOL_SSLv23))
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_update_smoothed_response_time(self): self.assertIsNone(self.cp.conn.smoothed_rt) self.cp.conn._update_smoothed_response_time(1.0) self.assertEqual(self.cp.conn.smoothed_rt, 1.0) self.cp.conn._update_smoothed_response_time(1.0) self.assertEqual(self.cp.conn.smoothed_rt, 1.0) self.cp.conn._update_smoothed_response_time(1.5) self.assertEqual(self.cp.conn.smoothed_rt, 1.05) def test_get_environment_by_name_requires_owner(self): self.assertRaises(Exception, self.cp.getEnvironment, None, {"name": "env name"}) @mock.patch('locale.getlocale') def test_has_proper_language_header_utf8(self, mock_locale): # First test it with Japanese mock_locale.return_value = ('ja_JP', 'UTF-8') self.cp.conn.headers = {} self.cp.conn._set_accept_language_in_header() self.assertEqual(self.cp.conn.headers['Accept-Language'], 'ja-jp') # Test that another rest api call would be called with different locale mock_locale.return_value = ('es_ES', 'UTF-8') self.cp.conn.headers = {} self.cp.conn._set_accept_language_in_header() self.assertEqual(self.cp.conn.headers['Accept-Language'], 'es-es') @mock.patch('locale.getlocale') def test_has_proper_language_header_not_utf8(self, mock_locale): mock_locale.return_value = ('ja_JP', '') self.cp.conn.headers = {} self.cp.conn._set_accept_language_in_header() self.assertEqual(self.cp.conn.headers['Accept-Language'], 'ja-jp') 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') with self.assertRaises(NoValidEntitlement): cont_conn = ContentConnection(host="foobar", username="******", password="******", insecure=True, cert_dir=self.temp_ent_dir) cont_conn.get_versions('/') 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)) def test_hypervisor_check_in_capability_and_reporter(self): self.cp.conn = Mock() self.cp.has_capability = Mock(return_value=True) Options = namedtuple('Options', 'reporter_id') options = Options('tester') self.cp.hypervisorHeartbeat("owner", options=options) self.cp.conn.request_put.assert_called_with( "/hypervisors/owner/heartbeat?reporter_id=tester") def test_hypervisor_check_in_no_capability(self): self.cp.conn = Mock() self.cp.has_capability = Mock(return_value=False) Options = namedtuple('Options', 'reporter_id') options = Options('tester') self.cp.hypervisorHeartbeat("owner", options=options) self.cp.conn.request_put.assert_not_called() def test_hypervisor_check_in_no_reporter(self): self.cp.conn = Mock() self.cp.has_capability = Mock(return_value=True) Options = namedtuple('Options', 'reporter_id') options = Options('') self.cp.hypervisorHeartbeat("owner", options=options) self.cp.conn.request_put.assert_not_called()
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)
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))