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 HypervisorCheckinTests(unittest.TestCase):

    def setUp(self):
        self.cp = UEPConnection(username="******", password="******",
                insecure=True)

    def test_hypervisor_checkin_can_pass_empty_map_and_updates_nothing(self):
        response = self.cp.hypervisorCheckIn("admin", "", {})
        if self.cp.has_capability('hypervisors_async'):
            self.assertEqual(response['resultData'], None)
        else:
            self.assertEqual(len(response['failedUpdate']), 0)
            self.assertEqual(len(response['updated']), 0)
            self.assertEqual(len(response['created']), 0)
class RestlibTests(unittest.TestCase):

    def setUp(self):
        # Get handle to Restlib
        self.conn = UEPConnection().conn
        self.request_type = "GET"
        self.handler = "https://server/path"

    def _validate_response(self, response):
        # wrapper to specify request_type and handler
        return self.conn.validateResponse(response,
                                          request_type=self.request_type,
                                          handler=self.handler)

    def test_invalid_credentitals_thrown_on_401_with_empty_body(self):
        mock_response = {"status": 401}
        self.assertRaises(UnauthorizedException, self._validate_response,
                          mock_response)

    def test_standard_error_handling_on_401_with_defined_body(self):
        self._run_standard_error_handling_test(401)

    def test_standard_error_handling_on_401_with_invalid_json_body(self):
        self._run_standard_error_handling_test_invalid_json(401, UnauthorizedException)

    def test_invalid_credentitals_thrown_on_403_with_empty_body(self):
        mock_response = {"status": 403}
        self.assertRaises(ForbiddenException, self._validate_response,
                          mock_response)

    def test_standard_error_handling_on_403_with_defined_body(self):
        self._run_standard_error_handling_test(403)

    def test_standard_error_handling_on_403_with_invalid_json_body(self):
        self._run_standard_error_handling_test_invalid_json(403, ForbiddenException)

    def _run_standard_error_handling_test_invalid_json(self, expected_error_code,
                                                       expected_exception):
        mock_response = {"status": expected_error_code,
                         "content": '<this is not valid json>>'}

        self._check_for_remote_server_exception(expected_error_code,
                                                expected_exception,
                                                mock_response)

    def _run_standard_error_handling_test(self, expected_error):
        expected_error = "My Expected Error."
        mock_response = {"status": expected_error,
                         "content": '{"displayMessage":"%s"}' % expected_error}

        try:
            self._validate_response(mock_response)
            self.fail("An exception should have been thrown.")
        except Exception, ex:
            self.assertTrue(isinstance(ex, RestlibException))
            self.assertEquals(expected_error, ex.code)
            self.assertEqual(expected_error, str(ex))
class DatetimeFormattingTests(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 tearDown(self):
        locale.resetlocale()

    def test_date_formatted_properly_with_japanese_locale(self):
        locale.setlocale(locale.LC_ALL, 'ja_JP.UTF8')
        expected_headers = {
            'If-Modified-Since': 'Fri, 13 Feb 2009 23:31:30 GMT'
        }
        timestamp = 1234567890
        self.cp.conn = Mock()
        self.cp.getAccessibleContent(consumerId='bob', if_modified_since=datetime.datetime.fromtimestamp(timestamp))
        self.cp.conn.request_get.assert_called_with('/consumers/bob/accessible_content', headers=expected_headers)
class OwnerInfoTests(unittest.TestCase):
    def setUp(self):
        self.cp = UEPConnection(username="******", password="******",
                                insecure=True)
        self.owner_key = "test_owner_%d" % (random.randint(1, 5000))
        self.cp.conn.request_post('/owners', {'key': self.owner_key,
                                              'displayName': self.owner_key})

    def test_get_owner_info(self):
        owner_info = self.cp.getOwnerInfo(self.owner_key)
        self.assertTrue(owner_info is not None)
Example #6
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="******",
                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 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 setUp(self):
        self.cp = UEPConnection(username="******", password="******", insecure=True)

        self.consumer = self.cp.registerConsumer("test-consumer", "system", owner="admin")
        self.consumer_uuid = self.consumer['uuid']

        # This product is present in the Candlepin test data
        self.cp.bindByProduct(self.consumer_uuid, ["awesomeos-instancebased"])

        entitlements = self.cp.getEntitlementList(self.consumer_uuid)
        self.assertTrue(len(entitlements) > 0)

        self.entitlement = entitlements[0]
        self.entitlement_id = self.entitlement['id']
Example #9
0
def is_valid_server_info(hostname, port, prefix):
    """
    Check if we can communicate with a subscription service at the given
    location.

    Returns true or false.

    May throw a MissingCaCertException if the CA certificate has not been
    imported yet, which may be relevant to the caller.
    """
    # Proxy info should already be in config file and used by default:
    try:
        conn = UEPConnection(host=hostname, ssl_port=int(port), handler=prefix)
        conn.ping()
        return True
    except RestlibException, e:
        # If we're getting Unauthorized that's a good indication this is a
        # valid subscription service:
        if e.code == 401:
            return True
        else:
            log.exception(e)
            return False
Example #10
0
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)
Example #11
0
#!/usr/bin/env python

