def test_get_status_on_date(self): # Prime the injected dependencies with those built in injection_definitions service = EntitlementService() # Verify the cert_sorter was constructed for a specific date mock_sorter = self.mock_sorter_class.return_value self.mock_identity.is_valid.return_value = True mock_reasons = mock.Mock(spec=Reasons, name="Reasons").return_value mock_reasons.get_name_message_map.return_value = {"RHEL": ["Not supported by a valid subscription"]} mock_sorter.get_system_status.return_value = "Invalid" mock_sorter.reasons = mock_reasons mock_sorter.is_valid.return_value = False expected_value = { 'status': 'Invalid', 'reasons': { 'RHEL': ['Not supported by a valid subscription'] }, 'valid': False } self.assertEqual(expected_value, service.get_status("some_date")) self.mock_sorter_class.assert_called_once_with("some_date")
def _enable_content(cp, consumer: dict) -> None: """ Try to enable content. Try to do auto-attach in non-SCA mode or try to do refresh SCA mode. :param cp: Object representing connection to candlepin server :param consumer: Dictionary representing consumer :return: None """ content_access_mode = consumer["owner"]["contentAccessMode"] enabled_content = None if content_access_mode == "entitlement": log.debug("Auto-attaching due to enable_content option") attach_service = AttachService(cp) enabled_content = attach_service.attach_auto() elif content_access_mode == "org_environment": log.debug( "Refreshing due to enabled_content option and simple content access mode" ) entitlement_service = EntitlementService(cp) # TODO: try get anything useful from refresh result. It is not possible atm. entitlement_service.refresh(remove_cache=False, force=False) else: log.error( f"Unable to enable content due to unsupported content access mode: " f"{content_access_mode}") # When it was possible to enable content, then extend consumer # with information about enabled content if enabled_content is not None: consumer["enabledContent"] = enabled_content
def GetPools(self, options, proxy_options, locale, sender=None): """ Try to get pools installed/available/consumed at this system :param options: D-Bus object storing options of query :param proxy_options: D-Bus object with proxy configuration :param locale: String with locale (e.g. de_DE.UTF-8) :param sender: Not used argument :return: String with JSON dump """ options = dbus_utils.dbus_to_python(options, expected_type=dict) proxy_options = dbus_utils.dbus_to_python(proxy_options, expected_type=dict) locale = dbus_utils.dbus_to_python(locale, expected_type=str) Locale.set(locale) on_date = options.setdefault('on_date', "") if on_date != "": options['on_date'] = self._parse_date(on_date) after_date = options.setdefault("after_date", "") if after_date != "": options["after_date"] = self._parse_date(after_date) future = options.setdefault("future", "") if future != "": options["future"] = future cp = self.build_uep(proxy_options, proxy_only=True) entitlement_service = EntitlementService(cp) pools = entitlement_service.get_pools(**options) return json.dumps(pools)
def test_get_status_when_unregistered(self): # Prime the injected dependencies with those built in injection_definitions service = EntitlementService() self.mock_identity.is_valid.return_value = False expected_value = {'status': 'Unknown', 'reasons': {}, 'valid': False} self.assertEqual(expected_value, service.get_status())
def test_no_pool_with_specified_filter(self, mock_managerlib): service = EntitlementService() pools = [{'service_level': 'Level1'}] mock_managerlib.get_available_entitlements.return_value = pools filtered = service.get_available_pools(service_level="NotFound") self.assertEqual(0, len(filtered))
def test_remove_all_pools_by_id(self): """ Test of removing all pools by IDs of pool """ ent_service = EntitlementService(self.mock_cp) ent_service.cp.unbindByPoolId = mock.Mock() ent_service.entitlement_dir.list_serials_for_pool_ids = mock.Mock( return_value={ "4028fa7a5dea087d015dea0b025003f6": ["6219625278114868779"], "4028fa7a5dea087d015dea0adf560152": ["3573249574655121394"], }) ent_service.entcertlib = mock.Mock().return_value ent_service.entcertlib.update = mock.Mock() removed_pools, unremoved_pools, removed_serials = ent_service.remove_entilements_by_pool_ids( [ "4028fa7a5dea087d015dea0b025003f6", "4028fa7a5dea087d015dea0adf560152" ]) expected_removed_serials = [ "6219625278114868779", "3573249574655121394" ] expected_removed_pools = [ "4028fa7a5dea087d015dea0b025003f6", "4028fa7a5dea087d015dea0adf560152" ] self.assertEqual(expected_removed_serials, removed_serials) self.assertEqual(expected_removed_pools, removed_pools) self.assertEqual([], unremoved_pools)
def test_remove_dupli_pools_by_id(self): """ Test of removing pools specified with duplicities (one pool id is set twice) """ ent_service = EntitlementService(self.mock_cp) ent_service.cp.unbindByPoolId = mock.Mock() ent_service.entitlement_dir.list_serials_for_pool_ids = mock.Mock(return_value={ '4028fa7a5dea087d015dea0b025003f6': ['6219625278114868779'], '4028fa7a5dea087d015dea0adf560152': ['3573249574655121394'] }) ent_service.entcertlib = mock.Mock().return_value ent_service.entcertlib.update = mock.Mock() removed_pools, unremoved_pools, removed_serials = ent_service.remove_entilements_by_pool_ids( ['4028fa7a5dea087d015dea0b025003f6', '4028fa7a5dea087d015dea0b025003f6', '4028fa7a5dea087d015dea0adf560152'] ) expected_removed_serials = [ '6219625278114868779', '3573249574655121394' ] expected_removed_pools = [ '4028fa7a5dea087d015dea0b025003f6', '4028fa7a5dea087d015dea0adf560152' ] self.assertEqual(expected_removed_serials, removed_serials) self.assertEqual(expected_removed_pools, removed_pools) self.assertEqual([], unremoved_pools)
def RemoveEntitlementsBySerials(self, serials, proxy_options, locale, sender=None): """ Try to remove entitlements (subscriptions) by serials :param serials: List of serial numbers of subscriptions :param proxy_options: Settings of proxy :param locale: String with locale (e.g. de_DE.UTF-8) :param sender: Not used argument :return: Json string representing list of serial numbers """ serials = dbus_utils.dbus_to_python(serials, expected_type=list) proxy_options = dbus_utils.dbus_to_python(proxy_options, expected_type=dict) locale = dbus_utils.dbus_to_python(locale, expected_type=str) Locale.set(locale) cp = self.build_uep(proxy_options, proxy_only=True) entitlement_service = EntitlementService(cp) removed_serials, unremoved_serials = entitlement_service.remove_entitlements_by_serials( serials) return json.dumps(removed_serials)
def test_no_pagged_result(self, mock_managerlib): service = EntitlementService() pools = [ { "id": "ff8080816ea20fb9016ea21283ab02e0" }, { "id": "ff8080816ea20fb9016ea21283ab02e1" }, { "id": "ff8080816ea20fb9016ea21283ab02e2" }, { "id": "ff8080816ea20fb9016ea21283ab02e3" }, { "id": "ff8080816ea20fb9016ea21283ab02e4" }, ] mock_managerlib.get_available_entitlements.return_value = pools filtered = service.get_available_pools(page=0, items_per_page=0) self.assertEqual(5, len(filtered)) self.assertEqual("ff8080816ea20fb9016ea21283ab02e0", filtered[0]["id"]) self.assertNotIn("page", filtered[0]) self.assertNotIn("items_per_page", filtered[0])
def test_remove_some_pools_by_id(self): """ Test of removing only some pools, because one pool ID is not valid """ ent_service = EntitlementService(self.mock_cp) def stub_unbind(uuid, pool_id): if pool_id == 'does_not_exist_d015dea0adf560152': raise connection.RestlibException(400, 'Error') ent_service.cp.unbindByPoolId = mock.Mock(side_effect=stub_unbind) ent_service.entitlement_dir.list_serials_for_pool_ids = mock.Mock(return_value={ '4028fa7a5dea087d015dea0b025003f6': ['6219625278114868779'], '4028fa7a5dea087d015dea0adf560152': ['3573249574655121394'] }) ent_service.entcertlib = mock.Mock().return_value ent_service.entcertlib.update = mock.Mock() removed_pools, unremoved_pools, removed_serials = ent_service.remove_entilements_by_pool_ids( ['4028fa7a5dea087d015dea0b025003f6', 'does_not_exist_d015dea0adf560152'] ) expected_removed_serials = ['6219625278114868779'] expected_removed_pools = ['4028fa7a5dea087d015dea0b025003f6'] expected_unremoved_pools = ['does_not_exist_d015dea0adf560152'] self.assertEqual(expected_removed_serials, removed_serials) self.assertEqual(expected_removed_pools, removed_pools) self.assertEqual(expected_unremoved_pools, unremoved_pools)
def GetPools(self, options, proxy_options, locale, sender=None): """ Try to get pools installed/available/consumed at this system :param options: D-Bus object storing options of query :param proxy_options: D-Bus object with proxy configuration :param locale: String with locale (e.g. de_DE.UTF-8) :param sender: Not used argument :return: String with JSON dump """ options = dbus_utils.dbus_to_python(options, expected_type=dict) proxy_options = dbus_utils.dbus_to_python(proxy_options, expected_type=dict) locale = dbus_utils.dbus_to_python(locale, expected_type=str) Locale.set(locale) on_date = options.setdefault('on_date', "") if on_date != "": options['on_date'] = self._parse_date(on_date) after_date = options.setdefault("after_date", "") if after_date != "": options["after_date"] = self._parse_date(after_date) future = options.setdefault("future", "") if future != "": options["future"] = future cp = self.build_uep(proxy_options, proxy_only=True) entitlement_service = EntitlementService(cp) pools = entitlement_service.get_pools(**options) return json.dumps(pools)
def test_remove_some_pools_by_serial(self): """ Test of removing some of pools by serial numbers, because one serial number is not valid. """ ent_service = EntitlementService(self.mock_cp) def stub_unbind(uuid, serial): if serial == 'does_not_exist_1394': raise connection.RestlibException(400, 'Error') ent_service.cp.unbindBySerial = mock.Mock(side_effect=stub_unbind) ent_service.entcertlib = mock.Mock().return_value ent_service.entcertlib.update = mock.Mock() removed_serial, unremoved_serials = ent_service.remove_entitlements_by_serials( ['6219625278114868779', 'does_not_exist_1394'] ) expected_removed_serials = ['6219625278114868779'] expected_unremoved_serials = ['does_not_exist_1394'] self.assertEqual(expected_removed_serials, removed_serial) self.assertEqual(expected_unremoved_serials, unremoved_serials)
def test_get_status(self): # Prime the injected dependencies built in injection_definitions service = EntitlementService() self.mock_identity.is_valid.return_value = True mock_reasons = mock.Mock(spec=Reasons, name="Reasons").return_value mock_reasons.get_name_message_map.return_value = { "RHEL": ["Not supported by a valid subscription"] } mock_sorter = self.mock_sorter_class.return_value mock_sorter.get_system_status.return_value = "Invalid" mock_sorter.reasons = mock_reasons mock_sorter.is_valid.return_value = False expected_value = { 'status': 'Invalid', 'reasons': { 'RHEL': ['Not supported by a valid subscription'] }, 'valid': False } self.assertEqual(expected_value, service.get_status())
def test_available_requires_registration(self): service = EntitlementService() self.mock_identity.is_valid.return_value = False options = self._build_options(pool_subsets=['available']) with self.assertRaisesRegexp(exceptions.ValidationError, r'.*not registered.*'): service.validate_options(options)
def test_parse_valid_date(self): """ Test parsing valid date """ on_date = datetime.date.today().strftime('%Y-%m-%d') ent_service = EntitlementService(self.mock_cp) expected_result = datetime.datetime.strptime(on_date, "%Y-%m-%d") parsed_date = ent_service.parse_date(on_date) self.assertEqual(expected_result, parsed_date)
def test_parse_valid_date(self): """ Test parsing valid date """ on_date = datetime.date.today().strftime('%Y-%m-%d') ent_service = EntitlementService(self.mock_cp) expected_result = datetime.datetime.strptime(on_date, "%Y-%m-%d") parsed_date = ent_service.parse_date(on_date) self.assertEqual(expected_result, parsed_date)
def test_filter_only_specified_service_level(self, mock_managerlib): service = EntitlementService() pools = [{'service_level': 'Level1'}, {'service_level': 'Level2'}, {'service_level': 'Level3'}] mock_managerlib.get_available_entitlements.return_value = pools filtered = service.get_available_pools(service_level="Level2") self.assertEqual(1, len(filtered)) self.assertEqual("Level2", filtered[0]['service_level'])
def test_remove_all_pools(self): """ Test of removing all pools """ ent_service = EntitlementService(self.mock_cp) ent_service.entcertlib = mock.Mock().return_value ent_service.entcertlib.update = mock.Mock() ent_service.cp.unbindAll = mock.Mock(return_value='[]') response = ent_service.remove_all_entitlements() self.assertEqual(response, '[]')
def test_pagged_result_too_big_page_value(self, mock_managerlib): service = EntitlementService() pools = [{'id': 'ff8080816ea20fb9016ea21283ab02e0'}, {'id': 'ff8080816ea20fb9016ea21283ab02e1'}, {'id': 'ff8080816ea20fb9016ea21283ab02e2'}, {'id': 'ff8080816ea20fb9016ea21283ab02e3'}, {'id': 'ff8080816ea20fb9016ea21283ab02e4'}] mock_managerlib.get_available_entitlements.return_value = pools filtered = service.get_available_pools(page=10, items_per_page=3) self.assertEqual(0, len(filtered))
def test_get_status_when_unregistered(self): # Prime the injected dependencies with those built in injection_definitions service = EntitlementService() self.mock_identity.is_valid.return_value = False expected_value = { "status": "Unknown", "status_id": "unknown", "reasons": {}, "reason_ids": {}, "valid": False, } self.assertEqual(expected_value, service.get_status())
def RemoveAllEntitlements(self, proxy_options, sender=None): """ Try to remove all entitlements (subscriptions) from the system :param proxy_options: Settings of proxy :param sender: Not used argument :return: Json string containing response """ proxy_options = dbus_utils.dbus_to_python(proxy_options, expected_type=dict) cp = self.build_uep(proxy_options, proxy_only=True) entitlement_service = EntitlementService(cp) result = entitlement_service.remove_all_entitlements() return json.dumps(result)
def test_no_pagged_result(self, mock_managerlib): service = EntitlementService() pools = [{'id': 'ff8080816ea20fb9016ea21283ab02e0'}, {'id': 'ff8080816ea20fb9016ea21283ab02e1'}, {'id': 'ff8080816ea20fb9016ea21283ab02e2'}, {'id': 'ff8080816ea20fb9016ea21283ab02e3'}, {'id': 'ff8080816ea20fb9016ea21283ab02e4'}] mock_managerlib.get_available_entitlements.return_value = pools filtered = service.get_available_pools(page=0, items_per_page=0) self.assertEqual(5, len(filtered)) self.assertEqual("ff8080816ea20fb9016ea21283ab02e0", filtered[0]['id']) self.assertNotIn('page', filtered[0]) self.assertNotIn('items_per_page', filtered[0])
def GetStatus(self, on_date, locale, sender=None): """ Get status of entitlements :param on_date: Date :param locale: String with locale (e.g. de_DE.UTF-8) :param sender: Not used argument :return: String with JSON dump """ on_date = dbus_utils.dbus_to_python(on_date, expected_type=str) locale = dbus_utils.dbus_to_python(locale, expected_type=str) if on_date == "": on_date = None else: on_date = self._parse_date(on_date) Locale.set(locale) try: # get_status doesn't need a Candlepin connection status = EntitlementService(None).get_status(on_date) except Exception as e: log.exception(e) raise dbus.DBusException(str(e)) return json.dumps(status)
def test_parse_invalid_date(self): """ Test parsing invalid date (invalid format) """ on_date = "2000-20-20" ent_service = EntitlementService(self.mock_cp) self.assertRaises(ValueError, ent_service.parse_date, on_date)
def RemoveAllEntitlements(self, proxy_options, locale, sender=None): """ Try to remove all entitlements (subscriptions) from the system :param proxy_options: Settings of proxy :param locale: String with locale (e.g. de_DE.UTF-8) :param sender: Not used argument :return: Json string containing response """ proxy_options = dbus_utils.dbus_to_python(proxy_options, expected_type=dict) cp = self.build_uep(proxy_options, proxy_only=True) locale = dbus_utils.dbus_to_python(locale, expected_type=str) Locale.set(locale) entitlement_service = EntitlementService(cp) result = entitlement_service.remove_all_entitlements() return json.dumps(result)
def test_parse_yesterday(self): """ Test parsing invalid date (past dates are not allowed) """ yesterday = datetime.date.today() - datetime.timedelta(1) on_date = yesterday.strftime('%Y-%m-%d') ent_service = EntitlementService(self.mock_cp) self.assertRaises(ValueError, ent_service.parse_date, on_date)
def test_remove_all_pools_by_serial(self): """ Test of removing all pools by serial numbers """ ent_service = EntitlementService(self.mock_cp) ent_service.cp.unbindBySerial = mock.Mock() ent_service.entcertlib = mock.Mock().return_value ent_service.entcertlib.update = mock.Mock() removed_serial, unremoved_serials = ent_service.remove_entitlements_by_serials( ['6219625278114868779', '3573249574655121394'] ) expected_removed_serials = ['6219625278114868779', '3573249574655121394'] self.assertEqual(expected_removed_serials, removed_serial) self.assertEqual([], unremoved_serials)
def test_get_status_on_date(self): # Prime the injected dependencies with those built in injection_definitions service = EntitlementService() # Verify the cert_sorter was constructed for a specific date mock_sorter = self.mock_sorter_class.return_value self.mock_identity.is_valid.return_value = True mock_reasons = mock.Mock(spec=Reasons, name="Reasons").return_value mock_reasons.get_name_message_map.return_value = { "RHEL": ["Not supported by a valid subscription"] } mock_reasons.get_reason_ids_map.return_value = { "69": { "key": "NOTCOVERED", "product_name": "RHEL" } } mock_sorter.get_system_status.return_value = "Invalid" mock_sorter.get_system_status_id.return_value = "invalid" mock_sorter.reasons = mock_reasons mock_sorter.is_valid.return_value = False expected_value = { "status": "Invalid", "status_id": "invalid", "reasons": { "RHEL": ["Not supported by a valid subscription"] }, "reason_ids": { "69": { "key": "NOTCOVERED", "product_name": "RHEL" } }, "valid": False, } self.assertEqual(expected_value, service.get_status("some_date")) self.mock_sorter_class.assert_called_once_with("some_date")
def RemoveEntitlementsBySerials(self, serials, proxy_options, locale, sender=None): """ Try to remove entitlements (subscriptions) by serials :param serials: List of serial numbers of subscriptions :param proxy_options: Settings of proxy :param locale: String with locale (e.g. de_DE.UTF-8) :param sender: Not used argument :return: Json string representing list of serial numbers """ serials = dbus_utils.dbus_to_python(serials, expected_type=list) proxy_options = dbus_utils.dbus_to_python(proxy_options, expected_type=dict) locale = dbus_utils.dbus_to_python(locale, expected_type=str) Locale.set(locale) cp = self.build_uep(proxy_options, proxy_only=True) entitlement_service = EntitlementService(cp) removed_serials, unremoved_serials = entitlement_service.remove_entitlements_by_serials(serials) return json.dumps(removed_serials)
def _parse_date(on_date): """ Return new datetime parsed from date :param on_date: String representing date :return It returns datetime.datime structure representing date """ try: on_date = EntitlementService.parse_date(on_date) except ValueError as err: raise dbus.DBusException(err) return on_date
def _parse_date(on_date): """ Return new datetime parsed from date :param on_date: String representing date :return It returns datetime.datime structure representing date """ try: on_date = EntitlementService.parse_date(on_date) except ValueError as err: raise dbus.DBusException(err) return on_date
def RemoveEntitlementsByPoolIds(self, pool_ids, proxy_options, sender=None): """ Try to remove entitlements (subscriptions) by pool_ids :param pool_ids: List of pool IDs :param proxy_options: Settings of proxy :param sender: Not used argument :return: Json string representing list of serial numbers """ pool_ids = dbus_utils.dbus_to_python(pool_ids, expected_type=list) proxy_options = dbus_utils.dbus_to_python(proxy_options, expected_type=dict) cp = self.build_uep(proxy_options, proxy_only=True) entitlement_service = EntitlementService(cp) removed_pools, unremoved_pools, removed_serials = entitlement_service.remove_entilements_by_pool_ids( pool_ids) return json.dumps(removed_serials)
def test_pool_only_requires_consumed_or_available(self): service = EntitlementService() options = self._build_options(pool_subsets=['installed'], pool_only=True) with self.assertRaisesRegexp(exceptions.ValidationError, r'.*only applicable with --available'): service.validate_options(options) options['pool_subsets'].append('available') service.validate_options(options)
def test_on_date_requires_available(self): service = EntitlementService() on_date = datetime.date.today().strftime('%Y-%m-%d') options = self._build_options(pool_subsets=['installed', 'consumed'], on_date=on_date) with self.assertRaisesRegexp(exceptions.ValidationError, r'.*only applicable with --available'): service.validate_options(options) options['pool_subsets'].append('available') service.validate_options(options)
def test_get_status(self): # Prime the injected dependencies built in injection_definitions service = EntitlementService() self.mock_identity.is_valid.return_value = True mock_reasons = mock.Mock(spec=Reasons, name="Reasons").return_value mock_reasons.get_name_message_map.return_value = {"RHEL": ["Not supported by a valid subscription"]} mock_sorter = self.mock_sorter_class.return_value mock_sorter.get_system_status.return_value = "Invalid" mock_sorter.reasons = mock_reasons mock_sorter.is_valid.return_value = False expected_value = { 'status': 'Invalid', 'reasons': { 'RHEL': ['Not supported by a valid subscription'] }, 'valid': False } self.assertEqual(expected_value, service.get_status())
def test_remove_dupli_pools_by_serial(self): """ Test of removing pools specified with duplicities (one serial number is set twice) """ ent_service = EntitlementService(self.mock_cp) ent_service.cp.unbindBySerial = mock.Mock() ent_service.entcertlib = mock.Mock().return_value ent_service.entcertlib.update = mock.Mock() removed_serial, unremoved_serials = ent_service.remove_entitlements_by_serials( [ "6219625278114868779", "6219625278114868779", "3573249574655121394" ]) expected_removed_serials = [ "6219625278114868779", "3573249574655121394" ] self.assertEqual(expected_removed_serials, removed_serial) self.assertEqual([], unremoved_serials)
def reload(self): entitlement_service = EntitlementService() # TODO: find better solution entitlement_service.identity.reload() entitlement_service.reload()
def test_available_requires_registration(self): service = EntitlementService() self.mock_identity.is_valid.return_value = False options = self._build_options(pool_subsets=['available']) with self.assertRaisesRegexp(exceptions.ValidationError, r'.*not registered.*'): service.validate_options(options)
def test_only_accepts_correct_pool_subsets(self): service = EntitlementService() options = self._build_options(pool_subsets=['foo']) with self.assertRaisesRegexp(exceptions.ValidationError, r'.*invalid listing type.*'): service.validate_options(options)