def test_get_expected_target_repoids_best_candidate_produced(monkeypatch):
    """
    Test for the RepoMapDataHandler.get_expected_target_repoids method.

    Verifies that the method is able to produce a correct map that maps target pesid to the best
    candidate pesid repository when there are two repositories with different priority channels
    belonging to the same pesid family enabled on the source system and both have target
    equivalents.
    """
    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(arch='x86_64', src_ver='7.9', dst_ver='8.4'))

    repositories_mapping = RepositoriesMapping(
        mapping=[RepoMapEntry(source='pesid1', target=['pesid2'])],
        repositories=[
            make_pesid_repo('pesid1', '7', 'pesid1-repoid-ga'),
            make_pesid_repo('pesid1', '7', 'pesid1-repoid-eus', channel='eus'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid-ga'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid-eus', channel='eus'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid-e4s', channel='e4s'),
        ])

    handler = RepoMapDataHandler(repositories_mapping)
    target_repoids = handler.get_expected_target_pesid_repos(
        ['pesid1-repoid-eus'])

    fail_description = (
        'The get_expected_target_repoids failed to map target pesid to a pesid repository'
        'with the highest priority channel.')
    assert {
        'pesid2': repositories_mapping.repositories[3]
    } == target_repoids, fail_description
def test_get_expected_target_repoids_fallback(monkeypatch):
    """
    Test for the RepoMapDataHandler.get_expected_target_repoids method.

    Verifies that the RepoMapDataHandler.get_expected_target_repoids method is able to produce a correct
    map that maps target pesid to the best candidate pesid repository when there is a repository
    on the source system that does not have exact match equivalent and some other with a fallback channel
    must be found.
    """
    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(arch='x86_64', src_ver='7.9', dst_ver='8.4'))

    repositories_mapping = RepositoriesMapping(
        mapping=[RepoMapEntry(source='pesid1', target=['pesid2'])],
        repositories=[
            make_pesid_repo('pesid1', '7', 'pesid1-repoid-eus', channel='eus'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid-ga'),
            make_pesid_repo('pesid1', '8', 'pesid2-repoid-e4s', channel='e4s'),
        ])

    fail_description = (
        'The get_expected_target_repoids failed to find repository with a failback channel '
        'since there were no exact target equivalents.')

    handler = RepoMapDataHandler(repositories_mapping)
    handler.set_default_channels(['ga'])
    target_repoids = handler.get_expected_target_pesid_repos(
        ['pesid1-repoid-eus'])

    assert {
        'pesid2': repositories_mapping.repositories[1]
    } == target_repoids, fail_description
def mapping_data_for_find_repository_equiv():
    repositories = [
        make_pesid_repo('pesid1', '7', 'pesid1-repoid'),
        make_pesid_repo('pesid1',
                        '7',
                        'pesid1-repoid',
                        channel='e4s',
                        rhui='aws'),
        make_pesid_repo('pesid2', '8', 'pesid2-repoid1'),
        make_pesid_repo('pesid2', '8', 'pesid2-repoid2-s390x', arch='s390x'),
        # This repository is a better candidate than the full match equivalent, but _find_repository_target_equivalent
        # should not take into account channel priorities
        make_pesid_repo('pesid2',
                        '8',
                        'pesid2-repoid2',
                        arch='x86_64',
                        channel='eus'),
        make_pesid_repo('pesid2', '8', 'pesid2-repoid3-srpm',
                        repo_type='srpm'),
        make_pesid_repo('pesid2', '8', 'pesid2-repoid4.1', rhui='aws'),
        make_pesid_repo('pesid2',
                        '8',
                        'pesid2-repoid4.2',
                        channel='eus',
                        rhui='aws'),
        make_pesid_repo('pesid3', '8', 'pesid3-repoid')
    ]
    return RepositoriesMapping(
        mapping=[RepoMapEntry(source='pesid1', target=['pesid2', 'pesid3'])],
        repositories=repositories)
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_get_expected_target_pesid_repos_unmapped_repository(monkeypatch):
    """
    Test for the RepoMapDataHandler.get_expected_target_repoids method.

    Verifies that the RepoMapDataHandler.get_expected_target_repoids method does not fail
    when there is a repository on the source system that is not mapped.
    """
    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(arch='x86_64', src_ver='7.9', dst_ver='8.4'))

    repositories_mapping = RepositoriesMapping(
        mapping=[RepoMapEntry(source='pesid1', target=['pesid2'])],
        repositories=[
            make_pesid_repo('pesid1', '7', 'pesid1-repoid-ga'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid-ga')
        ])

    fail_description = 'Failed to get_expected_target_repoids when one of the source repoids is unmapped.'
    handler = RepoMapDataHandler(repositories_mapping)
    target_repoids = handler.get_expected_target_pesid_repos(
        ['pesid1-repoid-ga', 'unmapped-repoid'])

    assert {
        'pesid2': repositories_mapping.repositories[1]
    } == target_repoids, fail_description
def test_find_repository_equivalent_with_priority_channel(monkeypatch):
    """
    Tests whether the _find_repository_target_equivalent correctly respects the chosen preferred channel.
    """
    envars = {'LEAPP_DEVEL_TARGET_PRODUCT_TYPE': 'eus'}

    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(arch='x86_64',
                           src_ver='7.9',
                           dst_ver='8.4',
                           envars=envars))
    repositories_mapping = RepositoriesMapping(
        mapping=[RepoMapEntry(source='pesid1', target=['pesid2'])],
        repositories=[
            make_pesid_repo('pesid1', '7', 'pesid1-repoid-ga'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid-ga', channel='ga'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid-eus', channel='eus'),
        ])

    handler = RepoMapDataHandler(repositories_mapping)
    handler.set_default_channels(['ga'])

    assert handler.prio_channel == 'eus'

    fail_description = '_find_repository_target_equivalent does not correcly respect preferred channel.'
    expected_target_equivalent = repositories_mapping.repositories[2]
    actual_target_equivalent = handler._find_repository_target_equivalent(
        repositories_mapping.repositories[0], 'pesid2')
    assert expected_target_equivalent == actual_target_equivalent, fail_description
