def test_no_hybrid_image(monkeypatch, is_symlink, realpath_match, is_bios,
                         agent_installed, tmpdir):
    grubenv_efi = tmpdir.join('grubenv_efi')
    grubenv_efi.write('grubenv')
    grubenv_efi_false = tmpdir.join('grubenv_efi_false')
    grubenv_efi.write('nope')
    grubenv_boot = tmpdir.join('grubenv_boot')

    grubenv_target = grubenv_efi if realpath_match else grubenv_efi_false

    if is_symlink:
        grubenv_boot.mksymlinkto(grubenv_target)

    firmw = BIOS_FIRMWARE if is_bios else EFI_FIRMWARE
    inst_rpms = INSTALLED_AGENT if agent_installed else NOT_INSTALLED_AGENT

    monkeypatch.setattr(checkhybridimage, 'BIOS_PATH', grubenv_boot.strpath)
    monkeypatch.setattr(checkhybridimage, 'EFI_PATH', grubenv_efi.strpath)
    monkeypatch.setattr(reporting, 'create_report', create_report_mocked())
    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(arch='x86_64', msgs=[firmw, inst_rpms]))
    monkeypatch.setattr(api, "produce", produce_mocked())

    checkhybridimage.check_hybrid_image()
    assert not reporting.create_report.called
    assert not api.produce.called
def test_get_grub_device(monkeypatch):
    run_mocked = RunMocked()
    monkeypatch.setattr(library, 'run', run_mocked)
    monkeypatch.setattr(api, 'produce', testutils.produce_mocked())
    library.get_grub_device()
    assert library.run.called == 3
    assert BOOT_DEVICE == api.produce.model_instances[0].grub_device
def test_custom_repos(monkeypatch):
    """
    Tests whether the CustomRepos provided to the actor are propagated to the TargetRepositories after
    blacklist filtering is applied on them.
    """
    custom = CustomTargetRepository(
        repoid='rhel-8-server-rpms',
        name='RHEL 8 Server (RPMs)',
        baseurl='https://.../dist/rhel/server/8/os',
        enabled=True)

    blacklisted = CustomTargetRepository(
        repoid='rhel-8-blacklisted-rpms',
        name='RHEL 8 Blacklisted (RPMs)',
        baseurl='https://.../dist/rhel/blacklisted/8/os',
        enabled=True)

    repos_blacklisted = RepositoriesBlacklisted(
        repoids=['rhel-8-blacklisted-rpms'])

    repositories_mapping = RepositoriesMapping(mapping=[], repositories=[])

    msgs = [custom, blacklisted, repos_blacklisted, repositories_mapping]

    monkeypatch.setattr(api, 'current_actor', CurrentActorMocked(msgs=msgs))
    monkeypatch.setattr(api, 'produce', produce_mocked())

    setuptargetrepos.process()

    assert api.produce.called

    custom_repos = api.produce.model_instances[0].custom_repos
    assert len(custom_repos) == 1
    assert custom_repos[0].repoid == 'rhel-8-server-rpms'
def test_bz_1899455_crash_iface(monkeypatch, current_actor_context, adjust_cwd):
    """
    Cover situation when network device is discovered on the src sys but not
    inside the upgrade environment.

    This typically happens when the network device needs specific drivers which
    are not present inside the upgrade initramfs. Usually it points to a missing
    actors that should influence the upgrade initramfs in a way the drivers are
    installed. In this situation, only correct thing we can do in this actor
    is print warning / report that we couldn't located particular devices so
    we cannot handle interface names related to this devices.
    """
    with open(os.path.join(CUR_DIR, 'files/crashed_ifaces.json')) as fp:
        json_msgs = json.load(fp)
    msgs = [
        PersistentNetNamesFacts.create(json_msgs["PersistentNetNamesFacts"]),
        PersistentNetNamesFactsInitramfs.create(json_msgs["PersistentNetNamesFactsInitramfs"]),
    ]
    monkeypatch.setattr(persistentnetnamesconfig, 'generate_link_file', generate_link_file_mocked)
    monkeypatch.setattr(persistentnetnamesconfig.api, 'current_actor', CurrentActorMocked(msgs=msgs))
    monkeypatch.setattr(persistentnetnamesconfig.api, 'current_logger', logger_mocked())
    monkeypatch.setattr(persistentnetnamesconfig.api, 'produce', produce_mocked())
    persistentnetnamesconfig.process()

    for prod_models in [RenamedInterfaces, InitrdIncludes]:
        any(isinstance(i, prod_models) for i in persistentnetnamesconfig.api.produce.model_instances)
    assert any(['Some network devices' in x for x in persistentnetnamesconfig.api.current_logger.warnmsg])
Beispiel #5
0
def test_scan_boot_entries(monkeypatch):
    """Tests whether the library correctly identifies boot entries in the grubby output."""
    def run_mocked(cmd, **kwargs):
        if cmd == ['grubby', '--info', 'ALL']:
            return {'stdout': GRUBBY_INFO_ALL_STDOUT.split('\n')}
        raise ValueError('Tried to run unexpected command.')

    actor_produces = produce_mocked()

    # The library imports `run` all the way (from ... import run), therefore,
    # we must monkeypatch the reference directly in the actor's library namespace
    monkeypatch.setattr(sourcebootloaderscanner, 'run', run_mocked)
    monkeypatch.setattr(stdlib.api, 'produce', actor_produces)

    sourcebootloaderscanner.scan_source_boot_loader_configuration()

    fail_description = 'Only one SourceBootLoaderConfiguration message should be produced.'
    assert len(actor_produces.model_instances) == 1, fail_description

    bootloader_config = actor_produces.model_instances[0]

    fail_description = 'Found different number of boot entries than present in provided mocks.'
    assert len(bootloader_config.entries) == 2, fail_description

    expected_boot_entry_titles = ['Linux', 'Linux old-kernel']
    for actual_boot_entry in bootloader_config.entries:
        assert actual_boot_entry.title in expected_boot_entry_titles
def test_device_no_grub(monkeypatch):
    run_mocked = RunMocked(no_grub=True)
    monkeypatch.setattr(library, 'run', run_mocked)
    monkeypatch.setattr(api, 'produce', testutils.produce_mocked())
    library.get_grub_device()
    assert library.run.called == 3
    assert not api.produce.model_instances
def test_perform_ok(monkeypatch):
    repoids = ['repoidX', 'repoidY']
    monkeypatch.setattr(userspacegen, '_InputData', mocked_consume_data)
    monkeypatch.setattr(userspacegen, '_get_product_certificate_path',
                        lambda: _DEFAULT_CERT_PATH)
    monkeypatch.setattr(overlaygen, 'create_source_overlay',
                        MockedMountingBase)
    monkeypatch.setattr(userspacegen, '_gather_target_repositories',
                        lambda *x: repoids)
    monkeypatch.setattr(userspacegen, '_create_target_userspace',
                        lambda *x: None)
    monkeypatch.setattr(userspacegen.api, 'current_actor',
                        CurrentActorMocked())
    monkeypatch.setattr(userspacegen.api, 'produce', produce_mocked())
    monkeypatch.setattr(repofileutils, 'get_repodirs',
                        lambda: ['/etc/yum.repos.d'])
    userspacegen.perform()
    msg_target_repos = models.UsedTargetRepositories(
        repos=[models.UsedTargetRepository(repoid=repo) for repo in repoids])
    assert userspacegen.api.produce.called == 3
    assert isinstance(userspacegen.api.produce.model_instances[0],
                      models.TMPTargetRepositoriesFacts)
    assert userspacegen.api.produce.model_instances[1] == msg_target_repos
    # this one is full of contants, so it's safe to check just the instance
    assert isinstance(userspacegen.api.produce.model_instances[2],
                      models.TargetUserSpaceInfo)
def test_grub_device_env_var(monkeypatch):
    run_mocked = RunMocked()
    monkeypatch.setenv('LEAPP_GRUB_DEVICE', BOOT_DEVICE_ENV)
    monkeypatch.setattr(library, 'run', run_mocked)
    monkeypatch.setattr(api, 'produce', testutils.produce_mocked())
    library.get_grub_device()
    assert library.run.called == 0
    assert BOOT_DEVICE_ENV == api.produce.model_instances[0].grub_device
def test_get_grub_device_fail(monkeypatch):
    run_mocked = RunMocked(raise_err=True)
    monkeypatch.setattr(library, 'run', run_mocked)
    monkeypatch.setattr(api, 'produce', testutils.produce_mocked())
    with pytest.raises(StopActorExecution):
        library.get_grub_device()
    assert library.run.called == 1
    assert not api.produce.model_instances
def test_no_removed_vars(monkeypatch):
    envars = {'LEAPP_SKIP_RHSM': '1'}
    monkeypatch.setattr(api, 'current_actor',
                        CurrentActorMocked(envars=envars))
    monkeypatch.setattr(api.current_actor, "produce", produce_mocked())
    checkremovedenvvars.process()
    assert not api.current_actor.produce.called
    assert not api.current_actor.produce.model_instances
