Exemplo n.º 1
0
    def setUp(self):
        current_pkgs = [
            Package(name="package1", version="1.0.0", release=1,
                    arch="x86_64"),
            Package(name="package2", version="2.0.0", release=2, arch="x86_64")
        ]
        temp_repo_dir = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, temp_repo_dir)
        repo_file_name = os.path.join(temp_repo_dir, 'awesome.repo')
        with open(repo_file_name, 'w') as repo_file:
            repo_file.write(CONTENT_REPO_FILE)

        patcher = patch('rhsm.profile.dnf')
        self.addCleanup(patcher.stop)
        dnf_mock = patcher.start()
        dnf_mock.dnf = Mock()
        mock_db = Mock()
        mock_db.conf = Mock()
        mock_db.conf.substitutions = {'releasever': '1', 'basearch': 'x86_64'}
        dnf_mock.dnf.Base = Mock(return_value=mock_db)

        self.current_profile = self._mock_pkg_profile(current_pkgs,
                                                      repo_file_name,
                                                      ENABLED_MODULES)
        self.profile_mgr = ProfileManager()
        self.profile_mgr.current_profile = self.current_profile
Exemplo n.º 2
0
 def setUp(self):
     current_pkgs = [
         Package(name="package1", version="1.0.0", release=1,
                 arch="x86_64"),
         Package(name="package2", version="2.0.0", release=2, arch="x86_64")
     ]
     self.current_profile = self._mock_pkg_profile(current_pkgs)
     self.profile_mgr = ProfileManager(current_profile=self.current_profile)
Exemplo n.º 3
0
def unregister(uep, consumer_uuid):
    """
    Shared logic for un-registration.
    """
    uep.unregisterConsumer(consumer_uuid)
    log.info("Successfully un-registered.")
    system_log("Unregistered machine with identity: %s" % consumer_uuid)

    # Clean up certificates, these are no longer valid:
    shutil.rmtree(cfg.get('rhsm', 'consumerCertDir'), ignore_errors=True)
    shutil.rmtree(cfg.get('rhsm', 'entitlementCertDir'), ignore_errors=True)
    ProfileManager.delete_cache()
    Facts.delete_cache()
    InstalledProductsManager.delete_cache()
Exemplo n.º 4
0
def unregister(uep, consumer_uuid):
    """
    Shared logic for un-registration.
    """
    uep.unregisterConsumer(consumer_uuid)
    log.info("Successfully un-registered.")
    system_log("Unregistered machine with identity: %s" % consumer_uuid)

    # Clean up certificates, these are no longer valid:
    shutil.rmtree(cfg.get('rhsm', 'consumerCertDir'), ignore_errors=True)
    shutil.rmtree(cfg.get('rhsm', 'entitlementCertDir'), ignore_errors=True)
    ProfileManager.delete_cache()
    Facts.delete_cache()
    InstalledProductsManager.delete_cache()
Exemplo n.º 5
0
def list_pools(uep, consumer_uuid, facts, list_all=False, active_on=None):
    """
    Wrapper around the UEP call to fetch pools, which forces a facts update
    if anything has changed before making the request. This ensures the
    rule checks server side will have the most up to date info about the
    consumer possible.
    """
    facts.update_check(uep, consumer_uuid)

    profile_mgr = ProfileManager()
    profile_mgr.update_check(uep, consumer_uuid)

    owner = uep.getOwner(consumer_uuid)
    ownerid = owner["key"]
    return uep.getPoolsList(consumer=consumer_uuid, listAll=list_all, active_on=active_on, owner=ownerid)
Exemplo n.º 6
0
    def _register_consumer(self, name, facts, owner, env, callback):
        """
        method run in the worker thread.
        """
        try:
            installed_mgr = InstalledProductsManager()
            retval = self.backend.admin_uep.registerConsumer(
                name=name,
                facts=facts.get_facts(),
                owner=owner,
                environment=env,
                installed_products=installed_mgr.format_for_server())

            # Facts and installed products went out with the registration
            # request, manually write caches to disk:
            facts.write_cache()
            installed_mgr.write_cache()

            ProfileManager().update_check(self.backend.admin_uep,
                                          retval['uuid'])

            # We have new credentials, restart virt-who
            restart_virt_who()

            self.queue.put((callback, retval, None))
        except Exception, e:
            self.queue.put((callback, None, e))
 def setUp(self):
     current_pkgs = [
         Package(name="package1", version="1.0.0", release=1,
                 arch="x86_64"),
         Package(name="package2", version="2.0.0", release=2, arch="x86_64")
     ]
     temp_repo_dir = tempfile.mkdtemp()
     self.addCleanup(shutil.rmtree, temp_repo_dir)
     repo_file_name = os.path.join(temp_repo_dir, 'awesome.repo')
     with open(repo_file_name, 'w') as repo_file:
         repo_file.write(CONTENT_REPO_FILE)
     self.current_profile = self._mock_pkg_profile(current_pkgs,
                                                   repo_file_name,
                                                   ENABLED_MODULES)
     self.profile_mgr = ProfileManager()
     self.profile_mgr.current_profile = self.current_profile
 def setUp(self):
     current_pkgs = [
         Package(name="package1", version="1.0.0", release=1, arch="x86_64"),
         Package(name="package2", version="2.0.0", release=2, arch="x86_64"),
     ]
     self.current_profile = self._mock_pkg_profile(current_pkgs)
     self.profile_mgr = ProfileManager(current_profile=self.current_profile)