from rhsm.connection import UEPConnection
import json

cp = UEPConnection(host='lenovo.local.rm-rf.ca',
                   ssl_port=8443,
                   handler='/candlepin',
                   username='******',
                   password='******')

#cp = UEPConnection(
#    host='subscription.rhn.redhat.com',
#    ssl_port=443,
#    cert_file='/etc/pki/consumer/cert.pem',
#    key_file='/etc/pki/consumer/key.pem')

mapping = json.loads(
    open('/home/dgoodwin/src/candlepin/server/virtperf/checkin.json').read())
cp.hypervisorCheckIn('virtperf', None, mapping)
#cp.hypervisorCheckIn('5894300', None, mapping)
Example #12
0
class ConnectionTests(unittest.TestCase):

    def setUp(self):
        self.cp = UEPConnection(username="******", password="******", insecure=True)

        self.consumer = self.cp.registerConsumer("test-consumer", "system", owner="admin")
        self.consumer_uuid = self.consumer['uuid']

    def test_supports_resource(self):
        self.assertTrue(self.cp.supports_resource('consumers'))
        self.assertTrue(self.cp.supports_resource('admin'))
        self.assertFalse(self.cp.supports_resource('boogity'))

    def test_has_capability(self):
        self.cp.capabilities = ['cores', 'hypervisors_async']
        self.assertTrue(self.cp.has_capability('cores'))
        self.assertFalse(self.cp.has_capability('boogityboo'))

    def test_update_consumer_can_update_guests_with_empty_list(self):
        self.cp.updateConsumer(self.consumer_uuid, guest_uuids=[])

    def test_update_consumer_can_update_facts_with_empty_dict(self):
        self.cp.updateConsumer(self.consumer_uuid, facts={})

    def test_update_consumer_can_update_installed_products_with_empty_list(self):
        self.cp.updateConsumer(self.consumer_uuid, installed_products=[])

    def test_update_consumer_sets_hypervisor_id(self):
        testing_hypervisor_id = random_string("testHypervisor")
        self.cp.updateConsumer(self.consumer_uuid, hypervisor_id=testing_hypervisor_id)
        hypervisor_id = self.cp.getConsumer(self.consumer_uuid)['hypervisorId']
        # Hypervisor ID should be set and lower case
        expected = testing_hypervisor_id.lower()
        self.assertEqual(expected, hypervisor_id['hypervisorId'])

    def test_create_consumer_sets_hypervisor_id(self):
        testing_hypervisor_id = random_string("someId")
        consumerInfo = self.cp.registerConsumer("other-test-consumer",
                "system", owner="admin", hypervisor_id=testing_hypervisor_id)
        # Unregister before making assertions, that way it should always happen
        self.cp.unregisterConsumer(consumerInfo['uuid'])
        # Hypervisor ID should be set and lower case
        expected = testing_hypervisor_id.lower()
        self.assertEqual(expected, consumerInfo['hypervisorId']['hypervisorId'])

    def test_add_single_guest_id_string(self):
        testing_guest_id = random_string("guestid")
        self.cp.addOrUpdateGuestId(self.consumer_uuid, testing_guest_id)
        guestIds = self.cp.getGuestIds(self.consumer_uuid)
        self.assertEqual(1, len(guestIds))

    def test_add_single_guest_id(self):
        testing_guest_id = random_string("guestid")
        guest_id_object = {"guestId": testing_guest_id, "attributes": {"some attr": "some value"}}
        self.cp.addOrUpdateGuestId(self.consumer_uuid, guest_id_object)

        guestId = self.cp.getGuestId(self.consumer_uuid, testing_guest_id)

        # This check seems silly...
        self.assertEqual(testing_guest_id, guestId['guestId'])
        self.assertEqual('some value', guestId['attributes']['some attr'])

    def test_remove_single_guest_id(self):
        testing_guest_id = random_string("guestid")
        self.cp.addOrUpdateGuestId(self.consumer_uuid, testing_guest_id)
        guestIds = self.cp.getGuestIds(self.consumer_uuid)
        self.assertEqual(1, len(guestIds))

        # Delete the guestId
        self.cp.removeGuestId(self.consumer_uuid, testing_guest_id)

        # Check that no guestIds exist anymore
        guestIds = self.cp.getGuestIds(self.consumer_uuid)
        self.assertEqual(0, len(guestIds))

    def test_update_single_guest_id(self):
        testing_guest_id = random_string("guestid")
        guest_id_object = {"guestId": testing_guest_id, "attributes": {"some attr": "some value"}}
        self.cp.addOrUpdateGuestId(self.consumer_uuid, guest_id_object)
        guestId = self.cp.getGuestId(self.consumer_uuid, testing_guest_id)
        # check the guestId was created and has the expected attribute
        self.assertEqual('some value', guestId['attributes']['some attr'])

        guest_id_object['attributes']['some attr'] = 'crazy new value'
        self.cp.addOrUpdateGuestId(self.consumer_uuid, guest_id_object)
        guestId = self.cp.getGuestId(self.consumer_uuid, testing_guest_id)

        # Verify there's still only one guestId
        guestIds = self.cp.getGuestIds(self.consumer_uuid)
        self.assertEqual(1, len(guestIds))

        # Check that the attribute has changed
        self.assertEqual('crazy new value', guestId['attributes']['some attr'])

    def test_get_owner_hypervisors(self):
        testing_hypervisor_id = random_string("testHypervisor")
        self.cp.updateConsumer(self.consumer_uuid, hypervisor_id=testing_hypervisor_id)
        self.cp.getConsumer(self.consumer_uuid)['hypervisorId']

        hypervisors = self.cp.getOwnerHypervisors("admin", [testing_hypervisor_id])

        self.assertEqual(1, len(hypervisors))
        self.assertEqual(self.consumer_uuid, hypervisors[0]['uuid'])

    def tearDown(self):
        self.cp.unregisterConsumer(self.consumer_uuid)