def test_get_expected_target_repoids_simple(monkeypatch):
    """
    Test for the RepoMapDataHandler.get_expected_target_repoids method.

    Verifies that the method is able to produce a correct map that maps target pesid to the best
    candidate pesid repository when there is only one repoid enabled and the corresponding source
    pesid repository has exact match target equivalent.
    """
    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(arch='x86_64', src_ver='7.9', dst_ver='8.4'))

    repositories_mapping = RepositoriesMapping(
        mapping=[RepoMapEntry(source='pesid1', target=['pesid2'])],
        repositories=[
            make_pesid_repo('pesid1', '7', 'pesid1-repoid'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid')
        ])
    fail_description = 'Failed to get_expected_target_repoids with only one repository enabled on the source system.'
    handler = RepoMapDataHandler(repositories_mapping)
    target_repoids = handler.get_expected_target_pesid_repos(['pesid1-repoid'])

    assert {
        'pesid2': repositories_mapping.repositories[1]
    } == target_repoids, fail_description
def test_get_expected_target_pesid_repos_multiple_repositories(monkeypatch):
    """
    Test for the RepoMapDataHandler.get_expected_target_repoids method.

    Verifies that the RepoMapDataHandler.get_expected_target_repoids method is able to produce a correct
    map that maps target pesid to the best candidate pesid repository when one source pesid is mapped
    to multiple target pesids (every target pesid should have an entry in the returned map).
    """
    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(arch='x86_64', src_ver='7.9', dst_ver='8.4'))

    repositories_mapping = RepositoriesMapping(
        mapping=[RepoMapEntry(source='pesid1', target=['pesid2', 'pesid3'])],
        repositories=[
            make_pesid_repo('pesid1', '7', 'pesid1-repoid-ga'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid-ga'),
            make_pesid_repo('pesid3', '8', 'pesid3-repoid-ga')
        ])

    fail_description = 'Failed to get_expected_target_repoids when one source pesid is mapped to two target pesids.'
    handler = RepoMapDataHandler(repositories_mapping)
    target_repoids = handler.get_expected_target_pesid_repos(
        ['pesid1-repoid-ga'])

    assert {
        'pesid2': repositories_mapping.repositories[1],
        'pesid3': repositories_mapping.repositories[2]
    } == target_repoids, fail_description
def _setup_repomap_handler(src_repoids):
    repo_mappig_msg = next(api.consume(RepositoriesMapping),
                           RepositoriesMapping())
    repomap = setuptargetrepos_repomap.RepoMapDataHandler(repo_mappig_msg)
    # TODO(pstodulk): what about skip this completely and keep the default 'ga'..?
    default_channels = setuptargetrepos_repomap.get_default_repository_channels(
        repomap, src_repoids)
    repomap.set_default_channels(default_channels)
    return repomap
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_request_pesid_repo_not_mapped_by_default(monkeypatch, source_repoid, expected_target_repoid):
    """
    Tests whether a target repository that is not mapped by default (e.g. CRB)
    is requested to be enabled on the target system if it results from the relevant events.

    Note: Since the resulting target repository is not mapped by default from the enabled repositories,
          the data handler should fail to get expected repoids for the given pesid as it works with enabled
          repositories. Therefor, this test tests whether the fallback lookup with representative repository works.
    """

    repositories_mapping = RepositoriesMapping(
        mapping=[
            RepoMapEntry(source='rhel7-base', target=['rhel8-BaseOS', 'rhel8-AppStream']),
            RepoMapEntry(source='rhel7-optional', target=['rhel8-CRB']),
        ],
        repositories=[
            PESIDRepositoryEntry(pesid='rhel7-base', major_version='7', repoid='rhel7-base-repoid',
                                 arch='x86_64', repo_type='rpm', channel='ga', rhui=''),
            PESIDRepositoryEntry(pesid='rhel7-base', major_version='7', repoid='rhel7-base-repoid-eus',
                                 arch='x86_64', repo_type='rpm', channel='eus', rhui=''),
            PESIDRepositoryEntry(pesid='rhel7-optional', major_version='7', repoid='rhel7-optional-repoid',
                                 arch='x86_64', repo_type='rpm', channel='ga', rhui=''),
            PESIDRepositoryEntry(pesid='rhel8-BaseOS', major_version='8', repoid='rhel8-baseos-repoid',
                                 arch='x86_64', repo_type='rpm', channel='ga', rhui=''),
            PESIDRepositoryEntry(pesid='rhel8-BaseOS', major_version='8', repoid='rhel8-baseos-repoid-eus',
                                 arch='x86_64', repo_type='rpm', channel='eus', rhui=''),
            PESIDRepositoryEntry(pesid='rhel8-AppStream', major_version='8', repoid='rhel8-appstream-repoid',
                                 arch='x86_64', repo_type='rpm', channel='ga', rhui=''),
            PESIDRepositoryEntry(pesid='rhel8-CRB', major_version='8', repoid='rhel8-crb-repoid',
                                 arch='x86_64', repo_type='rpm', channel='ga', rhui=''),
            PESIDRepositoryEntry(pesid='rhel8-CRB', major_version='8', repoid='rhel8-crb-repoid-eus',
                                 arch='x86_64', repo_type='rpm', channel='eus', rhui=''),
        ])

    monkeypatch.setattr(peseventsscanner, '_get_enabled_repoids', lambda: {source_repoid})
    monkeypatch.setattr(api,
                        'current_actor',
                        CurrentActorMocked(msgs=[repositories_mapping], src_ver='7.9', dst_ver='8.4'))

    event = Event(1, Action.MOVED, {'test-pkg': 'rhel7-base'}, {'test-pkg': 'rhel8-CRB'},
                  (7, 9), (8, 0), [])
    installed_pkgs = {'test-pkg'}

    tasks = process_events([(8, 0)], [event], installed_pkgs)

    assert tasks[Task.KEEP] == {'test-pkg': expected_target_repoid}
def scan_repositories(read_repofile_func=_read_repofile):
    """
    Scan the repository mapping file and produce RepositoriesMap msg.

    See the description of the actor for more details.
    """
    # TODO: add filter based on the current arch
    # TODO: deprecate the product type and introduce the "channels" ?.. more or less
    # NOTE: product type is changed, now it's channel: eus,e4s,aus,tus,ga,beta

    if os.path.exists(os.path.join('/etc/leapp/files', OLD_REPOMAP_FILE)):
        # NOTE: what about creating the report (instead of warning)
        api.current_logger().warning(
            'The old repomap file /etc/leapp/files/repomap.csv is present.'
            ' The file has been replaced by the repomap.json file and it is'
            ' not used anymore.')

    json_data = read_repofile_func(REPOMAP_FILE)
    try:
        repomap_data = RepoMapData.load_from_dict(json_data)
        mapping = repomap_data.get_mappings(get_source_major_version(),
                                            get_target_major_version())

        valid_major_versions = [
            get_source_major_version(),
            get_target_major_version()
        ]
        api.produce(
            RepositoriesMapping(mapping=mapping,
                                repositories=repomap_data.get_repositories(
                                    valid_major_versions)))
    except ModelViolationError as err:
        err_message = (
            'The repository mapping file is invalid: '
            'the JSON does not match required schema (wrong field type/value): {}'
            .format(err))
        _inhibit_upgrade(err_message)
    except KeyError as err:
        _inhibit_upgrade(
            'The repository mapping file is invalid: the JSON is missing a required field: {}'
            .format(err))
    except ValueError as err:
        # The error should contain enough information, so we do not need to clarify it further
        _inhibit_upgrade(
            'The repository mapping file is invalid: {}'.format(err))
def test_get_repositories_mapping(monkeypatch):
    """
    Tests whether the actor is able to correctly determine the dictionary that maps the target PES ids
    determined from the event processing to the actual target repository ids.
    (tests for the _get_repositories_mapping).
    """

    make_pesid_repo = functools.partial(PESIDRepositoryEntry, arch='x86_64', repo_type='rpm', channel='ga', rhui='')
    repositories_mapping = RepositoriesMapping(
        mapping=[
            RepoMapEntry(source='rhel7-base', target=['rhel8-BaseOS', 'rhel8-AppStream']),
            RepoMapEntry(source='rhel7-optional', target=['rhel8-CRB']),
        ],
        repositories=[
            make_pesid_repo(pesid='rhel7-base', major_version='7', repoid='rhel7-base-repoid'),
            make_pesid_repo(pesid='rhel7-optional', major_version='7', repoid='rhel7-optional-repoid'),
            make_pesid_repo(pesid='rhel8-BaseOS', major_version='8', repoid='rhel8-baseos-repoid'),
            make_pesid_repo(pesid='rhel8-AppStream', major_version='8', repoid='rhel8-appstream-repoid'),
            make_pesid_repo(pesid='rhel8-CRB', major_version='8', repoid='rhel8-crb-repoid'),
            # Extra repositories to make sure the created map contains the correct repoids
            PESIDRepositoryEntry(pesid='rhel8-CRB', major_version='8', repoid='rhel8-crb-repoid-azure',
                                 arch='x86_64', repo_type='rpm', channel='ga', rhui='azure'),
            PESIDRepositoryEntry(pesid='rhel8-BaseOS', major_version='8', repoid='rhel8-baseos-repoid-eus',
                                 arch='x86_64', repo_type='rpm', channel='eus', rhui=''),
            PESIDRepositoryEntry(pesid='rhel8-BaseOS', major_version='8', repoid='rhel8-baseos-repoid-s390x',
                                 arch='s390x', repo_type='rpm', channel='ga', rhui=''),
        ])

    monkeypatch.setattr(peseventsscanner, '_get_enabled_repoids', lambda: {'rhel7-base-repoid'})
    monkeypatch.setattr(api,
                        'current_actor',
                        CurrentActorMocked(msgs=[repositories_mapping], src_ver='7.9', dst_ver='8.4'))

    target_pesids = {'rhel8-BaseOS', 'rhel8-AppStream', 'rhel8-CRB'}
    expected_pesid_to_target_repoids = {
        'rhel8-BaseOS': 'rhel8-baseos-repoid',
        'rhel8-AppStream': 'rhel8-appstream-repoid',
        'rhel8-CRB': 'rhel8-crb-repoid'
    }

    actual_pesid_to_target_repoids = peseventsscanner._get_repositories_mapping(target_pesids)

    fail_description = 'Actor failed to determine what repoid to enable for given target pesids.'
    assert actual_pesid_to_target_repoids == expected_pesid_to_target_repoids, fail_description
def repomap_data_for_pesid_repo_retrieval():
    # NOTE: do not change order or repositories; particular unit-tests tests
    # use specific repositories for the comparison, expecting them on the right
    # position in the list
    repomap_data = RepositoriesMapping(
        mapping=[
            RepoMapEntry(source='pesid1', target=['pesid3', 'pesid2']),
            RepoMapEntry(source='pesid4', target=['pesid4']),
        ],
        repositories=[
            make_pesid_repo('pesid1', '7', 'pesid1-repoid'),
            make_pesid_repo('pesid1', '7', 'pesid1-repoid-eus', channel='eus'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid'),
            make_pesid_repo('pesid3', '8', 'pesid3-repoid'),
            make_pesid_repo('pesid3', '8', 'pesid3-repoid-eus', channel='eus'),
            make_pesid_repo('pesid3', '8', 'pesid3-repoid-aws', rhui='aws'),
            make_pesid_repo('pesid4', '7', 'pesid4-repoid1'),
            make_pesid_repo('pesid4', '8', 'pesid4-repoid2'),
        ])
    return repomap_data
def test_repositories_setup_tasks(monkeypatch):
    """
    Tests whether the actor propagates repositories received via a RepositoriesSetupTasks message
    to the resulting TargetRepositories (and blacklist filtering is applied to them).
    """
    repositories_setup_tasks = RepositoriesSetupTasks(
        to_enable=['rhel-8-server-rpms', 'rhel-8-blacklisted-rpms'])
    repos_blacklisted = RepositoriesBlacklisted(
        repoids=['rhel-8-blacklisted-rpms'])
    repositories_mapping = RepositoriesMapping(mapping=[], repositories=[])
    msgs = [repositories_setup_tasks, repos_blacklisted, repositories_mapping]

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

    setuptargetrepos.process()

    assert api.produce.called

    rhel_repos = api.produce.model_instances[0].rhel_repos
    assert len(rhel_repos) == 1
    assert rhel_repos[0].repoid == 'rhel-8-server-rpms'
def test_get_expected_target_pesid_repos_repo_with_no_equivalent(
        monkeypatch, caplog):
    """
    Test for the RepoMapDataHandler.get_expected_target_repoids method.

    Verifies that the RepoMapDataHandler.get_expected_target_repoids method does not fail
    when there is a repository on the source system that does not have any equivalents.
    A warning should be produced when a situation like this occurs.
    """
    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(arch='x86_64', src_ver='7.9', dst_ver='8.4'))

    repositories_mapping = RepositoriesMapping(
        mapping=[RepoMapEntry(source='pesid1', target=['pesid2'])],
        repositories=[
            make_pesid_repo('pesid1', '7', 'pesid1-repoid-ga'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid-eus', channel='eus'),
        ])

    handler = RepoMapDataHandler(repositories_mapping)
    target_repoids = handler.get_expected_target_pesid_repos(
        ['pesid1-repoid-ga'])

    fail_description = (
        'Failed get_expected_target_repoids with a source repository that does not have any target equivalent.'
    )
    assert {'pesid2': None} == target_repoids, fail_description
    missing_target_equivalent_message = (
        'Cannot find any mapped target repository from the pesid2 family for the pesid1-repoid-ga repository.'
    )

    # A warning should be produced when a target equivalent was not found.
    warning_produced = False
    for record in caplog.records:
        if record.levelno == logging.WARNING and record.message == missing_target_equivalent_message:
            warning_produced = True
            break
    assert warning_produced, 'A warning should be produced when a repository has no equivalent.'
def test_get_default_repository_channels_no_default_pesid_repo(monkeypatch):
    """
    Test for the get_default_repository_channels function.

    Verifies that the returned list contains some fallback channel even if no repository from the default
    pesid family in which are the channels searched is enabled.
    """
    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(arch='x86_64', src_ver='7.9', dst_ver='8.4'))
    repository_mapping = RepositoriesMapping(
        mapping=[],
        repositories=[
            make_pesid_repo('rhel7-base', '7', 'rhel7-repoid-ga',
                            channel='ga'),
            make_pesid_repo('rhel7-base',
                            '7',
                            'rhel7-repoid-eus',
                            channel='eus'),
        ])
    handler = RepoMapDataHandler(repository_mapping)

    assert ['ga'] == get_default_repository_channels(handler, ['some-repoid'])
def test_get_default_repository_channels_simple(monkeypatch):
    """
    Test for the get_default_repository_channels function.

    Verifies that the function returns correct list of default channels on a source system
    where there is only one repository enabled from the pesid family in which are
    the default repositories searched in.
    """
    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(arch='x86_64', src_ver='7.9', dst_ver='8.4'))
    repository_mapping = RepositoriesMapping(mapping=[],
                                             repositories=[
                                                 make_pesid_repo(
                                                     'rhel7-base',
                                                     '7',
                                                     'rhel7-repoid-ga',
                                                     channel='ga')
                                             ])
    handler = RepoMapDataHandler(repository_mapping)

    assert ['ga'] == get_default_repository_channels(handler,
                                                     ['rhel7-repoid-ga'])