Exemplo n.º 9
0
def list_pools(uep, consumer_uuid, facts, list_all=False, active_on=None):
    """
    Wrapper around the UEP call to fetch pools, which forces a facts update
    if anything has changed before making the request. This ensures the
    rule checks server side will have the most up to date info about the
    consumer possible.
    """
    facts.update_check(uep, consumer_uuid)

    profile_mgr = ProfileManager()
    profile_mgr.update_check(uep, consumer_uuid)

    owner = uep.getOwner(consumer_uuid)
    ownerid = owner['key']
    return uep.getPoolsList(consumer=consumer_uuid,
                            listAll=list_all,
                            active_on=active_on,
                            owner=ownerid)
Exemplo n.º 10
0
def clean_all_data(backup=True):
    consumer_dir = cfg.get('rhsm', 'consumerCertDir')
    if backup:
        if consumer_dir[-1] == "/":
            consumer_dir_backup = consumer_dir[0:-1] + ".old"
        else:
            consumer_dir_backup = consumer_dir + ".old"

        shutil.rmtree(consumer_dir_backup, ignore_errors=True)
        os.rename(consumer_dir, consumer_dir_backup)
    else:
        shutil.rmtree(consumer_dir, ignore_errors=True)

    shutil.rmtree(cfg.get('rhsm', 'entitlementCertDir'), ignore_errors=True)

    ProfileManager.delete_cache()
    InstalledProductsManager.delete_cache()
    Facts.delete_cache()
    RepoLib.delete_repo_file()
    log.info("Cleaned local data")
Exemplo n.º 11
0
def clean_all_data(backup=True):
    consumer_dir = cfg.get('rhsm', 'consumerCertDir')
    if backup:
        if consumer_dir[-1] == "/":
            consumer_dir_backup = consumer_dir[0:-1] + ".old"
        else:
            consumer_dir_backup = consumer_dir + ".old"

        shutil.rmtree(consumer_dir_backup, ignore_errors=True)
        os.rename(consumer_dir, consumer_dir_backup)
    else:
        shutil.rmtree(consumer_dir, ignore_errors=True)

    shutil.rmtree(cfg.get('rhsm', 'entitlementCertDir'), ignore_errors=True)

    ProfileManager.delete_cache()
    InstalledProductsManager.delete_cache()
    Facts.delete_cache()
    RepoLib.delete_repo_file()
    log.info("Cleaned local data")
Exemplo n.º 12
0
 def setUp(self):
     current_pkgs = [
         Package(name="package1", version="1.0.0", release=1, arch="x86_64"),
         Package(name="package2", version="2.0.0", release=2, arch="x86_64")
     ]
     temp_repo_dir = tempfile.mkdtemp()
     self.addCleanup(shutil.rmtree, temp_repo_dir)
     repo_file_name = os.path.join(temp_repo_dir, 'awesome.repo')
     with open(repo_file_name, 'w') as repo_file:
         repo_file.write(CONTENT_REPO_FILE)
     self.current_profile = self._mock_pkg_profile(current_pkgs, repo_file_name, ENABLED_MODULES)
     self.profile_mgr = ProfileManager()
     self.profile_mgr.current_profile = self.current_profile
Exemplo n.º 13
0
    def _register_consumer(self, name, facts, owner, env, activation_keys, callback):
        """
        method run in the worker thread.
        """
        try:
            installed_mgr = InstalledProductsManager()

            self.plugin_manager.run("pre_register_consumer", name=name,
                facts=facts.get_facts())
            retval = self.backend.cp_provider.get_basic_auth_cp().registerConsumer(name=name,
                    facts=facts.get_facts(), owner=owner, environment=env,
                    keys=activation_keys,
                    installed_products=installed_mgr.format_for_server())
            self.plugin_manager.run("post_register_consumer", consumer=retval,
                facts=facts.get_facts())

            # Facts and installed products went out with the registration
            # request, manually write caches to disk:
            facts.write_cache()
            installed_mgr.write_cache()

            cp = self.backend.cp_provider.get_basic_auth_cp()

            # In practice, the only time this condition should be true is
            # when we are working with activation keys.  See BZ #888790.
            if not self.backend.cp_provider.get_basic_auth_cp().username and \
                not self.backend.cp_provider.get_basic_auth_cp().password:
                # Write the identity cert to disk
                managerlib.persist_consumer_cert(retval)
                self.backend.update()
                cp = self.backend.cp_provider.get_consumer_auth_cp()

            ProfileManager().update_check(cp, retval['uuid'])

            # We have new credentials, restart virt-who
            restart_virt_who()

            self.queue.put((callback, retval, None))
        except Exception:
            self.queue.put((callback, None, sys.exc_info()))