Example #13
0
 def setUp(self):
     # Get handle to Restlib
     self.conn = UEPConnection().conn
     self.request_type = "GET"
     self.handler = "https://server/path"
Example #14
0
class RestlibTests(unittest.TestCase):

    def setUp(self):
        # Get handle to Restlib
        self.conn = UEPConnection().conn
        self.request_type = "GET"
        self.handler = "https://server/path"

    def _validate_response(self, response):
        # wrapper to specify request_type and handler
        return self.conn.validateResponse(response,
                                          request_type=self.request_type,
                                          handler=self.handler)

    def test_invalid_credentitals_thrown_on_401_with_empty_body(self):
        mock_response = {"status": 401}
        self.assertRaises(UnauthorizedException, self._validate_response,
                          mock_response)

    def test_standard_error_handling_on_401_with_defined_body(self):
        self._run_standard_error_handling_test(401)

    def test_standard_error_handling_on_401_with_invalid_json_body(self):
        self._run_standard_error_handling_test_invalid_json(401, UnauthorizedException)

    def test_invalid_credentitals_thrown_on_403_with_empty_body(self):
        mock_response = {"status": 403}
        self.assertRaises(ForbiddenException, self._validate_response,
                          mock_response)

    def test_standard_error_handling_on_403_with_defined_body(self):
        self._run_standard_error_handling_test(403)

    def test_standard_error_handling_on_403_with_invalid_json_body(self):
        self._run_standard_error_handling_test_invalid_json(403, ForbiddenException)

    def _run_standard_error_handling_test_invalid_json(self, expected_error_code,
                                                       expected_exception):
        mock_response = {"status": expected_error_code,
                         "content": '<this is not valid json>>'}

        self._check_for_remote_server_exception(expected_error_code,
                                                expected_exception,
                                                mock_response)

    def _run_standard_error_handling_test(self, expected_error):
        expected_error = "My Expected Error."
        mock_response = {"status": expected_error,
                         "content": '{"displayMessage":"%s"}' % expected_error}

        try:
            self._validate_response(mock_response)
            self.fail("An exception should have been thrown.")
        except Exception as ex:
            self.assertTrue(isinstance(ex, RestlibException))
            self.assertEqual(expected_error, ex.code)
            self.assertEqual(expected_error, str(ex))

    def _check_for_remote_server_exception(self, expected_error_code,
                                           expected_exception, mock_response):
        try:
            self._validate_response(mock_response)
            self.fail("An %s exception should have been thrown." % expected_exception)
        except Exception as ex:
            self.assertTrue(isinstance(ex, expected_exception))
            self.assertEqual(expected_error_code, ex.code)
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))
Example #16
0
 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)