def test_get_expected_target_pesid_repos_with_priority_channel_set(
        monkeypatch):
    """
    Tests whether the get_expected_target_peid_repos correctly respects the chosen preferred channel.
    """

    envars = {'LEAPP_DEVEL_TARGET_PRODUCT_TYPE': 'eus'}

    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(arch='x86_64',
                           src_ver='7.9',
                           dst_ver='8.4',
                           envars=envars))

    repositories_mapping = RepositoriesMapping(
        mapping=[RepoMapEntry(source='pesid1', target=['pesid2', 'pesid3'])],
        repositories=[
            make_pesid_repo('pesid1', '7', 'pesid1-repoid-ga'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid-ga'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid-eus', channel='eus'),
            make_pesid_repo('pesid2', '8', 'pesid2-repoid-tuv', channel='tuv'),
            make_pesid_repo('pesid3', '8', 'pesid3-repoid-ga')
        ])

    handler = RepoMapDataHandler(repositories_mapping)
    # Set defaults to verify that the priority channel is not overwritten by defaults
    handler.set_default_channels(['tuv', 'ga'])
    target_repoids = handler.get_expected_target_pesid_repos(
        ['pesid1-repoid-ga'])

    fail_description = 'get_expected_target_peid_repos does not correcly respect preferred channel.'
    assert {
        'pesid2': repositories_mapping.repositories[2],
        'pesid3': repositories_mapping.repositories[4]
    } == target_repoids, fail_description
