diff --git a/conf/dynaconf_hooks.py b/conf/dynaconf_hooks.py index 6d09d6e5bec..4249ce4e604 100644 --- a/conf/dynaconf_hooks.py +++ b/conf/dynaconf_hooks.py @@ -157,7 +157,7 @@ def get_dogfood_satclient_repos(settings): def get_ohsnap_repo_url(settings, repo, product=None, release=None, os_release=None, snap=''): - repourl = dogfood_repository( + return dogfood_repository( settings.ohsnap, repo=repo, product=product, @@ -165,4 +165,3 @@ def get_ohsnap_repo_url(settings, repo, product=None, release=None, os_release=N os_release=os_release, snap=snap, ).baseurl - return repourl diff --git a/pyproject.toml b/pyproject.toml index 4f5c8af613f..72a8e2b8f3a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,6 +27,8 @@ select = [ "I", # isort # "Q", # flake8-quotes "PT", # flake8-pytest + "RET", # flake8-return + "SIM", # flake8-simplify "UP", # pyupgrade "W", # pycodestyle ] diff --git a/pytest_fixtures/component/activationkey.py b/pytest_fixtures/component/activationkey.py index b0f7c77bd8a..982775670ae 100644 --- a/pytest_fixtures/component/activationkey.py +++ b/pytest_fixtures/component/activationkey.py @@ -8,41 +8,37 @@ @pytest.fixture(scope='module') def module_activation_key(module_sca_manifest_org, module_target_sat): """Create activation key using default CV and library environment.""" - activation_key = module_target_sat.api.ActivationKey( + return module_target_sat.api.ActivationKey( content_view=module_sca_manifest_org.default_content_view.id, environment=module_sca_manifest_org.library.id, organization=module_sca_manifest_org, ).create() - return activation_key @pytest.fixture(scope='module') def module_ak(module_lce, module_org, module_target_sat): - ak = module_target_sat.api.ActivationKey( + return module_target_sat.api.ActivationKey( environment=module_lce, organization=module_org, ).create() - return ak @pytest.fixture(scope='module') def module_ak_with_cv(module_lce, module_org, module_promoted_cv, module_target_sat): - ak = module_target_sat.api.ActivationKey( + return module_target_sat.api.ActivationKey( content_view=module_promoted_cv, environment=module_lce, organization=module_org, ).create() - return ak @pytest.fixture(scope='module') def module_ak_with_cv_repo(module_lce, module_org, module_cv_repo, module_target_sat): - ak = module_target_sat.api.ActivationKey( + return module_target_sat.api.ActivationKey( content_view=module_cv_repo, environment=module_lce, organization=module_org, ).create() - return ak @pytest.fixture(scope='module') @@ -55,7 +51,7 @@ def module_ak_with_synced_repo(module_org, module_target_sat): {'product-id': new_product['id'], 'content-type': 'yum'} ) Repository.synchronize({'id': new_repo['id']}) - ak = module_target_sat.cli_factory.make_activation_key( + return module_target_sat.cli_factory.make_activation_key( { 'lifecycle-environment': 'Library', 'content-view': 'Default Organization View', @@ -63,4 +59,3 @@ def module_ak_with_synced_repo(module_org, module_target_sat): 'auto-attach': False, } ) - return ak diff --git a/pytest_fixtures/component/architecture.py b/pytest_fixtures/component/architecture.py index 96d758f3d64..5ff90f3cb37 100644 --- a/pytest_fixtures/component/architecture.py +++ b/pytest_fixtures/component/architecture.py @@ -6,22 +6,20 @@ @pytest.fixture(scope='session') def default_architecture(session_target_sat): - arch = ( + return ( session_target_sat.api.Architecture() .search(query={'search': f'name="{DEFAULT_ARCHITECTURE}"'})[0] .read() ) - return arch @pytest.fixture(scope='session') def session_puppet_default_architecture(session_puppet_enabled_sat): - arch = ( + return ( session_puppet_enabled_sat.api.Architecture() .search(query={'search': f'name="{DEFAULT_ARCHITECTURE}"'})[0] .read() ) - return arch @pytest.fixture(scope='module') diff --git a/pytest_fixtures/component/contentview.py b/pytest_fixtures/component/contentview.py index c1879f43338..79d66014949 100644 --- a/pytest_fixtures/component/contentview.py +++ b/pytest_fixtures/component/contentview.py @@ -36,12 +36,11 @@ def module_ak_cv_lce(module_org, module_lce, module_published_cv, module_target_ content_view_version = module_published_cv.version[0] content_view_version.promote(data={'environment_ids': module_lce.id}) module_published_cv = module_published_cv.read() - module_ak_with_cv_lce = module_target_sat.api.ActivationKey( + return module_target_sat.api.ActivationKey( content_view=module_published_cv, environment=module_lce, organization=module_org, ).create() - return module_ak_with_cv_lce @pytest.fixture(scope='module') diff --git a/pytest_fixtures/component/os.py b/pytest_fixtures/component/os.py index e6039c1b6f9..0c94baa09ce 100644 --- a/pytest_fixtures/component/os.py +++ b/pytest_fixtures/component/os.py @@ -26,8 +26,7 @@ def default_os( os.ptable.append(default_partitiontable) os.provisioning_template.append(default_pxetemplate) os.update(['architecture', 'ptable', 'provisioning_template']) - os = entities.OperatingSystem(id=os.id).read() - return os + return entities.OperatingSystem(id=os.id).read() @pytest.fixture(scope='module') diff --git a/pytest_fixtures/component/provision_azure.py b/pytest_fixtures/component/provision_azure.py index 27bcea16e1f..7e2a05f0707 100644 --- a/pytest_fixtures/component/provision_azure.py +++ b/pytest_fixtures/component/provision_azure.py @@ -44,17 +44,16 @@ def sat_azure_default_os(sat_azure): @pytest.fixture(scope='module') def sat_azure_default_architecture(sat_azure): - arch = ( + return ( sat_azure.api.Architecture() .search(query={'search': f'name="{DEFAULT_ARCHITECTURE}"'})[0] .read() ) - return arch @pytest.fixture(scope='session') def azurerm_settings(): - deps = { + return { 'tenant': settings.azurerm.tenant_id, 'app_ident': settings.azurerm.client_id, 'sub_id': settings.azurerm.subscription_id, @@ -62,7 +61,6 @@ def azurerm_settings(): 'secret': settings.azurerm.client_secret, 'region': settings.azurerm.azure_region.lower().replace(' ', ''), } - return deps @pytest.fixture(scope='session') @@ -86,7 +84,7 @@ def azurermclient(azurerm_settings): @pytest.fixture(scope='module') def module_azurerm_cr(azurerm_settings, sat_azure_org, sat_azure_loc, sat_azure): """Create AzureRM Compute Resource""" - azure_cr = sat_azure.api.AzureRMComputeResource( + return sat_azure.api.AzureRMComputeResource( name=gen_string('alpha'), provider='AzureRm', tenant=azurerm_settings['tenant'], @@ -97,7 +95,6 @@ def module_azurerm_cr(azurerm_settings, sat_azure_org, sat_azure_loc, sat_azure) organization=[sat_azure_org], location=[sat_azure_loc], ).create() - return azure_cr @pytest.fixture(scope='module') @@ -108,7 +105,7 @@ def module_azurerm_finishimg( module_azurerm_cr, ): """Creates Finish Template image on AzureRM Compute Resource""" - finish_image = sat_azure.api.Image( + return sat_azure.api.Image( architecture=sat_azure_default_architecture, compute_resource=module_azurerm_cr, name=gen_string('alpha'), @@ -116,7 +113,6 @@ def module_azurerm_finishimg( username=settings.azurerm.username, uuid=AZURERM_RHEL7_FT_IMG_URN, ).create() - return finish_image @pytest.fixture(scope='module') @@ -127,7 +123,7 @@ def module_azurerm_byos_finishimg( sat_azure, ): """Creates BYOS Finish Template image on AzureRM Compute Resource""" - finish_image = sat_azure.api.Image( + return sat_azure.api.Image( architecture=sat_azure_default_architecture, compute_resource=module_azurerm_cr, name=gen_string('alpha'), @@ -135,7 +131,6 @@ def module_azurerm_byos_finishimg( username=settings.azurerm.username, uuid=AZURERM_RHEL7_FT_BYOS_IMG_URN, ).create() - return finish_image @pytest.fixture(scope='module') @@ -146,7 +141,7 @@ def module_azurerm_cloudimg( module_azurerm_cr, ): """Creates cloudinit image on AzureRM Compute Resource""" - finish_image = sat_azure.api.Image( + return sat_azure.api.Image( architecture=sat_azure_default_architecture, compute_resource=module_azurerm_cr, name=gen_string('alpha'), @@ -155,7 +150,6 @@ def module_azurerm_cloudimg( uuid=AZURERM_RHEL7_UD_IMG_URN, user_data=True, ).create() - return finish_image @pytest.fixture(scope='module') @@ -166,7 +160,7 @@ def module_azurerm_gallery_finishimg( module_azurerm_cr, ): """Creates Shared Gallery Finish Template image on AzureRM Compute Resource""" - finish_image = sat_azure.api.Image( + return sat_azure.api.Image( architecture=sat_azure_default_architecture, compute_resource=module_azurerm_cr, name=gen_string('alpha'), @@ -174,7 +168,6 @@ def module_azurerm_gallery_finishimg( username=settings.azurerm.username, uuid=AZURERM_RHEL7_FT_GALLERY_IMG_URN, ).create() - return finish_image @pytest.fixture(scope='module') @@ -185,7 +178,7 @@ def module_azurerm_custom_finishimg( module_azurerm_cr, ): """Creates Custom Finish Template image on AzureRM Compute Resource""" - finish_image = sat_azure.api.Image( + return sat_azure.api.Image( architecture=sat_azure_default_architecture, compute_resource=module_azurerm_cr, name=gen_string('alpha'), @@ -193,4 +186,3 @@ def module_azurerm_custom_finishimg( username=settings.azurerm.username, uuid=AZURERM_RHEL7_FT_CUSTOM_IMG_URN, ).create() - return finish_image diff --git a/pytest_fixtures/component/provision_capsule_pxe.py b/pytest_fixtures/component/provision_capsule_pxe.py index 04a2c4fb475..4360ba6e4bd 100644 --- a/pytest_fixtures/component/provision_capsule_pxe.py +++ b/pytest_fixtures/component/provision_capsule_pxe.py @@ -209,7 +209,7 @@ def capsule_provisioning_rhel_content( releasever=constants.REPOS['kickstart'][name]['version'], ) # do not sync content repos for discovery based provisioning. - if not capsule_provisioning_sat.provisioning_type == 'discovery': + if capsule_provisioning_sat.provisioning_type != 'discovery': rh_repo_id = sat.api_factory.enable_rhrepo_and_fetchid( basearch=constants.DEFAULT_ARCHITECTURE, org_id=module_sca_manifest_org.id, diff --git a/pytest_fixtures/component/provision_gce.py b/pytest_fixtures/component/provision_gce.py index 4c11ecb0918..64b706d772e 100644 --- a/pytest_fixtures/component/provision_gce.py +++ b/pytest_fixtures/component/provision_gce.py @@ -53,12 +53,11 @@ def sat_gce_default_partition_table(sat_gce): @pytest.fixture(scope='module') def sat_gce_default_architecture(sat_gce): - arch = ( + return ( sat_gce.api.Architecture() .search(query={'search': f'name="{DEFAULT_ARCHITECTURE}"'})[0] .read() ) - return arch @pytest.fixture(scope='session') @@ -96,8 +95,7 @@ def gce_latest_rhel_uuid(googleclient): filter_expr=f'name:{GCE_TARGET_RHEL_IMAGE_NAME}*', ) latest_template_name = max(tpl.name for tpl in templates) - latest_template_uuid = next(tpl for tpl in templates if tpl.name == latest_template_name).uuid - return latest_template_uuid + return next(tpl for tpl in templates if tpl.name == latest_template_name).uuid @pytest.fixture(scope='session') @@ -116,7 +114,7 @@ def session_default_os(session_target_sat): @pytest.fixture(scope='module') def module_gce_compute(sat_gce, sat_gce_org, sat_gce_loc, gce_cert): - gce_cr = sat_gce.api.GCEComputeResource( + return sat_gce.api.GCEComputeResource( name=gen_string('alphanumeric'), provider='GCE', key_path=settings.gce.cert_path, @@ -124,7 +122,6 @@ def module_gce_compute(sat_gce, sat_gce_org, sat_gce_loc, gce_cert): organization=[sat_gce_org], location=[sat_gce_loc], ).create() - return gce_cr @pytest.fixture(scope='module') @@ -206,7 +203,7 @@ def gce_hostgroup( googleclient, ): """Sets Hostgroup for GCE Host Provisioning""" - hgroup = sat_gce.api.HostGroup( + return sat_gce.api.HostGroup( architecture=sat_gce_default_architecture, compute_resource=module_gce_compute, domain=sat_gce_domain, @@ -216,7 +213,6 @@ def gce_hostgroup( organization=[sat_gce_org], ptable=sat_gce_default_partition_table, ).create() - return hgroup @pytest.fixture(scope='module') @@ -250,7 +246,7 @@ def module_gce_cloudimg( sat_gce, ): """Creates cloudinit image on GCE Compute Resource""" - cloud_image = sat_gce.api.Image( + return sat_gce.api.Image( architecture=sat_gce_default_architecture, compute_resource=module_gce_compute, name=gen_string('alpha'), @@ -259,7 +255,6 @@ def module_gce_cloudimg( uuid=gce_custom_cloudinit_uuid, user_data=True, ).create() - return cloud_image @pytest.fixture(scope='module') @@ -271,7 +266,7 @@ def module_gce_finishimg( sat_gce, ): """Creates finish image on GCE Compute Resource""" - finish_image = sat_gce.api.Image( + return sat_gce.api.Image( architecture=sat_gce_default_architecture, compute_resource=module_gce_compute, name=gen_string('alpha'), @@ -279,7 +274,6 @@ def module_gce_finishimg( username=gen_string('alpha'), uuid=gce_latest_rhel_uuid, ).create() - return finish_image @pytest.fixture diff --git a/pytest_fixtures/component/provision_pxe.py b/pytest_fixtures/component/provision_pxe.py index 2fc375bc5f1..beef717d94d 100644 --- a/pytest_fixtures/component/provision_pxe.py +++ b/pytest_fixtures/component/provision_pxe.py @@ -70,7 +70,7 @@ def module_provisioning_rhel_content( releasever=constants.REPOS['kickstart'][name]['version'], ) # do not sync content repos for discovery based provisioning. - if not module_provisioning_sat.provisioning_type == 'discovery': + if module_provisioning_sat.provisioning_type != 'discovery': rh_repo_id = sat.api_factory.enable_rhrepo_and_fetchid( basearch=constants.DEFAULT_ARCHITECTURE, org_id=module_sca_manifest_org.id, diff --git a/pytest_fixtures/component/provision_vmware.py b/pytest_fixtures/component/provision_vmware.py index 507f180a158..385f49bae38 100644 --- a/pytest_fixtures/component/provision_vmware.py +++ b/pytest_fixtures/component/provision_vmware.py @@ -15,7 +15,7 @@ def vmware(request): @pytest.fixture(scope='module') def module_vmware_cr(module_provisioning_sat, module_sca_manifest_org, module_location, vmware): - vmware_cr = module_provisioning_sat.sat.api.VMWareComputeResource( + return module_provisioning_sat.sat.api.VMWareComputeResource( name=gen_string('alpha'), provider='Vmware', url=vmware.hostname, @@ -25,7 +25,6 @@ def module_vmware_cr(module_provisioning_sat, module_sca_manifest_org, module_lo organization=[module_sca_manifest_org], location=[module_location], ).create() - return vmware_cr @pytest.fixture diff --git a/pytest_fixtures/component/provisioning_template.py b/pytest_fixtures/component/provisioning_template.py index 97439a8a07a..294edcbb22e 100644 --- a/pytest_fixtures/component/provisioning_template.py +++ b/pytest_fixtures/component/provisioning_template.py @@ -17,8 +17,7 @@ def module_provisioningtemplate_default(module_org, module_location): provisioning_template.organization.append(module_org) provisioning_template.location.append(module_location) provisioning_template.update(['organization', 'location']) - provisioning_template = entities.ProvisioningTemplate(id=provisioning_template.id).read() - return provisioning_template + return entities.ProvisioningTemplate(id=provisioning_template.id).read() @pytest.fixture(scope='module') @@ -30,8 +29,7 @@ def module_provisioningtemplate_pxe(module_org, module_location): pxe_template.organization.append(module_org) pxe_template.location.append(module_location) pxe_template.update(['organization', 'location']) - pxe_template = entities.ProvisioningTemplate(id=pxe_template.id).read() - return pxe_template + return entities.ProvisioningTemplate(id=pxe_template.id).read() @pytest.fixture(scope='session') @@ -39,6 +37,7 @@ def default_partitiontable(): ptables = entities.PartitionTable().search(query={'search': f'name="{DEFAULT_PTABLE}"'}) if ptables: return ptables[0].read() + return None @pytest.fixture(scope='module') diff --git a/pytest_fixtures/component/puppet.py b/pytest_fixtures/component/puppet.py index 38cad7163c0..c531c7888ac 100644 --- a/pytest_fixtures/component/puppet.py +++ b/pytest_fixtures/component/puppet.py @@ -44,6 +44,7 @@ def default_puppet_environment(module_puppet_org, session_puppet_enabled_sat): ) if environments: return environments[0].read() + return None @pytest.fixture(scope='module') @@ -101,10 +102,7 @@ def module_puppet_classes( @pytest.fixture(scope='session', params=[True, False], ids=["puppet_enabled", "puppet_disabled"]) def parametrized_puppet_sat(request, session_target_sat, session_puppet_enabled_sat): - if request.param: - sat = session_puppet_enabled_sat - else: - sat = session_target_sat + sat = session_puppet_enabled_sat if request.param else session_target_sat return {'sat': sat, 'enabled': request.param} diff --git a/pytest_fixtures/component/repository.py b/pytest_fixtures/component/repository.py index f287b35898f..15614433f9f 100644 --- a/pytest_fixtures/component/repository.py +++ b/pytest_fixtures/component/repository.py @@ -68,8 +68,7 @@ def repo_setup(): product = entities.Product(organization=org).create() repo = entities.Repository(name=repo_name, product=product).create() lce = entities.LifecycleEnvironment(organization=org).create() - details = {'org': org, 'product': product, 'repo': repo, 'lce': lce} - return details + return {'org': org, 'product': product, 'repo': repo, 'lce': lce} @pytest.fixture(scope='module') @@ -190,7 +189,7 @@ def repos_collection(request, target_sat): """ repos = getattr(request, 'param', []) repo_distro, repos = _simplify_repos(request, repos) - _repos_collection = target_sat.cli_factory.RepositoryCollection( + return target_sat.cli_factory.RepositoryCollection( distro=repo_distro or request.getfixturevalue('distro'), repositories=[ getattr(target_sat.cli_factory, repo_name)(**repo_params) @@ -198,7 +197,6 @@ def repos_collection(request, target_sat): for repo_name, repo_params in repo.items() ], ) - return _repos_collection @pytest.fixture(scope='module') diff --git a/pytest_fixtures/component/rh_cloud.py b/pytest_fixtures/component/rh_cloud.py index ead92f68db2..fd035f653c3 100644 --- a/pytest_fixtures/component/rh_cloud.py +++ b/pytest_fixtures/component/rh_cloud.py @@ -15,7 +15,7 @@ def rhcloud_manifest_org(module_target_sat, module_extra_rhel_entitlement_manife def rhcloud_activation_key(module_target_sat, rhcloud_manifest_org): """A module-level fixture to create an Activation key in module_org""" purpose_addons = "test-addon1, test-addon2" - ak = module_target_sat.api.ActivationKey( + return module_target_sat.api.ActivationKey( content_view=rhcloud_manifest_org.default_content_view, organization=rhcloud_manifest_org, environment=module_target_sat.api.LifecycleEnvironment(id=rhcloud_manifest_org.library.id), @@ -25,7 +25,6 @@ def rhcloud_activation_key(module_target_sat, rhcloud_manifest_org): purpose_role='test-role', auto_attach=False, ).create() - return ak @pytest.fixture(scope='module') diff --git a/pytest_fixtures/component/satellite_auth.py b/pytest_fixtures/component/satellite_auth.py index 4eb984390f6..c6df8df1897 100644 --- a/pytest_fixtures/component/satellite_auth.py +++ b/pytest_fixtures/component/satellite_auth.py @@ -271,11 +271,12 @@ def auth_data(request, ad_data, ipa_data): ad_data['attr_login'] = LDAP_ATTR['login_ad'] ad_data['auth_type'] = auth_type return ad_data - elif auth_type == 'ipa': + if auth_type == 'ipa': ipa_data['server_type'] = LDAP_SERVER_TYPE['UI']['ipa'] ipa_data['attr_login'] = LDAP_ATTR['login'] ipa_data['auth_type'] = auth_type return ipa_data + return None @pytest.fixture(scope='module') diff --git a/pytest_fixtures/component/user.py b/pytest_fixtures/component/user.py index 3f4d1034e6e..a1b9b7a1a9f 100644 --- a/pytest_fixtures/component/user.py +++ b/pytest_fixtures/component/user.py @@ -9,5 +9,4 @@ def user_not_exists(request): if users: users[0].delete() return True - else: - return False + return False diff --git a/pytest_fixtures/core/broker.py b/pytest_fixtures/core/broker.py index 9d207fcd9d7..f3356dbbef5 100644 --- a/pytest_fixtures/core/broker.py +++ b/pytest_fixtures/core/broker.py @@ -16,6 +16,7 @@ def _default_sat(align_to_satellite): return Satellite.get_host_by_hostname(settings.server.hostname) except ContentHostError: return Satellite() + return None @contextmanager diff --git a/pytest_fixtures/core/reporting.py b/pytest_fixtures/core/reporting.py index baf9d3cde7d..c89c87d46da 100644 --- a/pytest_fixtures/core/reporting.py +++ b/pytest_fixtures/core/reporting.py @@ -35,13 +35,14 @@ def pytest_sessionstart(session): remove if resolved and set autouse=True for record_testsuite_timestamp_xml fixture """ - if get_xdist_worker_id(session) == 'master': - if session.config.pluginmanager.hasplugin('junitxml'): - xml = session.config._store.get(xml_key, None) - if xml: - xml.add_global_property( - 'start_time', datetime.datetime.utcnow().strftime(FMT_XUNIT_TIME) - ) + if get_xdist_worker_id(session) == 'master' and session.config.pluginmanager.hasplugin( + 'junitxml' + ): + xml = session.config._store.get(xml_key, None) + if xml: + xml.add_global_property( + 'start_time', datetime.datetime.utcnow().strftime(FMT_XUNIT_TIME) + ) @pytest.fixture(autouse=False, scope='session') diff --git a/pytest_fixtures/core/ui.py b/pytest_fixtures/core/ui.py index c266e363c7e..1c24d6f04a9 100644 --- a/pytest_fixtures/core/ui.py +++ b/pytest_fixtures/core/ui.py @@ -102,7 +102,8 @@ def ui_session_record_property(request, record_property): test_file_path = request.node.fspath.strpath if any(directory in test_file_path for directory in test_directories): for fixture in request.node.fixturenames: - if request.fixturename != fixture: - if isinstance(request.getfixturevalue(fixture), Satellite): - sat = request.getfixturevalue(fixture) - sat.record_property = record_property + if request.fixturename != fixture and isinstance( + request.getfixturevalue(fixture), Satellite + ): + sat = request.getfixturevalue(fixture) + sat.record_property = record_property diff --git a/pytest_fixtures/core/upgrade.py b/pytest_fixtures/core/upgrade.py index caf4532713b..5726f9f80a9 100644 --- a/pytest_fixtures/core/upgrade.py +++ b/pytest_fixtures/core/upgrade.py @@ -10,12 +10,11 @@ def dependent_scenario_name(request): """ This fixture is used to collect the dependent test case name. """ - depend_test_name = [ + return [ mark.kwargs['depend_on'].__name__ for mark in request.node.own_markers if 'depend_on' in mark.kwargs ][0] - return depend_test_name @pytest.fixture(scope="session") diff --git a/pytest_plugins/fixture_markers.py b/pytest_plugins/fixture_markers.py index 951be635ac6..f1e87d3b7f7 100644 --- a/pytest_plugins/fixture_markers.py +++ b/pytest_plugins/fixture_markers.py @@ -17,7 +17,7 @@ def pytest_generate_tests(metafunc): content_host_fixture = ''.join([i for i in TARGET_FIXTURES if i in metafunc.fixturenames]) if content_host_fixture in metafunc.fixturenames: function_marks = getattr(metafunc.function, 'pytestmark', []) - no_containers = any('no_containers' == mark.name for mark in function_marks) + no_containers = any(mark.name == 'no_containers' for mark in function_marks) # process eventual rhel_version_list markers matchers = [i.args for i in function_marks if i.name == 'rhel_ver_list'] list_params = [] @@ -87,6 +87,7 @@ def chost_rhelver(params): for param in params: if 'contenthost' in param: return params[param].get('rhel_version') + return None content_host_fixture_names = [m[0] for m in getmembers(contenthosts, isfunction)] for item in items: diff --git a/pytest_plugins/logging_hooks.py b/pytest_plugins/logging_hooks.py index 9cd7ea4c84f..c15136a647a 100644 --- a/pytest_plugins/logging_hooks.py +++ b/pytest_plugins/logging_hooks.py @@ -1,3 +1,4 @@ +import contextlib import logging import logzero @@ -13,10 +14,8 @@ robottelo_log_file, ) -try: +with contextlib.suppress(ImportError): from pytest_reportportal import RPLogger, RPLogHandler -except ImportError: - pass @pytest.fixture(autouse=True, scope='session') @@ -37,37 +36,36 @@ def configure_logging(request, worker_id): if use_rp_logger: logging.setLoggerClass(RPLogger) - if is_xdist_worker(request): - if f'{worker_id}' not in [h.get_name() for h in logger.handlers]: - # Track the core logger's file handler level, set it in case core logger wasn't set - worker_log_level = 'INFO' - handlers_to_remove = [ - h - for h in logger.handlers - if isinstance(h, logging.FileHandler) - and getattr(h, 'baseFilename', None) == str(robottelo_log_file) - ] - for handler in handlers_to_remove: - logger.removeHandler(handler) - worker_log_level = handler.level - worker_handler = logging.FileHandler( - robottelo_log_dir.joinpath(f'robottelo_{worker_id}.log') - ) - worker_handler.set_name(f'{worker_id}') - worker_handler.setFormatter(worker_formatter) - worker_handler.setLevel(worker_log_level) - logger.addHandler(worker_handler) - broker_log_setup( - level=logging_yaml.broker.level, - file_level=logging_yaml.broker.fileLevel, - formatter=worker_formatter, - path=robottelo_log_dir.joinpath(f'robottelo_{worker_id}.log'), - ) + if is_xdist_worker(request) and f'{worker_id}' not in [h.get_name() for h in logger.handlers]: + # Track the core logger's file handler level, set it in case core logger wasn't set + worker_log_level = 'INFO' + handlers_to_remove = [ + h + for h in logger.handlers + if isinstance(h, logging.FileHandler) + and getattr(h, 'baseFilename', None) == str(robottelo_log_file) + ] + for handler in handlers_to_remove: + logger.removeHandler(handler) + worker_log_level = handler.level + worker_handler = logging.FileHandler( + robottelo_log_dir.joinpath(f'robottelo_{worker_id}.log') + ) + worker_handler.set_name(f'{worker_id}') + worker_handler.setFormatter(worker_formatter) + worker_handler.setLevel(worker_log_level) + logger.addHandler(worker_handler) + broker_log_setup( + level=logging_yaml.broker.level, + file_level=logging_yaml.broker.fileLevel, + formatter=worker_formatter, + path=robottelo_log_dir.joinpath(f'robottelo_{worker_id}.log'), + ) - if use_rp_logger: - rp_handler = RPLogHandler(request.node.config.py_test_service) - rp_handler.setFormatter(worker_formatter) - # logger.addHandler(rp_handler) + if use_rp_logger: + rp_handler = RPLogHandler(request.node.config.py_test_service) + rp_handler.setFormatter(worker_formatter) + # logger.addHandler(rp_handler) def pytest_runtest_logstart(nodeid, location): diff --git a/pytest_plugins/rerun_rp/rerun_rp.py b/pytest_plugins/rerun_rp/rerun_rp.py index 5b14873a885..7007880ce4b 100644 --- a/pytest_plugins/rerun_rp/rerun_rp.py +++ b/pytest_plugins/rerun_rp/rerun_rp.py @@ -123,7 +123,7 @@ def pytest_collection_modifyitems(items, config): test_args['status'].append('SKIPPED') if fail_args: test_args['status'].append('FAILED') - if not fail_args == 'all': + if fail_args != 'all': defect_types = fail_args.split(',') allowed_args = [*rp.defect_types.keys()] if not set(defect_types).issubset(set(allowed_args)): diff --git a/pytest_plugins/sanity_plugin.py b/pytest_plugins/sanity_plugin.py index f955d9cf4ca..1d93a4b45f3 100644 --- a/pytest_plugins/sanity_plugin.py +++ b/pytest_plugins/sanity_plugin.py @@ -43,10 +43,12 @@ def pytest_collection_modifyitems(session, items, config): deselected.append(item) continue # Remove parametrization from organization test - if 'test_positive_create_with_name_and_description' in item.name: - if 'alphanumeric' not in item.name: - deselected.append(item) - continue + if ( + 'test_positive_create_with_name_and_description' in item.name + and 'alphanumeric' not in item.name + ): + deselected.append(item) + continue # Else select selected.append(item) diff --git a/pytest_plugins/settings_skip.py b/pytest_plugins/settings_skip.py index 6ee053adee5..e345338d5d8 100644 --- a/pytest_plugins/settings_skip.py +++ b/pytest_plugins/settings_skip.py @@ -22,7 +22,7 @@ def pytest_runtest_setup(item): skip_marker = item.get_closest_marker('skip_if_not_set', None) if skip_marker and skip_marker.args: options_set = {arg.upper() for arg in skip_marker.args} - settings_set = {key for key in settings.keys() if not key.endswith('_FOR_DYNACONF')} + settings_set = {key for key in settings if not key.endswith('_FOR_DYNACONF')} if not options_set.issubset(settings_set): invalid = options_set.difference(settings_set) raise ValueError( diff --git a/pytest_plugins/upgrade/scenario_workers.py b/pytest_plugins/upgrade/scenario_workers.py index 099ff1c0fe3..9deeb0ddf25 100644 --- a/pytest_plugins/upgrade/scenario_workers.py +++ b/pytest_plugins/upgrade/scenario_workers.py @@ -23,6 +23,7 @@ def save_worker_hostname(test_name, target_sat): def shared_workers(): if json_file.exists(): return json.loads(json_file.read_text()) + return None def get_worker_hostname_from_testname(test_name, shared_workers): diff --git a/pytest_plugins/video_cleanup.py b/pytest_plugins/video_cleanup.py index 08bbf5721d9..320864b7060 100644 --- a/pytest_plugins/video_cleanup.py +++ b/pytest_plugins/video_cleanup.py @@ -64,15 +64,14 @@ def pytest_runtest_makereport(item): 'longrepr': str(report.longrepr), } ) - if report.when == "teardown": - if item.nodeid in test_results: - result_info = test_results[item.nodeid] - if result_info.outcome == 'passed': - report.user_properties = [ - (key, value) for key, value in report.user_properties if key != 'video_url' - ] - session_id_tuple = next( - (t for t in report.user_properties if t[0] == 'session_id'), None - ) - session_id = session_id_tuple[1] if session_id_tuple else None - _clean_video(session_id, item.nodeid) + if report.when == "teardown" and item.nodeid in test_results: + result_info = test_results[item.nodeid] + if result_info.outcome == 'passed': + report.user_properties = [ + (key, value) for key, value in report.user_properties if key != 'video_url' + ] + session_id_tuple = next( + (t for t in report.user_properties if t[0] == 'session_id'), None + ) + session_id = session_id_tuple[1] if session_id_tuple else None + _clean_video(session_id, item.nodeid) diff --git a/robottelo/cli/base.py b/robottelo/cli/base.py index 2d3e6dbf850..2a3ad35ff4f 100644 --- a/robottelo/cli/base.py +++ b/robottelo/cli/base.py @@ -139,9 +139,7 @@ def delete_parameter(cls, options=None): cls.command_sub = 'delete-parameter' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def dump(cls, options=None): @@ -151,9 +149,7 @@ def dump(cls, options=None): cls.command_sub = 'dump' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def _get_username_password(cls, username=None, password=None): @@ -211,16 +207,14 @@ def execute( ) if return_raw_response: return response - else: - return cls._handle_response(response, ignore_stderr=ignore_stderr) + return cls._handle_response(response, ignore_stderr=ignore_stderr) @classmethod def sm_execute(cls, command, hostname=None, timeout=None, **kwargs): """Executes the satellite-maintain cli commands on the server via ssh""" env_var = kwargs.get('env_var') or '' client = get_client(hostname=hostname or cls.hostname) - result = client.execute(f'{env_var} satellite-maintain {command}', timeout=timeout) - return result + return client.execute(f'{env_var} satellite-maintain {command}', timeout=timeout) @classmethod def exists(cls, options=None, search=None): @@ -375,6 +369,4 @@ def _construct_command(cls, options=None): if isinstance(val, list): val = ','.join(str(el) for el in val) tail += f' --{key}="{val}"' - cmd = f"{cls.command_base or ''} {cls.command_sub or ''} {tail.strip()} {cls.command_end or ''}" - - return cmd + return f"{cls.command_base or ''} {cls.command_sub or ''} {tail.strip()} {cls.command_end or ''}" diff --git a/robottelo/cli/capsule.py b/robottelo/cli/capsule.py index 2f27ba2f5c0..bb6825cc783 100644 --- a/robottelo/cli/capsule.py +++ b/robottelo/cli/capsule.py @@ -35,9 +35,7 @@ def content_add_lifecycle_environment(cls, options): cls.command_sub = 'content add-lifecycle-environment' - result = cls.execute(cls._construct_command(options), output_format='csv') - - return result + return cls.execute(cls._construct_command(options), output_format='csv') @classmethod def content_available_lifecycle_environments(cls, options): @@ -45,9 +43,7 @@ def content_available_lifecycle_environments(cls, options): cls.command_sub = 'content available-lifecycle-environments' - result = cls.execute(cls._construct_command(options), output_format='csv') - - return result + return cls.execute(cls._construct_command(options), output_format='csv') @classmethod def content_info(cls, options): @@ -55,9 +51,7 @@ def content_info(cls, options): cls.command_sub = 'content info' - result = cls.execute(cls._construct_command(options), output_format='json') - - return result + return cls.execute(cls._construct_command(options), output_format='json') @classmethod def content_lifecycle_environments(cls, options): @@ -65,9 +59,7 @@ def content_lifecycle_environments(cls, options): cls.command_sub = 'content lifecycle-environments' - result = cls.execute(cls._construct_command(options), output_format='csv') - - return result + return cls.execute(cls._construct_command(options), output_format='csv') @classmethod def content_remove_lifecycle_environment(cls, options): @@ -75,9 +67,7 @@ def content_remove_lifecycle_environment(cls, options): cls.command_sub = 'content remove-lifecycle-environment' - result = cls.execute(cls._construct_command(options), output_format='csv') - - return result + return cls.execute(cls._construct_command(options), output_format='csv') @classmethod def content_synchronization_status(cls, options): @@ -85,9 +75,7 @@ def content_synchronization_status(cls, options): cls.command_sub = 'content synchronization-status' - result = cls.execute(cls._construct_command(options), output_format='csv') - - return result + return cls.execute(cls._construct_command(options), output_format='csv') @classmethod def content_synchronize(cls, options, return_raw_response=None, timeout=3600000): @@ -95,7 +83,7 @@ def content_synchronize(cls, options, return_raw_response=None, timeout=3600000) cls.command_sub = 'content synchronize' - result = cls.execute( + return cls.execute( cls._construct_command(options), output_format='csv', ignore_stderr=True, @@ -103,17 +91,13 @@ def content_synchronize(cls, options, return_raw_response=None, timeout=3600000) timeout=timeout, ) - return result - @classmethod def content_update_counts(cls, options): """Trigger content counts update.""" cls.command_sub = 'content update-counts' - result = cls.execute(cls._construct_command(options), output_format='json') - - return result + return cls.execute(cls._construct_command(options), output_format='json') @classmethod def import_classes(cls, options): @@ -121,9 +105,7 @@ def import_classes(cls, options): cls.command_sub = 'import-classes' - result = cls.execute(cls._construct_command(options), output_format='csv') - - return result + return cls.execute(cls._construct_command(options), output_format='csv') @classmethod def refresh_features(cls, options): @@ -131,6 +113,4 @@ def refresh_features(cls, options): cls.command_sub = 'refresh-features' - result = cls.execute(cls._construct_command(options), output_format='csv') - - return result + return cls.execute(cls._construct_command(options), output_format='csv') diff --git a/robottelo/cli/hammer.py b/robottelo/cli/hammer.py index 0471754002f..4e35b0c7612 100644 --- a/robottelo/cli/hammer.py +++ b/robottelo/cli/hammer.py @@ -26,10 +26,10 @@ def _normalize_obj(obj): """ if isinstance(obj, dict): return {_normalize(k): _normalize_obj(v) for k, v in obj.items()} - elif isinstance(obj, list): + if isinstance(obj, list): return [_normalize_obj(v) for v in obj] # doing this to conform to csv parser - elif isinstance(obj, int) and not isinstance(obj, bool): + if isinstance(obj, int) and not isinstance(obj, bool): return str(obj) return obj @@ -48,8 +48,8 @@ def parse_csv(output): """Parse CSV output from Hammer CLI and convert it to python dictionary.""" # ignore warning about puppet and ostree deprecation output.replace('Puppet and OSTree will no longer be supported in Katello 3.16\n', '') - is_rex = True if 'Job invocation' in output else False - is_pkg_list = True if 'Nvra' in output else False + is_rex = 'Job invocation' in output + is_pkg_list = 'Nvra' in output # Validate if the output is eligible for CSV conversions else return as it is if not is_csv(output) and not is_rex and not is_pkg_list: return output @@ -200,7 +200,7 @@ def parse_info(output): if line.startswith(' '): # sub-properties are indented # values are separated by ':' or '=>', but not by '::' which can be # entity name like 'test::params::keys' - if line.find(':') != -1 and not line.find('::') != -1: + if line.find(':') != -1 and line.find('::') == -1: key, value = line.lstrip().split(":", 1) elif line.find('=>') != -1 and len(line.lstrip().split(" =>", 1)) == 2: key, value = line.lstrip().split(" =>", 1) diff --git a/robottelo/cli/host.py b/robottelo/cli/host.py index 6ec096cfe10..05f042f9dde 100644 --- a/robottelo/cli/host.py +++ b/robottelo/cli/host.py @@ -215,9 +215,7 @@ def reboot(cls, options=None): cls.command_sub = 'reboot' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def reports(cls, options=None): @@ -268,9 +266,7 @@ def start(cls, options=None): cls.command_sub = 'start' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def status(cls, options=None): @@ -290,9 +286,7 @@ def status(cls, options=None): cls.command_sub = 'status' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def stop(cls, options=None): @@ -313,9 +307,7 @@ def stop(cls, options=None): cls.command_sub = 'stop' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def subscription_register(cls, options=None): diff --git a/robottelo/cli/lifecycleenvironment.py b/robottelo/cli/lifecycleenvironment.py index 72435669b62..c22d2268746 100644 --- a/robottelo/cli/lifecycleenvironment.py +++ b/robottelo/cli/lifecycleenvironment.py @@ -29,9 +29,7 @@ class LifecycleEnvironment(Base): @classmethod def list(cls, options=None, per_page=False): - result = super().list(options, per_page=per_page) - - return result + return super().list(options, per_page=per_page) @classmethod def paths(cls, options=None): diff --git a/robottelo/cli/operatingsys.py b/robottelo/cli/operatingsys.py index 1a1a63bdebd..8bf4411d56d 100644 --- a/robottelo/cli/operatingsys.py +++ b/robottelo/cli/operatingsys.py @@ -45,9 +45,7 @@ def add_architecture(cls, options=None): cls.command_sub = 'add-architecture' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def add_provisioning_template(cls, options=None): @@ -57,9 +55,7 @@ def add_provisioning_template(cls, options=None): cls.command_sub = 'add-provisioning-template' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def add_ptable(cls, options=None): @@ -69,9 +65,7 @@ def add_ptable(cls, options=None): cls.command_sub = 'add-ptable' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def remove_architecture(cls, options=None): @@ -81,9 +75,7 @@ def remove_architecture(cls, options=None): cls.command_sub = 'remove-architecture' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def remove_provisioning_template(cls, options=None): @@ -93,9 +85,7 @@ def remove_provisioning_template(cls, options=None): cls.command_sub = 'remove-provisioning-template' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def remove_ptable(cls, options=None): @@ -105,6 +95,4 @@ def remove_ptable(cls, options=None): cls.command_sub = 'remove-ptable ' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) diff --git a/robottelo/cli/product.py b/robottelo/cli/product.py index efbf7ed09e1..7a7f03eeff4 100644 --- a/robottelo/cli/product.py +++ b/robottelo/cli/product.py @@ -39,9 +39,7 @@ def remove_sync_plan(cls, options=None): cls.command_sub = 'remove-sync-plan' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def set_sync_plan(cls, options=None): @@ -51,9 +49,7 @@ def set_sync_plan(cls, options=None): cls.command_sub = 'set-sync-plan' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def synchronize(cls, options=None): @@ -69,6 +65,4 @@ def update_proxy(cls, options=None): cls.command_sub = 'update-proxy' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) diff --git a/robottelo/cli/srpm.py b/robottelo/cli/srpm.py index b0e71d8969d..62578bbaa69 100644 --- a/robottelo/cli/srpm.py +++ b/robottelo/cli/srpm.py @@ -25,15 +25,11 @@ def info(cls, options=None): """Show a SRPM Info""" cls.command_sub = 'info' - result = cls.execute(cls._construct_command(options), output_format='csv') - - return result + return cls.execute(cls._construct_command(options), output_format='csv') @classmethod def list(cls, options=None): """List SRPMs""" cls.command_sub = 'list' - result = cls.execute(cls._construct_command(options), output_format='csv') - - return result + return cls.execute(cls._construct_command(options), output_format='csv') diff --git a/robottelo/cli/template.py b/robottelo/cli/template.py index 4dbe709c33b..3729fc4bf76 100644 --- a/robottelo/cli/template.py +++ b/robottelo/cli/template.py @@ -46,18 +46,14 @@ def add_operatingsystem(cls, options=None): """Adds operating system, requires "id" and "operatingsystem-id".""" cls.command_sub = 'add-operatingsystem' - result = cls.execute(cls._construct_command(options), output_format='csv') - - return result + return cls.execute(cls._construct_command(options), output_format='csv') @classmethod def remove_operatingsystem(cls, options=None): """Remove operating system, requires "id" and "operatingsystem-id".""" cls.command_sub = 'remove-operatingsystem' - result = cls.execute(cls._construct_command(options), output_format='csv') - - return result + return cls.execute(cls._construct_command(options), output_format='csv') @classmethod def clone(cls, options=None): diff --git a/robottelo/cli/template_sync.py b/robottelo/cli/template_sync.py index 6da3b683653..72ee70fa00f 100644 --- a/robottelo/cli/template_sync.py +++ b/robottelo/cli/template_sync.py @@ -50,15 +50,11 @@ def exports(cls, options=None): """Export Satellite Templates to Git/Local Directory.""" cls.command_base = 'export-templates' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) @classmethod def imports(cls, options=None): """Import Satellite Templates to Git/Local Directory.""" cls.command_base = 'import-templates' - result = cls.execute(cls._construct_command(options)) - - return result + return cls.execute(cls._construct_command(options)) diff --git a/robottelo/cli/webhook.py b/robottelo/cli/webhook.py index 379555630c5..c7b93f76d99 100644 --- a/robottelo/cli/webhook.py +++ b/robottelo/cli/webhook.py @@ -41,5 +41,4 @@ def create(cls, options=None): 'See See "hammer webhook create --help" for the list of supported methods' ) - result = super().create(options) - return result + return super().create(options) diff --git a/robottelo/config/__init__.py b/robottelo/config/__init__.py index 2d66d00054b..cca2258c7e6 100644 --- a/robottelo/config/__init__.py +++ b/robottelo/config/__init__.py @@ -183,7 +183,7 @@ def configure_airgun(): 'webdriver': settings.ui.webdriver, 'webdriver_binary': settings.ui.webdriver_binary, }, - 'webkaifuku': {'config': settings.ui.webkaifuku} or {}, + 'webkaifuku': {'config': settings.ui.webkaifuku}, } ) diff --git a/robottelo/host_helpers/api_factory.py b/robottelo/host_helpers/api_factory.py index 027d00d4919..bae286dc8ac 100644 --- a/robottelo/host_helpers/api_factory.py +++ b/robottelo/host_helpers/api_factory.py @@ -51,6 +51,7 @@ def make_http_proxy(self, org, http_proxy_type): password=settings.http_proxy.password, organization=[org.id], ).create() + return None def cv_publish_promote(self, name=None, env_name=None, repo_id=None, org_id=None): """Create, publish and promote CV to selected environment""" @@ -607,10 +608,9 @@ def update_provisioning_template(self, name=None, old=None, new=None): self.temp.template = self.temp.template.replace(old, new, 1) update = self.temp.update(['template']) return new in update.template - elif new in self.temp.template: + if new in self.temp.template: return True - else: - raise ValueError(f'{old} does not exists in template {name}') + raise ValueError(f'{old} does not exists in template {name}') def disable_syncplan(self, sync_plan): """ @@ -694,10 +694,7 @@ def wait_for_errata_applicability_task( task.label == 'Actions::Katello::Applicability::Hosts::BulkGenerate' and 'host_ids' in task.input and host_id in task.input['host_ids'] - ): - task.poll(poll_rate=poll_rate, timeout=poll_timeout) - tasks_finished += 1 - elif ( + ) or ( task.label == 'Actions::Katello::Host::UploadPackageProfile' and 'host' in task.input and host_id == task.input['host']['id'] @@ -766,7 +763,7 @@ def wait_for_syncplan_tasks(self, repo_backend_id=None, timeout=10, repo_name=No if len(req.content) > 2: if req.json()[0].get('state') in ['finished']: return True - elif req.json()[0].get('error'): + if req.json()[0].get('error'): raise AssertionError( f"Pulp task with repo_id {repo_backend_id} error or not found: " f"'{req.json().get('error')}'" diff --git a/robottelo/host_helpers/capsule_mixins.py b/robottelo/host_helpers/capsule_mixins.py index 9e283509696..1f3769e0f22 100644 --- a/robottelo/host_helpers/capsule_mixins.py +++ b/robottelo/host_helpers/capsule_mixins.py @@ -55,8 +55,7 @@ def wait_for_tasks( for task in tasks: task.poll(poll_rate=poll_rate, timeout=poll_timeout, must_succeed=must_succeed) break - else: - time.sleep(search_rate) + time.sleep(search_rate) else: raise AssertionError(f"No task was found using query '{search_query}'") return tasks @@ -94,5 +93,4 @@ def get_published_repo_url(self, org, prod, repo, lce=None, cv=None): """ if lce and cv: return f'{self.url}/pulp/content/{org}/{lce}/{cv}/custom/{prod}/{repo}/' - else: - return f'{self.url}/pulp/content/{org}/Library/custom/{prod}/{repo}/' + return f'{self.url}/pulp/content/{org}/Library/custom/{prod}/{repo}/' diff --git a/robottelo/host_helpers/cli_factory.py b/robottelo/host_helpers/cli_factory.py index 6debf436c11..964ec2a97b3 100644 --- a/robottelo/host_helpers/cli_factory.py +++ b/robottelo/host_helpers/cli_factory.py @@ -276,15 +276,13 @@ def __getattr__(self, name): # evaluate functions that provide default values fields = self._evaluate_functions(fields) return partial(create_object, entity_cls, fields) - else: - raise AttributeError(f'unknown factory method name: {name}') + raise AttributeError(f'unknown factory method name: {name}') def _evaluate_function(self, function): """Some functions may require an instance reference""" if 'self' in inspect.signature(function).parameters: return function(self) - else: - return function() + return function() def _evaluate_functions(self, iterable): """Run functions that are used to populate data in lists/dicts""" @@ -296,6 +294,7 @@ def _evaluate_functions(self, iterable): for key, item in iterable.items() if not key.startswith('_') } + return None @lru_cache def _find_entity_class(self, entity_name): @@ -303,6 +302,7 @@ def _find_entity_class(self, entity_name): for name, class_obj in self._satellite.cli.__dict__.items(): if entity_name == name.lower(): return class_obj + return None def make_content_credential(self, options=None): """Creates a content credential. @@ -530,7 +530,7 @@ def make_template(self, options=None): } # Write content to file or random text - if options is not None and 'content' in options.keys(): + if options is not None and 'content' in options: content = options.pop('content') else: content = gen_alphanumeric() @@ -874,32 +874,31 @@ def setup_org_for_a_rh_repo( custom_repo_url = settings.repos.capsule_repo if force_use_cdn or settings.robottelo.cdn or not custom_repo_url: return self._setup_org_for_a_rh_repo(options) - else: - options['url'] = custom_repo_url - result = self.setup_org_for_a_custom_repo(options) - if force_manifest_upload: - with clone() as manifest: - self._satellite.put(manifest.path, manifest.name) - try: - self._satellite.cli.Subscription.upload( - { - 'file': manifest.name, - 'organization-id': result.get('organization-id'), - } - ) - except CLIReturnCodeError as err: - raise CLIFactoryError(f'Failed to upload manifest\n{err.msg}') from err + options['url'] = custom_repo_url + result = self.setup_org_for_a_custom_repo(options) + if force_manifest_upload: + with clone() as manifest: + self._satellite.put(manifest.path, manifest.name) + try: + self._satellite.cli.Subscription.upload( + { + 'file': manifest.name, + 'organization-id': result.get('organization-id'), + } + ) + except CLIReturnCodeError as err: + raise CLIFactoryError(f'Failed to upload manifest\n{err.msg}') from err - # Add default subscription to activation-key, if SCA mode is disabled - if self._satellite.is_sca_mode_enabled(result['organization-id']) is False: - self.activationkey_add_subscription_to_repo( - { - 'activationkey-id': result['activationkey-id'], - 'organization-id': result['organization-id'], - 'subscription': constants.DEFAULT_SUBSCRIPTION_NAME, - } - ) - return result + # Add default subscription to activation-key, if SCA mode is disabled + if self._satellite.is_sca_mode_enabled(result['organization-id']) is False: + self.activationkey_add_subscription_to_repo( + { + 'activationkey-id': result['activationkey-id'], + 'organization-id': result['organization-id'], + 'subscription': constants.DEFAULT_SUBSCRIPTION_NAME, + } + ) + return result @staticmethod def _get_capsule_vm_distro_repos(distro): diff --git a/robottelo/host_helpers/repository_mixins.py b/robottelo/host_helpers/repository_mixins.py index aeb06a0c97e..0ff2bdecd68 100644 --- a/robottelo/host_helpers/repository_mixins.py +++ b/robottelo/host_helpers/repository_mixins.py @@ -388,8 +388,7 @@ def __repr__(self): f'' ) - else: - return f'' + return f'' def create( self, diff --git a/robottelo/host_helpers/satellite_mixins.py b/robottelo/host_helpers/satellite_mixins.py index 27c12c7b3be..0997bad3b83 100644 --- a/robottelo/host_helpers/satellite_mixins.py +++ b/robottelo/host_helpers/satellite_mixins.py @@ -145,9 +145,12 @@ def upload_manifest(self, org_id, manifest=None, interface='API', timeout=None): :returns: the manifest upload result """ - if not isinstance(manifest, bytes | io.BytesIO): - if not hasattr(manifest, 'content') or manifest.content is None: - manifest = clone() + if ( + not isinstance(manifest, bytes | io.BytesIO) + and not hasattr(manifest, 'content') + or manifest.content is None + ): + manifest = clone() if timeout is None: # Set the timeout to 1500 seconds to align with the API timeout. timeout = 1500000 @@ -191,8 +194,7 @@ def publish_content_view(self, org, repo_list): repo = repo_list if isinstance(repo_list, list) else [repo_list] content_view = self.api.ContentView(organization=org, repository=repo).create() content_view.publish() - content_view = content_view.read() - return content_view + return content_view.read() def move_pulp_archive(self, org, export_message): """ @@ -208,11 +210,7 @@ def move_pulp_archive(self, org, export_message): # removes everything before export path, # replaces EXPORT_PATH by IMPORT_PATH, # removes metadata filename - import_path = os.path.dirname( - re.sub(rf'.*{PULP_EXPORT_DIR}', PULP_IMPORT_DIR, export_message) - ) - - return import_path + return os.path.dirname(re.sub(rf'.*{PULP_EXPORT_DIR}', PULP_IMPORT_DIR, export_message)) class SystemInfo: diff --git a/robottelo/hosts.py b/robottelo/hosts.py index 2ff72bbe367..06e86a3b9f7 100644 --- a/robottelo/hosts.py +++ b/robottelo/hosts.py @@ -76,8 +76,7 @@ def lru_sat_ready_rhel(rhel_ver): 'promtail_config_template_file': 'config_sat.j2', 'workflow': settings.server.deploy_workflows.os, } - sat_ready_rhel = Broker(**deploy_args, host_class=Satellite).checkout() - return sat_ready_rhel + return Broker(**deploy_args, host_class=Satellite).checkout() def get_sat_version(): @@ -245,8 +244,8 @@ def nailgun_host(self): logger.error(f'Failed to get nailgun host for {self.hostname}: {err}') host = None return host - else: - logger.warning(f'Host {self.hostname} not registered to {self.satellite.hostname}') + logger.warning(f'Host {self.hostname} not registered to {self.satellite.hostname}') + return None @property def subscribed(self): @@ -515,6 +514,7 @@ def enable_repo(self, repo, force=False): downstream_repo = settings.repos.capsule_repo if force or settings.robottelo.cdn or not downstream_repo: return self.execute(f'subscription-manager repos --enable {repo}') + return None def subscription_manager_list_repos(self): return self.execute('subscription-manager repos --list') @@ -1586,6 +1586,7 @@ def check_services(self): for line in result.stdout.splitlines(): if error_msg in line: return line.replace(error_msg, '').strip() + return None def install(self, installer_obj=None, cmd_args=None, cmd_kwargs=None): """General purpose installer""" @@ -1754,7 +1755,7 @@ def _swap_nailgun(self, new_version): pip_main(['uninstall', '-y', 'nailgun']) pip_main(['install', f'https://github.com/SatelliteQE/nailgun/archive/{new_version}.zip']) self._api = type('api', (), {'_configured': False}) - to_clear = [k for k in sys.modules.keys() if 'nailgun' in k] + to_clear = [k for k in sys.modules if 'nailgun' in k] [sys.modules.pop(k) for k in to_clear] @property @@ -1844,6 +1845,7 @@ def get_caller(): for frame in inspect.stack(): if frame.function.startswith('test_'): return frame.function + return None try: ui_session = Session( diff --git a/robottelo/ssh.py b/robottelo/ssh.py index c82a7ebc071..8b72bed3497 100644 --- a/robottelo/ssh.py +++ b/robottelo/ssh.py @@ -16,13 +16,12 @@ def get_client( from robottelo.config import settings from robottelo.hosts import ContentHost - client = ContentHost( + return ContentHost( hostname=hostname or settings.server.hostname, username=username or settings.server.ssh_username, password=password or settings.server.ssh_password, port=port or settings.server.ssh_client.port, ) - return client def command( diff --git a/robottelo/utils/datafactory.py b/robottelo/utils/datafactory.py index 7de716e1046..c5ccc38ba14 100644 --- a/robottelo/utils/datafactory.py +++ b/robottelo/utils/datafactory.py @@ -64,11 +64,10 @@ def parametrized(data): 'ids': list(data.keys()), 'argvalues': list(data.values()), } - else: - return { - 'ids': [str(i) for i in range(len(data))], - 'argvalues': list(data), - } + return { + 'ids': [str(i) for i in range(len(data))], + 'argvalues': list(data), + } @filtered_datapoint @@ -196,14 +195,13 @@ def valid_domain_names(interface=None, length=None): length = random.randint(1, max_len) if length > max_len: raise ValueError(f'length is too large, max: {max_len}') - names = { + return { 'alphanumeric': DOMAIN % gen_string('alphanumeric', length), 'alpha': DOMAIN % gen_string('alpha', length), 'numeric': DOMAIN % gen_string('numeric', length), 'latin1': DOMAIN % gen_string('latin1', length), 'utf8': DOMAIN % gen_utf8(length), } - return names @filtered_datapoint @@ -243,8 +241,8 @@ def invalid_values_list(interface=None): raise InvalidArgumentError('Valid interface values are api, cli, ui only') if interface == 'ui': return ['', ' '] + invalid_names_list() - else: # interface = api or cli or None - return ['', ' ', '\t'] + invalid_names_list() + # else: interface = api or cli or None + return ['', ' ', '\t'] + invalid_names_list() @filtered_datapoint @@ -274,7 +272,7 @@ def valid_data_list(interface=None): @filtered_datapoint def valid_docker_repository_names(): """Generates a list of valid names for Docker repository.""" - names = [ + return [ gen_string('alphanumeric', random.randint(1, 255)), gen_string('alpha', random.randint(1, 255)), gen_string('cjk', random.randint(1, 85)), @@ -283,7 +281,6 @@ def valid_docker_repository_names(): gen_string('utf8', random.randint(1, 85)), gen_string('html', random.randint(1, 85)), ] - return names @filtered_datapoint @@ -512,8 +509,7 @@ def valid_http_credentials(url_encoded=False): } for cred in credentials ] - else: - return credentials + return credentials def invalid_http_credentials(url_encoded=False): @@ -535,8 +531,7 @@ def invalid_http_credentials(url_encoded=False): } for cred in credentials ] - else: - return credentials + return credentials @filtered_datapoint diff --git a/robottelo/utils/decorators/func_locker.py b/robottelo/utils/decorators/func_locker.py index 4d82c3add28..08f4073c614 100644 --- a/robottelo/utils/decorators/func_locker.py +++ b/robottelo/utils/decorators/func_locker.py @@ -112,10 +112,7 @@ def _get_scope_path(scope, scope_kwargs=None, scope_context=None, create=True): scope_path_list = [_get_temp_lock_function_dir(create=create)] if scope: - if callable(scope): - scope_dir_name = scope(**scope_kwargs) - else: - scope_dir_name = scope + scope_dir_name = scope(**scope_kwargs) if callable(scope) else scope if scope_dir_name: scope_path_list.append(scope_dir_name) if scope_context: @@ -168,8 +165,8 @@ def _check_deadlock(lock_file_path, process_id): """ if os.path.exists(lock_file_path): try: - lock_file_handler = open(lock_file_path) - lock_file_content = lock_file_handler.read() + with open(lock_file_path) as lock_file_handler: + lock_file_content = lock_file_handler.read() except OSError as exp: # do nothing, but anyway log the exception logger.exception(exp) @@ -265,8 +262,7 @@ def wait_function(func): if function: return main_wrapper(function) - else: - return wait_function + return wait_function @contextmanager diff --git a/robottelo/utils/decorators/func_shared/shared.py b/robottelo/utils/decorators/func_shared/shared.py index 072ebc3fb47..73961df50b5 100644 --- a/robottelo/utils/decorators/func_shared/shared.py +++ b/robottelo/utils/decorators/func_shared/shared.py @@ -565,5 +565,4 @@ def wait_function(func): if function_: return main_wrapper(function_) - else: - return wait_function + return wait_function diff --git a/robottelo/utils/io/__init__.py b/robottelo/utils/io/__init__.py index 33a4381fd4c..ac23b5e83b5 100644 --- a/robottelo/utils/io/__init__.py +++ b/robottelo/utils/io/__init__.py @@ -82,6 +82,7 @@ def get_remote_report_checksum(satellite, org_id): continue checksum, _ = result.stdout.split(maxsplit=1) return checksum + return None def get_report_data(report_path): diff --git a/robottelo/utils/issue_handlers/__init__.py b/robottelo/utils/issue_handlers/__init__.py index 4789bbc8a74..d59c97aec63 100644 --- a/robottelo/utils/issue_handlers/__init__.py +++ b/robottelo/utils/issue_handlers/__init__.py @@ -2,7 +2,7 @@ from robottelo.utils.issue_handlers import bugzilla handler_methods = {'BZ': bugzilla.is_open_bz} -SUPPORTED_HANDLERS = tuple(f"{handler}:" for handler in handler_methods.keys()) +SUPPORTED_HANDLERS = tuple(f"{handler}:" for handler in handler_methods) def add_workaround(data, matches, usage, validation=(lambda *a, **k: True), **kwargs): @@ -17,10 +17,11 @@ def should_deselect(issue, data=None): """Check if test should be deselected based on marked issue.""" # Handlers can be extended to support different issue trackers. handlers = {'BZ': bugzilla.should_deselect_bz} - supported_handlers = tuple(f"{handler}:" for handler in handlers.keys()) + supported_handlers = tuple(f"{handler}:" for handler in handlers) if str(issue).startswith(supported_handlers): handler_code = str(issue).partition(":")[0] return handlers[handler_code.strip()](issue.strip(), data) + return None def is_open(issue, data=None): diff --git a/robottelo/utils/ohsnap.py b/robottelo/utils/ohsnap.py index 89eb6a97e22..96241a759b6 100644 --- a/robottelo/utils/ohsnap.py +++ b/robottelo/utils/ohsnap.py @@ -121,7 +121,8 @@ def ohsnap_snap_rpms(ohsnap, sat_version, snap_version, os_major, is_all=True): rpm_repos = [f'satellite {sat_xy}', f'maintenance {sat_xy}'] if res.status_code == 200: for repo_data in res.json(): - if repo_data['rhel'] == os_major: - if any(repo in repo_data['repository'].lower() for repo in rpm_repos): - rpms += repo_data['rpms'] + if repo_data['rhel'] == os_major and any( + repo in repo_data['repository'].lower() for repo in rpm_repos + ): + rpms += repo_data['rpms'] return rpms diff --git a/robottelo/utils/report_portal/portal.py b/robottelo/utils/report_portal/portal.py index 3d44ac6c691..c7e0df5d54e 100644 --- a/robottelo/utils/report_portal/portal.py +++ b/robottelo/utils/report_portal/portal.py @@ -101,10 +101,9 @@ def get_launches( resp.raise_for_status() # this should further filter out unfinished launches as RP API currently doesn't # support usage of the same filter type multiple times (filter.ne.status) - launches = [ + return [ launch for launch in resp.json()['content'] if launch['status'] not in ['INTERRUPTED'] ] - return launches @retry( stop=stop_after_attempt(6), diff --git a/robottelo/utils/ssh.py b/robottelo/utils/ssh.py index c82a7ebc071..8b72bed3497 100644 --- a/robottelo/utils/ssh.py +++ b/robottelo/utils/ssh.py @@ -16,13 +16,12 @@ def get_client( from robottelo.config import settings from robottelo.hosts import ContentHost - client = ContentHost( + return ContentHost( hostname=hostname or settings.server.hostname, username=username or settings.server.ssh_username, password=password or settings.server.ssh_password, port=port or settings.server.ssh_client.port, ) - return client def command( diff --git a/robottelo/utils/vault.py b/robottelo/utils/vault.py index d447331ac15..97f95755bbd 100644 --- a/robottelo/utils/vault.py +++ b/robottelo/utils/vault.py @@ -10,7 +10,6 @@ class Vault: - HELP_TEXT = ( "Vault CLI in not installed in your system, " "refer link https://learn.hashicorp.com/tutorials/vault/getting-started-install to " @@ -41,12 +40,15 @@ def export_vault_addr(self): os.environ['VAULT_ADDR'] = vaulturl # Dynaconf Vault Env Vars - if self.vault_enabled and self.vault_enabled in ['True', 'true']: - if 'localhost:8200' in vaulturl: - raise InvalidVaultURLForOIDC( - f"{vaulturl} doesn't support OIDC login," - "please change url to corp vault in env file!" - ) + if ( + self.vault_enabled + and self.vault_enabled in ['True', 'true'] + and 'localhost:8200' in vaulturl + ): + raise InvalidVaultURLForOIDC( + f"{vaulturl} doesn't support OIDC login," + "please change url to corp vault in env file!" + ) def exec_vault_command(self, command: str, **kwargs): """A wrapper to execute the vault CLI commands @@ -74,31 +76,29 @@ def login(self, **kwargs): self.vault_enabled and self.vault_enabled in ['True', 'true'] and 'VAULT_SECRET_ID_FOR_DYNACONF' not in os.environ + and self.status(**kwargs).returncode != 0 ): - if self.status(**kwargs).returncode != 0: - logger.info( - "Warning! The browser is about to open for vault OIDC login, " - "close the tab once the sign-in is done!" - ) - if ( - self.exec_vault_command(command="vault login -method=oidc", **kwargs).returncode - == 0 - ): - self.exec_vault_command(command="vault token renew -i 10h", **kwargs) - logger.info("Success! Vault OIDC Logged-In and extended for 10 hours!") - # Fetching tokens - token = self.exec_vault_command("vault token lookup --format json").stdout - token = json.loads(str(token.decode('UTF-8')))['data']['id'] - # Setting new token in env file - _envdata = re.sub( - '.*VAULT_TOKEN_FOR_DYNACONF=.*', - f"VAULT_TOKEN_FOR_DYNACONF={token}", - self.envdata, - ) - self.env_path.write_text(_envdata) - logger.info( - "Success! New OIDC token added to .env file to access secrets from vault!" - ) + logger.info( + "Warning! The browser is about to open for vault OIDC login, " + "close the tab once the sign-in is done!" + ) + if ( + self.exec_vault_command(command="vault login -method=oidc", **kwargs).returncode + == 0 + ): + self.exec_vault_command(command="vault token renew -i 10h", **kwargs) + logger.info("Success! Vault OIDC Logged-In and extended for 10 hours!") + # Fetching tokens + token = self.exec_vault_command("vault token lookup --format json").stdout + token = json.loads(str(token.decode('UTF-8')))['data']['id'] + # Setting new token in env file + _envdata = re.sub( + '.*VAULT_TOKEN_FOR_DYNACONF=.*', + f"VAULT_TOKEN_FOR_DYNACONF={token}", + self.envdata, + ) + self.env_path.write_text(_envdata) + logger.info("Success! New OIDC token added to .env file to access secrets from vault!") def logout(self): # Teardown - Setting dymmy token in env file diff --git a/robottelo/utils/virtwho.py b/robottelo/utils/virtwho.py index 5e0f3a4657a..e159a487394 100644 --- a/robottelo/utils/virtwho.py +++ b/robottelo/utils/virtwho.py @@ -47,16 +47,15 @@ def get_system(system_type): 'password': getattr(settings.virtwho, system_type).guest_password, 'port': getattr(settings.virtwho, system_type).guest_port, } - elif system_type == 'satellite': + if system_type == 'satellite': return { 'hostname': settings.server.hostname, 'username': settings.server.ssh_username, 'password': settings.server.ssh_password, } - else: - raise VirtWhoError( - f'"{system_type}" system type is not supported. Please use one of {system_type_list}' - ) + raise VirtWhoError( + f'"{system_type}" system type is not supported. Please use one of {system_type_list}' + ) def get_guest_info(hypervisor_type): @@ -115,8 +114,7 @@ def register_system(system, activation_key=None, org='Default_Organization', env ret, stdout = runcmd(cmd, system) if ret == 0 or "system has been registered" in stdout: return True - else: - raise VirtWhoError(f'Failed to register system: {system}') + raise VirtWhoError(f'Failed to register system: {system}') def virtwho_cleanup(): @@ -150,10 +148,9 @@ def get_virtwho_status(): return 'logerror' if any(key in stdout for key in running_stauts): return 'running' - elif any(key in stdout for key in stopped_status): + if any(key in stdout for key in stopped_status): return 'stopped' - else: - return 'undefined' + return 'undefined' def get_configure_id(name): @@ -164,8 +161,7 @@ def get_configure_id(name): config = VirtWhoConfig.info({'name': name}) if 'id' in config['general-information']: return config['general-information']['id'] - else: - raise VirtWhoError(f"No configure id found for {name}") + raise VirtWhoError(f"No configure id found for {name}") def get_configure_command(config_id, org=DEFAULT_ORG): @@ -198,10 +194,8 @@ def get_configure_option(option, filename): cmd = f"grep -v '^#' {filename} | grep ^{option}" ret, stdout = runcmd(cmd) if ret == 0 and option in stdout: - value = stdout.split('=')[1].strip() - return value - else: - raise VirtWhoError(f"option {option} is not exist or not be enabled in {filename}") + return stdout.split('=')[1].strip() + raise VirtWhoError(f"option {option} is not exist or not be enabled in {filename}") def get_rhsm_log(): @@ -264,8 +258,7 @@ def _get_hypervisor_mapping(hypervisor_type): break if hypervisor_name: return hypervisor_name, guest_name - else: - raise VirtWhoError(f"Failed to get the hypervisor_name for guest {guest_name}") + raise VirtWhoError(f"Failed to get the hypervisor_name for guest {guest_name}") def get_hypervisor_ahv_mapping(hypervisor_type): @@ -348,6 +341,7 @@ def deploy_configure_by_command(command, hypervisor_type, debug=False, org='Defa raise VirtWhoError(f"Failed to deploy configure by {command}") if debug: return deploy_validation(hypervisor_type) + return None def deploy_configure_by_script( @@ -371,6 +365,7 @@ def deploy_configure_by_script( raise VirtWhoError(f"Failed to deploy configure by {script_filename}") if debug: return deploy_validation(hypervisor_type) + return None def deploy_configure_by_command_check(command): @@ -389,8 +384,7 @@ def deploy_configure_by_command_check(command): else: if ret != 0 or 'Finished successfully' not in stdout: raise VirtWhoError(f"Failed to deploy configure by {command}") - else: - return 'Finished successfully' + return 'Finished successfully' def restart_virtwho_service(): @@ -469,8 +463,7 @@ def hypervisor_json_create(hypervisors, guests): name = str(uuid.uuid4()) hypervisor = {"guestIds": guest_list, "name": name, "hypervisorId": {"hypervisorId": name}} hypervisors_list.append(hypervisor) - mapping = {"hypervisors": hypervisors_list} - return mapping + return {"hypervisors": hypervisors_list} def create_fake_hypervisor_content(org_label, hypervisors, guests): @@ -537,7 +530,8 @@ def get_configure_command_option(deploy_type, args, org=DEFAULT_ORG): username, password = Base._get_username_password() if deploy_type == 'location-id': return f"hammer -u {username} -p {password} virt-who-config deploy --id {args['id']} --location-id '{args['location-id']}' " - elif deploy_type == 'organization-title': + if deploy_type == 'organization-title': return f"hammer -u {username} -p {password} virt-who-config deploy --id {args['id']} --organization-title '{args['organization-title']}' " - elif deploy_type == 'name': + if deploy_type == 'name': return f"hammer -u {username} -p {password} virt-who-config deploy --name {args['name']} --organization '{org}' " + return None diff --git a/scripts/config_helpers.py b/scripts/config_helpers.py index feb37c9bd62..cf422588b05 100644 --- a/scripts/config_helpers.py +++ b/scripts/config_helpers.py @@ -35,7 +35,7 @@ def merge_nested_dictionaries(original, new, overwrite=False): user_choice = click.prompt(choice_prompt, type=int, default=1, show_default=True) if user_choice == 1: continue - elif user_choice == 2: + if user_choice == 2: original[key] = value elif user_choice == 3 and isinstance(value, list): original[key] = original[key] + value @@ -110,7 +110,7 @@ def merge(from_, strategy): user_choice = click.prompt(choice_prompt, type=int, default=1, show_default=True) if user_choice == 1: continue - elif user_choice == 2: + if user_choice == 2: logger.warning(f"Overwriting {real_name} with {file}") real_name.unlink() real_name.write_text(file.read_text()) diff --git a/scripts/customer_scenarios.py b/scripts/customer_scenarios.py index eb806468e21..b81137042b9 100755 --- a/scripts/customer_scenarios.py +++ b/scripts/customer_scenarios.py @@ -19,8 +19,7 @@ def make_path_list(path_list): paths = path_list.split(',') paths = [path for path in paths if any(target in path for target in targets)] return set(paths) - else: - return targets + return targets def get_bz_data(paths): @@ -31,12 +30,10 @@ def get_bz_data(paths): for test in tests: test_dict = test.to_dict() test_data = {**test_dict['tokens'], **test_dict['invalid-tokens']} - if 'bz' in test_data.keys(): - if ( - 'customerscenario' not in test_data.keys() - or test_data['customerscenario'] == 'false' - ): - path_result.append([test.name, test_data['bz']]) + if 'bz' in test_data and ( + 'customerscenario' not in test_data or test_data['customerscenario'] == 'false' + ): + path_result.append([test.name, test_data['bz']]) if path_result: result[path] = path_result return result @@ -64,8 +61,7 @@ def get_response(bzs): ) assert response.status_code == 200, 'BZ query unsuccessful' assert response.json().get('error') is not True, response.json().get('message') - bugs = response.json().get('bugs') - return bugs + return response.json().get('bugs') def query_bz(data): @@ -75,7 +71,7 @@ def query_bz(data): for test in tests: bugs = get_response(test[1]) for bug in bugs: - if 'external_bugs' in bug.keys() and len(bug['external_bugs']) > 1: + if 'external_bugs' in bug and len(bug['external_bugs']) > 1: customer_cases = [ case for case in bug['external_bugs'] diff --git a/scripts/fixture_cli.py b/scripts/fixture_cli.py index 5963394e21f..c68559d3c1b 100644 --- a/scripts/fixture_cli.py +++ b/scripts/fixture_cli.py @@ -16,13 +16,13 @@ def fixture_to_test(fixture_name): """ if ":" not in fixture_name: return f"def test_runfake_{fixture_name}({fixture_name}):\n assert True" - else: - fixture_name, params = fixture_name.split(":") - params = params.split(",") - return ( - f"@pytest.mark.parametrize('{fixture_name}', {params}, indirect=True)\n" - f"def test_runfake_{fixture_name}({fixture_name}):\n assert True" - ) + + fixture_name, params = fixture_name.split(":") + params = params.split(",") + return ( + f"@pytest.mark.parametrize('{fixture_name}', {params}, indirect=True)\n" + f"def test_runfake_{fixture_name}({fixture_name}):\n assert True" + ) @click.command() diff --git a/scripts/graph_entities.py b/scripts/graph_entities.py index a404c616911..46038a3e3b0 100755 --- a/scripts/graph_entities.py +++ b/scripts/graph_entities.py @@ -24,9 +24,7 @@ def graph(): for entity_name, entity in entities_.items(): # Graph out which entities this entity depends on. for field_name, field in entity.get_fields().items(): - if isinstance(field, entity_mixins.OneToOneField) or isinstance( - field, entity_mixins.OneToManyField - ): + if isinstance(field, (entity_mixins.OneToOneField | entity_mixins.OneToManyField)): print( '{} -> {} [label="{}"{}]'.format( entity_name, diff --git a/tests/foreman/api/test_activationkey.py b/tests/foreman/api/test_activationkey.py index 56513c03d85..ef5add381fc 100644 --- a/tests/foreman/api/test_activationkey.py +++ b/tests/foreman/api/test_activationkey.py @@ -171,7 +171,7 @@ def test_positive_update_limited_host(max_host, target_sat): for key, value in want.items(): setattr(act_key, key, value) act_key = act_key.update(want.keys()) - actual = {attr: getattr(act_key, attr) for attr in want.keys()} + actual = {attr: getattr(act_key, attr) for attr in want} assert want == actual @@ -219,7 +219,7 @@ def test_negative_update_limit(max_host, target_sat): with pytest.raises(HTTPError): act_key.update(want.keys()) act_key = act_key.read() - actual = {attr: getattr(act_key, attr) for attr in want.keys()} + actual = {attr: getattr(act_key, attr) for attr in want} assert want == actual @@ -293,7 +293,7 @@ def test_positive_get_releases_content(target_sat): """ act_key = target_sat.api.ActivationKey().create() response = client.get(act_key.path('releases'), auth=get_credentials(), verify=False).json() - assert 'results' in response.keys() + assert 'results' in response assert isinstance(response['results'], list) diff --git a/tests/foreman/api/test_capsulecontent.py b/tests/foreman/api/test_capsulecontent.py index abbfd9f9f32..48db1e11a7b 100644 --- a/tests/foreman/api/test_capsulecontent.py +++ b/tests/foreman/api/test_capsulecontent.py @@ -1513,7 +1513,7 @@ def test_positive_content_counts_for_mixed_cv( # Check the counts for CVV are not present at the Capsule side before sync. caps_counts = module_capsule_configured.nailgun_capsule.content_counts() - assert caps_counts is None or cvv.id not in caps_counts['content_view_versions'].keys() + assert caps_counts is None or cvv.id not in caps_counts['content_view_versions'] # Sync, wait for counts to be updated and get them from the Capsule. sync_status = module_capsule_configured.nailgun_capsule.content_sync() @@ -1528,7 +1528,7 @@ def test_positive_content_counts_for_mixed_cv( caps_counts = module_capsule_configured.nailgun_capsule.content_counts()[ 'content_view_versions' ] - assert str(cvv.id) in caps_counts.keys(), 'CVV is missing in content counts.' + assert str(cvv.id) in caps_counts, 'CVV is missing in content counts.' caps_counts = caps_counts[str(cvv.id)] # Every "environment repo" (the one promoted to an LCE and synced to the Capsule) diff --git a/tests/foreman/api/test_computeresource_azurerm.py b/tests/foreman/api/test_computeresource_azurerm.py index 66f25f74b2b..47bf8313066 100644 --- a/tests/foreman/api/test_computeresource_azurerm.py +++ b/tests/foreman/api/test_computeresource_azurerm.py @@ -580,4 +580,4 @@ def test_positive_azurerm_custom_image_host_provisioned( # Azure cloud assert self.hostname.lower() == azureclient_host.name - assert AZURERM_VM_SIZE_DEFAULT == azureclient_host.type + assert azureclient_host.type == AZURERM_VM_SIZE_DEFAULT diff --git a/tests/foreman/api/test_contentview.py b/tests/foreman/api/test_contentview.py index 73575dd4b1a..c822234a628 100644 --- a/tests/foreman/api/test_contentview.py +++ b/tests/foreman/api/test_contentview.py @@ -96,8 +96,7 @@ def apply_package_filter(content_view, repo, package, target_sat, inclusion=True assert cv_filter.id == cv_filter_rule.content_view_filter.id content_view.publish() content_view = content_view.read() - content_view_version_info = content_view.version[0].read() - return content_view_version_info + return content_view.version[0].read() class TestContentView: diff --git a/tests/foreman/api/test_errata.py b/tests/foreman/api/test_errata.py index 5bafb65d9b2..da257c8d983 100644 --- a/tests/foreman/api/test_errata.py +++ b/tests/foreman/api/test_errata.py @@ -76,12 +76,11 @@ def activation_key(module_sca_manifest_org, module_cv, module_lce, module_target module_cv, module_lce, )['content-view'] - activation_key = module_target_sat.api.ActivationKey( + return module_target_sat.api.ActivationKey( organization=module_sca_manifest_org, environment=module_lce, content_view=_cv, ).create() - return activation_key @pytest.fixture(scope='module') @@ -144,7 +143,7 @@ def _fetch_available_errata(host, expected_amount=None, timeout=120): for _ in range(timeout // 5): if expected_amount is None: return errata['results'] - elif len(errata['results']) == expected_amount: + if len(errata['results']) == expected_amount: return errata['results'] sleep(5) errata = host.errata() @@ -407,7 +406,7 @@ def package_applicability_changed_as_expected( prior_package = None # package must not have been present before this modification else: prior_package = package_filename - _applicables = { + return { 'result': True, 'errata_count': host.applicable_errata_count, 'package_count': host.applicable_package_count, @@ -416,7 +415,6 @@ def package_applicability_changed_as_expected( 'change_in_errata': change_in_errata, 'changed_errata': list(app_errata_diff_ids), } - return _applicables return True @@ -1347,6 +1345,7 @@ def _run_remote_command_on_content_host(command, vm, return_result=False): assert result.status == 0 if return_result: return result.stdout + return None def _set_prerequisites_for_swid_repos(vm): @@ -1688,7 +1687,7 @@ def test_positive_incremental_update_apply_to_envs_cvs( assert set(FAKE_9_YUM_SECURITY_ERRATUM).issubset(post_app_errata_ids) # expected packages from the security erratum were added to host added_packages = response['output']['changed_content'][0]['added_units']['rpm'] - assert 12 == len(added_packages) + assert len(added_packages) == 12 # expected that not all of the added packages will be applicable assert 8 == host_app_packages == rhel8_contenthost.applicable_package_count # install all of the newly added packages, recalculate applicability diff --git a/tests/foreman/api/test_filter.py b/tests/foreman/api/test_filter.py index ed61c98c76a..d13d5a7ecad 100644 --- a/tests/foreman/api/test_filter.py +++ b/tests/foreman/api/test_filter.py @@ -22,10 +22,9 @@ @pytest.fixture(scope='module') def module_perms(module_target_sat): """Search for provisioning template permissions. Set ``cls.ct_perms``.""" - ct_perms = module_target_sat.api.Permission().search( + return module_target_sat.api.Permission().search( query={'search': 'resource_type="ProvisioningTemplate"'} ) - return ct_perms @pytest.mark.tier1 diff --git a/tests/foreman/api/test_hostcollection.py b/tests/foreman/api/test_hostcollection.py index aea239ac1ad..985f989718e 100644 --- a/tests/foreman/api/test_hostcollection.py +++ b/tests/foreman/api/test_hostcollection.py @@ -28,8 +28,7 @@ @pytest.fixture(scope='module') def fake_hosts(module_org, module_target_sat): """Create content hosts that can be shared by tests.""" - hosts = [module_target_sat.api.Host(organization=module_org).create() for _ in range(2)] - return hosts + return [module_target_sat.api.Host(organization=module_org).create() for _ in range(2)] @pytest.mark.parametrize('name', **parametrized(valid_data_list())) diff --git a/tests/foreman/api/test_multiple_paths.py b/tests/foreman/api/test_multiple_paths.py index 30531f77025..8c683ca309a 100644 --- a/tests/foreman/api/test_multiple_paths.py +++ b/tests/foreman/api/test_multiple_paths.py @@ -130,7 +130,7 @@ def test_positive_get_status_code(self, entity_cls): logger.info('test_get_status_code arg: %s', entity_cls) response = client.get(entity_cls().path(), auth=get_credentials(), verify=False) response.raise_for_status() - assert http.client.OK == response.status_code + assert response.status_code == http.client.OK assert 'application/json' in response.headers['content-type'] @pytest.mark.tier1 @@ -151,7 +151,7 @@ def test_negative_get_unauthorized(self, entity_cls): """ logger.info('test_get_unauthorized arg: %s', entity_cls) response = client.get(entity_cls().path(), auth=(), verify=False) - assert http.client.UNAUTHORIZED == response.status_code + assert response.status_code == http.client.UNAUTHORIZED @pytest.mark.tier3 @pytest.mark.parametrize( @@ -173,7 +173,7 @@ def test_positive_post_status_code(self, entity_cls): :BZ: 1118015 """ response = entity_cls().create_raw() - assert http.client.CREATED == response.status_code + assert response.status_code == http.client.CREATED assert 'application/json' in response.headers['content-type'] @pytest.mark.tier1 @@ -195,7 +195,7 @@ def test_negative_post_unauthorized(self, entity_cls): """ server_cfg = user_nailgun_config() return_code = entity_cls(server_cfg).create_raw(create_missing=False).status_code - assert http.client.UNAUTHORIZED == return_code + assert return_code == http.client.UNAUTHORIZED class TestEntityId: @@ -217,7 +217,7 @@ def test_positive_get_status_code(self, entity_cls): """ entity = entity_cls(id=entity_cls().create_json()['id']) response = entity.read_raw() - assert http.client.OK == response.status_code + assert response.status_code == http.client.OK assert 'application/json' in response.headers['content-type'] @pytest.mark.tier1 @@ -248,7 +248,7 @@ def test_positive_put_status_code(self, entity_cls): auth=get_credentials(), verify=False, ) - assert http.client.OK == response.status_code + assert response.status_code == http.client.OK assert 'application/json' in response.headers['content-type'] @pytest.mark.tier1 @@ -325,7 +325,7 @@ def test_positive_put_and_get_requests(self, entity_cls): payload = _get_readable_attributes(new_entity) entity_attrs = entity_cls(id=entity['id']).read_json() for key, value in payload.items(): - assert key in entity_attrs.keys() + assert key in entity_attrs assert value == entity_attrs[key] @pytest.mark.tier1 @@ -349,7 +349,7 @@ def test_positive_post_and_get_requests(self, entity_cls): payload = _get_readable_attributes(entity) entity_attrs = entity_cls(id=entity_id).read_json() for key, value in payload.items(): - assert key in entity_attrs.keys() + assert key in entity_attrs assert value == entity_attrs[key] @pytest.mark.tier1 @@ -369,7 +369,7 @@ def test_positive_delete_and_get_requests(self, entity_cls): # Create an entity, delete it and get it. entity = entity_cls(id=entity_cls().create_json()['id']) entity.delete() - assert http.client.NOT_FOUND == entity.read_raw().status_code + assert entity.read_raw().status_code == http.client.NOT_FOUND class TestEntityRead: diff --git a/tests/foreman/api/test_organization.py b/tests/foreman/api/test_organization.py index 89988935f98..7edc09d0dc2 100644 --- a/tests/foreman/api/test_organization.py +++ b/tests/foreman/api/test_organization.py @@ -77,7 +77,7 @@ def test_positive_create(self, target_sat): if is_open('BZ:2228820'): assert response.status_code in [http.client.UNSUPPORTED_MEDIA_TYPE, 500] else: - assert http.client.UNSUPPORTED_MEDIA_TYPE == response.status_code + assert response.status_code == http.client.UNSUPPORTED_MEDIA_TYPE @pytest.mark.tier1 @pytest.mark.build_sanity diff --git a/tests/foreman/api/test_provisioningtemplate.py b/tests/foreman/api/test_provisioningtemplate.py index 95f0b3883f0..354f15ed47d 100644 --- a/tests/foreman/api/test_provisioningtemplate.py +++ b/tests/foreman/api/test_provisioningtemplate.py @@ -120,7 +120,7 @@ def tftpboot(module_org, module_target_sat): for setting in default_settings: if setting.value is None: setting.value = '' - setting.update(fields=['value'] or '') + setting.update(fields=['value']) class TestProvisioningTemplate: diff --git a/tests/foreman/api/test_registration.py b/tests/foreman/api/test_registration.py index 606dbae9dca..5b7554b480e 100644 --- a/tests/foreman/api/test_registration.py +++ b/tests/foreman/api/test_registration.py @@ -62,7 +62,7 @@ def test_host_registration_end_to_end( # Verify server.hostname and server.port from subscription-manager config assert module_target_sat.hostname == rhel_contenthost.subscription_config['server']['hostname'] - assert constants.CLIENT_PORT == rhel_contenthost.subscription_config['server']['port'] + assert rhel_contenthost.subscription_config['server']['port'] == constants.CLIENT_PORT # Update module_capsule_configured to include module_org/module_location nc = module_capsule_configured.nailgun_smart_proxy @@ -86,7 +86,7 @@ def test_host_registration_end_to_end( module_capsule_configured.hostname == rhel_contenthost.subscription_config['server']['hostname'] ) - assert constants.CLIENT_PORT == rhel_contenthost.subscription_config['server']['port'] + assert rhel_contenthost.subscription_config['server']['port'] == constants.CLIENT_PORT @pytest.mark.tier3 diff --git a/tests/foreman/api/test_repository.py b/tests/foreman/api/test_repository.py index 897c27d5f53..206dddb976f 100644 --- a/tests/foreman/api/test_repository.py +++ b/tests/foreman/api/test_repository.py @@ -488,7 +488,7 @@ def test_negative_update_to_invalid_download_policy(self, repo, target_sat): **datafactory.parametrized( [ {'content_type': content_type, 'download_policy': 'on_demand'} - for content_type in constants.REPO_TYPE.keys() + for content_type in constants.REPO_TYPE if content_type != 'yum' ] ), @@ -2301,7 +2301,7 @@ def test_positive_upload_file_to_file_repo(self, repo, target_sat): filesearch = target_sat.api.File().search( query={"search": f"name={constants.RPM_TO_UPLOAD}"} ) - assert constants.RPM_TO_UPLOAD == filesearch[0].name + assert filesearch[0].name == constants.RPM_TO_UPLOAD @pytest.mark.tier1 @pytest.mark.upgrade diff --git a/tests/foreman/api/test_role.py b/tests/foreman/api/test_role.py index 1ce1014f269..7d5a12bc591 100644 --- a/tests/foreman/api/test_role.py +++ b/tests/foreman/api/test_role.py @@ -72,7 +72,7 @@ def create_org_admin_role(self, target_sat, name=None, orgs=None, locs=None): :return dict: This function returns dict representation of cloned role data returned from 'clone' function """ - name = gen_string('alpha') if not name else name + name = name if name else gen_string('alpha') default_org_admin = target_sat.api.Role().search( query={'search': 'name="Organization admin"'} ) diff --git a/tests/foreman/api/test_subscription.py b/tests/foreman/api/test_subscription.py index 316ef4e7448..282dac528b0 100644 --- a/tests/foreman/api/test_subscription.py +++ b/tests/foreman/api/test_subscription.py @@ -54,7 +54,7 @@ def custom_repo(rh_repo, module_sca_manifest_org, module_target_sat): @pytest.fixture(scope='module') def module_ak(module_sca_manifest_org, rh_repo, custom_repo, module_target_sat): """rh_repo and custom_repo are included here to ensure their execution before the AK""" - module_ak = module_target_sat.api.ActivationKey( + return module_target_sat.api.ActivationKey( content_view=module_sca_manifest_org.default_content_view, max_hosts=100, organization=module_sca_manifest_org, @@ -63,7 +63,6 @@ def module_ak(module_sca_manifest_org, rh_repo, custom_repo, module_target_sat): ), auto_attach=True, ).create() - return module_ak @pytest.mark.tier1 diff --git a/tests/foreman/api/test_template_combination.py b/tests/foreman/api/test_template_combination.py index a10125e0a54..7e9d5f11be8 100644 --- a/tests/foreman/api/test_template_combination.py +++ b/tests/foreman/api/test_template_combination.py @@ -49,10 +49,10 @@ def test_positive_end_to_end_template_combination(request, module_target_sat, mo assert module_hostgroup.id == combination.hostgroup.id # DELETE - assert 1 == len(template.read().template_combinations) + assert len(template.read().template_combinations) == 1 combination.delete() with pytest.raises(HTTPError): combination.read() - assert 0 == len(template.read().template_combinations) + assert len(template.read().template_combinations) == 0 template.delete() module_hostgroup.delete() diff --git a/tests/foreman/api/test_templatesync.py b/tests/foreman/api/test_templatesync.py index d91c8ad378d..bda401ef373 100644 --- a/tests/foreman/api/test_templatesync.py +++ b/tests/foreman/api/test_templatesync.py @@ -693,7 +693,7 @@ def test_positive_import_json_output_name_key( template = target_sat.api.Template().imports( data={'repo': dir_path, 'organization_ids': [module_org.id]} ) - assert 'name' in template['message']['templates'][0].keys() + assert 'name' in template['message']['templates'][0] assert template_name == template['message']['templates'][0]['name'] @pytest.mark.tier2 @@ -748,7 +748,7 @@ def test_positive_import_json_output_file_key( template = module_target_sat.api.Template().imports( data={'repo': dir_path, 'organization_ids': [module_org.id]} ) - assert 'example_template.erb' == template['message']['templates'][0]['file'] + assert template['message']['templates'][0]['file'] == 'example_template.erb' @pytest.mark.tier2 def test_positive_import_json_output_corrupted_metadata( @@ -780,7 +780,7 @@ def test_positive_import_json_output_corrupted_metadata( ) assert not bool(template['message']['templates'][0]['imported']) assert ( - 'Failed to parse metadata' == template['message']['templates'][0]['additional_errors'] + template['message']['templates'][0]['additional_errors'] == 'Failed to parse metadata' ) @pytest.mark.skip_if_open('BZ:1787355') @@ -816,8 +816,8 @@ def test_positive_import_json_output_filtered_skip_message( ) assert not bool(template['message']['templates'][0]['imported']) assert ( - "Skipping, 'name' filtered out based on 'filter' and 'negate' settings" - == template['message']['templates'][0]['additional_info'] + template['message']['templates'][0]['additional_info'] + == "Skipping, 'name' filtered out based on 'filter' and 'negate' settings" ) @pytest.mark.tier2 @@ -850,8 +850,8 @@ def test_positive_import_json_output_no_name_error( ) assert not bool(template['message']['templates'][0]['imported']) assert ( - "No 'name' found in metadata" - == template['message']['templates'][0]['additional_errors'] + template['message']['templates'][0]['additional_errors'] + == "No 'name' found in metadata" ) @pytest.mark.tier2 @@ -884,8 +884,8 @@ def test_positive_import_json_output_no_model_error( ) assert not bool(template['message']['templates'][0]['imported']) assert ( - "No 'model' found in metadata" - == template['message']['templates'][0]['additional_errors'] + template['message']['templates'][0]['additional_errors'] + == "No 'model' found in metadata" ) @pytest.mark.tier2 @@ -918,8 +918,8 @@ def test_positive_import_json_output_blank_model_error( ) assert not bool(template['message']['templates'][0]['imported']) assert ( - "Template type was not found, are you missing a plugin?" - == template['message']['templates'][0]['additional_errors'] + template['message']['templates'][0]['additional_errors'] + == "Template type was not found, are you missing a plugin?" ) @pytest.mark.tier2 @@ -965,7 +965,7 @@ def test_positive_export_json_output( template['exported'] for template in exported_templates['message']['templates'] ].count(True) assert exported_count == 17 - assert 'name' in exported_templates['message']['templates'][0].keys() + assert 'name' in exported_templates['message']['templates'][0] assert ( target_sat.execute( f'[ -d {dir_path}/job_templates ] && ' diff --git a/tests/foreman/cli/test_activationkey.py b/tests/foreman/cli/test_activationkey.py index 7a0d5f57dd4..cbcfaea5700 100644 --- a/tests/foreman/cli/test_activationkey.py +++ b/tests/foreman/cli/test_activationkey.py @@ -257,9 +257,8 @@ def test_negative_create_with_usage_limit_with_not_integers(module_org, limit, m module_target_sat.cli_factory.make_activation_key( {'organization-id': module_org.id, 'max-hosts': limit} ) - if isinstance(limit, int): - if limit < 1: - assert 'Max hosts cannot be less than one' in str(raise_ctx) + if isinstance(limit, int) and limit < 1: + assert 'Max hosts cannot be less than one' in str(raise_ctx) if isinstance(limit, str): assert 'Numeric value is required.' in str(raise_ctx) @@ -1404,7 +1403,7 @@ def test_positive_update_autoattach(module_org, module_target_sat): result = module_target_sat.cli.ActivationKey.update( {'auto-attach': new_value, 'id': new_ak['id'], 'organization-id': module_org.id} ) - assert 'Activation key updated.' == result[0]['message'] + assert result[0]['message'] == 'Activation key updated.' @pytest.mark.tier2 diff --git a/tests/foreman/cli/test_computeresource_azurerm.py b/tests/foreman/cli/test_computeresource_azurerm.py index 1621b48d12f..1756a0ed674 100644 --- a/tests/foreman/cli/test_computeresource_azurerm.py +++ b/tests/foreman/cli/test_computeresource_azurerm.py @@ -37,7 +37,7 @@ def azurerm_hostgroup( ): """Sets Hostgroup for AzureRm Host Provisioning""" - hgroup = sat_azure.api.HostGroup( + return sat_azure.api.HostGroup( architecture=sat_azure_default_architecture, compute_resource=module_azurerm_cr, domain=sat_azure_domain, @@ -46,7 +46,6 @@ def azurerm_hostgroup( operatingsystem=sat_azure_default_os, organization=[sat_azure_org], ).create() - return hgroup class TestAzureRMComputeResourceTestCase: @@ -344,29 +343,30 @@ def class_host_ft( Provisions the host on AzureRM using Finish template Later in tests this host will be used to perform assertions """ - with sat_azure.hammer_api_timeout(): - with sat_azure.skip_yum_update_during_provisioning(template='Kickstart default finish'): - host = sat_azure.cli.Host.create( - { - 'name': self.hostname, - 'compute-resource': module_azurerm_cr.name, - 'compute-attributes': self.compute_attrs, - 'interface': self.interfaces_attributes, - 'location-id': sat_azure_loc.id, - 'organization-id': sat_azure_org.id, - 'domain-id': sat_azure_domain.id, - 'domain': sat_azure_domain.name, - 'architecture-id': sat_azure_default_architecture.id, - 'operatingsystem-id': sat_azure_default_os.id, - 'root-password': gen_string('alpha'), - 'image': module_azurerm_custom_finishimg.name, - }, - timeout=1800000, - ) - yield host - with sat_azure.api_factory.satellite_setting('destroy_vm_on_host_delete=True'): - if sat_azure.cli.Host.exists(search=('name', host['name'])): - sat_azure.cli.Host.delete({'name': self.fullhostname}, timeout=1800000) + with sat_azure.hammer_api_timeout(), sat_azure.skip_yum_update_during_provisioning( + template='Kickstart default finish' + ): + host = sat_azure.cli.Host.create( + { + 'name': self.hostname, + 'compute-resource': module_azurerm_cr.name, + 'compute-attributes': self.compute_attrs, + 'interface': self.interfaces_attributes, + 'location-id': sat_azure_loc.id, + 'organization-id': sat_azure_org.id, + 'domain-id': sat_azure_domain.id, + 'domain': sat_azure_domain.name, + 'architecture-id': sat_azure_default_architecture.id, + 'operatingsystem-id': sat_azure_default_os.id, + 'root-password': gen_string('alpha'), + 'image': module_azurerm_custom_finishimg.name, + }, + timeout=1800000, + ) + yield host + with sat_azure.api_factory.satellite_setting('destroy_vm_on_host_delete=True'): + if sat_azure.cli.Host.exists(search=('name', host['name'])): + sat_azure.cli.Host.delete({'name': self.fullhostname}, timeout=1800000) @pytest.fixture(scope='class') def azureclient_host(self, azurermclient, class_host_ft): @@ -472,27 +472,26 @@ def class_host_ud( Provisions the host on AzureRM using UserData template Later in tests this host will be used to perform assertions """ - with sat_azure.hammer_api_timeout(): - with sat_azure.skip_yum_update_during_provisioning( - template='Kickstart default user data' - ): - host = sat_azure.cli.Host.create( - { - 'name': self.hostname, - 'compute-attributes': self.compute_attrs, - 'interface': self.interfaces_attributes, - 'image': module_azurerm_cloudimg.name, - 'hostgroup': azurerm_hostgroup.name, - 'location': sat_azure_loc.name, - 'organization': sat_azure_org.name, - 'operatingsystem-id': sat_azure_default_os.id, - }, - timeout=1800000, - ) - yield host - with sat_azure.api_factory.satellite_setting('destroy_vm_on_host_delete=True'): - if sat_azure.cli.Host.exists(search=('name', host['name'])): - sat_azure.cli.Host.delete({'name': self.fullhostname}, timeout=1800000) + with sat_azure.hammer_api_timeout(), sat_azure.skip_yum_update_during_provisioning( + template='Kickstart default user data' + ): + host = sat_azure.cli.Host.create( + { + 'name': self.hostname, + 'compute-attributes': self.compute_attrs, + 'interface': self.interfaces_attributes, + 'image': module_azurerm_cloudimg.name, + 'hostgroup': azurerm_hostgroup.name, + 'location': sat_azure_loc.name, + 'organization': sat_azure_org.name, + 'operatingsystem-id': sat_azure_default_os.id, + }, + timeout=1800000, + ) + yield host + with sat_azure.api_factory.satellite_setting('destroy_vm_on_host_delete=True'): + if sat_azure.cli.Host.exists(search=('name', host['name'])): + sat_azure.cli.Host.delete({'name': self.fullhostname}, timeout=1800000) @pytest.fixture(scope='class') def azureclient_host(self, azurermclient, class_host_ud): diff --git a/tests/foreman/cli/test_computeresource_libvirt.py b/tests/foreman/cli/test_computeresource_libvirt.py index a53959f277b..2a4720750a0 100644 --- a/tests/foreman/cli/test_computeresource_libvirt.py +++ b/tests/foreman/cli/test_computeresource_libvirt.py @@ -364,7 +364,7 @@ def test_negative_update(libvirt_url, options, module_target_sat): # check attributes have not changed assert result['name'] == comp_res['name'] options.pop('new-name', None) - for key in options.keys(): + for key in options: assert comp_res[key] == result[key] diff --git a/tests/foreman/cli/test_contentview.py b/tests/foreman/cli/test_contentview.py index 0b4ee4041ef..9b261f57218 100644 --- a/tests/foreman/cli/test_contentview.py +++ b/tests/foreman/cli/test_contentview.py @@ -233,7 +233,7 @@ def test_positive_update_filter(self, repo_setup, module_target_sat): } ) cvf = module_target_sat.cli.ContentView.filter.info({'id': cvf['filter-id']}) - assert 'security' == cvf['rules'][0]['types'] + assert cvf['rules'][0]['types'] == 'security' @pytest.mark.tier1 def test_positive_delete_by_id(self, module_org, module_target_sat): diff --git a/tests/foreman/cli/test_docker.py b/tests/foreman/cli/test_docker.py index a4dd51c17c2..10b1d1dd4fc 100644 --- a/tests/foreman/cli/test_docker.py +++ b/tests/foreman/cli/test_docker.py @@ -114,7 +114,7 @@ def test_positive_read_docker_tags(self, repo, module_target_sat): manifests_list = module_target_sat.cli.Docker.manifest.list({'repository-id': repo['id']}) # Some manifests do not have tags associated with it, ignore those # because we want to check the tag information - manifests = [m_iter for m_iter in manifests_list if not m_iter['tags'] == ''] + manifests = [m_iter for m_iter in manifests_list if m_iter['tags'] != ''] assert manifests tags_list = module_target_sat.cli.Docker.tag.list({'repository-id': repo['id']}) # Extract tag names for the repository out of docker tag list diff --git a/tests/foreman/cli/test_domain.py b/tests/foreman/cli/test_domain.py index 8b1c157c657..32f81369592 100644 --- a/tests/foreman/cli/test_domain.py +++ b/tests/foreman/cli/test_domain.py @@ -42,8 +42,7 @@ def valid_create_params(): @filtered_datapoint def invalid_create_params(): """Returns a list of invalid domain create parameters""" - params = [{'name': gen_string(str_type='utf8', length=256)}] - return params + return [{'name': gen_string(str_type='utf8', length=256)}] @filtered_datapoint @@ -66,8 +65,7 @@ def valid_update_params(): @filtered_datapoint def invalid_update_params(): """Returns a list of invalid domain update parameters""" - params = [{'name': ''}, {'name': gen_string(str_type='utf8', length=256)}] - return params + return [{'name': ''}, {'name': gen_string(str_type='utf8', length=256)}] @filtered_datapoint @@ -218,7 +216,7 @@ def test_negative_update(module_domain, options, module_target_sat): module_target_sat.cli.Domain.update(dict(options, id=module_domain.id)) # check - domain not updated result = module_target_sat.cli.Domain.info({'id': module_domain.id}) - for key in options.keys(): + for key in options: assert result[key] == getattr(module_domain, key) diff --git a/tests/foreman/cli/test_errata.py b/tests/foreman/cli/test_errata.py index bbfe7af1380..95bdbc3d256 100644 --- a/tests/foreman/cli/test_errata.py +++ b/tests/foreman/cli/test_errata.py @@ -358,7 +358,7 @@ def filter_sort_errata(sat, org, sort_by_date='issued', filter_by_org=None): elif filter_by_org == 'label': list_param['organization-label'] = org.label - sort_reversed = True if sort_order == 'DESC' else False + sort_reversed = sort_order == 'DESC' errata_list = sat.cli.Erratum.list(list_param) assert len(errata_list) > 0 @@ -1275,7 +1275,7 @@ def test_apply_errata_using_default_content_view(errata_host, module_sca_manifes # job invocation started, check status assert 'created' in _job_invoc[0]['message'] assert (_id := _job_invoc[0]['id']) - assert 'succeeded' == target_sat.cli.JobInvocation().info(options={'id': _id})['status'] + assert target_sat.cli.JobInvocation().info(options={'id': _id})['status'] == 'succeeded' start_and_wait_errata_recalculate(target_sat, errata_host) # Assert that the erratum is no longer applicable @@ -1331,7 +1331,7 @@ def test_update_applicable_package_using_default_content_view(errata_host, targe # job invocation created, assert status assert 'created' in _job_invoc[0]['message'] assert (_id := _job_invoc[0]['id']) - assert 'succeeded' == target_sat.cli.JobInvocation().info(options={'id': _id})['status'] + assert target_sat.cli.JobInvocation().info(options={'id': _id})['status'] == 'succeeded' start_and_wait_errata_recalculate(target_sat, errata_host) # Assert that the package is no longer applicable applicable_packages = target_sat.cli.Package.list( diff --git a/tests/foreman/cli/test_filter.py b/tests/foreman/cli/test_filter.py index 9c12b239089..4108ce07d6b 100644 --- a/tests/foreman/cli/test_filter.py +++ b/tests/foreman/cli/test_filter.py @@ -19,13 +19,12 @@ @pytest.fixture(scope='module') def module_perms(module_target_sat): """Search for provisioning template permissions. Set ``cls.ct_perms``.""" - perms = [ + return [ permission['name'] for permission in module_target_sat.cli.Filter.available_permissions( {"search": "resource_type=User"} ) ] - return perms @pytest.fixture diff --git a/tests/foreman/cli/test_host.py b/tests/foreman/cli/test_host.py index 287e59ab9bb..b00540d9323 100644 --- a/tests/foreman/cli/test_host.py +++ b/tests/foreman/cli/test_host.py @@ -232,7 +232,7 @@ def parse_cli_entity_list_help_message(help_message): name = name[:-1] # remove colon from name if 'Usage' in name: continue - elif 'Options' in name: + if 'Options' in name: # used together with previous_line when line (message) is appended to previous line options = parse_two_columns(content, options_start_with_dash=True) elif 'field sets' in name: @@ -1061,18 +1061,18 @@ def test_positive_parameter_crud(function_host, target_sat): {'host-id': function_host['id'], 'name': name, 'value': value} ) host = target_sat.cli.Host.info({'id': function_host['id']}) - assert name in host['parameters'].keys() + assert name in host['parameters'] assert value == host['parameters'][name] new_value = valid_data_list()[name] target_sat.cli.Host.set_parameter({'host-id': host['id'], 'name': name, 'value': new_value}) host = target_sat.cli.Host.info({'id': host['id']}) - assert name in host['parameters'].keys() + assert name in host['parameters'] assert new_value == host['parameters'][name] target_sat.cli.Host.delete_parameter({'host-id': host['id'], 'name': name}) host = target_sat.cli.Host.info({'id': host['id']}) - assert name not in host['parameters'].keys() + assert name not in host['parameters'] # -------------------------- HOST PARAMETER SCENARIOS ------------------------- @@ -1098,7 +1098,7 @@ def test_negative_add_parameter(function_host, target_sat): } ) host = target_sat.cli.Host.info({'id': function_host['id']}) - assert name not in host['parameters'].keys() + assert name not in host['parameters'] @pytest.mark.cli_host_parameter diff --git a/tests/foreman/cli/test_leapp_client.py b/tests/foreman/cli/test_leapp_client.py index 6ab248b0f92..4ea36bbf37a 100644 --- a/tests/foreman/cli/test_leapp_client.py +++ b/tests/foreman/cli/test_leapp_client.py @@ -91,8 +91,7 @@ def function_leapp_cv(module_target_sat, module_sca_manifest_org, leapp_repos, m function_leapp_cv.publish() cvv = function_leapp_cv.read().version[0] cvv.promote(data={'environment_ids': module_leapp_lce.id, 'force': True}) - function_leapp_cv = function_leapp_cv.read() - return function_leapp_cv + return function_leapp_cv.read() @pytest.fixture @@ -121,7 +120,7 @@ def leapp_repos( source = upgrade_path['source_version'] target = upgrade_path['target_version'] all_repos = [] - for rh_repo_key in RHEL_REPOS.keys(): + for rh_repo_key in RHEL_REPOS: release_version = RHEL_REPOS[rh_repo_key]['releasever'] if release_version in str(source) or release_version in target: prod = 'rhel' if 'rhel7' in rh_repo_key else rh_repo_key.split('_')[0] diff --git a/tests/foreman/cli/test_registration.py b/tests/foreman/cli/test_registration.py index 212be27b756..e3bc35fa58b 100644 --- a/tests/foreman/cli/test_registration.py +++ b/tests/foreman/cli/test_registration.py @@ -56,7 +56,7 @@ def test_host_registration_end_to_end( # Verify server.hostname and server.port from subscription-manager config assert module_target_sat.hostname == rhel_contenthost.subscription_config['server']['hostname'] - assert CLIENT_PORT == rhel_contenthost.subscription_config['server']['port'] + assert rhel_contenthost.subscription_config['server']['port'] == CLIENT_PORT # Update module_capsule_configured to include module_org/module_location module_target_sat.cli.Capsule.update( @@ -81,7 +81,7 @@ def test_host_registration_end_to_end( module_capsule_configured.hostname == rhel_contenthost.subscription_config['server']['hostname'] ) - assert CLIENT_PORT == rhel_contenthost.subscription_config['server']['port'] + assert rhel_contenthost.subscription_config['server']['port'] == CLIENT_PORT def test_upgrade_katello_ca_consumer_rpm( @@ -118,7 +118,7 @@ def test_upgrade_katello_ca_consumer_rpm( f'rpm -Uvh "http://{target_sat.hostname}/pub/{consumer_cert_name}-1.0-1.noarch.rpm"' ) # Check server URL is not Red Hat CDN's "subscription.rhsm.redhat.com" - assert 'subscription.rhsm.redhat.com' != vm.subscription_config['server']['hostname'] + assert vm.subscription_config['server']['hostname'] != 'subscription.rhsm.redhat.com' assert target_sat.hostname == vm.subscription_config['server']['hostname'] # Get consumer cert source file @@ -139,7 +139,7 @@ def test_upgrade_katello_ca_consumer_rpm( # Install new rpmbuild/RPMS/noarch/katello-ca-consumer-*-2.noarch.rpm assert vm.execute(f'yum install -y rpmbuild/RPMS/noarch/{new_consumer_cert_rpm}') # Check server URL is not Red Hat CDN's "subscription.rhsm.redhat.com" - assert 'subscription.rhsm.redhat.com' != vm.subscription_config['server']['hostname'] + assert vm.subscription_config['server']['hostname'] != 'subscription.rhsm.redhat.com' assert target_sat.hostname == vm.subscription_config['server']['hostname'] # Register as final check diff --git a/tests/foreman/cli/test_remoteexecution.py b/tests/foreman/cli/test_remoteexecution.py index 2bf4b6a3ba4..c030e54e113 100644 --- a/tests/foreman/cli/test_remoteexecution.py +++ b/tests/foreman/cli/test_remoteexecution.py @@ -47,7 +47,7 @@ def valid_feature_names(): @pytest.fixture def fixture_sca_vmsetup(request, module_sca_manifest_org, target_sat): """Create VM and register content host to Simple Content Access organization""" - if '_count' in request.param.keys(): + if '_count' in request.param: with Broker( nick=request.param['nick'], host_class=ContentHost, diff --git a/tests/foreman/cli/test_reporttemplates.py b/tests/foreman/cli/test_reporttemplates.py index f778eaa802b..9c9bcf0e5a6 100644 --- a/tests/foreman/cli/test_reporttemplates.py +++ b/tests/foreman/cli/test_reporttemplates.py @@ -706,7 +706,7 @@ def test_positive_generate_ansible_template(module_target_sat): :CaseImportance: Medium """ settings = module_target_sat.cli.Settings.list({'search': 'name=ansible_inventory_template'}) - assert 1 == len(settings) + assert len(settings) == 1 template_name = settings[0]['value'] report_list = module_target_sat.cli.ReportTemplate.list() diff --git a/tests/foreman/cli/test_repository.py b/tests/foreman/cli/test_repository.py index cc1a230bd96..db04dfd3305 100644 --- a/tests/foreman/cli/test_repository.py +++ b/tests/foreman/cli/test_repository.py @@ -652,7 +652,7 @@ def test_negative_update_to_invalid_download_policy(self, repo_options, repo, ta **parametrized( [ {'content-type': content_type, 'download-policy': 'on_demand'} - for content_type in REPO_TYPE.keys() + for content_type in REPO_TYPE if content_type != 'yum' if content_type != 'ostree' ] @@ -2660,7 +2660,7 @@ def test_positive_upload_file_to_file_repo(self, repo_options, repo, target_sat) filesearch = entities.File().search( query={"search": f"name={RPM_TO_UPLOAD} and repository={repo['name']}"} ) - assert RPM_TO_UPLOAD == filesearch[0].name + assert filesearch[0].name == RPM_TO_UPLOAD @pytest.mark.tier1 @pytest.mark.upgrade diff --git a/tests/foreman/cli/test_role.py b/tests/foreman/cli/test_role.py index 5eb4e8569f8..7ccdafdf4f1 100644 --- a/tests/foreman/cli/test_role.py +++ b/tests/foreman/cli/test_role.py @@ -296,7 +296,7 @@ def test_system_admin_role_end_to_end(self, target_sat): ).set({'name': "outofsync_interval", 'value': "32"}) sync_time = target_sat.cli.Settings.list({'search': 'name=outofsync_interval'})[0] # Asserts if the setting was updated successfully - assert '32' == sync_time['value'] + assert sync_time['value'] == '32' # Create another System Admin user using the first one system_admin = target_sat.cli.User.with_user( diff --git a/tests/foreman/cli/test_satellitesync.py b/tests/foreman/cli/test_satellitesync.py index dd80e98df8f..aac7d5f5b46 100644 --- a/tests/foreman/cli/test_satellitesync.py +++ b/tests/foreman/cli/test_satellitesync.py @@ -85,8 +85,7 @@ def export_import_cleanup_module(target_sat, module_org): @pytest.fixture def function_import_org(target_sat): """Creates an Organization for content import.""" - org = target_sat.api.Organization().create() - return org + return target_sat.api.Organization().create() @pytest.fixture @@ -152,14 +151,13 @@ def function_synced_rh_repo(request, target_sat, function_sca_manifest_org): # Update the download policy to 'immediate' and sync target_sat.cli.Repository.update({'download-policy': 'immediate', 'id': repo['id']}) target_sat.cli.Repository.synchronize({'id': repo['id']}, timeout='2h') - repo = target_sat.cli.Repository.info( + return target_sat.cli.Repository.info( { 'organization-id': function_sca_manifest_org.id, 'name': repo_dict['name'], 'product': repo_dict['product'], } ) - return repo @pytest.fixture diff --git a/tests/foreman/cli/test_subscription.py b/tests/foreman/cli/test_subscription.py index 90106c867bc..60280f67278 100644 --- a/tests/foreman/cli/test_subscription.py +++ b/tests/foreman/cli/test_subscription.py @@ -28,7 +28,7 @@ def golden_ticket_host_setup(request, module_sca_manifest_org, module_target_sat ) new_repo = module_target_sat.cli_factory.make_repository({'product-id': new_product['id']}) module_target_sat.cli.Repository.synchronize({'id': new_repo['id']}) - new_ak = module_target_sat.cli_factory.make_activation_key( + return module_target_sat.cli_factory.make_activation_key( { 'lifecycle-environment': 'Library', 'content-view': 'Default Organization View', @@ -36,7 +36,6 @@ def golden_ticket_host_setup(request, module_sca_manifest_org, module_target_sat 'auto-attach': False, } ) - return new_ak @pytest.mark.tier1 @@ -166,7 +165,7 @@ def test_positive_subscription_list(function_entitlement_manifest_org, module_ta {'organization-id': function_entitlement_manifest_org.id}, per_page=False ) for column in ['start-date', 'end-date']: - assert column in subscription_list[0].keys() + assert column in subscription_list[0] @pytest.mark.tier2 diff --git a/tests/foreman/cli/test_templatesync.py b/tests/foreman/cli/test_templatesync.py index 9959ae18459..b0cc31b2003 100644 --- a/tests/foreman/cli/test_templatesync.py +++ b/tests/foreman/cli/test_templatesync.py @@ -44,7 +44,7 @@ def setUpClass(self, module_target_sat): """ # Check all Downloadable templates exists - if not requests.get(FOREMAN_TEMPLATE_IMPORT_URL).status_code == 200: + if requests.get(FOREMAN_TEMPLATE_IMPORT_URL).status_code != 200: pytest.fail('The foreman templates git url is not accessible') # Download the Test Template in test running folder diff --git a/tests/foreman/cli/test_user.py b/tests/foreman/cli/test_user.py index c549b9e667a..3646e301db0 100644 --- a/tests/foreman/cli/test_user.py +++ b/tests/foreman/cli/test_user.py @@ -56,8 +56,8 @@ def roles_helper(): for role_name in valid_usernames_list() + include_list: yield module_target_sat.cli_factory.make_role({'name': role_name}) - stubbed_roles = {role['id']: role for role in roles_helper()} - return stubbed_roles + # return stubbed roles + return {role['id']: role for role in roles_helper()} @pytest.mark.parametrize('email', **parametrized(valid_emails_list())) @pytest.mark.tier2 diff --git a/tests/foreman/cli/test_usergroup.py b/tests/foreman/cli/test_usergroup.py index 6ad115d96f6..1c757b4e766 100644 --- a/tests/foreman/cli/test_usergroup.py +++ b/tests/foreman/cli/test_usergroup.py @@ -22,8 +22,7 @@ @pytest.fixture def function_user_group(target_sat): """Create new usergroup per each test""" - user_group = target_sat.cli_factory.usergroup() - return user_group + return target_sat.cli_factory.usergroup() @pytest.mark.tier1 @@ -230,9 +229,9 @@ def test_negative_automate_bz1437578(ldap_auth_source, function_user_group, modu } ) assert ( - 'Could not create external user group: ' + result == 'Could not create external user group: ' 'Name is not found in the authentication source' 'Name Domain Users is a special group in AD.' ' Unfortunately, we cannot obtain membership information' - ' from a LDAP search and therefore sync it.' == result + ' from a LDAP search and therefore sync it.' ) diff --git a/tests/foreman/conftest.py b/tests/foreman/conftest.py index 59616f233b7..e867e118be3 100644 --- a/tests/foreman/conftest.py +++ b/tests/foreman/conftest.py @@ -66,7 +66,8 @@ def ui_session_record_property(request, record_property): test_file_path = request.node.fspath.strpath if any(directory in test_file_path for directory in test_directories): for fixture in request.node.fixturenames: - if request.fixturename != fixture: - if isinstance(request.getfixturevalue(fixture), Satellite): - sat = request.getfixturevalue(fixture) - sat.record_property = record_property + if request.fixturename != fixture and isinstance( + request.getfixturevalue(fixture), Satellite + ): + sat = request.getfixturevalue(fixture) + sat.record_property = record_property diff --git a/tests/foreman/destructive/test_capsule_loadbalancer.py b/tests/foreman/destructive/test_capsule_loadbalancer.py index a0675abec2b..990a61b8f09 100644 --- a/tests/foreman/destructive/test_capsule_loadbalancer.py +++ b/tests/foreman/destructive/test_capsule_loadbalancer.py @@ -273,7 +273,7 @@ def test_client_register_through_lb( loadbalancer_setup['setup_haproxy']['haproxy'].hostname in rhel_contenthost.subscription_config['server']['hostname'] ) - assert CLIENT_PORT == rhel_contenthost.subscription_config['server']['port'] + assert rhel_contenthost.subscription_config['server']['port'] == CLIENT_PORT assert loadbalancer_setup['module_target_sat'].cli.Host.info( {'name': rhel_contenthost.hostname}, output_format='json' )['content-information']['content-source']['name'] in [ @@ -294,7 +294,7 @@ def test_client_register_through_lb( loadbalancer_setup['setup_haproxy']['haproxy'].hostname in rhel_contenthost.subscription_config['server']['hostname'] ) - assert CLIENT_PORT == rhel_contenthost.subscription_config['server']['port'] + assert rhel_contenthost.subscription_config['server']['port'] == CLIENT_PORT hosts = loadbalancer_setup['module_target_sat'].cli.Host.list( {'organization-id': loadbalancer_setup['module_org'].id} diff --git a/tests/foreman/destructive/test_discoveredhost.py b/tests/foreman/destructive/test_discoveredhost.py index bcf73a14ed7..8034957ec72 100644 --- a/tests/foreman/destructive/test_discoveredhost.py +++ b/tests/foreman/destructive/test_discoveredhost.py @@ -34,7 +34,7 @@ def _read_log(ch, pattern): def _wait_for_log(channel, pattern, timeout=5, delay=0.2): """_read_log method enclosed in wait_for method""" - matching_log = wait_for( + return wait_for( _read_log, func_args=( channel, @@ -45,7 +45,6 @@ def _wait_for_log(channel, pattern, timeout=5, delay=0.2): delay=delay, logger=logger, ) - return matching_log def _assert_discovered_host(host, channel=None, user_config=None, sat=None): diff --git a/tests/foreman/destructive/test_ldap_authentication.py b/tests/foreman/destructive/test_ldap_authentication.py index 304c608734a..58f3121dbec 100644 --- a/tests/foreman/destructive/test_ldap_authentication.py +++ b/tests/foreman/destructive/test_ldap_authentication.py @@ -198,9 +198,8 @@ def test_positive_create_with_https( assert ldap_source['ldap_server']['port'] == '636' with module_target_sat.ui_session( test_name, username, auth_data['ldap_user_passwd'] - ) as ldapsession: - with pytest.raises(NavigationTriesExceeded): - ldapsession.user.search('') + ) as ldapsession, pytest.raises(NavigationTriesExceeded): + ldapsession.user.search('') assert module_target_sat.api.User().search(query={'search': f'login="{username}"'}) diff --git a/tests/foreman/destructive/test_realm.py b/tests/foreman/destructive/test_realm.py index a4baa15e7bf..cbddcdc3bc8 100644 --- a/tests/foreman/destructive/test_realm.py +++ b/tests/foreman/destructive/test_realm.py @@ -87,7 +87,7 @@ def test_positive_realm_info_name( ) request.addfinalizer(lambda: module_target_sat.cli.Realm.delete({'id': realm['id']})) info = module_target_sat.cli.Realm.info({'name': realm['name']}) - for key in info.keys(): + for key in info: assert info[key] == realm[key] @@ -115,7 +115,7 @@ def test_positive_realm_info_id( ) request.addfinalizer(lambda: module_target_sat.cli.Realm.delete({'id': realm['id']})) info = module_target_sat.cli.Realm.info({'id': realm['id']}) - for key in info.keys(): + for key in info: assert info[key] == realm[key] assert info == module_target_sat.cli.Realm.info({'id': realm['id']}) diff --git a/tests/foreman/longrun/test_inc_updates.py b/tests/foreman/longrun/test_inc_updates.py index 5c648609222..d47f6ef5677 100644 --- a/tests/foreman/longrun/test_inc_updates.py +++ b/tests/foreman/longrun/test_inc_updates.py @@ -53,11 +53,10 @@ def dev_lce(module_entitlement_manifest_org): @pytest.fixture(scope='module') -def qe_lce(module_entitlement_manifest_org, dev_lce): - qe_lce = entities.LifecycleEnvironment( - name='QE', prior=dev_lce, organization=module_entitlement_manifest_org +def qe_lce(module_sca_manifest_org, dev_lce): + return entities.LifecycleEnvironment( + name='QE', prior=dev_lce, organization=module_sca_manifest_org ).create() - return qe_lce @pytest.fixture(scope='module') @@ -95,8 +94,7 @@ def module_cv(module_entitlement_manifest_org, rhel7_sat6tools_repo, custom_repo repository=[rhel7_sat6tools_repo.id, custom_repo.id], ).create() module_cv.publish() - module_cv = module_cv.read() - return module_cv + return module_cv.read() @pytest.fixture(scope='module') diff --git a/tests/foreman/longrun/test_oscap.py b/tests/foreman/longrun/test_oscap.py index 045f18db639..53777de356b 100644 --- a/tests/foreman/longrun/test_oscap.py +++ b/tests/foreman/longrun/test_oscap.py @@ -70,10 +70,7 @@ def default_proxy(module_target_sat): @pytest.fixture(scope='module') def lifecycle_env(module_org): """Create lifecycle environment""" - lce_env = entities.LifecycleEnvironment( - organization=module_org, name=gen_string('alpha') - ).create() - return lce_env + return entities.LifecycleEnvironment(organization=module_org, name=gen_string('alpha')).create() @pytest.fixture(scope='module') diff --git a/tests/foreman/maintain/test_advanced.py b/tests/foreman/maintain/test_advanced.py index 2771994d568..2453f27a3ae 100644 --- a/tests/foreman/maintain/test_advanced.py +++ b/tests/foreman/maintain/test_advanced.py @@ -28,13 +28,12 @@ def get_satellite_capsule_repos( os_major_ver = get_sat_rhel_version().major if product == 'capsule': product = 'satellite-capsule' - repos = [ + return [ f'{product}-{x_y_release}-for-rhel-{os_major_ver}-x86_64-rpms', f'satellite-maintenance-{x_y_release}-for-rhel-{os_major_ver}-x86_64-rpms', f'rhel-{os_major_ver}-for-x86_64-baseos-rpms', f'rhel-{os_major_ver}-for-x86_64-appstream-rpms', ] - return repos def test_positive_advanced_run_service_restart(sat_maintain): diff --git a/tests/foreman/ui/test_acs.py b/tests/foreman/ui/test_acs.py index 726a60c9ccb..40da1c22002 100644 --- a/tests/foreman/ui/test_acs.py +++ b/tests/foreman/ui/test_acs.py @@ -239,7 +239,7 @@ def gen_params(): # It loops through the keys in the parameters dictionary, and uses the keys to create a scenario ID # and then it uses the scenario ID to access the scenario values from the parameters dictionary. # The code then adds the scenario values to the list of scenario values. - for acs in parameters_dict.keys(): + for acs in parameters_dict: if not acs.startswith('_'): for cnt in parameters_dict[acs]: if not cnt.startswith('_'): diff --git a/tests/foreman/ui/test_capsulecontent.py b/tests/foreman/ui/test_capsulecontent.py index f2e8db514e3..43fc34b430f 100644 --- a/tests/foreman/ui/test_capsulecontent.py +++ b/tests/foreman/ui/test_capsulecontent.py @@ -229,4 +229,4 @@ def test_positive_content_counts_for_mixed_cv( # Remove the LCEs from Capsule and ensure they are not listed anymore. session.capsule.edit(module_capsule_configured.hostname, remove_all_lces=True) details = session.capsule.read_details(module_capsule_configured.hostname) - assert 'content' not in details.keys(), 'Content still listed for removed LCEs' + assert 'content' not in details, 'Content still listed for removed LCEs' diff --git a/tests/foreman/ui/test_containerimagetag.py b/tests/foreman/ui/test_containerimagetag.py index 86fb97ebab1..b46cc15bc4e 100644 --- a/tests/foreman/ui/test_containerimagetag.py +++ b/tests/foreman/ui/test_containerimagetag.py @@ -71,5 +71,5 @@ def test_positive_search(session, module_org, module_product, module_repository) None, ) assert module_product.name == repo_line['Product'] - assert DEFAULT_CV == repo_line['Content View'] + assert repo_line['Content View'] == DEFAULT_CV assert 'Success' in repo_line['Last Sync'] diff --git a/tests/foreman/ui/test_contenthost.py b/tests/foreman/ui/test_contenthost.py index ffbe571c5b2..5f351076e5b 100644 --- a/tests/foreman/ui/test_contenthost.py +++ b/tests/foreman/ui/test_contenthost.py @@ -116,7 +116,7 @@ def get_rhel_lifecycle_support(rhel_version): rhel_lifecycle_status = 'Unknown' if rhel_version not in rhels: return rhel_lifecycle_status - elif rhels.index(rhel_version) <= 1: + if rhels.index(rhel_version) <= 1: rhel_lifecycle_status = 'Full support' elif rhels.index(rhel_version) == 2: rhel_lifecycle_status = 'Approaching end of maintenance support' diff --git a/tests/foreman/ui/test_discoveredhost.py b/tests/foreman/ui/test_discoveredhost.py index 92ea28d185a..64476188f89 100644 --- a/tests/foreman/ui/test_discoveredhost.py +++ b/tests/foreman/ui/test_discoveredhost.py @@ -40,8 +40,7 @@ def _is_host_reachable(host, retries=12, iteration_sleep=5, expect_reachable=Tru result = ssh.command(cmd.format(retries, host, operator, iteration_sleep)) if expect_reachable: return not result.status - else: - return bool(result.status) + return bool(result.status) @pytest.mark.tier3 diff --git a/tests/foreman/ui/test_host.py b/tests/foreman/ui/test_host.py index b3564fb04b1..6db27252587 100644 --- a/tests/foreman/ui/test_host.py +++ b/tests/foreman/ui/test_host.py @@ -60,7 +60,7 @@ def ui_user(ui_user, smart_proxy_location, module_target_sat): @pytest.fixture def scap_policy(scap_content, target_sat): - scap_policy = target_sat.cli_factory.make_scap_policy( + return target_sat.cli_factory.make_scap_policy( { 'name': gen_string('alpha'), 'deploy-by': 'ansible', @@ -70,7 +70,6 @@ def scap_policy(scap_content, target_sat): 'weekday': OSCAP_WEEKDAY['friday'].lower(), } ) - return scap_policy second_scap_policy = scap_policy @@ -1090,8 +1089,8 @@ def test_rex_new_ui(session, target_sat, rex_contenthost): task_status = target_sat.api.ForemanTask(id=task_result[0].id).poll() assert task_status['result'] == 'success' recent_jobs = session.host_new.get_details(hostname, "overview.recent_jobs")['overview'] - assert "Run ls" == recent_jobs['recent_jobs']['finished']['table'][0]['column0'] - assert "succeeded" == recent_jobs['recent_jobs']['finished']['table'][0]['column2'] + assert recent_jobs['recent_jobs']['finished']['table'][0]['column0'] == "Run ls" + assert recent_jobs['recent_jobs']['finished']['table'][0]['column2'] == "succeeded" @pytest.mark.tier4 @@ -1216,18 +1215,18 @@ def test_positive_update_delete_package( if not is_open('BZ:2132680'): product_name = module_repos_collection_with_setup.custom_product.name repos = session.host_new.get_repo_sets(client.hostname, product_name) - assert 'Enabled' == repos[0].status + assert repos[0].status == 'Enabled' session.host_new.override_repo_sets( client.hostname, product_name, "Override to disabled" ) - assert 'Disabled' == repos[0].status + assert repos[0].status == 'Disabled' session.host_new.install_package(client.hostname, FAKE_8_CUSTOM_PACKAGE_NAME) result = client.run(f'yum install -y {FAKE_7_CUSTOM_PACKAGE}') assert result.status != 0 session.host_new.override_repo_sets( client.hostname, product_name, "Override to enabled" ) - assert 'Enabled' == repos[0].status + assert repos[0].status == 'Enabled' # refresh repos on system client.run('subscription-manager repos') # install package @@ -1284,7 +1283,7 @@ def test_positive_update_delete_package( task_status = target_sat.api.ForemanTask(id=task_result[0].id).poll() assert task_status['result'] == 'success' packages = session.host_new.get_packages(client.hostname, FAKE_8_CUSTOM_PACKAGE_NAME) - assert 'table' not in packages.keys() + assert 'table' not in packages result = client.run(f'rpm -q {FAKE_8_CUSTOM_PACKAGE}') assert result.status != 0 @@ -1361,7 +1360,7 @@ def test_positive_apply_erratum( assert task_status['result'] == 'success' # verify values = session.host_new.get_details(client.hostname, widget_names='content.errata') - assert 'table' not in values['content']['errata'].keys() + assert 'table' not in values['content']['errata'] result = client.run( 'yum update --assumeno --security | grep "No packages needed for security"' ) diff --git a/tests/foreman/ui/test_hostcollection.py b/tests/foreman/ui/test_hostcollection.py index 546e70faae0..b6c90d685ec 100644 --- a/tests/foreman/ui/test_hostcollection.py +++ b/tests/foreman/ui/test_hostcollection.py @@ -93,10 +93,9 @@ def vm_host_collection(module_target_sat, module_org_with_parameter, vm_content_ module_target_sat.api.Host().search(query={'search': f'name={host.hostname}'})[0].id for host in vm_content_hosts ] - host_collection = module_target_sat.api.HostCollection( + return module_target_sat.api.HostCollection( host=host_ids, organization=module_org_with_parameter ).create() - return host_collection @pytest.fixture @@ -107,10 +106,9 @@ def vm_host_collection_module_stream( module_target_sat.api.Host().search(query={'search': f'name={host.hostname}'})[0].id for host in vm_content_hosts_module_stream ] - host_collection = module_target_sat.api.HostCollection( + return module_target_sat.api.HostCollection( host=host_ids, organization=module_org_with_parameter ).create() - return host_collection def _run_remote_command_on_content_hosts(command, vm_clients): @@ -136,7 +134,7 @@ def _is_package_installed( if result.status == 0 and expect_installed: installed += 1 break - elif result.status != 0 and not expect_installed: + if result.status != 0 and not expect_installed: installed -= 1 break if ind < retries - 1: @@ -146,8 +144,7 @@ def _is_package_installed( if expect_installed: return installed == len(vm_clients) - else: - return bool(installed) + return bool(installed) def _install_package_with_assertion(vm_clients, package_name): diff --git a/tests/foreman/ui/test_ldap_authentication.py b/tests/foreman/ui/test_ldap_authentication.py index 8c799a72dc8..6fcb71a7efa 100644 --- a/tests/foreman/ui/test_ldap_authentication.py +++ b/tests/foreman/ui/test_ldap_authentication.py @@ -406,9 +406,8 @@ def test_positive_delete_external_roles( ) with target_sat.ui_session( test_name, ldap_data['ldap_user_name'], ldap_data['ldap_user_passwd'] - ) as ldapsession: - with pytest.raises(NavigationTriesExceeded): - ldapsession.location.create({'name': gen_string('alpha')}) + ) as ldapsession, pytest.raises(NavigationTriesExceeded): + ldapsession.location.create({'name': gen_string('alpha')}) @pytest.mark.parametrize('ldap_auth_source', ['AD', 'IPA'], indirect=True) @@ -677,7 +676,7 @@ def test_positive_add_katello_role_with_org( results = session.activationkey.search(ak_name) assert results[0]['Name'] == ak_name session.organization.select(different_org.name) - assert not session.activationkey.search(ak_name)[0]['Name'] == ak_name + assert session.activationkey.search(ak_name)[0]['Name'] != ak_name ak = ( target_sat.api.ActivationKey(organization=module_org) .search(query={'search': f'name={ak_name}'})[0] @@ -761,9 +760,8 @@ def test_positive_login_user_basic_roles( target_sat.api_factory.create_role_permissions(role, permissions) with target_sat.ui_session( test_name, ldap_data['ldap_user_name'], ldap_data['ldap_user_passwd'] - ) as ldapsession: - with pytest.raises(NavigationTriesExceeded): - ldapsession.usergroup.search('') + ) as ldapsession, pytest.raises(NavigationTriesExceeded): + ldapsession.usergroup.search('') with session: session.user.update(ldap_data['ldap_user_name'], {'roles.resources.assigned': [role.name]}) with target_sat.ui_session( @@ -796,9 +794,8 @@ def test_positive_login_user_password_otp( ) with target_sat.ui_session( test_name, default_ipa_host.ipa_otp_username, otp_pass - ) as ldapsession: - with pytest.raises(NavigationTriesExceeded): - ldapsession.user.search('') + ) as ldapsession, pytest.raises(NavigationTriesExceeded): + ldapsession.user.search('') users = target_sat.api.User().search( query={'search': f'login="{default_ipa_host.ipa_otp_username}"'} ) @@ -1215,12 +1212,11 @@ def test_userlist_with_external_admin( # verify the users count with local admin and remote/external admin with target_sat.ui_session( user=idm_admin, password=settings.server.ssh_password - ) as remote_admin_session: - with target_sat.ui_session( - user=settings.server.admin_username, password=settings.server.admin_password - ) as local_admin_session: - assert local_admin_session.user.search(idm_user)[0]['Username'] == idm_user - assert remote_admin_session.user.search(idm_user)[0]['Username'] == idm_user + ) as remote_admin_session, target_sat.ui_session( + user=settings.server.admin_username, password=settings.server.admin_password + ) as local_admin_session: + assert local_admin_session.user.search(idm_user)[0]['Username'] == idm_user + assert remote_admin_session.user.search(idm_user)[0]['Username'] == idm_user @pytest.mark.skip_if_open('BZ:1883209') diff --git a/tests/foreman/ui/test_organization.py b/tests/foreman/ui/test_organization.py index 8a3651b0ade..83fc999d907 100644 --- a/tests/foreman/ui/test_organization.py +++ b/tests/foreman/ui/test_organization.py @@ -342,7 +342,7 @@ def test_positive_product_view_organization_switch(session, module_org, module_p with session: assert session.product.search(module_product.name) session.organization.select(org_name="Default Organization") - assert not session.product.search(module_product.name) == module_product.name + assert session.product.search(module_product.name) != module_product.name @pytest.mark.tier2 diff --git a/tests/foreman/ui/test_provisioningtemplate.py b/tests/foreman/ui/test_provisioningtemplate.py index bc88d687f88..da2b8446dce 100644 --- a/tests/foreman/ui/test_provisioningtemplate.py +++ b/tests/foreman/ui/test_provisioningtemplate.py @@ -200,7 +200,7 @@ def test_positive_verify_supported_templates_rhlogo(target_sat, module_org, modu with target_sat.ui_session() as session: session.organization.select(org_name=module_org.name) session.location.select(loc_name=module_location.name) - for template in random_templates.keys(): + for template in random_templates: assert ( session.provisioningtemplate.is_locked(template) == random_templates[template]['locked'] diff --git a/tests/foreman/ui/test_registration.py b/tests/foreman/ui/test_registration.py index 22c34545ac7..51d608eec4d 100644 --- a/tests/foreman/ui/test_registration.py +++ b/tests/foreman/ui/test_registration.py @@ -539,7 +539,7 @@ def test_positive_host_registration_with_non_admin_user( # Verify server.hostname and server.port from subscription-manager config assert target_sat.hostname == rhel8_contenthost.subscription_config['server']['hostname'] - assert constants.CLIENT_PORT == rhel8_contenthost.subscription_config['server']['port'] + assert rhel8_contenthost.subscription_config['server']['port'] == constants.CLIENT_PORT @pytest.mark.tier2 diff --git a/tests/foreman/ui/test_subscription.py b/tests/foreman/ui/test_subscription.py index 9981e371cd8..45bfcd47d91 100644 --- a/tests/foreman/ui/test_subscription.py +++ b/tests/foreman/ui/test_subscription.py @@ -93,9 +93,8 @@ def test_positive_end_to_end(session, target_sat): ] org = target_sat.api.Organization().create() _, temporary_local_manifest_path = mkstemp(prefix='manifest-', suffix='.zip') - with clone() as manifest: - with open(temporary_local_manifest_path, 'wb') as file_handler: - file_handler.write(manifest.content.read()) + with clone() as manifest, open(temporary_local_manifest_path, 'wb') as file_handler: + file_handler.write(manifest.content.read()) with session: session.organization.select(org.name) # Ignore "Danger alert: Katello::Errors::UpstreamConsumerNotFound'" as server will connect diff --git a/tests/robottelo/conftest.py b/tests/robottelo/conftest.py index d8ffb1ad75b..dbd1fe41b50 100644 --- a/tests/robottelo/conftest.py +++ b/tests/robottelo/conftest.py @@ -1,3 +1,4 @@ +import contextlib import glob import os from pathlib import Path @@ -44,8 +45,6 @@ def exec_test(request, dummy_test): yield report_file for logfile in glob.glob('robottelo*.log'): os.remove(logfile) - try: - os.remove(report_file) - except OSError: + with contextlib.suppress(OSError): # the file might not exist if the test fails prematurely - pass + os.remove(report_file) diff --git a/tests/robottelo/test_cli.py b/tests/robottelo/test_cli.py index fcc583eaee0..debbc8c6e42 100644 --- a/tests/robottelo/test_cli.py +++ b/tests/robottelo/test_cli.py @@ -146,9 +146,9 @@ def assert_response_error(self, expected_error, stderr='some error'): def test_add_operating_system(self, construct, execute): """Check command_sub edited when executing add_operating_system""" options = {'foo': 'bar'} - assert 'add-operatingsystem' != Base.command_sub + assert Base.command_sub != 'add-operatingsystem' assert execute.return_value == Base.add_operating_system(options) - assert 'add-operatingsystem' == Base.command_sub + assert Base.command_sub == 'add-operatingsystem' construct.called_once_with(options) execute.called_once_with(construct.return_value) @@ -158,7 +158,7 @@ def test_add_create_with_empty_result(self, construct, execute): """Check command create when result is empty""" execute.return_value = [] assert execute.return_value == Base.create() - assert 'create' == Base.command_sub + assert Base.command_sub == 'create' construct.called_once_with({}) execute.called_once_with(construct.return_value, output_format='csv') @@ -169,7 +169,7 @@ def test_add_create_with_result_dct_without_id(self, construct, execute, info): """Check command create when result has dct but dct hasn't id key""" execute.return_value = [{'not_id': 'foo'}] assert execute.return_value == Base.create() - assert 'create' == Base.command_sub + assert Base.command_sub == 'create' construct.called_once_with({}) execute.called_once_with(construct.return_value, output_format='csv') assert not info.called @@ -184,7 +184,7 @@ def test_add_create_with_result_dct_with_id_not_required_org(self, construct, ex execute.return_value = [{'id': 'foo', 'bar': 'bas'}] Base.command_requires_org = False assert execute.return_value == Base.create() - assert 'create' == Base.command_sub + assert Base.command_sub == 'create' construct.called_once_with({}) execute.called_once_with(construct.return_value, output_format='csv') info.called_once_with({'id': 'foo'}) @@ -199,7 +199,7 @@ def test_add_create_with_result_dct_with_id_required_org(self, construct, execut execute.return_value = [{'id': 'foo', 'bar': 'bas'}] Base.command_requires_org = True assert execute.return_value == Base.create({'organization-id': 'org-id'}) - assert 'create' == Base.command_sub + assert Base.command_sub == 'create' construct.called_once_with({}) execute.called_once_with(construct.return_value, output_format='csv') info.called_once_with({'id': 'foo', 'organization-id': 'org-id'}) @@ -214,7 +214,7 @@ def test_add_create_with_result_dct_id_required_org_error(self, construct, execu Base.command_requires_org = True with pytest.raises(CLIError): Base.create() - assert 'create' == Base.command_sub + assert Base.command_sub == 'create' construct.called_once_with({}) execute.called_once_with(construct.return_value, output_format='csv') @@ -298,7 +298,7 @@ def test_exists_with_option_and_no_empty_return(self, lst_method): my_options = {'search': 'foo=bar'} response = Base.exists(my_options, search=['id', 1]) lst_method.assert_called_once_with(my_options) - assert 1 == response + assert response == 1 @mock.patch('robottelo.cli.base.Base.command_requires_org') def test_info_requires_organization_id(self, _): # noqa: PT019 - not a fixture @@ -347,7 +347,7 @@ def test_info_parsing_response(self, construct, execute, parse): def test_list_with_default_per_page(self, construct, execute): """Check list method set per_page as 1000 by default""" assert execute.return_value == Base.list(options={'organization-id': 1}) - assert 'list' == Base.command_sub + assert Base.command_sub == 'list' construct.called_once_with({'per-page': 1000}) execute.called_once_with(construct.return_value, output_format='csv') diff --git a/tests/robottelo/test_decorators.py b/tests/robottelo/test_decorators.py index 0f8ac441ce9..6c5e60f568a 100644 --- a/tests/robottelo/test_decorators.py +++ b/tests/robottelo/test_decorators.py @@ -28,12 +28,12 @@ def test_create_and_not_add_to_cache(self, make_foo): """ make_foo(cached=False) assert 'foo' not in decorators.OBJECT_CACHE - assert decorators.OBJECT_CACHE == {} + assert {} == decorators.OBJECT_CACHE def test_build_cache(self, make_foo): """Create a new object and add it to the cache.""" obj = make_foo(cached=True) - assert decorators.OBJECT_CACHE == {'foo': {'id': 42}} + assert {'foo': {'id': 42}} == decorators.OBJECT_CACHE assert id(decorators.OBJECT_CACHE['foo']) == id(obj) def test_return_from_cache(self, make_foo): diff --git a/tests/robottelo/test_dependencies.py b/tests/robottelo/test_dependencies.py index 185f0866737..78b0dc499ea 100644 --- a/tests/robottelo/test_dependencies.py +++ b/tests/robottelo/test_dependencies.py @@ -1,4 +1,5 @@ """Test important behavior in robottelo's direct dependencies""" +import contextlib def test_cryptography(): @@ -115,10 +116,8 @@ def test_tenacity(): def test(): raise Exception('test') - try: + with contextlib.suppress(Exception): test() - except Exception: - pass def test_testimony(): diff --git a/tests/robottelo/test_func_locker.py b/tests/robottelo/test_func_locker.py index ad4ab5c74aa..d0da97431e0 100644 --- a/tests/robottelo/test_func_locker.py +++ b/tests/robottelo/test_func_locker.py @@ -35,9 +35,7 @@ def __init__(self): def read(self): with open(self.file_name) as cf: - content = cf.read() - - return content + return cf.read() def write(self, content): with open(self.file_name, 'wb') as cf: @@ -98,9 +96,10 @@ def simple_recursive_locking_function(): """try to trigger the same lock from the same process, an exception should be expected """ - with func_locker.locking_function(simple_locked_function): - with func_locker.locking_function(simple_locked_function): - pass + with func_locker.locking_function(simple_locked_function), func_locker.locking_function( + simple_locked_function + ): + pass return 'I should not be reached' @@ -126,9 +125,10 @@ def simple_function_to_lock(): def simple_with_locking_function(index=None): global counter_file time.sleep(0.05) - with func_locker.locking_function(simple_locked_function): - with open(_get_function_lock_path('simple_locked_function')) as rf: - content = rf.read() + with func_locker.locking_function(simple_locked_function), open( + _get_function_lock_path('simple_locked_function') + ) as rf: + content = rf.read() if index is not None: saved_counter = int(counter_file.read()) @@ -169,7 +169,7 @@ def simple_scoped_lock_function(): """This function do nothing, when called the lock function must create a lock file """ - return None + return @func_locker.lock_function @@ -182,14 +182,14 @@ def simple_scoped_locking_function(): ): pass - return None + return def simple_function_not_locked(): """This function do nothing, when called with locking, exception must be raised that this function is not locked """ - return None + return class TestFuncLocker: @@ -234,9 +234,10 @@ def test_locker_file_location_when_in_class(self): content = '' assert str(os.getpid()) != content - with func_locker.locking_function(SimpleClass.simple_function_to_lock): - with open(file_path) as rf: - content = rf.read() + with func_locker.locking_function(SimpleClass.simple_function_to_lock), open( + file_path + ) as rf: + content = rf.read() assert str(os.getpid()) == content @@ -248,9 +249,10 @@ def test_locker_file_location_when_in_class(self): content = '' assert str(os.getpid()) != content - with func_locker.locking_function(SimpleClass.simple_function_to_lock_cls): - with open(file_path) as rf: - content = rf.read() + with func_locker.locking_function(SimpleClass.simple_function_to_lock_cls), open( + file_path + ) as rf: + content = rf.read() assert str(os.getpid()) == content @@ -294,9 +296,10 @@ def test_locker_file_location_when_in_class(self): else: content = '' assert str(os.getpid()) != content - with func_locker.locking_function(SimpleClass.SubClass.simple_function_to_lock_cls): - with open(file_path) as rf: - content = rf.read() + with func_locker.locking_function(SimpleClass.SubClass.simple_function_to_lock_cls), open( + file_path + ) as rf: + content = rf.read() assert str(os.getpid()) == content @@ -407,7 +410,7 @@ def test_scoped_with_locking(self): assert os.path.exists(lock_file_path) def test_negative_with_locking_not_locked(self): - - with pytest.raises(func_locker.FunctionLockerError, match=r'.*Cannot ensure locking.*'): - with func_locker.locking_function(simple_function_not_locked): - pass + with pytest.raises( + func_locker.FunctionLockerError, match=r'.*Cannot ensure locking.*' + ), func_locker.locking_function(simple_function_not_locked): + pass diff --git a/tests/upgrades/conftest.py b/tests/upgrades/conftest.py index d75929cb7b4..4c759f66b72 100644 --- a/tests/upgrades/conftest.py +++ b/tests/upgrades/conftest.py @@ -154,8 +154,7 @@ def get_entity_data(scenario_name): """ with open('scenario_entities') as pref: entity_data = json.load(pref) - entity_data = entity_data.get(scenario_name) - return entity_data + return entity_data.get(scenario_name) def get_all_entity_data(): @@ -171,8 +170,7 @@ def get_all_entity_data(): with scenario_name as keys and corresponding attribute data as values. """ with open('scenario_entities') as pref: - entity_data = json.load(pref) - return entity_data + return json.load(pref) def _read_test_data(test_node_id): @@ -334,17 +332,18 @@ def __initiate(config): global POST_UPGRADE global PRE_UPGRADE_TESTS_FILE_PATH PRE_UPGRADE_TESTS_FILE_PATH = getattr(config.option, PRE_UPGRADE_TESTS_FILE_OPTION) - if not [ - upgrade_mark - for upgrade_mark in (PRE_UPGRADE_MARK, POST_UPGRADE_MARK) - if upgrade_mark in config.option.markexpr - ]: - # Raise only if the `tests/upgrades` directory is selected - if 'upgrades' in config.args[0]: - pytest.fail( - f'For upgrade scenarios either {PRE_UPGRADE_MARK} or {POST_UPGRADE_MARK} mark ' - 'must be provided' - ) + if ( + not [ + upgrade_mark + for upgrade_mark in (PRE_UPGRADE_MARK, POST_UPGRADE_MARK) + if upgrade_mark in config.option.markexpr + ] + and 'upgrades' in config.args[0] + ): # Raise only if the `tests/upgrades` directory is selected + pytest.fail( + f'For upgrade scenarios either {PRE_UPGRADE_MARK} or {POST_UPGRADE_MARK} mark ' + 'must be provided' + ) if PRE_UPGRADE_MARK in config.option.markexpr: pre_upgrade_failed_tests = [] PRE_UPGRADE = True diff --git a/tests/upgrades/test_activation_key.py b/tests/upgrades/test_activation_key.py index bac55d78c35..11d37ccdab0 100644 --- a/tests/upgrades/test_activation_key.py +++ b/tests/upgrades/test_activation_key.py @@ -39,8 +39,7 @@ def activation_key_setup(self, request, target_sat): ak = target_sat.api.ActivationKey( content_view=cv, organization=org, name=f"{request.param}_ak" ).create() - ak_details = {'org': org, "cv": cv, 'ak': ak, 'custom_repo': custom_repo} - return ak_details + return {'org': org, "cv": cv, 'ak': ak, 'custom_repo': custom_repo} @pytest.mark.pre_upgrade @pytest.mark.parametrize( diff --git a/tests/upgrades/test_classparameter.py b/tests/upgrades/test_classparameter.py index ba63148b102..b7f8d1c6ed1 100644 --- a/tests/upgrades/test_classparameter.py +++ b/tests/upgrades/test_classparameter.py @@ -82,7 +82,7 @@ def _validate_value(self, data, sc_param): :param sc_param: The Actual Value of parameter """ if data['sc_type'] == 'boolean': - assert sc_param.default_value == (True if data['value'] == '1' else False) + assert sc_param.default_value == (data['value'] == '1') elif data['sc_type'] == 'array': string_list = [str(element) for element in sc_param.default_value] assert str(string_list) == data['value'] diff --git a/tests/upgrades/test_host.py b/tests/upgrades/test_host.py index 642fef7f2b5..5d0e9fda247 100644 --- a/tests/upgrades/test_host.py +++ b/tests/upgrades/test_host.py @@ -72,7 +72,7 @@ def class_host( Later in tests this host will be used to perform assertions """ - host = sat_gce.api.Host( + return sat_gce.api.Host( architecture=sat_gce_default_architecture, compute_attributes=self.compute_attrs, domain=sat_gce_domain, @@ -85,7 +85,6 @@ def class_host( image=module_gce_finishimg, root_pass=gen_string('alphanumeric'), ).create() - return host def google_host(self, googleclient): """Returns the Google Client Host object to perform the assertions""" diff --git a/tests/upgrades/test_puppet.py b/tests/upgrades/test_puppet.py index 5cf7b4e9ae6..b0c96394cc8 100644 --- a/tests/upgrades/test_puppet.py +++ b/tests/upgrades/test_puppet.py @@ -18,8 +18,7 @@ def upgrade_server(request, module_target_sat, pre_configured_capsule): if request.param: return module_target_sat - else: - return pre_configured_capsule + return pre_configured_capsule class TestPuppet: diff --git a/tests/upgrades/test_satellite_maintain.py b/tests/upgrades/test_satellite_maintain.py index 5091f8508fd..6029078bdb6 100644 --- a/tests/upgrades/test_satellite_maintain.py +++ b/tests/upgrades/test_satellite_maintain.py @@ -35,8 +35,7 @@ def satellite_upgradable_version_list(sat_obj): cmd = 'satellite-maintain upgrade list-versions --disable-self-upgrade' list_versions = sat_obj.execute(cmd).stdout regex = re.compile(r'^\d+\.\d+') - upgradeable_versions = [version for version in list_versions if regex.match(version)] - return upgradeable_versions + return [version for version in list_versions if regex.match(version)] @pytest.mark.pre_upgrade def test_pre_satellite_maintain_upgrade_list_versions(self, target_sat): diff --git a/tests/upgrades/test_subscription.py b/tests/upgrades/test_subscription.py index 70e8b53f9c1..116d8956120 100644 --- a/tests/upgrades/test_subscription.py +++ b/tests/upgrades/test_subscription.py @@ -70,7 +70,7 @@ def test_post_manifest_scenario_refresh(self, request, target_sat, pre_upgrade_d history = target_sat.api.Subscription(organization=org).manifest_history( data={'organization_id': org.id} ) - assert "Subscriptions deleted by foreman_admin" == history[0]['statusMessage'] + assert history[0]['statusMessage'] == "Subscriptions deleted by foreman_admin" class TestSubscriptionAutoAttach: