From 1c3a2fc1fc053246925fe2f48d6284db8f17b4be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Gajdu=C5=A1ek?= Date: Thu, 7 Mar 2024 17:04:10 +0100 Subject: [PATCH 1/2] Add flake8-simplify and flake8-return to ruff config (#14100) (cherry picked from commit db19610b89dd4577b59f27555382c4aa736eaa3d) --- conf/dynaconf_hooks.py | 3 +- pyproject.toml | 2 + pytest_fixtures/component/activationkey.py | 12 +-- pytest_fixtures/component/architecture.py | 6 +- pytest_fixtures/component/contentview.py | 3 +- pytest_fixtures/component/os.py | 3 +- pytest_fixtures/component/provision_azure.py | 24 ++--- .../component/provision_capsule_pxe.py | 2 +- pytest_fixtures/component/provision_gce.py | 18 ++-- pytest_fixtures/component/provision_pxe.py | 2 +- pytest_fixtures/component/provision_vmware.py | 3 +- .../component/provisioning_template.py | 7 +- pytest_fixtures/component/puppet.py | 6 +- pytest_fixtures/component/repository.py | 6 +- pytest_fixtures/component/rh_cloud.py | 3 +- pytest_fixtures/component/satellite_auth.py | 3 +- pytest_fixtures/component/user.py | 3 +- pytest_fixtures/core/broker.py | 1 + pytest_fixtures/core/reporting.py | 15 +-- pytest_fixtures/core/ui.py | 9 +- pytest_fixtures/core/upgrade.py | 3 +- pytest_plugins/fixture_markers.py | 3 +- pytest_plugins/logging_hooks.py | 64 +++++++------ pytest_plugins/rerun_rp/rerun_rp.py | 2 +- pytest_plugins/sanity_plugin.py | 10 +- pytest_plugins/settings_skip.py | 2 +- pytest_plugins/upgrade/scenario_workers.py | 1 + pytest_plugins/video_cleanup.py | 23 +++-- robottelo/cli/base.py | 18 +--- robottelo/cli/capsule.py | 36 ++------ robottelo/cli/hammer.py | 10 +- robottelo/cli/host.py | 16 +--- robottelo/cli/lifecycleenvironment.py | 4 +- robottelo/cli/operatingsys.py | 24 ++--- robottelo/cli/product.py | 12 +-- robottelo/cli/srpm.py | 8 +- robottelo/cli/template.py | 8 +- robottelo/cli/template_sync.py | 8 +- robottelo/cli/webhook.py | 3 +- robottelo/config/__init__.py | 2 +- robottelo/host_helpers/api_factory.py | 13 +-- robottelo/host_helpers/capsule_mixins.py | 6 +- robottelo/host_helpers/cli_factory.py | 59 ++++++------ robottelo/host_helpers/repository_mixins.py | 3 +- robottelo/host_helpers/satellite_mixins.py | 18 ++-- robottelo/hosts.py | 18 ++-- robottelo/ssh.py | 3 +- robottelo/utils/datafactory.py | 25 ++--- robottelo/utils/decorators/func_locker.py | 12 +-- .../utils/decorators/func_shared/shared.py | 3 +- robottelo/utils/io/__init__.py | 1 + robottelo/utils/issue_handlers/__init__.py | 5 +- robottelo/utils/ohsnap.py | 7 +- robottelo/utils/report_portal/portal.py | 3 +- robottelo/utils/ssh.py | 3 +- robottelo/utils/vault.py | 62 ++++++------- robottelo/utils/virtwho.py | 42 ++++----- scripts/config_helpers.py | 4 +- scripts/customer_scenarios.py | 18 ++-- scripts/fixture_cli.py | 14 +-- scripts/graph_entities.py | 4 +- tests/foreman/api/test_activationkey.py | 6 +- .../api/test_computeresource_azurerm.py | 2 +- tests/foreman/api/test_contentview.py | 3 +- tests/foreman/api/test_errata.py | 6 +- tests/foreman/api/test_filter.py | 3 +- tests/foreman/api/test_hostcollection.py | 3 +- tests/foreman/api/test_multiple_paths.py | 18 ++-- tests/foreman/api/test_organization.py | 2 +- .../foreman/api/test_provisioningtemplate.py | 2 +- tests/foreman/api/test_registration.py | 4 +- tests/foreman/api/test_repository.py | 4 +- tests/foreman/api/test_role.py | 2 +- tests/foreman/api/test_subscription.py | 3 +- .../foreman/api/test_template_combination.py | 4 +- tests/foreman/api/test_templatesync.py | 24 ++--- tests/foreman/cli/test_activationkey.py | 7 +- .../cli/test_computeresource_azurerm.py | 91 +++++++++---------- .../cli/test_computeresource_libvirt.py | 2 +- tests/foreman/cli/test_contentview.py | 2 +- tests/foreman/cli/test_docker.py | 2 +- tests/foreman/cli/test_domain.py | 8 +- tests/foreman/cli/test_errata.py | 3 +- tests/foreman/cli/test_filter.py | 3 +- tests/foreman/cli/test_host.py | 10 +- tests/foreman/cli/test_leapp_client.py | 5 +- tests/foreman/cli/test_registration.py | 8 +- tests/foreman/cli/test_remoteexecution.py | 2 +- tests/foreman/cli/test_reporttemplates.py | 2 +- tests/foreman/cli/test_repository.py | 4 +- tests/foreman/cli/test_role.py | 2 +- tests/foreman/cli/test_satellitesync.py | 4 +- tests/foreman/cli/test_subscription.py | 5 +- tests/foreman/cli/test_templatesync.py | 2 +- tests/foreman/cli/test_user.py | 4 +- tests/foreman/cli/test_usergroup.py | 7 +- tests/foreman/conftest.py | 9 +- .../destructive/test_capsule_loadbalancer.py | 4 +- .../destructive/test_discoveredhost.py | 3 +- .../destructive/test_ldap_authentication.py | 5 +- tests/foreman/destructive/test_realm.py | 4 +- tests/foreman/longrun/test_inc_updates.py | 6 +- tests/foreman/longrun/test_oscap.py | 5 +- tests/foreman/maintain/test_advanced.py | 3 +- tests/foreman/ui/test_discoveredhost.py | 3 +- tests/foreman/ui/test_host.py | 17 ++-- tests/foreman/ui/test_hostcollection.py | 11 +-- tests/foreman/ui/test_ldap_authentication.py | 28 +++--- tests/foreman/ui/test_organization.py | 2 +- tests/foreman/ui/test_provisioningtemplate.py | 2 +- tests/foreman/ui/test_registration.py | 2 +- tests/foreman/ui/test_subscription.py | 5 +- tests/robottelo/conftest.py | 7 +- tests/robottelo/test_cli.py | 18 ++-- tests/robottelo/test_decorators.py | 4 +- tests/robottelo/test_dependencies.py | 5 +- tests/robottelo/test_func_locker.py | 53 ++++++----- tests/upgrades/conftest.py | 29 +++--- tests/upgrades/test_activation_key.py | 3 +- tests/upgrades/test_classparameter.py | 2 +- tests/upgrades/test_host.py | 3 +- tests/upgrades/test_puppet.py | 3 +- tests/upgrades/test_satellite_maintain.py | 3 +- tests/upgrades/test_subscription.py | 2 +- 124 files changed, 525 insertions(+), 686 deletions(-) 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 98deb66c3cb..e2a68959d29 100644 --- a/pytest_fixtures/component/activationkey.py +++ b/pytest_fixtures/component/activationkey.py @@ -8,31 +8,28 @@ @pytest.fixture(scope='module') def module_activation_key(module_entitlement_manifest_org, module_target_sat): """Create activation key using default CV and library environment.""" - activation_key = module_target_sat.api.ActivationKey( + module_target_sat.api.ActivationKey( content_view=module_entitlement_manifest_org.default_content_view.id, environment=module_entitlement_manifest_org.library.id, organization=module_entitlement_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') @@ -45,7 +42,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', @@ -53,4 +50,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 948d37350f7..c1dadd9589a 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 601750c3a33..24efae4c98d 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 542d8c7a017..7efc442bf7b 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 cb4ea6d84d5..7b797e1da7c 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 a3a48083d1c..b7a26560980 100644 --- a/pytest_fixtures/component/repository.py +++ b/pytest_fixtures/component/repository.py @@ -67,8 +67,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') @@ -189,7 +188,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) @@ -197,7 +196,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 298632f59f6..debfa81f101 100644 --- a/pytest_fixtures/core/ui.py +++ b/pytest_fixtures/core/ui.py @@ -95,7 +95,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 41e12b85bab..6fe2f4df4af 100644 --- a/pytest_plugins/fixture_markers.py +++ b/pytest_plugins/fixture_markers.py @@ -16,7 +16,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 = [] @@ -86,6 +86,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 9f126e5a2a4..1e4e4a20b36 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 import_classes(cls, options): """Import puppet classes from puppet Capsule.""" 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): @@ -121,6 +105,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 13cdfb41dbb..b84e6bf2158 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 @@ -199,7 +199,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 0fff2579352..da6a39ecd76 100644 --- a/robottelo/host_helpers/api_factory.py +++ b/robottelo/host_helpers/api_factory.py @@ -50,6 +50,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""" @@ -606,10 +607,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): """ @@ -681,10 +681,7 @@ def wait_for_errata_applicability_task( if ( task.label == 'Actions::Katello::Host::GenerateApplicability' 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_id == task.input['host']['id'] ): @@ -752,7 +749,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 16fd7fa5712..89274435ec2 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 d440ce4376a..16d92d82666 100644 --- a/robottelo/host_helpers/cli_factory.py +++ b/robottelo/host_helpers/cli_factory.py @@ -273,15 +273,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""" @@ -293,6 +291,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): @@ -300,6 +299,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. @@ -527,7 +527,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() @@ -864,32 +864,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 f6ff272a724..d65762cd40c 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 9e5632a3a8c..20877ad1e0d 100644 --- a/robottelo/host_helpers/satellite_mixins.py +++ b/robottelo/host_helpers/satellite_mixins.py @@ -144,9 +144,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 @@ -190,8 +193,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): """ @@ -207,11 +209,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 6ed546f1fd0..f7a13971154 100644 --- a/robottelo/hosts.py +++ b/robottelo/hosts.py @@ -70,8 +70,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(): @@ -218,8 +217,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): @@ -488,6 +487,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') @@ -1532,8 +1532,7 @@ def is_upstream(self): def version(self): if not self.is_upstream: return self.execute('rpm -q satellite-capsule').stdout.split('-')[2] - else: - return 'upstream' + return 'upstream' @cached_property def url(self): @@ -1562,6 +1561,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""" @@ -1727,7 +1727,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 @@ -1817,6 +1817,7 @@ def get_caller(): for frame in inspect.stack(): if frame.function.startswith('test_'): return frame.function + return None try: ui_session = Session( @@ -1858,8 +1859,7 @@ def is_upstream(self): def version(self): if not self.is_upstream: return self.execute('rpm -q satellite').stdout.split('-')[1] - else: - return 'upstream' + return 'upstream' def is_remote_db(self): return ( 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 fa37ca82561..d07bcc2f71f 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 @@ -217,7 +217,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 @@ -287,7 +287,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_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 0a6283f89e2..e43ecd4d0b6 100644 --- a/tests/foreman/api/test_contentview.py +++ b/tests/foreman/api/test_contentview.py @@ -95,8 +95,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 df24f7c66d2..6cce6e5e258 100644 --- a/tests/foreman/api/test_errata.py +++ b/tests/foreman/api/test_errata.py @@ -34,10 +34,7 @@ @pytest.fixture(scope='module') def activation_key(module_org, module_lce, module_target_sat): - activation_key = module_target_sat.api.ActivationKey( - environment=module_lce, organization=module_org - ).create() - return activation_key + module_target_sat.api.ActivationKey(environment=module_lce, organization=module_org).create() @pytest.fixture(scope='module') @@ -626,6 +623,7 @@ def _run_remote_command_on_content_host(module_org, command, vm, return_result=F assert result.status == 0 if return_result: return result.stdout + return None def _set_prerequisites_for_swid_repos(module_org, vm): diff --git a/tests/foreman/api/test_filter.py b/tests/foreman/api/test_filter.py index efcf26e7b49..b676a67c6da 100644 --- a/tests/foreman/api/test_filter.py +++ b/tests/foreman/api/test_filter.py @@ -23,10 +23,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 9e467ddbefe..439f75ad1be 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 f6232848619..5ed53acc386 100644 --- a/tests/foreman/api/test_registration.py +++ b/tests/foreman/api/test_registration.py @@ -58,7 +58,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 @@ -82,7 +82,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 5e5abdf07ae..7064fb456cd 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' ] ), @@ -2247,7 +2247,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 c63888f212d..409525d33e9 100644 --- a/tests/foreman/cli/test_activationkey.py +++ b/tests/foreman/cli/test_activationkey.py @@ -256,9 +256,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) @@ -1403,7 +1402,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 0f76f479730..51f25746302 100644 --- a/tests/foreman/cli/test_errata.py +++ b/tests/foreman/cli/test_errata.py @@ -311,7 +311,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 @@ -1414,7 +1414,6 @@ def test_update_applicable_package_using_default_content_view(errata_host, targe search_rate=30, max_tries=10, ) - # Assert that the package is no longer applicable target_sat.cli.Host.errata_recalculate({'host-id': errata_host.nailgun_host.id}) 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 269b2bfac0d..9a6e481f75d 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: @@ -1058,18 +1058,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 ------------------------- @@ -1095,7 +1095,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 45641f9d0e6..9071ecc770a 100644 --- a/tests/foreman/cli/test_registration.py +++ b/tests/foreman/cli/test_registration.py @@ -52,7 +52,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( @@ -77,7 +77,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( @@ -114,7 +114,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 @@ -135,7 +135,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 72376de6375..ed046cd8531 100644 --- a/tests/foreman/cli/test_remoteexecution.py +++ b/tests/foreman/cli/test_remoteexecution.py @@ -28,7 +28,7 @@ @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 ca93b8a7318..64c35117180 100644 --- a/tests/foreman/cli/test_reporttemplates.py +++ b/tests/foreman/cli/test_reporttemplates.py @@ -710,7 +710,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 53d3e18e88b..7fa04769b13 100644 --- a/tests/foreman/cli/test_repository.py +++ b/tests/foreman/cli/test_repository.py @@ -651,7 +651,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' ] @@ -2627,7 +2627,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 099fe6697c5..e44a7479699 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 @@ -159,7 +158,6 @@ def function_synced_rh_repo(request, target_sat, function_sca_manifest_org): '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 c6d053a4659..a7a74f4360c 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 4526577b41d..168090e0c98 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 6384b172ecb..b334a7184ca 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 ba06d219e7e..1efb52ec042 100644 --- a/tests/foreman/destructive/test_capsule_loadbalancer.py +++ b/tests/foreman/destructive/test_capsule_loadbalancer.py @@ -272,7 +272,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 # Host registration by Second Capsule through Loadbalancer result = rhel_contenthost.register( @@ -287,7 +287,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 a848665cbdb..c495e29176e 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 652f1a20e56..839d9381a5b 100644 --- a/tests/foreman/longrun/test_inc_updates.py +++ b/tests/foreman/longrun/test_inc_updates.py @@ -54,10 +54,9 @@ def dev_lce(module_entitlement_manifest_org): @pytest.fixture(scope='module') def qe_lce(module_entitlement_manifest_org, dev_lce): - qe_lce = entities.LifecycleEnvironment( + entities.LifecycleEnvironment( name='QE', prior=dev_lce, organization=module_entitlement_manifest_org ).create() - return qe_lce @pytest.fixture(scope='module') @@ -95,8 +94,7 @@ def module_cv(module_entitlement_manifest_org, sat_client_repo, custom_repo): repository=[sat_client_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 1b03a1192dd..babcf930fb4 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_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 ba6c7d8ded5..c5482a50a9a 100644 --- a/tests/foreman/ui/test_host.py +++ b/tests/foreman/ui/test_host.py @@ -57,7 +57,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', @@ -67,7 +67,6 @@ def scap_policy(scap_content, target_sat): 'weekday': OSCAP_WEEKDAY['friday'].lower(), } ) - return scap_policy @pytest.fixture(scope='module') @@ -1059,8 +1058,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 @@ -1186,18 +1185,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 @@ -1254,7 +1253,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 @@ -1333,7 +1332,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 c2acfd7a26a..06af17c4a5a 100644 --- a/tests/foreman/ui/test_hostcollection.py +++ b/tests/foreman/ui/test_hostcollection.py @@ -95,10 +95,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 @@ -109,10 +108,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): @@ -138,7 +136,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: @@ -148,8 +146,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 e80fe958313..4365697efca 100644 --- a/tests/foreman/ui/test_organization.py +++ b/tests/foreman/ui/test_organization.py @@ -341,4 +341,4 @@ 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 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 cb1a79264c2..d8b979ba0c2 100644 --- a/tests/foreman/ui/test_registration.py +++ b/tests/foreman/ui/test_registration.py @@ -538,7 +538,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 15e4de7c96c..9ef5ff377d3 100644 --- a/tests/foreman/ui/test_subscription.py +++ b/tests/foreman/ui/test_subscription.py @@ -98,9 +98,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: From c5040796c1c6bdf1e83c0562f4f25c5ba1d8a0ea Mon Sep 17 00:00:00 2001 From: Omkar Khatavkar Date: Fri, 8 Mar 2024 14:08:40 +0530 Subject: [PATCH 2/2] fixed sanity suite, AttributeError due to not matching scope (#14309) (cherry picked from commit 063ac02e6d350a02b6cce2eb4fad9376f0a365a5) --- robottelo/host_helpers/satellite_mixins.py | 6 ++---- tests/foreman/api/test_errata.py | 4 +++- tests/foreman/cli/test_satellitesync.py | 2 +- tests/foreman/longrun/test_inc_updates.py | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/robottelo/host_helpers/satellite_mixins.py b/robottelo/host_helpers/satellite_mixins.py index 20877ad1e0d..1a7f9f86dfc 100644 --- a/robottelo/host_helpers/satellite_mixins.py +++ b/robottelo/host_helpers/satellite_mixins.py @@ -144,10 +144,8 @@ def upload_manifest(self, org_id, manifest=None, interface='API', timeout=None): :returns: the manifest upload result """ - if ( - not isinstance(manifest, bytes | io.BytesIO) - and not hasattr(manifest, 'content') - or manifest.content is None + if not isinstance(manifest, bytes | io.BytesIO) and ( + not hasattr(manifest, 'content') or manifest.content is None ): manifest = clone() if timeout is None: diff --git a/tests/foreman/api/test_errata.py b/tests/foreman/api/test_errata.py index 6cce6e5e258..cb831425778 100644 --- a/tests/foreman/api/test_errata.py +++ b/tests/foreman/api/test_errata.py @@ -34,7 +34,9 @@ @pytest.fixture(scope='module') def activation_key(module_org, module_lce, module_target_sat): - module_target_sat.api.ActivationKey(environment=module_lce, organization=module_org).create() + return module_target_sat.api.ActivationKey( + environment=module_lce, organization=module_org + ).create() @pytest.fixture(scope='module') diff --git a/tests/foreman/cli/test_satellitesync.py b/tests/foreman/cli/test_satellitesync.py index e44a7479699..bab092a3ea7 100644 --- a/tests/foreman/cli/test_satellitesync.py +++ b/tests/foreman/cli/test_satellitesync.py @@ -151,7 +151,7 @@ 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=7200000) - repo = target_sat.cli.Repository.info( + return target_sat.cli.Repository.info( { 'organization-id': function_sca_manifest_org.id, 'name': repo_dict['name'], diff --git a/tests/foreman/longrun/test_inc_updates.py b/tests/foreman/longrun/test_inc_updates.py index 839d9381a5b..8ffb84fb36c 100644 --- a/tests/foreman/longrun/test_inc_updates.py +++ b/tests/foreman/longrun/test_inc_updates.py @@ -54,7 +54,7 @@ def dev_lce(module_entitlement_manifest_org): @pytest.fixture(scope='module') def qe_lce(module_entitlement_manifest_org, dev_lce): - entities.LifecycleEnvironment( + return entities.LifecycleEnvironment( name='QE', prior=dev_lce, organization=module_entitlement_manifest_org ).create()