def test_get_default_repository_channels_highest_priority_channel(monkeypatch):
    """
    Test for the get_default_repository_channels function.

    Verifies that the returned list contains the highest priority channel if there is a repository
    with the channel enabled on the source system.
    """
    monkeypatch.setattr(
        api, 'current_actor',
        CurrentActorMocked(arch='x86_64', src_ver='7.9', dst_ver='8.4'))
    repository_mapping = RepositoriesMapping(
        mapping=[],
        repositories=[
            make_pesid_repo('rhel7-base', '7', 'rhel7-repoid-ga',
                            channel='ga'),
            make_pesid_repo('rhel7-base',
                            '7',
                            'rhel7-repoid-eus',
                            channel='eus'),
        ])
    handler = RepoMapDataHandler(repository_mapping)

    assert ['eus', 'ga'] == get_default_repository_channels(
        handler, ['rhel7-repoid-ga', 'rhel7-repoid-eus'])
def test_repos_mapping(monkeypatch):
    """
    Tests whether actor correctly determines what repositories should be enabled on target based
    on the information about what repositories are enabled on the source system using
    the RepositoriesMapping information.
    """
    repos_data = [
        RepositoryData(repoid='rhel-7-server-rpms', name='RHEL 7 Server'),
        RepositoryData(repoid='rhel-7-blacklisted-rpms',
                       name='RHEL 7 Blacklisted')
    ]

    repos_files = [
        RepositoryFile(file='/etc/yum.repos.d/redhat.repo', data=repos_data)
    ]
    facts = RepositoriesFacts(repositories=repos_files)

    repomap = RepositoriesMapping(
        mapping=[
            RepoMapEntry(
                source='rhel7-base',
                target=['rhel8-baseos', 'rhel8-appstream', 'rhel8-blacklist'])
        ],
        repositories=[
            PESIDRepositoryEntry(pesid='rhel7-base',
                                 repoid='rhel-7-server-rpms',
                                 major_version='7',
                                 arch='x86_64',
                                 repo_type='rpm',
                                 channel='ga',
                                 rhui=''),
            PESIDRepositoryEntry(pesid='rhel8-baseos',
                                 repoid='rhel-8-for-x86_64-baseos-htb-rpms',
                                 major_version='8',
                                 arch='x86_64',
                                 repo_type='rpm',
                                 channel='ga',
                                 rhui=''),
            PESIDRepositoryEntry(pesid='rhel8-appstream',
                                 repoid='rhel-8-for-x86_64-appstream-htb-rpms',
                                 major_version='8',
                                 arch='x86_64',
                                 repo_type='rpm',
                                 channel='ga',
                                 rhui=''),
            PESIDRepositoryEntry(pesid='rhel8-blacklist',
                                 repoid='rhel-8-blacklisted-rpms',
                                 major_version='8',
                                 arch='x86_64',
                                 repo_type='rpm',
                                 channel='ga',
                                 rhui=''),
        ])

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

    msgs = [facts, repomap, repos_blacklisted]

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

    setuptargetrepos.process()
    assert api.produce.called

    rhel_repos = api.produce.model_instances[0].rhel_repos
    assert len(rhel_repos) == 2

    produced_rhel_repoids = {repo.repoid for repo in rhel_repos}
    expected_rhel_repoids = {
        'rhel-8-for-x86_64-baseos-htb-rpms',
        'rhel-8-for-x86_64-appstream-htb-rpms'
    }
    assert produced_rhel_repoids == expected_rhel_repoids
def repomap_opts_only(rhel7_optional_pesidrepo, rhel8_crb_pesidrepo):
    return RepositoriesMapping(
        mapping=[RepoMapEntry(source='rhel7-optional', target=['rhel8-CRB'])],
        repositories=[rhel7_optional_pesidrepo, rhel8_crb_pesidrepo])