Exemplo n.º 14
0
class TestProfileManager(unittest.TestCase):
    def setUp(self):
        current_pkgs = [
                Package(name="package1", version="1.0.0", release=1, arch="x86_64"),
                Package(name="package2", version="2.0.0", release=2, arch="x86_64")]
        self.current_profile = self._mock_pkg_profile(current_pkgs)
        self.profile_mgr = ProfileManager(current_profile=self.current_profile)

    def test_update_check_no_change(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.updatePackageProfile = Mock()

        self.profile_mgr.has_changed = Mock(return_value=False)
        self.profile_mgr.write_cache = Mock()
        self.profile_mgr.update_check(uep, uuid)

        self.assertEqual(0, uep.updatePackageProfile.call_count)
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_update_check_has_changed(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        uep.updatePackageProfile.assert_called_with(uuid,
                FACT_MATCHER)
        self.assertEqual(1, self.profile_mgr.write_cache.call_count)

    def test_update_check_packages_not_supported(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.supports_resource = Mock(return_value=False)
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        self.assertEqual(0, uep.updatePackageProfile.call_count)
        uep.supports_resource.assert_called_with('packages')
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_update_check_packages_disabled(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        self.profile_mgr._set_report_package_profile(0)
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        self.assertEqual(0, uep.updatePackageProfile.call_count)
        uep.supports_resource.assert_called_with('packages')
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_update_check_error_uploading(self):
        uuid = 'FAKEUUID'
        uep = Mock()

        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()
        # Throw an exception when trying to upload:
        uep.updatePackageProfile = Mock(side_effect=Exception('BOOM!'))

        self.assertRaises(Exception, self.profile_mgr.update_check, uep, uuid)
        uep.updatePackageProfile.assert_called_with(uuid,
                FACT_MATCHER)
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_has_changed_no_cache(self):
        self.profile_mgr._cache_exists = Mock(return_value=False)
        self.assertTrue(self.profile_mgr.has_changed())

    def test_has_changed_no_changes(self):
        cached_pkgs = [
                Package(name="package1", version="1.0.0", release=1, arch="x86_64"),
                Package(name="package2", version="2.0.0", release=2, arch="x86_64")]
        cached_profile = self._mock_pkg_profile(cached_pkgs)

        self.profile_mgr._cache_exists = Mock(return_value=True)
        self.profile_mgr._read_cache = Mock(return_value=cached_profile)

        self.assertFalse(self.profile_mgr.has_changed())
        self.profile_mgr._read_cache.assert_called_with()

    def test_has_changed(self):
        cached_pkgs = [
                Package(name="package1", version="1.0.0", release=1, arch="x86_64"),
                Package(name="package3", version="3.0.0", release=3, arch="x86_64")]
        cached_profile = self._mock_pkg_profile(cached_pkgs)

        self.profile_mgr._cache_exists = Mock(return_value=True)
        self.profile_mgr._read_cache = Mock(return_value=cached_profile)

        self.assertTrue(self.profile_mgr.has_changed())
        self.profile_mgr._read_cache.assert_called_with()

    def test_update_check_consumer_uuid_none(self):
        uuid = None
        uep = Mock()

        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        res = self.profile_mgr.update_check(uep, uuid)
        self.assertEqual(0, res)

    def test_package_json_handles_non_unicode(self):
        package = Package(name=b'\xf6', version=b'\xf6', release=b'\xf6', arch=b'\xf6', vendor=b'\xf6')
        data = package.to_dict()
        json_str = json.dumps(data)  # to json
        data = json.loads(json_str)  # and back to an object
        for attr in ['name', 'version', 'release', 'arch', 'vendor']:
            self.assertEqual(u'\ufffd', data[attr])

    def test_package_json_as_unicode_type(self):
        # note that the data type at time of writing is bytes, so this is just defensive coding
        package = Package(name=u'Björk', version=u'Björk', release=u'Björk', arch=u'Björk', vendor=u'Björk')
        data = package.to_dict()
        json_str = json.dumps(data)  # to json
        data = json.loads(json_str)  # and back to an object
        for attr in ['name', 'version', 'release', 'arch', 'vendor']:
            self.assertEqual(u'Björk', data[attr])

    def test_package_json_missing_attributes(self):
        package = Package(name=None, version=None, release=None, arch=None, vendor=None)
        data = package.to_dict()
        json_str = json.dumps(data)  # to json
        data = json.loads(json_str)  # and back to an object
        for attr in ['name', 'version', 'release', 'arch', 'vendor']:
            self.assertEqual(None, data[attr])

    @staticmethod
    def _mock_pkg_profile(packages):
        """
        Turn a list of package objects into an RPMProfile object.
        """

        dict_list = []
        for pkg in packages:
            dict_list.append(pkg.to_dict())

        mock_file = Mock()
        mock_file.read = Mock(return_value=json.dumps(dict_list))

        mock_profile = RPMProfile(from_file=mock_file)
        return mock_profile
Exemplo n.º 15
0
class TestProfileManager(unittest.TestCase):

    def setUp(self):
        current_pkgs = [
                Package(name="package1", version="1.0.0", release=1, arch="x86_64"),
                Package(name="package2", version="2.0.0", release=2, arch="x86_64")]
        self.current_profile = self._mock_pkg_profile(current_pkgs)
        self.profile_mgr = ProfileManager(current_profile=self.current_profile)

    def test_update_check_no_change(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.updatePackageProfile = Mock()

        self.profile_mgr.has_changed = Mock(return_value=False)
        self.profile_mgr.write_cache = Mock()
        self.profile_mgr.update_check(uep, uuid)

        self.assertEquals(0, uep.updatePackageProfile.call_count)
        self.assertEquals(0, self.profile_mgr.write_cache.call_count)

    def test_update_check_has_changed(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        uep.updatePackageProfile.assert_called_with(uuid,
                FACT_MATCHER)
        self.assertEquals(1, self.profile_mgr.write_cache.call_count)

    def test_update_check_packages_not_supported(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.supports_resource = Mock(return_value=False)
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        self.assertEquals(0, uep.updatePackageProfile.call_count)
        uep.supports_resource.assert_called_with('packages')
        self.assertEquals(0, self.profile_mgr.write_cache.call_count)

    def test_update_check_packages_disabled(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        self.profile_mgr._set_report_package_profile(0)
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        self.assertEquals(0, uep.updatePackageProfile.call_count)
        uep.supports_resource.assert_called_with('packages')
        self.assertEquals(0, self.profile_mgr.write_cache.call_count)

    def test_update_check_error_uploading(self):
        uuid = 'FAKEUUID'
        uep = Mock()

        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()
        # Throw an exception when trying to upload:
        uep.updatePackageProfile = Mock(side_effect=Exception('BOOM!'))

        self.assertRaises(Exception, self.profile_mgr.update_check, uep, uuid)
        uep.updatePackageProfile.assert_called_with(uuid,
                FACT_MATCHER)
        self.assertEquals(0, self.profile_mgr.write_cache.call_count)

    def test_has_changed_no_cache(self):
        self.profile_mgr._cache_exists = Mock(return_value=False)
        self.assertTrue(self.profile_mgr.has_changed())

    def test_has_changed_no_changes(self):
        cached_pkgs = [
                Package(name="package1", version="1.0.0", release=1, arch="x86_64"),
                Package(name="package2", version="2.0.0", release=2, arch="x86_64")]
        cached_profile = self._mock_pkg_profile(cached_pkgs)

        self.profile_mgr._cache_exists = Mock(return_value=True)
        self.profile_mgr._read_cache = Mock(return_value=cached_profile)

        self.assertFalse(self.profile_mgr.has_changed())
        self.profile_mgr._read_cache.assert_called_with()

    def test_has_changed(self):
        cached_pkgs = [
                Package(name="package1", version="1.0.0", release=1, arch="x86_64"),
                Package(name="package3", version="3.0.0", release=3, arch="x86_64")]
        cached_profile = self._mock_pkg_profile(cached_pkgs)

        self.profile_mgr._cache_exists = Mock(return_value=True)
        self.profile_mgr._read_cache = Mock(return_value=cached_profile)

        self.assertTrue(self.profile_mgr.has_changed())
        self.profile_mgr._read_cache.assert_called_with()

    @staticmethod
    def _mock_pkg_profile(packages):
        """
        Turn a list of package objects into an RPMProfile object.
        """

        dict_list = []
        for pkg in packages:
            dict_list.append(pkg.to_dict())

        mock_file = Mock()
        mock_file.read = Mock(return_value=json.dumps(dict_list))

        mock_profile = RPMProfile(from_file=mock_file)
        return mock_profile
Exemplo n.º 16
0
class TestProfileManager(unittest.TestCase):
    def setUp(self):
        current_pkgs = [
            Package(name="package1", version="1.0.0", release=1,
                    arch="x86_64"),
            Package(name="package2", version="2.0.0", release=2, arch="x86_64")
        ]
        temp_repo_dir = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, temp_repo_dir)
        repo_file_name = os.path.join(temp_repo_dir, 'awesome.repo')
        with open(repo_file_name, 'w') as repo_file:
            repo_file.write(CONTENT_REPO_FILE)
        self.current_profile = self._mock_pkg_profile(current_pkgs,
                                                      repo_file_name,
                                                      ENABLED_MODULES)
        self.profile_mgr = ProfileManager()
        self.profile_mgr.current_profile = self.current_profile

    def test_update_check_no_change(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.updatePackageProfile = Mock()

        self.profile_mgr.has_changed = Mock(return_value=False)
        self.profile_mgr.write_cache = Mock()
        self.profile_mgr.update_check(uep, uuid)

        self.assertEqual(0, uep.updatePackageProfile.call_count)
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_update_check_has_changed(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.has_capability = Mock(return_value=False)
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        uep.updatePackageProfile.assert_called_with(uuid, FACT_MATCHER)
        self.assertEqual(1, self.profile_mgr.write_cache.call_count)

    def test_combined_profile_update_check_has_changed(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.has_capability = Mock(return_value=True)
        uep.updateCombinedProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        uep.updateCombinedProfile.assert_called_with(uuid, FACT_MATCHER)
        self.assertEqual(1, self.profile_mgr.write_cache.call_count)

    def test_update_check_packages_not_supported(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.supports_resource = Mock(return_value=False)
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        self.assertEqual(0, uep.updatePackageProfile.call_count)
        uep.supports_resource.assert_called_with('packages')
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_update_check_packages_disabled(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        self.profile_mgr.report_package_profile = 0
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        self.assertEqual(0, uep.updatePackageProfile.call_count)
        uep.supports_resource.assert_called_with('packages')
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_report_package_profile_environment_variable(self):
        with patch.dict('os.environ', {'SUBMAN_DISABLE_PROFILE_REPORTING': '1'}), \
            patch.object(cache, 'conf') as conf:
            # report_package_profile is set to 1 and SUBMAN_DISABLE_PROFILE_REPORTING is set to 1, the
            # package profile should not be reported.
            conf.__getitem__.return_value.get_int.return_value = 1
            self.assertFalse(self.profile_mgr.profile_reporting_enabled())
            # report_package_profile in rhsm.conf is set to 0 and SUBMAN_DISABLE_PROFILE_REPORTING is set
            # to 1, the package profile should not be reported.
            conf.__getitem__.return_value.get_int.return_value = 0
            self.assertFalse(self.profile_mgr.profile_reporting_enabled())

        with patch.dict('os.environ', {'SUBMAN_DISABLE_PROFILE_REPORTING': '0'}), \
            patch.object(cache, 'conf') as conf:
            # report_package_profile in rhsm.conf is set to 1 and SUBMAN_DISABLE_PROFILE_REPORTING is set
            # to 0, the package profile should be reported.
            conf.__getitem__.return_value.get_int.return_value = 1
            self.assertTrue(self.profile_mgr.profile_reporting_enabled())
            # report_package_profile in rhsm.conf is set to 0 and SUBMAN_DISABLE_PROFILE_REPORTING is set
            # to 0, the package profile should not be reported.
            conf.__getitem__.return_value.get_int.return_value = 0
            self.assertFalse(self.profile_mgr.profile_reporting_enabled())

        with patch.dict('os.environ', {}), patch.object(cache, 'conf') as conf:
            # report_package_profile in rhsm.conf is set to 1 and SUBMAN_DISABLE_PROFILE_REPORTING is not
            # set, the package profile should be reported.
            conf.__getitem__.return_value.get_int.return_value = 1
            self.assertTrue(self.profile_mgr.profile_reporting_enabled())
            # report_package_profile in rhsm.conf is set to 0 and SUBMAN_DISABLE_PROFILE_REPORTING is not
            # set, the package profile should not be reported.
            conf.__getitem__.return_value.get_int.return_value = 0
            self.assertFalse(self.profile_mgr.profile_reporting_enabled())

    def test_update_check_error_uploading(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.has_capability = Mock(return_value=False)

        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()
        # Throw an exception when trying to upload:
        uep.updatePackageProfile = Mock(side_effect=Exception('BOOM!'))

        self.assertRaises(Exception, self.profile_mgr.update_check, uep, uuid)
        uep.updatePackageProfile.assert_called_with(uuid, FACT_MATCHER)
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_combined_profile_update_check_error_uploading(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.has_capability = Mock(return_value=True)

        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()
        # Throw an exception when trying to upload:
        uep.updateCombinedProfile = Mock(side_effect=Exception('BOOM!'))

        self.assertRaises(Exception, self.profile_mgr.update_check, uep, uuid)
        uep.updateCombinedProfile.assert_called_with(uuid, FACT_MATCHER)
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_has_changed_no_cache(self):
        self.profile_mgr._cache_exists = Mock(return_value=False)
        self.assertTrue(self.profile_mgr.has_changed())

    def test_has_changed_no_changes(self):
        cached_pkgs = [
            Package(name="package1", version="1.0.0", release=1,
                    arch="x86_64"),
            Package(name="package2", version="2.0.0", release=2, arch="x86_64")
        ]
        temp_repo_dir = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, temp_repo_dir)
        repo_file_name = os.path.join(temp_repo_dir, 'awesome.repo')
        with open(repo_file_name, 'w') as repo_file:
            repo_file.write(CONTENT_REPO_FILE)
        cached_profile = self._mock_pkg_profile(cached_pkgs, repo_file_name,
                                                ENABLED_MODULES)

        self.profile_mgr._cache_exists = Mock(return_value=True)
        self.profile_mgr._read_cache = Mock(return_value=cached_profile)

        self.assertFalse(self.profile_mgr.has_changed())
        self.profile_mgr._read_cache.assert_called_with()

    def test_has_changed(self):
        cached_pkgs = [
            Package(name="package1", version="1.0.0", release=1,
                    arch="x86_64"),
            Package(name="package3", version="3.0.0", release=3, arch="x86_64")
        ]
        cached_profile = self._mock_pkg_profile(
            cached_pkgs, "/non/existing/path/to/repo/file", [])

        self.profile_mgr._cache_exists = Mock(return_value=True)
        self.profile_mgr._read_cache = Mock(return_value=cached_profile)

        self.assertTrue(self.profile_mgr.has_changed())
        self.profile_mgr._read_cache.assert_called_with()

    def test_update_check_consumer_uuid_none(self):
        uuid = None
        uep = Mock()

        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        res = self.profile_mgr.update_check(uep, uuid)
        self.assertEqual(0, res)

    def test_package_json_handles_non_unicode(self):
        package = Package(name=b'\xf6',
                          version=b'\xf6',
                          release=b'\xf6',
                          arch=b'\xf6',
                          vendor=b'\xf6')
        data = package.to_dict()
        json_str = json.dumps(data)  # to json
        data = json.loads(json_str)  # and back to an object
        for attr in ['name', 'version', 'release', 'arch', 'vendor']:
            self.assertEqual(u'\ufffd', data[attr])

    def test_package_json_as_unicode_type(self):
        # note that the data type at time of writing is bytes, so this is just defensive coding
        package = Package(name=u'Björk',
                          version=u'Björk',
                          release=u'Björk',
                          arch=u'Björk',
                          vendor=u'Björk')
        data = package.to_dict()
        json_str = json.dumps(data)  # to json
        data = json.loads(json_str)  # and back to an object
        for attr in ['name', 'version', 'release', 'arch', 'vendor']:
            self.assertEqual(u'Björk', data[attr])

    def test_package_json_missing_attributes(self):
        package = Package(name=None,
                          version=None,
                          release=None,
                          arch=None,
                          vendor=None)
        data = package.to_dict()
        json_str = json.dumps(data)  # to json
        data = json.loads(json_str)  # and back to an object
        for attr in ['name', 'version', 'release', 'arch', 'vendor']:
            self.assertEqual(None, data[attr])

    def test_module_md_uniquify(self):
        modules_input = [{
            "name": "duck",
            "stream": 0,
            "version": "20180730233102",
            "context": "deadbeef",
            "arch": "noarch",
            "profiles": ["default"],
            "installed_profiles": [],
            "status": "enabled"
        }, {
            "name": "duck",
            "stream": 0,
            "version": "20180707144203",
            "context": "c0ffee42",
            "arch": "noarch",
            "profiles": ["default", "server"],
            "installed_profiles": ["server"],
            "status": "unknown"
        }]

        self.assertEqual(modules_input,
                         ModulesProfile._uniquify(modules_input))
        # now test dup modules
        self.assertEqual(
            modules_input,
            ModulesProfile._uniquify(modules_input + [modules_input[0]]))

    @staticmethod
    def _mock_pkg_profile(packages, repo_file, enabled_modules):
        """
        Turn a list of package objects into an RPMProfile object.
        """

        dict_list = []
        for pkg in packages:
            dict_list.append(pkg.to_dict())

        mock_file = Mock()
        mock_file.read = Mock(return_value=json.dumps(dict_list))

        mock_rpm_profile = RPMProfile(from_file=mock_file)

        mock_enabled_repos_profile = EnabledReposProfile(repo_file=repo_file)

        mock_module_profile = ModulesProfile()
        mock_module_profile.collect = Mock(return_value=enabled_modules)

        mock_profile = {
            "rpm": mock_rpm_profile,
            "enabled_repos": mock_enabled_repos_profile,
            "modulemd": mock_module_profile
        }
        return mock_profile
Exemplo n.º 17
0
class TestProfileManager(unittest.TestCase):
    def setUp(self):
        current_pkgs = [
            Package(name="package1", version="1.0.0", release=1, arch="x86_64"),
            Package(name="package2", version="2.0.0", release=2, arch="x86_64")
        ]
        temp_repo_dir = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, temp_repo_dir)
        repo_file_name = os.path.join(temp_repo_dir, 'awesome.repo')
        with open(repo_file_name, 'w') as repo_file:
            repo_file.write(CONTENT_REPO_FILE)
        self.current_profile = self._mock_pkg_profile(current_pkgs, repo_file_name, ENABLED_MODULES)
        self.profile_mgr = ProfileManager()
        self.profile_mgr.current_profile = self.current_profile

    def test_update_check_no_change(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.updatePackageProfile = Mock()

        self.profile_mgr.has_changed = Mock(return_value=False)
        self.profile_mgr.write_cache = Mock()
        self.profile_mgr.update_check(uep, uuid)

        self.assertEqual(0, uep.updatePackageProfile.call_count)
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_update_check_has_changed(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.has_capability = Mock(return_value=False)
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid, True)

        uep.updatePackageProfile.assert_called_with(uuid,
                FACT_MATCHER)
        self.assertEqual(1, self.profile_mgr.write_cache.call_count)

    def test_combined_profile_update_check_has_changed(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.has_capability = Mock(return_value=True)
        uep.updateCombinedProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid, True)

        uep.updateCombinedProfile.assert_called_with(uuid,
                FACT_MATCHER)
        self.assertEqual(1, self.profile_mgr.write_cache.call_count)

    def test_update_check_packages_not_supported(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.supports_resource = Mock(return_value=False)
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        self.assertEqual(0, uep.updatePackageProfile.call_count)
        uep.supports_resource.assert_called_with('packages')
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_update_check_packages_disabled(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        self.profile_mgr.report_package_profile = 0
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        self.assertEqual(0, uep.updatePackageProfile.call_count)
        uep.supports_resource.assert_called_with('packages')
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_report_package_profile_environment_variable(self):
        with patch.dict('os.environ', {'SUBMAN_DISABLE_PROFILE_REPORTING': '1'}), \
            patch.object(cache, 'conf') as conf:
                # report_package_profile is set to 1 and SUBMAN_DISABLE_PROFILE_REPORTING is set to 1, the
                # package profile should not be reported.
                conf.__getitem__.return_value.get_int.return_value = 1
                self.assertFalse(self.profile_mgr.profile_reporting_enabled())
                # report_package_profile in rhsm.conf is set to 0 and SUBMAN_DISABLE_PROFILE_REPORTING is set
                # to 1, the package profile should not be reported.
                conf.__getitem__.return_value.get_int.return_value = 0
                self.assertFalse(self.profile_mgr.profile_reporting_enabled())

        with patch.dict('os.environ', {'SUBMAN_DISABLE_PROFILE_REPORTING': '0'}), \
            patch.object(cache, 'conf') as conf:
                # report_package_profile in rhsm.conf is set to 1 and SUBMAN_DISABLE_PROFILE_REPORTING is set
                # to 0, the package profile should be reported.
                conf.__getitem__.return_value.get_int.return_value = 1
                self.assertTrue(self.profile_mgr.profile_reporting_enabled())
                # report_package_profile in rhsm.conf is set to 0 and SUBMAN_DISABLE_PROFILE_REPORTING is set
                # to 0, the package profile should not be reported.
                conf.__getitem__.return_value.get_int.return_value = 0
                self.assertFalse(self.profile_mgr.profile_reporting_enabled())

        with patch.dict('os.environ', {}), patch.object(cache, 'conf') as conf:
                # report_package_profile in rhsm.conf is set to 1 and SUBMAN_DISABLE_PROFILE_REPORTING is not
                # set, the package profile should be reported.
                conf.__getitem__.return_value.get_int.return_value = 1
                self.assertTrue(self.profile_mgr.profile_reporting_enabled())
                # report_package_profile in rhsm.conf is set to 0 and SUBMAN_DISABLE_PROFILE_REPORTING is not
                # set, the package profile should not be reported.
                conf.__getitem__.return_value.get_int.return_value = 0
                self.assertFalse(self.profile_mgr.profile_reporting_enabled())

    def test_update_check_error_uploading(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.has_capability = Mock(return_value=False)

        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()
        # Throw an exception when trying to upload:
        uep.updatePackageProfile = Mock(side_effect=Exception('BOOM!'))

        self.assertRaises(Exception, self.profile_mgr.update_check, uep, uuid, True)
        uep.updatePackageProfile.assert_called_with(uuid,
                FACT_MATCHER)
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_combined_profile_update_check_error_uploading(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.has_capability = Mock(return_value=True)

        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()
        # Throw an exception when trying to upload:
        uep.updateCombinedProfile = Mock(side_effect=Exception('BOOM!'))

        self.assertRaises(Exception, self.profile_mgr.update_check, uep, uuid, True)
        uep.updateCombinedProfile.assert_called_with(uuid,
                FACT_MATCHER)
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_has_changed_no_cache(self):
        self.profile_mgr._cache_exists = Mock(return_value=False)
        self.assertTrue(self.profile_mgr.has_changed())

    def test_has_changed_no_changes(self):
        cached_pkgs = [
                Package(name="package1", version="1.0.0", release=1, arch="x86_64"),
                Package(name="package2", version="2.0.0", release=2, arch="x86_64")
        ]
        temp_repo_dir = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, temp_repo_dir)
        repo_file_name = os.path.join(temp_repo_dir, 'awesome.repo')
        with open(repo_file_name, 'w') as repo_file:
            repo_file.write(CONTENT_REPO_FILE)
        cached_profile = self._mock_pkg_profile(cached_pkgs, repo_file_name, ENABLED_MODULES)

        self.profile_mgr._cache_exists = Mock(return_value=True)
        self.profile_mgr._read_cache = Mock(return_value=cached_profile)

        self.assertFalse(self.profile_mgr.has_changed())
        self.profile_mgr._read_cache.assert_called_with()

    def test_has_changed(self):
        cached_pkgs = [
                Package(name="package1", version="1.0.0", release=1, arch="x86_64"),
                Package(name="package3", version="3.0.0", release=3, arch="x86_64")
        ]
        cached_profile = self._mock_pkg_profile(cached_pkgs, "/non/existing/path/to/repo/file", [])

        self.profile_mgr._cache_exists = Mock(return_value=True)
        self.profile_mgr._read_cache = Mock(return_value=cached_profile)

        self.assertTrue(self.profile_mgr.has_changed())
        self.profile_mgr._read_cache.assert_called_with()

    def test_update_check_consumer_uuid_none(self):
        uuid = None
        uep = Mock()

        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        res = self.profile_mgr.update_check(uep, uuid)
        self.assertEqual(0, res)

    def test_package_json_handles_non_unicode(self):
        package = Package(name=b'\xf6', version=b'\xf6', release=b'\xf6', arch=b'\xf6', vendor=b'\xf6')
        data = package.to_dict()
        json_str = json.dumps(data)  # to json
        data = json.loads(json_str)  # and back to an object
        for attr in ['name', 'version', 'release', 'arch', 'vendor']:
            self.assertEqual(u'\ufffd', data[attr])

    def test_package_json_as_unicode_type(self):
        # note that the data type at time of writing is bytes, so this is just defensive coding
        package = Package(name=u'Björk', version=u'Björk', release=u'Björk', arch=u'Björk', vendor=u'Björk')
        data = package.to_dict()
        json_str = json.dumps(data)  # to json
        data = json.loads(json_str)  # and back to an object
        for attr in ['name', 'version', 'release', 'arch', 'vendor']:
            self.assertEqual(u'Björk', data[attr])

    def test_package_json_missing_attributes(self):
        package = Package(name=None, version=None, release=None, arch=None, vendor=None)
        data = package.to_dict()
        json_str = json.dumps(data)  # to json
        data = json.loads(json_str)  # and back to an object
        for attr in ['name', 'version', 'release', 'arch', 'vendor']:
            self.assertEqual(None, data[attr])

    def test_module_md_uniquify(self):
        modules_input = [
            {
                "name": "duck",
                "stream": 0,
                "version": "20180730233102",
                "context": "deadbeef",
                "arch": "noarch",
                "profiles": ["default"],
                "installed_profiles": [],
                "status": "enabled"
            },
            {
                "name": "duck",
                "stream": 0,
                "version": "20180707144203",
                "context": "c0ffee42",
                "arch": "noarch",
                "profiles": ["default", "server"],
                "installed_profiles": ["server"],
                "status": "unknown"
            }

        ]

        self.assertEqual(modules_input, ModulesProfile._uniquify(modules_input))
        # now test dup modules
        self.assertEqual(modules_input, ModulesProfile._uniquify(modules_input + [modules_input[0]]))

    @staticmethod
    def _mock_pkg_profile(packages, repo_file, enabled_modules):
        """
        Turn a list of package objects into an RPMProfile object.
        """

        dict_list = []
        for pkg in packages:
            dict_list.append(pkg.to_dict())

        mock_file = Mock()
        mock_file.read = Mock(return_value=json.dumps(dict_list))

        mock_rpm_profile = RPMProfile(from_file=mock_file)

        mock_enabled_repos_profile = EnabledReposProfile(repo_file=repo_file)

        mock_module_profile = ModulesProfile()
        mock_module_profile.collect = Mock(return_value=enabled_modules)

        mock_profile = {
            "rpm": mock_rpm_profile,
            "enabled_repos": mock_enabled_repos_profile,
            "modulemd": mock_module_profile
        }
        return mock_profile
Exemplo n.º 18
0
class TestProfileManager(unittest.TestCase):
    def setUp(self):
        current_pkgs = [
            Package(name="package1", version="1.0.0", release=1,
                    arch="x86_64"),
            Package(name="package2", version="2.0.0", release=2, arch="x86_64")
        ]
        self.current_profile = self._mock_pkg_profile(current_pkgs)
        self.profile_mgr = ProfileManager(current_profile=self.current_profile)

    def test_update_check_no_change(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.updatePackageProfile = Mock()

        self.profile_mgr.has_changed = Mock(return_value=False)
        self.profile_mgr.write_cache = Mock()
        self.profile_mgr.update_check(uep, uuid)

        self.assertEqual(0, uep.updatePackageProfile.call_count)
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_update_check_has_changed(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        uep.updatePackageProfile.assert_called_with(uuid, FACT_MATCHER)
        self.assertEqual(1, self.profile_mgr.write_cache.call_count)

    def test_update_check_packages_not_supported(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        uep.supports_resource = Mock(return_value=False)
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        self.assertEqual(0, uep.updatePackageProfile.call_count)
        uep.supports_resource.assert_called_with('packages')
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_update_check_packages_disabled(self):
        uuid = 'FAKEUUID'
        uep = Mock()
        self.profile_mgr._set_report_package_profile(0)
        uep.updatePackageProfile = Mock()
        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        self.profile_mgr.update_check(uep, uuid)

        self.assertEqual(0, uep.updatePackageProfile.call_count)
        uep.supports_resource.assert_called_with('packages')
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_update_check_error_uploading(self):
        uuid = 'FAKEUUID'
        uep = Mock()

        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()
        # Throw an exception when trying to upload:
        uep.updatePackageProfile = Mock(side_effect=Exception('BOOM!'))

        self.assertRaises(Exception, self.profile_mgr.update_check, uep, uuid)
        uep.updatePackageProfile.assert_called_with(uuid, FACT_MATCHER)
        self.assertEqual(0, self.profile_mgr.write_cache.call_count)

    def test_has_changed_no_cache(self):
        self.profile_mgr._cache_exists = Mock(return_value=False)
        self.assertTrue(self.profile_mgr.has_changed())

    def test_has_changed_no_changes(self):
        cached_pkgs = [
            Package(name="package1", version="1.0.0", release=1,
                    arch="x86_64"),
            Package(name="package2", version="2.0.0", release=2, arch="x86_64")
        ]
        cached_profile = self._mock_pkg_profile(cached_pkgs)

        self.profile_mgr._cache_exists = Mock(return_value=True)
        self.profile_mgr._read_cache = Mock(return_value=cached_profile)

        self.assertFalse(self.profile_mgr.has_changed())
        self.profile_mgr._read_cache.assert_called_with()

    def test_has_changed(self):
        cached_pkgs = [
            Package(name="package1", version="1.0.0", release=1,
                    arch="x86_64"),
            Package(name="package3", version="3.0.0", release=3, arch="x86_64")
        ]
        cached_profile = self._mock_pkg_profile(cached_pkgs)

        self.profile_mgr._cache_exists = Mock(return_value=True)
        self.profile_mgr._read_cache = Mock(return_value=cached_profile)

        self.assertTrue(self.profile_mgr.has_changed())
        self.profile_mgr._read_cache.assert_called_with()

    def test_update_check_consumer_uuid_none(self):
        uuid = None
        uep = Mock()

        self.profile_mgr.has_changed = Mock(return_value=True)
        self.profile_mgr.write_cache = Mock()

        res = self.profile_mgr.update_check(uep, uuid)
        self.assertEqual(0, res)

    @staticmethod
    def _mock_pkg_profile(packages):
        """
        Turn a list of package objects into an RPMProfile object.
        """

        dict_list = []
        for pkg in packages:
            dict_list.append(pkg.to_dict())

        mock_file = Mock()
        mock_file.read = Mock(return_value=json.dumps(dict_list))

        mock_profile = RPMProfile(from_file=mock_file)
        return mock_profile