def test_scan_invalid_file_csv(monkeypatch, line):
    monkeypatch.setattr(api, 'current_actor',
                        CurrentActorMocked(architecture.ARCH_X86_64))
    monkeypatch.setattr(api, 'produce', produce_mocked())
    with pytest.raises(StopActorExecutionError) as err:
        library.scan_repositories(read_repofile_func=ReadRepoFileMock([line]))
    assert not api.produce.called
    assert 'The repository mapping file is invalid' in str(err)
def test_report_skipped_packages_no_verbose_mode(monkeypatch, caplog,
                                                 is_verbose_mode_on):
    """
    Tests whether the report_skipped_packages function creates message of the expected form
    and that the function respects whether leapp is running in verbose mode.
    """
    monkeypatch.setattr(api, 'produce', produce_mocked())
    monkeypatch.setattr(api, 'show_message', show_message_mocked())
    monkeypatch.setattr(reporting, 'create_report', create_report_mocked())
    monkeypatch.setenv('LEAPP_VERBOSE', '1')
    report_skipped_packages(title='Packages will not be installed',
                            message='packages will not be installed:',
                            package_repo_pairs=[
                                (('skipped01', None), 'bad_repo01'),
                                (('skipped02', ('module', 'stream')),
                                 'bad_repo02')
                            ])

    message = ('2 packages will not be installed:\n'
               '- skipped01 (repoid: bad_repo01)\n'
               '- skipped02 [module:stream] (repoid: bad_repo02)')
    assert message in caplog.messages
    assert reporting.create_report.called == 1
    assert reporting.create_report.report_fields[
        'title'] == 'Packages will not be installed'
    assert reporting.create_report.report_fields['summary'] == message

    leapp_verbose = '1' if is_verbose_mode_on else '0'

    monkeypatch.setenv('LEAPP_VERBOSE', leapp_verbose)
    # Reset reporting.create_report for next test part
    monkeypatch.setattr(reporting, 'create_report', create_report_mocked())
    report_skipped_packages(title='Packages will not be installed',
                            message='packages will not be installed:',
                            package_repo_pairs=[
                                (('skipped01', None), 'bad_repo01'),
                                (('skipped02', ('module', 'stream')),
                                 'bad_repo02')
                            ])

    # FIXME(pstodulk): this is obviously wrong. repoid is currently pesid.. so test
    # is incorrect, and code is incorrect. even the message is missleading.
    # this is going to be fixed in close future.
    message = ('2 packages will not be installed:\n'
               '- skipped01 (repoid: bad_repo01)\n'
               '- skipped02 [module:stream] (repoid: bad_repo02)')

    # Verbose level should only control whether show_message is called, report entry should be created
    # in both cases.
    if is_verbose_mode_on:
        assert message in caplog.messages
    else:
        assert api.show_message.called == 0

    assert reporting.create_report.called == 1
    assert reporting.create_report.report_fields[
        'title'] == 'Packages will not be installed'
    assert reporting.create_report.report_fields['summary'] == message
def test_no_repofile(monkeypatch):
    monkeypatch.setattr(os.path, 'isfile', lambda dummy: False)
    monkeypatch.setattr(api, 'produce', produce_mocked())
    monkeypatch.setattr(api, 'current_logger', LoggerMocked())
    scancustomrepofile.process()
    msg = "The {} file doesn't exist. Nothing to do.".format(
        scancustomrepofile.CUSTOM_REPO_PATH)
    assert api.current_logger.debugmsg == msg
    assert not api.produce.called
Beispiel #14
0
def test_with_low_memory(monkeypatch):
    with mock.patch(
            "__builtin__.open",
            mock.mock_open(read_data="MemTotal: 42 kB")) as mock_proc_meminfo:
        monkeypatch.setattr(api, 'produce', testutils.produce_mocked())
        library.process()
        mock_proc_meminfo.assert_called_once_with('/proc/meminfo')
        assert api.produce.called == 1
        assert MemoryInfo(mem_total=42) == api.produce.model_instances[0]
def test_repositoriesblacklist_not_empty(monkeypatch):
    name = 'test'
    monkeypatch.setattr(library, "_get_disabled_optional_repo", lambda: [name])
    monkeypatch.setattr(api, "produce", produce_mocked())

    library.process()
    assert api.produce.called == 1
    assert isinstance(api.produce.model_instances[0], RepositoriesBlacklisted)
    assert api.produce.model_instances[0].repoids[0] == name