Example #17
0
 def __init__(self):
     key = ConsumerIdentity.keypath()
     cert = ConsumerIdentity.certpath()
     UEPConnection.__init__(self, key_file=key, cert_file=cert)
Example #18
0
 def test_accepts_a_timeout(self):
     self.cp = UEPConnection(username="******",
                             password="******",
                             handler="/Test/",
                             insecure=True,
                             timeout=3)
Example #19
0
class EntitlementRegenerationTests(unittest.TestCase):
    def setUp(self):
        self.cp = UEPConnection(username="******", password="******", insecure=True)

        self.consumer = self.cp.registerConsumer("test-consumer", "system", owner="admin")
        self.consumer_uuid = self.consumer['uuid']

        # This product is present in the Candlepin test data
        self.cp.bindByProduct(self.consumer_uuid, ["awesomeos-instancebased"])

        entitlements = self.cp.getEntitlementList(self.consumer_uuid)
        self.assertTrue(len(entitlements) > 0)

        self.entitlement = entitlements[0]
        self.entitlement_id = self.entitlement['id']

    def test_regenerate_entitlements_default(self):
        result = self.cp.regenEntitlementCertificates(self.consumer_uuid)
        self.assertTrue(result)

    def test_regenerate_entitlements_lazy(self):
        result = self.cp.regenEntitlementCertificates(self.consumer_uuid, True)
        self.assertTrue(result)

    def test_regenerate_entitlements_eager(self):
        result = self.cp.regenEntitlementCertificates(self.consumer_uuid, False)
        self.assertTrue(result)

    def test_regenerate_entitlements_bad_uuid(self):
        result = self.cp.regenEntitlementCertificates("bad_consumer_uuid")
        self.assertFalse(result)

    def test_regenerate_entitlement_default(self):
        result = self.cp.regenEntitlementCertificate(self.consumer_uuid, self.entitlement_id)
        self.assertTrue(result)

    def test_regenerate_entitlement_lazy(self):
        result = self.cp.regenEntitlementCertificate(self.consumer_uuid, self.entitlement_id, True)
        self.assertTrue(result)

    def test_regenerate_entitlement_eager(self):
        result = self.cp.regenEntitlementCertificate(self.consumer_uuid, self.entitlement_id, False)
        self.assertTrue(result)

    def test_regenerate_entitlement_bad_consumer_uuid(self):
        result = self.cp.regenEntitlementCertificate("bad_consumer_uuid", self.entitlement_id)
        self.assertFalse(result)

    def test_regenerate_entitlement_bad_entitlement_id(self):
        result = self.cp.regenEntitlementCertificate(self.consumer_uuid, "bad_entitlement_id")
        self.assertFalse(result)

    def tearDown(self):
        self.cp.unregisterConsumer(self.consumer_uuid)
Example #20
0
 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)
Example #21
0
class ConnectionTests(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']

    def test_supports_resource(self):
        self.assertTrue(self.cp.supports_resource('consumers'))
        self.assertTrue(self.cp.supports_resource('admin'))
        self.assertFalse(self.cp.supports_resource('boogity'))

    def test_update_consumer_can_update_guests_with_empty_list(self):
        self.cp.updateConsumer(self.consumer_uuid, guest_uuids=[])

    def test_update_consumer_can_update_facts_with_empty_dict(self):
        self.cp.updateConsumer(self.consumer_uuid, facts={})

    def test_update_consumer_can_update_installed_products_with_empty_list(self):
        self.cp.updateConsumer(self.consumer_uuid, installed_products=[])

    def tearDown(self):
        self.cp.unregisterConsumer(self.consumer_uuid)
Example #22
0
def get_uep():
    key = ConsumerIdentity.keypath()
    cert = ConsumerIdentity.certpath()
    uep = UEPConnection(key_file=key, cert_file=cert)
    return uep
Example #23
0
 def setUp(self):
     self.cp = UEPConnection(username="******", password="******",
                             insecure=True)
     self.owner_key = "test_owner_%d" % (random.randint(1, 5000))
     self.cp.conn.request_post('/owners', {'key': self.owner_key,
                                           'displayName': self.owner_key})
Example #24
0
    def setUp(self):
        self.cp = UEPConnection(username="******", password="******", insecure=True)

        self.consumer = self.cp.registerConsumer("test-consumer", "system", owner="admin")
        self.consumer_uuid = self.consumer['uuid']
Example #25
0
class ConnectionTests(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']

    def test_supports_resource(self):
        self.assertTrue(self.cp.supports_resource('consumers'))
        self.assertTrue(self.cp.supports_resource('admin'))
        self.assertFalse(self.cp.supports_resource('boogity'))

    def test_update_consumer_can_update_guests_with_empty_list(self):
        self.cp.updateConsumer(self.consumer_uuid, guest_uuids=[])

    def test_update_consumer_can_update_facts_with_empty_dict(self):
        self.cp.updateConsumer(self.consumer_uuid, facts={})

    def test_update_consumer_can_update_installed_products_with_empty_list(
            self):
        self.cp.updateConsumer(self.consumer_uuid, installed_products=[])

    def tearDown(self):
        self.cp.unregisterConsumer(self.consumer_uuid)
Example #26
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)
Example #27
0
 def setUp(self):
     self.cp = UEPConnection(username="******", password="******",
             insecure=True)
Example #28
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"})

    @mock.patch('locale.getlocale')
    def test_has_proper_language_header_utf8(self, mock_locale):
        mock_locale.return_value = ('ja_JP', 'UTF-8')
        self.cp = UEPConnection()
        self.assertEqual(self.cp.conn.headers['Accept-Language'], 'ja-jp')

    @mock.patch('locale.getlocale')
    def test_has_proper_language_header_not_utf8(self, mock_locale):
        mock_locale.return_value = ('ja_JP', '')
        self.cp = UEPConnection()
        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')
        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))

    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
 def test_accepts_a_timeout(self):
     self.cp = UEPConnection(username="******", password="******",
             handler="/Test/", insecure=True, timeout=3)