Beispiel #16
0
def test_non_ibmz_arch(monkeypatch, isfile):
    monkeypatch.setattr(scandasd.architecture, 'matches_architecture',
                        lambda dummy: False)
    monkeypatch.setattr(scandasd.api, 'current_logger', logger_mocked())
    monkeypatch.setattr(scandasd.api, 'produce', produce_mocked())
    monkeypatch.setattr(os.path, 'isfile', lambda dummy: isfile)
    scandasd.process()
    assert not scandasd.api.current_logger.warnmsg
    assert not scandasd.api.produce.called
Beispiel #17
0
def test_get_grub_device(monkeypatch):
    run_mocked = RunMocked()
    monkeypatch.setattr(grubdevname, 'run', run_mocked)
    monkeypatch.setattr(api, 'produce', testutils.produce_mocked())
    monkeypatch.setattr(os, 'open', open_mocked)
    monkeypatch.setattr(os, 'read', read_mocked)
    monkeypatch.setattr(os, 'close', close_mocked)
    grubdevname.get_grub_device()
    assert grubdevname.run.called == 2
    assert BOOT_DEVICE == api.produce.model_instances[0].grub_device
def test_no_blacklist_produced_when_optional_repo_enabled(
        monkeypatch, repofacts_opts_disabled, repomap_opts_only):
    """
    Tests whether nothing is produced when an optional repository is enabled.

    Data are set up in such a fashion so that the determined blacklist would not be empty.
    """

    repofacts_opts_disabled.repositories[0].data[0].enabled = True

    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(msgs=[repofacts_opts_disabled, repomap_opts_only]))
    monkeypatch.setattr(api, "produce", produce_mocked())
    monkeypatch.setattr(reporting, "create_report", produce_mocked())

    repositoriesblacklist.process()

    assert not api.produce.called
def test_minimal_execution(monkeypatch):
    """
    Tests whether the actor does not fail if no messages except the RepositoriesMapping are provided.
    """
    msgs = [RepositoriesMapping(mapping=[], repositories=[])]

    monkeypatch.setattr(api, 'current_actor', CurrentActorMocked(msgs=msgs))
    monkeypatch.setattr(api, 'produce', produce_mocked())

    setuptargetrepos.process()
def test_enabledrepos(monkeypatch, envars, result):
    monkeypatch.setattr(api, 'produce', produce_mocked())
    monkeypatch.setattr(api, 'current_logger', LoggerMocked())
    monkeypatch.setattr(api, 'current_actor',
                        CurrentActorMocked(envars=envars))
    scanclienablerepo.process()
    assert api.current_logger.infomsg
    assert api.produce.called == len(result)
    for i in result:
        assert i in api.produce.model_instances
def test_scan_missing_or_empty_file(monkeypatch, isFile, err_summary):
    monkeypatch.setattr(api, 'current_actor',
                        CurrentActorMocked(architecture.ARCH_X86_64))
    monkeypatch.setattr(api, 'produce', produce_mocked())
    monkeypatch.setattr('os.path.isfile', lambda dummy: isFile)
    if isFile:
        monkeypatch.setattr('os.path.getsize', lambda dummy: 0)
    with pytest.raises(StopActorExecutionError) as err:
        library.scan_repositories()
    assert not api.produce.called
    assert err_summary in str(err)
def test_repositoriesblacklist_not_empty(monkeypatch, repofacts_opts_disabled,
                                         repomap_opts_only):
    """
    Tests whether a message containing correct packages from the determined blacklist is produced.
    """

    blacklisted_repoid = 'test'
    monkeypatch.setattr(repositoriesblacklist, "_get_repoids_to_exclude",
                        lambda dummy_mapping: {blacklisted_repoid})
    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(msgs=[repofacts_opts_disabled, repomap_opts_only]))
    monkeypatch.setattr(api, "produce", produce_mocked())
    monkeypatch.setattr(reporting, "create_report", produce_mocked())

    repositoriesblacklist.process()
    assert api.produce.called == 1
    assert isinstance(api.produce.model_instances[0], RepositoriesBlacklisted)
    assert api.produce.model_instances[0].repoids[0] == blacklisted_repoid
    assert reporting.create_report.called == 1
def test_blacklist_produced_when_optional_repo_disabled(
        monkeypatch, repofacts_opts_disabled, repomap_opts_only):
    """
    Tests whether a correct blacklist is generated when there is disabled optional repo on the system.
    """

    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(msgs=[repofacts_opts_disabled, repomap_opts_only]))
    monkeypatch.setattr(api, "produce", produce_mocked())
    monkeypatch.setattr(reporting, "create_report", produce_mocked())

    repositoriesblacklist.process()

    assert api.produce.model_instances, 'A blacklist should get generated.'

    expected_blacklisted_repoid = 'codeready-builder-for-rhel-8-x86_64-rpms'
    err_msg = 'Blacklist does not contain expected repoid.'
    assert expected_blacklisted_repoid in api.produce.model_instances[
        0].repoids, err_msg
def test_getting_interfaces(monkeypatch):
    monkeypatch.setattr(persistentnetnames, 'physical_interfaces',
                        provide_test_interfaces)
    monkeypatch.setattr(api, 'produce', produce_mocked())
    interface = next(persistentnetnames.interfaces())
    assert interface.name
    assert interface.devpath
    assert interface.driver
    assert interface.vendor
    assert interface.pci_info
    assert interface.mac
def test_removed_vars(monkeypatch):
    envars = {'LEAPP_GRUB_DEVICE': '/dev/sda'}
    monkeypatch.setattr(api, 'current_actor',
                        CurrentActorMocked(envars=envars))
    monkeypatch.setattr(api.current_actor, "produce", produce_mocked())
    checkremovedenvvars.process()
    assert api.current_actor.produce.called == 1
    assert 'LEAPP_GRUB_DEVICE' in api.current_actor.produce.model_instances[
        0].report['summary']
    assert 'inhibitor' in api.current_actor.produce.model_instances[0].report[
        'flags']
Beispiel #26
0
def test_get_grub_device_fail(monkeypatch):
    run_mocked = RunMocked(raise_err=True)
    monkeypatch.setattr(grubdevname, 'run', run_mocked)
    monkeypatch.setattr(api, 'produce', testutils.produce_mocked())
    monkeypatch.setattr(os, 'open', open_mocked)
    monkeypatch.setattr(os, 'read', read_mocked)
    monkeypatch.setattr(os, 'close', close_mocked)
    with pytest.raises(StopActorExecution):
        grubdevname.get_grub_device()
    assert grubdevname.run.called == 1
    assert not api.produce.model_instances
Beispiel #27
0
def test_scan_missing_or_empty_file(monkeypatch, isFile):
    monkeypatch.setattr(api, 'current_actor',
                        CurrentActorMocked(architecture.ARCH_X86_64))
    monkeypatch.setattr(api, 'produce', produce_mocked())
    monkeypatch.setattr('os.path.isfile', lambda dummy: False)
    monkeypatch.setattr(requests, 'get', get_mocked(200 if isFile else 404,
                                                    ''))

    with pytest.raises(StopActorExecutionError) as err:
        repositoriesmapping.scan_repositories()
    assert not api.produce.called
    assert 'invalid or could not be retrieved' in str(err)
Beispiel #28
0
def test_scan_repositories_with_empty_data(monkeypatch):
    """
    Tests whether the scanning process fails gracefully when empty json data received.
    """

    monkeypatch.setattr(api, 'current_actor',
                        CurrentActorMocked(src_ver='7.9', dst_ver='8.4'))
    monkeypatch.setattr(api, 'produce', produce_mocked())

    with pytest.raises(StopActorExecutionError) as empty_data_error:
        repositoriesmapping.scan_repositories(lambda dummy: {})
    assert 'the JSON is missing a required field' in str(empty_data_error)
def test_actor_schedule_relabelling(monkeypatch, mode):

    fact = create_selinuxfacts(static_mode=mode, enabled=True)

    monkeypatch.setattr(api, 'current_actor', CurrentActorMocked(msgs=[fact]))
    monkeypatch.setattr(api, 'produce', produce_mocked())
    monkeypatch.setattr(reporting, "create_report", create_report_mocked())

    checkselinux.process()

    assert api.produce.model_instances[0].set_relabel
    assert reporting.create_report.called
Beispiel #30
0
def test_scan_repositories_with_missing_data(monkeypatch):
    """
    Tests whether the scanning process fails gracefully when no data are read.
    """
    monkeypatch.setattr(api, 'current_actor',
                        CurrentActorMocked(src_ver='7.9', dst_ver='8.4'))
    monkeypatch.setattr(api, 'produce', produce_mocked())
    monkeypatch.setattr(repositoriesmapping, 'read_or_fetch', lambda dummy: '')

    with pytest.raises(StopActorExecutionError) as missing_data_error:
        repositoriesmapping.scan_repositories()
    assert 'does not contain a valid JSON object' in str(missing_data_error)