Example #30
0
 def test_has_proper_language_header_utf8(self, mock_locale):
     mock_locale.return_value = ('ja_JP', 'UTF-8')
     self.cp = UEPConnection()
     self.assertEqual(self.cp.conn.headers['Accept-Language'], 'ja-jp')
Example #31
0
 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)
#!/usr/bin/env python
# usage:
# vsphere-virt-who-simulator.py -o ACME_Corporation -e Dev host1:guest1,guest2 host3:guest3,guest4

from rhsm.connection import UEPConnection
from optparse import OptionParser

parser = OptionParser()

parser.add_option("-o", "--org", default="ACME_Corporation")
parser.add_option("-e", "--env", default="Dev")

[options, args] = parser.parse_args()

conn = UEPConnection(cert_file="/etc/pki/consumer/cert.pem",key_file="/etc/pki/consumer/key.pem", insecure=True)

# takes array in format ["host1:guest1,guest2","host2:guest3,guest4"]
# returns dict {"host1": ["guest1","guest2"], "host2": ["guest3","guest4"]}
mapping = dict([[host, guests.split(",")] for
		[host, guests] in [arg.split(":")
		for arg in args]])

print conn.hypervisorCheckIn(options.org, options.env, mapping) 
#!/usr/bin/env python
# usage:
# vsphere-virt-who-simulator.py -o ACME_Corporation -e Dev host1:guest1,guest2 host3:guest3,guest4

from rhsm.connection import UEPConnection
from optparse import OptionParser

parser = OptionParser()

parser.add_option("-o", "--org", default="ACME_Corporation")
parser.add_option("-e", "--env", default="Dev")

[options, args] = parser.parse_args()

conn = UEPConnection(cert_file="/etc/pki/consumer/cert.pem",
                     key_file="/etc/pki/consumer/key.pem",
                     insecure=True)

# takes array in format ["host1:guest1,guest2","host2:guest3,guest4"]
# returns dict {"host1": ["guest1","guest2"], "host2": ["guest3","guest4"]}
mapping = dict([[host, guests.split(",")]
                for [host, guests] in [arg.split(":") for arg in args]])

print conn.hypervisorCheckIn(options.org, options.env, mapping)
Example #34
0
 def __init__(self):
     key = ConsumerIdentity.keypath()
     cert = ConsumerIdentity.certpath()
     UEPConnection.__init__(self, key_file=key, cert_file=cert)
#!/usr/bin/env python

from rhsm.connection import UEPConnection
import json

cp = UEPConnection(
    host='lenovo.local.rm-rf.ca',
    ssl_port=8443,
    handler='/candlepin',
    username='******',
    password='******')

#cp = UEPConnection(
#    host='subscription.rhn.redhat.com',
#    ssl_port=443,
#    cert_file='/etc/pki/consumer/cert.pem',
#    key_file='/etc/pki/consumer/key.pem')

mapping = json.loads(open('/home/dgoodwin/src/candlepin/server/virtperf/checkin.json').read())
cp.hypervisorCheckIn('virtperf', None, mapping)
#cp.hypervisorCheckIn('5894300', None, mapping)