diff --git a/pyproject.toml b/pyproject.toml index b042ee54c72..7988aa2a58d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,12 +25,15 @@ select = [ "F", # flake8 "I", # isort # "Q", # flake8-quotes + "PT", # flake8-pytest "UP", # pyupgrade "W", # pycodestyle ] ignore = [ "E501", # line too long - handled by black + "PT004", # pytest underscrore prefix for non-return fixtures + "PT005", # pytest no underscrore prefix for return fixtures ] [tool.ruff.isort] @@ -40,6 +43,9 @@ known-first-party = [ ] combine-as-imports = true +[tool.ruff.flake8-pytest-style] +fixture-parentheses = false +mark-parentheses = false [tool.ruff.flake8-quotes] inline-quotes = "single" diff --git a/pytest_fixtures/component/http_proxy.py b/pytest_fixtures/component/http_proxy.py index ee8efc9c16a..8c6095092dd 100644 --- a/pytest_fixtures/component/http_proxy.py +++ b/pytest_fixtures/component/http_proxy.py @@ -3,7 +3,7 @@ from robottelo.config import settings -@pytest.fixture(scope='function') +@pytest.fixture def setup_http_proxy(request, module_manifest_org, target_sat): """Create a new HTTP proxy and set related settings based on proxy""" http_proxy = target_sat.api_factory.make_http_proxy(module_manifest_org, request.param) diff --git a/pytest_fixtures/component/katello_certs_check.py b/pytest_fixtures/component/katello_certs_check.py index f14299ebd52..1ee97acc565 100644 --- a/pytest_fixtures/component/katello_certs_check.py +++ b/pytest_fixtures/component/katello_certs_check.py @@ -13,7 +13,7 @@ def certs_data(sat_ready_rhel): cert_data['key_file_name'] = f'{sat_ready_rhel.hostname}/{sat_ready_rhel.hostname}.key' cert_data['cert_file_name'] = f'{sat_ready_rhel.hostname}/{sat_ready_rhel.hostname}.crt' sat_ready_rhel.custom_cert_generate(cert_data['capsule_hostname']) - yield cert_data + return cert_data @pytest.fixture diff --git a/pytest_fixtures/component/lce.py b/pytest_fixtures/component/lce.py index 368c1329131..2a3f113e9c8 100644 --- a/pytest_fixtures/component/lce.py +++ b/pytest_fixtures/component/lce.py @@ -16,7 +16,7 @@ def module_lce(module_org, module_target_sat): return module_target_sat.api.LifecycleEnvironment(organization=module_org).create() -@pytest.fixture(scope='function') +@pytest.fixture def function_lce(function_org, target_sat): return target_sat.api.LifecycleEnvironment(organization=function_org).create() @@ -31,7 +31,7 @@ def module_lce_library(module_org, module_target_sat): ) -@pytest.fixture(scope='function') +@pytest.fixture def function_lce_library(function_org, target_sat): """Returns the Library lifecycle environment from chosen organization""" return ( diff --git a/pytest_fixtures/component/maintain.py b/pytest_fixtures/component/maintain.py index 152656f8dc1..844f522de66 100644 --- a/pytest_fixtures/component/maintain.py +++ b/pytest_fixtures/component/maintain.py @@ -18,7 +18,7 @@ def module_stash(request): # Please refer the documentation for more details on stash # https://docs.pytest.org/en/latest/reference/reference.html#stash request.node.stash[synced_repos] = {} - yield request.node.stash + return request.node.stash @pytest.fixture(scope='module') @@ -98,7 +98,7 @@ def module_synced_repos(sat_maintain, module_capsule_configured, module_sca_mani sync_status = module_capsule_configured.nailgun_capsule.content_sync() assert sync_status['result'] == 'success' - yield { + return { 'custom': module_stash[synced_repos]['cust_repo'], 'rh': module_stash[synced_repos]['rh_repo'], } diff --git a/pytest_fixtures/component/provision_azure.py b/pytest_fixtures/component/provision_azure.py index 0483758b51a..27bcea16e1f 100644 --- a/pytest_fixtures/component/provision_azure.py +++ b/pytest_fixtures/component/provision_azure.py @@ -17,22 +17,22 @@ @pytest.fixture(scope='session') def sat_azure(request, session_puppet_enabled_sat, session_target_sat): hosts = {'sat': session_target_sat, 'puppet_sat': session_puppet_enabled_sat} - yield hosts[request.param] + return hosts[request.param] @pytest.fixture(scope='module') def sat_azure_org(sat_azure): - yield sat_azure.api.Organization().create() + return sat_azure.api.Organization().create() @pytest.fixture(scope='module') def sat_azure_loc(sat_azure): - yield sat_azure.api.Location().create() + return sat_azure.api.Location().create() @pytest.fixture(scope='module') def sat_azure_domain(sat_azure, sat_azure_loc, sat_azure_org): - yield sat_azure.api.Domain(location=[sat_azure_loc], organization=[sat_azure_org]).create() + return sat_azure.api.Domain(location=[sat_azure_loc], organization=[sat_azure_org]).create() @pytest.fixture(scope='module') diff --git a/pytest_fixtures/component/provision_gce.py b/pytest_fixtures/component/provision_gce.py index af260bdb38c..4c11ecb0918 100644 --- a/pytest_fixtures/component/provision_gce.py +++ b/pytest_fixtures/component/provision_gce.py @@ -20,22 +20,22 @@ @pytest.fixture(scope='session') def sat_gce(request, session_puppet_enabled_sat, session_target_sat): hosts = {'sat': session_target_sat, 'puppet_sat': session_puppet_enabled_sat} - yield hosts[getattr(request, 'param', 'sat')] + return hosts[getattr(request, 'param', 'sat')] @pytest.fixture(scope='module') def sat_gce_org(sat_gce): - yield sat_gce.api.Organization().create() + return sat_gce.api.Organization().create() @pytest.fixture(scope='module') def sat_gce_loc(sat_gce): - yield sat_gce.api.Location().create() + return sat_gce.api.Location().create() @pytest.fixture(scope='module') def sat_gce_domain(sat_gce, sat_gce_loc, sat_gce_org): - yield sat_gce.api.Domain(location=[sat_gce_loc], organization=[sat_gce_org]).create() + return sat_gce.api.Domain(location=[sat_gce_loc], organization=[sat_gce_org]).create() @pytest.fixture(scope='module') @@ -282,7 +282,7 @@ def module_gce_finishimg( return finish_image -@pytest.fixture() +@pytest.fixture def gce_setting_update(sat_gce): sat_gce.update_setting('destroy_vm_on_host_delete', True) yield diff --git a/pytest_fixtures/component/provision_libvirt.py b/pytest_fixtures/component/provision_libvirt.py index d8638d9a32a..b294ca27a29 100644 --- a/pytest_fixtures/component/provision_libvirt.py +++ b/pytest_fixtures/component/provision_libvirt.py @@ -18,4 +18,4 @@ def module_libvirt_image(module_target_sat, module_cr_libvirt): def module_libvirt_provisioning_sat(module_provisioning_sat): # Configure Libvirt CR for provisioning module_provisioning_sat.sat.configure_libvirt_cr() - yield module_provisioning_sat + return module_provisioning_sat diff --git a/pytest_fixtures/component/puppet.py b/pytest_fixtures/component/puppet.py index f088e05d0a8..0ff20685674 100644 --- a/pytest_fixtures/component/puppet.py +++ b/pytest_fixtures/component/puppet.py @@ -18,22 +18,22 @@ def session_puppet_enabled_sat(session_satellite_host): def session_puppet_enabled_capsule(session_capsule_host, session_puppet_enabled_sat): """Capsule with enabled puppet plugin""" session_capsule_host.capsule_setup(sat_host=session_puppet_enabled_sat) - yield session_capsule_host.enable_puppet_capsule(satellite=session_puppet_enabled_sat) + return session_capsule_host.enable_puppet_capsule(satellite=session_puppet_enabled_sat) @pytest.fixture(scope='module') def module_puppet_org(session_puppet_enabled_sat): - yield session_puppet_enabled_sat.api.Organization().create() + return session_puppet_enabled_sat.api.Organization().create() @pytest.fixture(scope='module') def module_puppet_loc(session_puppet_enabled_sat): - yield session_puppet_enabled_sat.api.Location().create() + return session_puppet_enabled_sat.api.Location().create() @pytest.fixture(scope='module') def module_puppet_domain(session_puppet_enabled_sat, module_puppet_loc, module_puppet_org): - yield session_puppet_enabled_sat.api.Domain( + return session_puppet_enabled_sat.api.Domain( location=[module_puppet_loc], organization=[module_puppet_org] ).create() diff --git a/pytest_fixtures/component/repository.py b/pytest_fixtures/component/repository.py index 209245ff649..74701c15203 100644 --- a/pytest_fixtures/component/repository.py +++ b/pytest_fixtures/component/repository.py @@ -22,7 +22,7 @@ def module_repo(module_repo_options, module_target_sat): return module_target_sat.api.Repository(**module_repo_options).create() -@pytest.fixture(scope='function') +@pytest.fixture def function_product(function_org): return entities.Product(organization=function_org).create() @@ -74,7 +74,7 @@ def module_rhst_repo(module_target_sat, module_org_with_manifest, module_promote return REPOS['rhst7']['id'] -@pytest.fixture(scope="function") +@pytest.fixture def repo_setup(): """ This fixture is used to create an organization, product, repository, and lifecycle environment @@ -86,7 +86,7 @@ def repo_setup(): repo = entities.Repository(name=repo_name, product=product).create() lce = entities.LifecycleEnvironment(organization=org).create() details = {'org': org, 'product': product, 'repo': repo, 'lce': lce} - yield details + return details @pytest.fixture(scope='module') diff --git a/pytest_fixtures/component/rh_cloud.py b/pytest_fixtures/component/rh_cloud.py index 617261c98c5..ead92f68db2 100644 --- a/pytest_fixtures/component/rh_cloud.py +++ b/pytest_fixtures/component/rh_cloud.py @@ -25,7 +25,7 @@ def rhcloud_activation_key(module_target_sat, rhcloud_manifest_org): purpose_role='test-role', auto_attach=False, ).create() - yield ak + return ak @pytest.fixture(scope='module') @@ -62,7 +62,7 @@ def rhel_insights_vm( module_target_sat.generate_inventory_report(rhcloud_manifest_org) # Sync inventory status module_target_sat.sync_inventory_status(rhcloud_manifest_org) - yield rhel_contenthost + return rhel_contenthost @pytest.fixture @@ -90,4 +90,4 @@ def rhcloud_capsule(module_capsule_host, module_target_sat, rhcloud_manifest_org 'location-ids': default_location.id, } ) - yield module_capsule_host + return module_capsule_host diff --git a/pytest_fixtures/component/satellite_auth.py b/pytest_fixtures/component/satellite_auth.py index 9c39ed3ade3..0a1031c9e25 100644 --- a/pytest_fixtures/component/satellite_auth.py +++ b/pytest_fixtures/component/satellite_auth.py @@ -35,7 +35,7 @@ def default_ipa_host(module_target_sat): return IPAHost(module_target_sat) -@pytest.fixture() +@pytest.fixture def ldap_cleanup(): """this is an extra step taken to clean any existing ldap source""" ldap_auth_sources = entities.AuthSourceLDAP().search() @@ -44,7 +44,7 @@ def ldap_cleanup(): for user in users: user.delete() ldap_auth.delete() - yield + return @pytest.fixture(scope='session') @@ -104,7 +104,7 @@ def open_ldap_data(): } -@pytest.fixture(scope='function') +@pytest.fixture def auth_source(ldap_cleanup, module_org, module_location, ad_data): ad_data = ad_data() return entities.AuthSourceLDAP( @@ -127,7 +127,7 @@ def auth_source(ldap_cleanup, module_org, module_location, ad_data): ).create() -@pytest.fixture(scope='function') +@pytest.fixture def auth_source_ipa(ldap_cleanup, default_ipa_host, module_org, module_location): return entities.AuthSourceLDAP( onthefly_register=True, @@ -149,7 +149,7 @@ def auth_source_ipa(ldap_cleanup, default_ipa_host, module_org, module_location) ).create() -@pytest.fixture(scope='function') +@pytest.fixture def auth_source_open_ldap(ldap_cleanup, module_org, module_location, open_ldap_data): return entities.AuthSourceLDAP( onthefly_register=True, @@ -259,7 +259,7 @@ def ldap_auth_source( else: ldap_data['server_type'] = LDAP_SERVER_TYPE['UI']['posix'] ldap_data['attr_login'] = LDAP_ATTR['login'] - yield ldap_data, auth_source + return ldap_data, auth_source @pytest.fixture @@ -459,7 +459,7 @@ def configure_hammer_no_negotiate(parametrized_enrolled_sat): @pytest.mark.external_auth -@pytest.fixture(scope='function') +@pytest.fixture def hammer_logout(parametrized_enrolled_sat): """Logout in Hammer.""" result = parametrized_enrolled_sat.cli.Auth.logout() diff --git a/pytest_fixtures/component/settings.py b/pytest_fixtures/component/settings.py index 937379bd6d6..b541e703733 100644 --- a/pytest_fixtures/component/settings.py +++ b/pytest_fixtures/component/settings.py @@ -2,7 +2,7 @@ import pytest -@pytest.fixture() +@pytest.fixture def setting_update(request, target_sat): """ This fixture is used to create an object of the provided settings parameter that we use in diff --git a/pytest_fixtures/component/taxonomy.py b/pytest_fixtures/component/taxonomy.py index c6140cebb63..ebfc9126eac 100644 --- a/pytest_fixtures/component/taxonomy.py +++ b/pytest_fixtures/component/taxonomy.py @@ -212,7 +212,7 @@ def class_sca_manifest(): yield manifest -@pytest.fixture(scope='function') +@pytest.fixture def function_entitlement_manifest(): """Yields a manifest in entitlement mode with subscriptions determined by the `manifest_category.entitlement` setting in conf/manifest.yaml.""" @@ -220,7 +220,7 @@ def function_entitlement_manifest(): yield manifest -@pytest.fixture(scope='function') +@pytest.fixture def function_secondary_entitlement_manifest(): """Yields a manifest in entitlement mode with subscriptions determined by the `manifest_category.entitlement` setting in conf/manifest.yaml. @@ -229,7 +229,7 @@ def function_secondary_entitlement_manifest(): yield manifest -@pytest.fixture(scope='function') +@pytest.fixture def function_sca_manifest(): """Yields a manifest in Simple Content Access mode with subscriptions determined by the `manifest_category.golden_ticket` setting in conf/manifest.yaml.""" @@ -245,7 +245,7 @@ def smart_proxy_location(module_org, module_target_sat, default_smart_proxy): return location -@pytest.fixture(scope='function') +@pytest.fixture def upgrade_entitlement_manifest(): """Returns a manifest in entitlement mode with subscriptions determined by the `manifest_category.entitlement` setting in conf/manifest.yaml. used only for diff --git a/pytest_fixtures/component/templatesync.py b/pytest_fixtures/component/templatesync.py index 3dee193cdd3..1e195ec838f 100644 --- a/pytest_fixtures/component/templatesync.py +++ b/pytest_fixtures/component/templatesync.py @@ -7,7 +7,7 @@ from robottelo.logging import logger -@pytest.fixture() +@pytest.fixture def create_import_export_local_dir(target_sat): """Creates a local directory inside root_dir on satellite from where the templates will be imported from or exported to. @@ -76,7 +76,7 @@ def git_pub_key(session_target_sat, git_port): res.raise_for_status() -@pytest.fixture(scope='function') +@pytest.fixture def git_repository(git_port, git_pub_key, request): """Creates a new repository on git provider for exporting templates. @@ -96,7 +96,7 @@ def git_repository(git_port, git_pub_key, request): res.raise_for_status() -@pytest.fixture() +@pytest.fixture def git_branch(git_repository): """Creates a new branch in the git repository for exporting templates. diff --git a/pytest_fixtures/core/contenthosts.py b/pytest_fixtures/core/contenthosts.py index 586fa95eb57..485591ed7d9 100644 --- a/pytest_fixtures/core/contenthosts.py +++ b/pytest_fixtures/core/contenthosts.py @@ -94,7 +94,7 @@ def rhel9_contenthost(request): yield host -@pytest.fixture() +@pytest.fixture def content_hosts(request): """A function-level fixture that provides two rhel content hosts object""" with Broker(**host_conf(request), host_class=ContentHost, _count=2) as hosts: @@ -110,7 +110,7 @@ def mod_content_hosts(request): yield hosts -@pytest.fixture() +@pytest.fixture def registered_hosts(request, target_sat, module_org, module_ak_with_cv): """Fixture that registers content hosts to Satellite, based on rh_cloud setup""" with Broker(**host_conf(request), host_class=ContentHost, _count=2) as hosts: @@ -134,7 +134,7 @@ def katello_host_tools_host(target_sat, module_org, rhel_contenthost): rhel_contenthost.register(module_org, None, ak.name, target_sat, repo=repo) rhel_contenthost.install_katello_host_tools() - yield rhel_contenthost + return rhel_contenthost @pytest.fixture @@ -149,7 +149,7 @@ def cockpit_host(class_target_sat, class_org, rhel_contenthost): rhel_contenthost.execute(f"hostnamectl set-hostname {rhel_contenthost.hostname} --static") rhel_contenthost.install_cockpit() rhel_contenthost.add_rex_key(satellite=class_target_sat) - yield rhel_contenthost + return rhel_contenthost @pytest.fixture @@ -174,7 +174,7 @@ def katello_host_tools_tracer_host(rex_contenthost, target_sat): **{f'rhel{rhelver}_os': settings.repos[f'rhel{rhelver}_os']} ) rex_contenthost.install_tracer() - yield rex_contenthost + return rex_contenthost @pytest.fixture diff --git a/pytest_fixtures/core/sat_cap_factory.py b/pytest_fixtures/core/sat_cap_factory.py index f08e722cbbf..2fbb8cec7b6 100644 --- a/pytest_fixtures/core/sat_cap_factory.py +++ b/pytest_fixtures/core/sat_cap_factory.py @@ -150,28 +150,28 @@ def session_capsule_host(request, capsule_factory): def capsule_configured(capsule_host, target_sat): """Configure the capsule instance with the satellite from settings.server.hostname""" capsule_host.capsule_setup(sat_host=target_sat) - yield capsule_host + return capsule_host @pytest.fixture def large_capsule_configured(large_capsule_host, target_sat): """Configure the capsule instance with the satellite from settings.server.hostname""" large_capsule_host.capsule_setup(sat_host=target_sat) - yield large_capsule_host + return large_capsule_host @pytest.fixture(scope='module') def module_capsule_configured(module_capsule_host, module_target_sat): """Configure the capsule instance with the satellite from settings.server.hostname""" module_capsule_host.capsule_setup(sat_host=module_target_sat) - yield module_capsule_host + return module_capsule_host @pytest.fixture(scope='session') def session_capsule_configured(session_capsule_host, session_target_sat): """Configure the capsule instance with the satellite from settings.server.hostname""" session_capsule_host.capsule_setup(sat_host=session_target_sat) - yield session_capsule_host + return session_capsule_host @pytest.fixture(scope='module') @@ -186,7 +186,7 @@ def module_capsule_configured_mqtt(module_capsule_configured): result = module_capsule_configured.execute('firewall-cmd --permanent --add-port="1883/tcp"') assert result.status == 0, 'Failed to open mqtt port on capsule' module_capsule_configured.execute('firewall-cmd --reload') - yield module_capsule_configured + return module_capsule_configured @pytest.fixture(scope='module') @@ -218,7 +218,7 @@ def module_capsule_configured_async_ssh(module_capsule_configured): """Configure the capsule instance with the satellite from settings.server.hostname, enable MQTT broker""" module_capsule_configured.set_rex_script_mode_provider('ssh-async') - yield module_capsule_configured + return module_capsule_configured @pytest.fixture(scope='module', params=['IDM', 'AD']) diff --git a/pytest_fixtures/core/sys.py b/pytest_fixtures/core/sys.py index b9106eac7ad..88768508ee4 100644 --- a/pytest_fixtures/core/sys.py +++ b/pytest_fixtures/core/sys.py @@ -54,7 +54,7 @@ def puppet_proxy_port_range(session_puppet_enabled_sat): @pytest.fixture(scope='class') def class_cockpit_sat(class_subscribe_satellite): class_subscribe_satellite.install_cockpit() - yield class_subscribe_satellite + return class_subscribe_satellite @pytest.fixture(scope='module') diff --git a/pytest_fixtures/core/upgrade.py b/pytest_fixtures/core/upgrade.py index a79f4867979..caf4532713b 100644 --- a/pytest_fixtures/core/upgrade.py +++ b/pytest_fixtures/core/upgrade.py @@ -5,7 +5,7 @@ from robottelo.logging import logger -@pytest.fixture(scope="function") +@pytest.fixture def dependent_scenario_name(request): """ This fixture is used to collect the dependent test case name. @@ -15,7 +15,7 @@ def dependent_scenario_name(request): for mark in request.node.own_markers if 'depend_on' in mark.kwargs ][0] - yield depend_test_name + return depend_test_name @pytest.fixture(scope="session") diff --git a/tests/foreman/api/test_activationkey.py b/tests/foreman/api/test_activationkey.py index 96da8a8f4c8..ae5cb15125a 100644 --- a/tests/foreman/api/test_activationkey.py +++ b/tests/foreman/api/test_activationkey.py @@ -296,7 +296,7 @@ def test_positive_get_releases_content(): act_key = entities.ActivationKey().create() response = client.get(act_key.path('releases'), auth=get_credentials(), verify=False).json() assert 'results' in response.keys() - assert type(response['results']) == list + assert isinstance(response['results'], list) @pytest.mark.tier2 diff --git a/tests/foreman/api/test_ansible.py b/tests/foreman/api/test_ansible.py index b01cab6401a..a842ec5c3ca 100644 --- a/tests/foreman/api/test_ansible.py +++ b/tests/foreman/api/test_ansible.py @@ -257,7 +257,7 @@ def test_add_and_remove_ansible_role_hostgroup(target_sat): assert len(host_roles) == 0 -@pytest.fixture(scope='function') +@pytest.fixture def filtered_user(target_sat, module_org, module_location): """ :Steps: @@ -286,7 +286,7 @@ def filtered_user(target_sat, module_org, module_location): return user, password -@pytest.fixture(scope='function') +@pytest.fixture def rex_host_in_org_and_loc(target_sat, module_org, module_location, rex_contenthost): api = target_sat.api host = api.Host().search(query={'search': f'name={rex_contenthost.hostname}'})[0] diff --git a/tests/foreman/api/test_bookmarks.py b/tests/foreman/api/test_bookmarks.py index 71ae30391ab..ad48053079b 100644 --- a/tests/foreman/api/test_bookmarks.py +++ b/tests/foreman/api/test_bookmarks.py @@ -83,7 +83,7 @@ def test_positive_create_with_query(controller): @pytest.mark.tier1 -@pytest.mark.parametrize('public', (True, False)) +@pytest.mark.parametrize('public', [True, False]) @pytest.mark.parametrize('controller', CONTROLLERS) def test_positive_create_public(controller, public): """Create a public bookmark @@ -368,7 +368,7 @@ def test_negative_update_empty_query(controller): @pytest.mark.tier1 -@pytest.mark.parametrize('public', (True, False)) +@pytest.mark.parametrize('public', [True, False]) @pytest.mark.parametrize('controller', CONTROLLERS) def test_positive_update_public(controller, public): """Update a bookmark public state to private and vice versa diff --git a/tests/foreman/api/test_capsulecontent.py b/tests/foreman/api/test_capsulecontent.py index cdc388fd149..7b5ad39168c 100644 --- a/tests/foreman/api/test_capsulecontent.py +++ b/tests/foreman/api/test_capsulecontent.py @@ -1177,7 +1177,7 @@ def test_positive_sync_CV_to_multiple_LCEs( result = module_capsule_configured.nailgun_capsule.content_lifecycle_environments() # there can and will be LCEs from other tests and orgs, but len() >= 2 assert len(result['results']) >= 2 - assert lce1.id and lce2.id in [capsule_lce['id'] for capsule_lce in result['results']] + assert {lce1.id, lce2.id}.issubset([capsule_lce['id'] for capsule_lce in result['results']]) # Create a Content View, add the repository and publish it. cv = target_sat.api.ContentView( diff --git a/tests/foreman/api/test_classparameters.py b/tests/foreman/api/test_classparameters.py index de34f81ae11..446bdf14182 100644 --- a/tests/foreman/api/test_classparameters.py +++ b/tests/foreman/api/test_classparameters.py @@ -137,10 +137,10 @@ def test_negative_update_parameter_type(self, test_data, module_puppet): 2. Error raised for invalid default value. """ sc_param = module_puppet['sc_params'].pop() + sc_param.override = True + sc_param.parameter_type = test_data['sc_type'] + sc_param.default_value = test_data['value'] with pytest.raises(HTTPError) as context: - sc_param.override = True - sc_param.parameter_type = test_data['sc_type'] - sc_param.default_value = test_data['value'] sc_param.update(['override', 'parameter_type', 'default_value']) assert sc_param.read().default_value != test_data['value'] assert 'Validation failed: Default value is invalid' in context.value.response.text @@ -370,9 +370,9 @@ def test_negative_validate_matcher_and_default_value( session_puppet_enabled_sat.api.OverrideValue( smart_class_parameter=sc_param, match='domain=example.com', value=gen_string('alpha') ).create() + sc_param.parameter_type = 'boolean' + sc_param.default_value = gen_string('alpha') with pytest.raises(HTTPError) as context: - sc_param.parameter_type = 'boolean' - sc_param.default_value = gen_string('alpha') sc_param.update(['parameter_type', 'default_value']) assert ( 'Validation failed: Default value is invalid, Lookup values is invalid' diff --git a/tests/foreman/api/test_computeresource_libvirt.py b/tests/foreman/api/test_computeresource_libvirt.py index e7e0112a0d8..a02d741e899 100644 --- a/tests/foreman/api/test_computeresource_libvirt.py +++ b/tests/foreman/api/test_computeresource_libvirt.py @@ -244,8 +244,8 @@ def test_negative_update_invalid_name( location=[module_location], name=name, organization=[module_org], url=LIBVIRT_URL ).create() request.addfinalizer(compresource.delete) + compresource.name = new_name with pytest.raises(HTTPError): - compresource.name = new_name compresource.update(['name']) assert compresource.read().name == name @@ -269,8 +269,8 @@ def test_negative_update_same_name(request, module_target_sat, module_org, modul new_compresource = module_target_sat.api.LibvirtComputeResource( location=[module_location], organization=[module_org], url=LIBVIRT_URL ).create() + new_compresource.name = name with pytest.raises(HTTPError): - new_compresource.name = name new_compresource.update(['name']) assert new_compresource.read().name != name @@ -299,7 +299,7 @@ def test_negative_update_url(url, request, module_target_sat, module_org, module location=[module_location], organization=[module_org], url=LIBVIRT_URL ).create() request.addfinalizer(compresource.delete) + compresource.url = url with pytest.raises(HTTPError): - compresource.url = url compresource.update(['url']) assert compresource.read().url != url diff --git a/tests/foreman/api/test_contentview.py b/tests/foreman/api/test_contentview.py index 0e1e94c88d4..4bf80287c3f 100644 --- a/tests/foreman/api/test_contentview.py +++ b/tests/foreman/api/test_contentview.py @@ -241,8 +241,8 @@ def test_negative_add_dupe_repos(self, content_view, module_product, module_org) yum_repo = entities.Repository(product=module_product).create() yum_repo.sync() assert len(content_view.repository) == 0 + content_view.repository = [yum_repo, yum_repo] with pytest.raises(HTTPError): - content_view.repository = [yum_repo, yum_repo] content_view.update(['repository']) assert len(content_view.read().repository) == 0 @@ -854,7 +854,7 @@ class TestContentViewUpdate: """Tests for updating content views.""" @pytest.mark.parametrize( - 'key, value', + ('key', 'value'), **(lambda x: {'argvalues': list(x.items()), 'ids': list(x.keys())})( {'description': gen_utf8(), 'name': gen_utf8()} ), @@ -908,8 +908,8 @@ def test_negative_update_name(self, module_cv, new_name): :CaseImportance: Critical """ + module_cv.name = new_name with pytest.raises(HTTPError): - module_cv.name = new_name module_cv.update(['name']) cv = module_cv.read() assert cv.name != new_name diff --git a/tests/foreman/api/test_discoveredhost.py b/tests/foreman/api/test_discoveredhost.py index 0db7c486bcf..08cf4b69abb 100644 --- a/tests/foreman/api/test_discoveredhost.py +++ b/tests/foreman/api/test_discoveredhost.py @@ -157,7 +157,7 @@ def assert_discovered_host_provisioned(channel, ksrepo): raise AssertionError(f'Timed out waiting for {pattern} from VM') -@pytest.fixture() +@pytest.fixture def discovered_host_cleanup(target_sat): hosts = target_sat.api.DiscoveredHost().search() for host in hosts: diff --git a/tests/foreman/api/test_docker.py b/tests/foreman/api/test_docker.py index e87dac66fb6..51a709d7bdc 100644 --- a/tests/foreman/api/test_docker.py +++ b/tests/foreman/api/test_docker.py @@ -899,8 +899,8 @@ def test_negative_promote_and_set_non_unique_name_pattern(self, module_org): cvv = content_view.read().version[0] lce = entities.LifecycleEnvironment(organization=module_org).create() cvv.promote(data={'environment_ids': lce.id, 'force': False}) + lce.registry_name_pattern = new_pattern with pytest.raises(HTTPError): - lce.registry_name_pattern = new_pattern lce.update(['registry_name_pattern']) diff --git a/tests/foreman/api/test_foremantask.py b/tests/foreman/api/test_foremantask.py index f7e8377e82f..23076dd5751 100644 --- a/tests/foreman/api/test_foremantask.py +++ b/tests/foreman/api/test_foremantask.py @@ -48,6 +48,6 @@ def test_positive_get_summary(): :CaseImportance: Critical """ summary = entities.ForemanTask().summary() - assert type(summary) is list + assert isinstance(summary, list) for item in summary: - assert type(item) is dict + assert isinstance(item, dict) diff --git a/tests/foreman/api/test_http_proxy.py b/tests/foreman/api/test_http_proxy.py index f9c3023c77e..b5ed102ed9d 100644 --- a/tests/foreman/api/test_http_proxy.py +++ b/tests/foreman/api/test_http_proxy.py @@ -293,7 +293,7 @@ def test_positive_sync_proxy_with_certificate(request, target_sat, module_org, m # Create and fetch new cerfiticate target_sat.custom_cert_generate(proxy_host) cacert = target_sat.execute(f'cat {cacert_path}').stdout - assert 'BEGIN CERTIFICATE' and 'END CERTIFICATE' in cacert + assert 'END CERTIFICATE' in cacert # Create http-proxy and repository http_proxy = target_sat.api.HTTPProxy( diff --git a/tests/foreman/api/test_lifecycleenvironment.py b/tests/foreman/api/test_lifecycleenvironment.py index b8e7b3ef347..a437d5b8a69 100644 --- a/tests/foreman/api/test_lifecycleenvironment.py +++ b/tests/foreman/api/test_lifecycleenvironment.py @@ -165,8 +165,8 @@ def test_negative_update_name(module_lce, new_name): :parametrized: yes """ + module_lce.name = new_name with pytest.raises(HTTPError): - module_lce.name = new_name module_lce.update(['name']) lce = module_lce.read() assert lce.name != new_name diff --git a/tests/foreman/api/test_media.py b/tests/foreman/api/test_media.py index e5524d914fd..89514610e72 100644 --- a/tests/foreman/api/test_media.py +++ b/tests/foreman/api/test_media.py @@ -41,7 +41,7 @@ def class_media(self, module_org): @pytest.mark.tier1 @pytest.mark.upgrade @pytest.mark.parametrize( - 'name, new_name', + ('name', 'new_name'), **parametrized(list(zip(valid_data_list().values(), valid_data_list().values()))) ) def test_positive_crud_with_name(self, module_org, name, new_name): diff --git a/tests/foreman/api/test_partitiontable.py b/tests/foreman/api/test_partitiontable.py index b1f64b8f5ac..6d78ba1135b 100644 --- a/tests/foreman/api/test_partitiontable.py +++ b/tests/foreman/api/test_partitiontable.py @@ -60,7 +60,7 @@ def test_positive_create_with_one_character_name(self, target_sat, name): @pytest.mark.tier1 @pytest.mark.parametrize( - 'name, new_name', + ('name', 'new_name'), **parametrized( list( zip( @@ -95,7 +95,7 @@ def test_positive_crud_with_name(self, target_sat, name, new_name): @pytest.mark.tier1 @pytest.mark.parametrize( - 'layout, new_layout', **parametrized(list(zip(valid_data_list(), valid_data_list()))) + ('layout', 'new_layout'), **parametrized(list(zip(valid_data_list(), valid_data_list()))) ) def test_positive_create_update_with_layout(self, target_sat, layout, new_layout): """Create new and update partition tables using different inputs as a diff --git a/tests/foreman/api/test_permission.py b/tests/foreman/api/test_permission.py index f8eb16a1500..5778682965c 100644 --- a/tests/foreman/api/test_permission.py +++ b/tests/foreman/api/test_permission.py @@ -366,13 +366,14 @@ def test_positive_check_update(self, entity_cls, class_org, class_location): new_entity = self.set_taxonomies(entity_cls(), class_org, class_location) new_entity = new_entity.create() name = new_entity.get_fields()['name'].gen_value() + if entity_cls is entities.ActivationKey: + update_entity = entity_cls( + self.cfg, id=new_entity.id, name=name, organization=class_org + ) + else: + update_entity = entity_cls(self.cfg, id=new_entity.id, name=name) with pytest.raises(HTTPError): - if entity_cls is entities.ActivationKey: - entity_cls(self.cfg, id=new_entity.id, name=name, organization=class_org).update( - ['name'] - ) - else: - entity_cls(self.cfg, id=new_entity.id, name=name).update(['name']) + update_entity.update(['name']) self.give_user_permission(_permission_name(entity_cls, 'update')) # update() calls read() under the hood, which triggers # permission error diff --git a/tests/foreman/api/test_repositories.py b/tests/foreman/api/test_repositories.py index 1303de40c27..864468c8318 100644 --- a/tests/foreman/api/test_repositories.py +++ b/tests/foreman/api/test_repositories.py @@ -65,10 +65,10 @@ def test_negative_disable_repository_with_cv(module_entitlement_manifest_org, ta with pytest.raises(HTTPError) as error: reposet.disable(data=data) # assert error.value.response.status_code == 500 - assert ( - 'Repository cannot be deleted since it has already been ' - 'included in a published Content View' in error.value.response.text - ) + assert ( + 'Repository cannot be deleted since it has already been ' + 'included in a published Content View' in error.value.response.text + ) @pytest.mark.tier1 diff --git a/tests/foreman/api/test_repository.py b/tests/foreman/api/test_repository.py index e6f03383dc2..56f77e55ba4 100644 --- a/tests/foreman/api/test_repository.py +++ b/tests/foreman/api/test_repository.py @@ -1187,7 +1187,8 @@ def test_positive_recreate_pulp_repositories(self, module_entitlement_manifest_o f' --key /etc/foreman/client_key.pem' ) command_output = target_sat.execute('foreman-rake katello:correct_repositories COMMIT=true') - assert 'Recreating' in command_output.stdout and 'TaskError' not in command_output.stdout + assert 'Recreating' in command_output.stdout + assert 'TaskError' not in command_output.stdout @pytest.mark.tier2 def test_positive_mirroring_policy(self, target_sat): diff --git a/tests/foreman/api/test_rhcloud_inventory.py b/tests/foreman/api/test_rhcloud_inventory.py index de1fe67d8cb..67bd321c073 100644 --- a/tests/foreman/api/test_rhcloud_inventory.py +++ b/tests/foreman/api/test_rhcloud_inventory.py @@ -108,7 +108,8 @@ def test_rhcloud_inventory_api_e2e( infrastructure_type = [ host['system_profile']['infrastructure_type'] for host in json_data['hosts'] ] - assert 'physical' and 'virtual' in infrastructure_type + assert 'physical' in infrastructure_type + assert 'virtual' in infrastructure_type # Verify installed packages are present in report. all_host_profiles = [host['system_profile'] for host in json_data['hosts']] for host_profiles in all_host_profiles: diff --git a/tests/foreman/api/test_rhsm.py b/tests/foreman/api/test_rhsm.py index 2ebd5b517e0..2194ecdb147 100644 --- a/tests/foreman/api/test_rhsm.py +++ b/tests/foreman/api/test_rhsm.py @@ -49,4 +49,4 @@ def test_positive_path(): response = client.get(path, auth=get_credentials(), verify=False) assert response.status_code == http.client.OK assert 'application/json' in response.headers['content-type'] - assert type(response.json()) is list + assert isinstance(response.json(), list) diff --git a/tests/foreman/api/test_role.py b/tests/foreman/api/test_role.py index 4b42408114d..233e5ffea15 100644 --- a/tests/foreman/api/test_role.py +++ b/tests/foreman/api/test_role.py @@ -38,7 +38,7 @@ class TestRole: @pytest.mark.tier1 @pytest.mark.upgrade @pytest.mark.parametrize( - 'name, new_name', + ('name', 'new_name'), **parametrized(list(zip(generate_strings_list(), generate_strings_list()))), ) def test_positive_crud(self, name, new_name): @@ -1245,6 +1245,7 @@ def test_positive_taxonomies_control_to_superadmin_without_org_admin( entities.User(id=user.id).delete() with pytest.raises(HTTPError): user_role.read() + with pytest.raises(HTTPError): user.read() try: entities.Domain().search( @@ -1318,9 +1319,9 @@ def test_negative_modify_roles_by_org_admin(self, role_taxonomies, target_sat): test_role = entities.Role().create() sc = self.user_config(user, target_sat) test_role = entities.Role(sc, id=test_role.id).read() + test_role.organization = [role_taxonomies['org']] + test_role.location = [role_taxonomies['loc']] with pytest.raises(HTTPError): - test_role.organization = [role_taxonomies['org']] - test_role.location = [role_taxonomies['loc']] test_role.update(['organization', 'location']) @pytest.mark.tier2 diff --git a/tests/foreman/api/test_subnet.py b/tests/foreman/api/test_subnet.py index c5188d12808..8c1fb2f7f8e 100644 --- a/tests/foreman/api/test_subnet.py +++ b/tests/foreman/api/test_subnet.py @@ -343,8 +343,8 @@ def test_negative_update_parameter(new_name): sub_param = entities.Parameter( name=gen_string('utf8'), subnet=subnet.id, value=gen_string('utf8') ).create() + sub_param.name = new_name with pytest.raises(HTTPError): - sub_param.name = new_name sub_param.update(['name']) diff --git a/tests/foreman/api/test_user.py b/tests/foreman/api/test_user.py index eff47fbba0f..626604be526 100644 --- a/tests/foreman/api/test_user.py +++ b/tests/foreman/api/test_user.py @@ -208,8 +208,8 @@ def test_negative_update_username(self, create_user, login): :CaseImportance: Critical """ + create_user.login = login with pytest.raises(HTTPError): - create_user.login = login create_user.update(['login']) @pytest.mark.tier1 @@ -284,8 +284,8 @@ def test_negative_update_email(self, create_user, mail): :CaseImportance: Critical """ + create_user.mail = mail with pytest.raises(HTTPError): - create_user.mail = mail create_user.update(['mail']) @pytest.mark.tier1 diff --git a/tests/foreman/cli/test_activationkey.py b/tests/foreman/cli/test_activationkey.py index 126b4144d3c..3a860981e0c 100644 --- a/tests/foreman/cli/test_activationkey.py +++ b/tests/foreman/cli/test_activationkey.py @@ -269,15 +269,15 @@ def test_negative_create_with_usage_limit_with_not_integers(module_org, limit): # invalid_values.append(0.5) with pytest.raises(CLIFactoryError) as raise_ctx: make_activation_key({'organization-id': module_org.id, 'max-hosts': limit}) - if type(limit) is int: + if isinstance(limit, int): if limit < 1: assert 'Max hosts cannot be less than one' in str(raise_ctx) - if type(limit) is str: + if isinstance(limit, str): assert 'Numeric value is required.' in str(raise_ctx) @pytest.mark.tier3 -@pytest.mark.parametrize('invalid_values', ('-1', '-500', 0)) +@pytest.mark.parametrize('invalid_values', ['-1', '-500', 0]) def test_negative_create_with_usage_limit_with_invalid_integers(module_org, invalid_values): """Create Activation key with invalid integers Usage Limit diff --git a/tests/foreman/cli/test_computeresource_osp.py b/tests/foreman/cli/test_computeresource_osp.py index c9018995dc2..acb74283973 100644 --- a/tests/foreman/cli/test_computeresource_osp.py +++ b/tests/foreman/cli/test_computeresource_osp.py @@ -46,7 +46,7 @@ def cr_cleanup(self, cr_id, id_type, target_sat): @pytest.fixture def osp_version(request): versions = {'osp16': settings.osp.api_url.osp16, 'osp17': settings.osp.api_url.osp17} - yield versions[getattr(request, 'param', 'osp16')] + return versions[getattr(request, 'param', 'osp16')] @pytest.mark.upgrade @pytest.mark.tier3 diff --git a/tests/foreman/cli/test_contentview.py b/tests/foreman/cli/test_contentview.py index 4effe29ecf4..2f22d4aefb1 100644 --- a/tests/foreman/cli/test_contentview.py +++ b/tests/foreman/cli/test_contentview.py @@ -2473,7 +2473,7 @@ def test_positive_sub_host_with_restricted_user_perm_at_default_loc( # role info (note: view_roles is not in the required permissions) with pytest.raises(CLIReturnCodeError) as context: Role.with_user(user_name, user_password).info({'id': role['id']}) - assert '403 Forbidden' in str(context) + assert '403 Forbidden' in str(context) # Create a lifecycle environment env = cli_factory.make_lifecycle_environment({'organization-id': org['id']}) # Create a product diff --git a/tests/foreman/cli/test_discoveryrule.py b/tests/foreman/cli/test_discoveryrule.py index efdc081d79f..8657e010b87 100644 --- a/tests/foreman/cli/test_discoveryrule.py +++ b/tests/foreman/cli/test_discoveryrule.py @@ -61,7 +61,7 @@ def gen_int32(min_value=1): class TestDiscoveryRule: """Implements Foreman discovery Rules tests in CLI.""" - @pytest.fixture(scope='function') + @pytest.fixture def discoveryrule_factory(self, class_org, class_location, class_hostgroup): def _create_discoveryrule(org, loc, hostgroup, options=None): """Makes a new discovery rule and asserts its success""" diff --git a/tests/foreman/cli/test_errata.py b/tests/foreman/cli/test_errata.py index f74c434b1ee..422860b64f2 100644 --- a/tests/foreman/cli/test_errata.py +++ b/tests/foreman/cli/test_errata.py @@ -185,7 +185,7 @@ def hosts(request): """Deploy hosts via broker.""" num_hosts = getattr(request, 'param', 2) with Broker(nick='rhel7', host_class=ContentHost, _count=num_hosts) as hosts: - if type(hosts) is not list or len(hosts) != num_hosts: + if not isinstance(hosts, list) or len(hosts) != num_hosts: pytest.fail('Failed to provision the expected number of hosts.') yield hosts @@ -398,9 +398,9 @@ def cv_filter_cleanup(sat, filter_id, cv, org, lce): @pytest.mark.tier3 -@pytest.mark.parametrize('filter_by_hc', ('id', 'name'), ids=('hc_id', 'hc_name')) +@pytest.mark.parametrize('filter_by_hc', ['id', 'name'], ids=('hc_id', 'hc_name')) @pytest.mark.parametrize( - 'filter_by_org', ('id', 'name', 'title'), ids=('org_id', 'org_name', 'org_title') + 'filter_by_org', ['id', 'name', 'title'], ids=('org_id', 'org_name', 'org_title') ) @pytest.mark.no_containers def test_positive_install_by_host_collection_and_org( @@ -1031,10 +1031,10 @@ def cleanup(): @pytest.mark.tier3 -@pytest.mark.parametrize('sort_by_date', ('issued', 'updated'), ids=('issued_date', 'updated_date')) +@pytest.mark.parametrize('sort_by_date', ['issued', 'updated'], ids=('issued_date', 'updated_date')) @pytest.mark.parametrize( 'filter_by_org', - ('id', 'name', 'label', None), + ['id', 'name', 'label', None], ids=('org_id', 'org_name', 'org_label', 'no_org_filter'), ) def test_positive_list_filter_by_org_sort_by_date( @@ -1081,9 +1081,9 @@ def test_positive_list_filter_by_product_id(products_with_repos): @pytest.mark.tier3 -@pytest.mark.parametrize('filter_by_product', ('id', 'name'), ids=('product_id', 'product_name')) +@pytest.mark.parametrize('filter_by_product', ['id', 'name'], ids=('product_id', 'product_name')) @pytest.mark.parametrize( - 'filter_by_org', ('id', 'name', 'label'), ids=('org_id', 'org_name', 'org_label') + 'filter_by_org', ['id', 'name', 'label'], ids=('org_id', 'org_name', 'org_label') ) def test_positive_list_filter_by_product_and_org( products_with_repos, filter_by_product, filter_by_org @@ -1147,7 +1147,7 @@ def test_negative_list_filter_by_product_name(products_with_repos): @pytest.mark.tier3 @pytest.mark.parametrize( - 'filter_by_org', ('id', 'name', 'label'), ids=('org_id', 'org_name', 'org_label') + 'filter_by_org', ['id', 'name', 'label'], ids=('org_id', 'org_name', 'org_label') ) def test_positive_list_filter_by_org(products_with_repos, filter_by_org): """Filter errata by org id, name, or label. diff --git a/tests/foreman/cli/test_filter.py b/tests/foreman/cli/test_filter.py index da5eccb86c2..6881d8b8b01 100644 --- a/tests/foreman/cli/test_filter.py +++ b/tests/foreman/cli/test_filter.py @@ -34,7 +34,7 @@ def module_perms(): return perms -@pytest.fixture(scope='function') +@pytest.fixture def function_role(): """Create a role that a filter would be assigned""" return make_role() diff --git a/tests/foreman/cli/test_host.py b/tests/foreman/cli/test_host.py index 5453de02b53..b7378829671 100644 --- a/tests/foreman/cli/test_host.py +++ b/tests/foreman/cli/test_host.py @@ -67,7 +67,7 @@ def module_default_proxy(module_target_sat): return module_target_sat.cli.Proxy.list({'search': f'url = {module_target_sat.url}:9090'})[0] -@pytest.fixture(scope="function") +@pytest.fixture def function_host(target_sat): host_template = target_sat.api.Host() host_template.create_missing() @@ -90,7 +90,7 @@ def function_host(target_sat): Host.delete({'id': host['id']}) -@pytest.fixture(scope="function") +@pytest.fixture def function_user(target_sat, function_host): """ Returns dict with user object and with password to this user @@ -116,7 +116,7 @@ def function_user(target_sat, function_host): user.delete() -@pytest.fixture(scope='function') +@pytest.fixture def tracer_host(katello_host_tools_tracer_host): # create a custom, rhel version-specific mock-service repo rhelver = katello_host_tools_tracer_host.os_version.major @@ -132,7 +132,7 @@ def tracer_host(katello_host_tools_tracer_host): ) katello_host_tools_tracer_host.execute(f'systemctl start {settings.repos["MOCK_SERVICE_RPM"]}') - yield katello_host_tools_tracer_host + return katello_host_tools_tracer_host def update_smart_proxy(sat, location, smart_proxy): @@ -1494,18 +1494,13 @@ def test_positive_provision_baremetal_with_uefi_secureboot(): """ -@pytest.fixture(scope="function") +@pytest.fixture def setup_custom_repo(target_sat, module_org, katello_host_tools_host, request): """Create custom repository content""" - def restore_sca_setting(): - """Restore the original SCA setting for module_org""" - module_org.sca_enable() if sca_enabled else module_org.sca_disable() - - if module_org.sca_eligible().get('simple_content_access_eligible', False): + if sca_eligible := module_org.sca_eligible().get('simple_content_access_eligible', False): sca_enabled = module_org.simple_content_access module_org.sca_disable() - request.addfinalizer(restore_sca_setting) # get package details details = {} @@ -1551,10 +1546,14 @@ def restore_sca_setting(): ) # refresh repository metadata katello_host_tools_host.subscription_manager_list_repos() - return details + if sca_eligible: + yield + module_org.sca_enable() if sca_enabled else module_org.sca_disable() + else: + return details -@pytest.fixture(scope="function") +@pytest.fixture def yum_security_plugin(katello_host_tools_host): """Enable yum-security-plugin if the distro version requires it. Rhel6 yum version does not support updating of a specific advisory out of the box. @@ -1825,10 +1824,10 @@ def test_positive_install_package_via_rex( # -------------------------- HOST SUBSCRIPTION SUBCOMMAND FIXTURES -------------------------- @pytest.mark.skip_if_not_set('clients') -@pytest.fixture(scope="function") +@pytest.fixture def host_subscription_client(rhel7_contenthost, target_sat): rhel7_contenthost.install_katello_ca(target_sat) - yield rhel7_contenthost + return rhel7_contenthost @pytest.fixture @@ -2503,14 +2502,14 @@ def test_positive_host_with_puppet( session_puppet_enabled_sat.cli.Host.delete({'id': host['id']}) -@pytest.fixture(scope="function") +@pytest.fixture def function_proxy(session_puppet_enabled_sat, puppet_proxy_port_range): proxy = session_puppet_enabled_sat.cli_factory.make_proxy() yield proxy session_puppet_enabled_sat.cli.Proxy.delete({'id': proxy['id']}) -@pytest.fixture(scope="function") +@pytest.fixture def function_host_content_source( session_puppet_enabled_sat, session_puppet_enabled_proxy, diff --git a/tests/foreman/cli/test_ldapauthsource.py b/tests/foreman/cli/test_ldapauthsource.py index 3feed9bad43..be218a95796 100644 --- a/tests/foreman/cli/test_ldapauthsource.py +++ b/tests/foreman/cli/test_ldapauthsource.py @@ -34,7 +34,7 @@ from robottelo.utils.datafactory import generate_strings_list, parametrized -@pytest.fixture() +@pytest.fixture def ldap_tear_down(): """Teardown the all ldap settings user, usergroup and ldap delete""" yield diff --git a/tests/foreman/cli/test_leapp_client.py b/tests/foreman/cli/test_leapp_client.py index 37d1784926c..a6d547f5314 100644 --- a/tests/foreman/cli/test_leapp_client.py +++ b/tests/foreman/cli/test_leapp_client.py @@ -78,7 +78,7 @@ def module_stash(request): # Please refer the documentation for more details on stash # https://docs.pytest.org/en/latest/reference/reference.html#stash request.node.stash[synced_repos] = {} - yield request.node.stash + return request.node.stash @pytest.fixture(scope='module') diff --git a/tests/foreman/cli/test_model.py b/tests/foreman/cli/test_model.py index fe8050d13e9..ddfd4dfe19c 100644 --- a/tests/foreman/cli/test_model.py +++ b/tests/foreman/cli/test_model.py @@ -33,7 +33,7 @@ class TestModel: """Test class for Model CLI""" - @pytest.fixture() + @pytest.fixture def class_model(self): """Shared model for tests""" return make_model() @@ -41,7 +41,7 @@ def class_model(self): @pytest.mark.tier1 @pytest.mark.upgrade @pytest.mark.parametrize( - 'name, new_name', + ('name', 'new_name'), **parametrized(list(zip(valid_data_list().values(), valid_data_list().values()))) ) def test_positive_crud_with_name(self, name, new_name): diff --git a/tests/foreman/cli/test_partitiontable.py b/tests/foreman/cli/test_partitiontable.py index 6540a5d755b..fa8af557d36 100644 --- a/tests/foreman/cli/test_partitiontable.py +++ b/tests/foreman/cli/test_partitiontable.py @@ -51,7 +51,7 @@ def test_positive_create_with_one_character_name(self, name): @pytest.mark.tier1 @pytest.mark.upgrade @pytest.mark.parametrize( - 'name, new_name', + ('name', 'new_name'), **parametrized( list( zip( diff --git a/tests/foreman/cli/test_remoteexecution.py b/tests/foreman/cli/test_remoteexecution.py index d360f1be8f7..f9ba13f1068 100644 --- a/tests/foreman/cli/test_remoteexecution.py +++ b/tests/foreman/cli/test_remoteexecution.py @@ -65,7 +65,7 @@ def valid_feature_names(): ] -@pytest.fixture() +@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(): @@ -83,10 +83,10 @@ def fixture_sca_vmsetup(request, module_sca_manifest_org, target_sat): yield client -@pytest.fixture() +@pytest.fixture def infra_host(request, target_sat, module_capsule_configured): infra_hosts = {'target_sat': target_sat, 'module_capsule_configured': module_capsule_configured} - yield infra_hosts[request.param] + return infra_hosts[request.param] def assert_job_invocation_result(invocation_command_id, client_hostname, expected_result='success'): @@ -924,7 +924,7 @@ def class_rexmanager_user(self, module_org): rexmanager = gen_string('alpha') make_user({'login': rexmanager, 'password': password, 'organization-ids': module_org.id}) User.add_role({'login': rexmanager, 'role': 'Remote Execution Manager'}) - yield (rexmanager, password) + return (rexmanager, password) @pytest.fixture(scope='class') def class_rexinfra_user(self, module_org): @@ -950,7 +950,7 @@ def class_rexinfra_user(self, module_org): make_filter({'role-id': role['id'], 'permissions': permissions}) User.add_role({'login': rexinfra, 'role': role['name']}) User.add_role({'login': rexinfra, 'role': 'Remote Execution Manager'}) - yield (rexinfra, password) + return (rexinfra, password) @pytest.mark.tier3 @pytest.mark.upgrade diff --git a/tests/foreman/cli/test_reporttemplates.py b/tests/foreman/cli/test_reporttemplates.py index 7f1b939f1e0..a4beba443b8 100644 --- a/tests/foreman/cli/test_reporttemplates.py +++ b/tests/foreman/cli/test_reporttemplates.py @@ -987,7 +987,7 @@ def test_negative_generate_hostpkgcompare_nonexistent_host(): 'inputs': 'Host 1 = nonexistent1, ' 'Host 2 = nonexistent2', } ) - assert "At least one of the hosts couldn't be found" in cm.exception.stderr + assert "At least one of the hosts couldn't be found" in cm.exception.stderr @pytest.mark.rhel_ver_list([7, 8, 9]) diff --git a/tests/foreman/cli/test_role.py b/tests/foreman/cli/test_role.py index feeb1c928be..21900c30523 100644 --- a/tests/foreman/cli/test_role.py +++ b/tests/foreman/cli/test_role.py @@ -44,7 +44,7 @@ class TestRole: @pytest.mark.tier1 @pytest.mark.parametrize( - 'name, new_name', + ('name', 'new_name'), **parametrized( list(zip(generate_strings_list(length=10), generate_strings_list(length=10))) ), @@ -147,14 +147,13 @@ def test_negative_list_filters_without_parameters(self): :BZ: 1296782 """ - with pytest.raises(CLIReturnCodeError) as err: - try: - Role.filters() - except CLIDataBaseError as err: - pytest.fail(err) + with pytest.raises(CLIReturnCodeError, CLIDataBaseError) as err: + Role.filters() + if isinstance(err.type, CLIDataBaseError): + pytest.fail(err) assert re.search('At least one of options .* is required', err.value.msg) - @pytest.fixture() + @pytest.fixture def make_role_with_permissions(self): """Create new role with a filter""" role = make_role() diff --git a/tests/foreman/cli/test_satellitesync.py b/tests/foreman/cli/test_satellitesync.py index d5a5cfdf9f6..542c1124a57 100644 --- a/tests/foreman/cli/test_satellitesync.py +++ b/tests/foreman/cli/test_satellitesync.py @@ -63,7 +63,7 @@ def config_export_import_settings(): Settings.set({'name': 'subscription_connection_enabled', 'value': subs_conn_enabled_value}) -@pytest.fixture(scope='function') +@pytest.fixture def export_import_cleanup_function(target_sat, function_org): """Deletes export/import dirs of function org""" yield @@ -73,7 +73,7 @@ def export_import_cleanup_function(target_sat, function_org): ) -@pytest.fixture(scope='function') # perform the cleanup after each testcase of a module +@pytest.fixture # perform the cleanup after each testcase of a module def export_import_cleanup_module(target_sat, module_org): """Deletes export/import dirs of module_org""" yield @@ -83,19 +83,19 @@ def export_import_cleanup_module(target_sat, module_org): ) -@pytest.fixture(scope='function') +@pytest.fixture def function_import_org(target_sat): """Creates an Organization for content import.""" org = target_sat.api.Organization().create() - yield org + return org -@pytest.fixture(scope='function') +@pytest.fixture def function_import_org_with_manifest(target_sat, function_import_org): """Creates and sets an Organization with a brand-new manifest for content import.""" with Manifester(manifest_category=settings.manifest.golden_ticket) as manifest: target_sat.upload_manifest(function_import_org.id, manifest) - yield function_import_org + return function_import_org @pytest.fixture(scope='class') @@ -112,7 +112,7 @@ def docker_repo(module_target_sat, module_org): } ) Repository.synchronize({'id': repo['id']}) - yield repo + return repo @pytest.fixture(scope='module') @@ -126,10 +126,10 @@ def module_synced_custom_repo(module_target_sat, module_org, module_product): } ) module_target_sat.cli.Repository.synchronize({'id': repo['id']}) - yield repo + return repo -@pytest.fixture(scope='function') +@pytest.fixture def function_synced_custom_repo(target_sat, function_org, function_product): repo = target_sat.cli_factory.make_repository( { @@ -140,10 +140,10 @@ def function_synced_custom_repo(target_sat, function_org, function_product): } ) target_sat.cli.Repository.synchronize({'id': repo['id']}) - yield repo + return repo -@pytest.fixture(scope='function') +@pytest.fixture def function_synced_rhel_repo(request, target_sat, function_sca_manifest_org): """Enable and synchronize rhel content with immediate policy""" repo_dict = ( diff --git a/tests/foreman/cli/test_subnet.py b/tests/foreman/cli/test_subnet.py index 6dc36a640f7..5eefb2c24ad 100644 --- a/tests/foreman/cli/test_subnet.py +++ b/tests/foreman/cli/test_subnet.py @@ -210,10 +210,10 @@ def test_negative_update_attributes(options): options['id'] = subnet['id'] with pytest.raises(CLIReturnCodeError, match='Could not update the subnet:'): Subnet.update(options) - # check - subnet is not updated - result = Subnet.info({'id': subnet['id']}) - for key in options.keys(): - assert subnet[key] == result[key] + # check - subnet is not updated + result = Subnet.info({'id': subnet['id']}) + for key in options.keys(): + assert subnet[key] == result[key] @pytest.mark.tier2 diff --git a/tests/foreman/cli/test_user.py b/tests/foreman/cli/test_user.py index 9f3537b139a..c9bbd81d145 100644 --- a/tests/foreman/cli/test_user.py +++ b/tests/foreman/cli/test_user.py @@ -72,7 +72,7 @@ def roles_helper(): yield make_role({'name': role_name}) stubbed_roles = {role['id']: role for role in roles_helper()} - yield stubbed_roles + return stubbed_roles @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 57e3c8b9b17..61feba18d2f 100644 --- a/tests/foreman/cli/test_usergroup.py +++ b/tests/foreman/cli/test_usergroup.py @@ -34,11 +34,11 @@ from robottelo.utils.datafactory import valid_usernames_list -@pytest.fixture(scope='function') +@pytest.fixture def function_user_group(): """Create new usergroup per each test""" user_group = make_usergroup() - yield user_group + return user_group @pytest.mark.tier1 @@ -241,10 +241,10 @@ def test_negative_automate_bz1437578(ldap_auth_source, function_user_group): 'name': 'Domain Users', } ) - assert ( - '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 - ) + assert ( + '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 + ) diff --git a/tests/foreman/cli/test_webhook.py b/tests/foreman/cli/test_webhook.py index 3ca83dbe70f..29c08189449 100644 --- a/tests/foreman/cli/test_webhook.py +++ b/tests/foreman/cli/test_webhook.py @@ -28,7 +28,7 @@ from robottelo.constants import WEBHOOK_EVENTS, WEBHOOK_METHODS -@pytest.fixture(scope='function') +@pytest.fixture def webhook_factory(request, class_org, class_location): def _create_webhook(org, loc, options=None): """Function for creating a new Webhook diff --git a/tests/foreman/destructive/test_capsule_loadbalancer.py b/tests/foreman/destructive/test_capsule_loadbalancer.py index 04ba4614438..77adccd1fcf 100644 --- a/tests/foreman/destructive/test_capsule_loadbalancer.py +++ b/tests/foreman/destructive/test_capsule_loadbalancer.py @@ -88,7 +88,7 @@ def setup_capsules( {'id': capsule_id, 'organization-id': module_org.id} ) - yield { + return { 'capsule_1': module_lb_capsule[0], 'capsule_2': module_lb_capsule[1], } diff --git a/tests/foreman/destructive/test_infoblox.py b/tests/foreman/destructive/test_infoblox.py index a9de1690305..1230507f8e0 100644 --- a/tests/foreman/destructive/test_infoblox.py +++ b/tests/foreman/destructive/test_infoblox.py @@ -91,7 +91,7 @@ @pytest.mark.tier4 @pytest.mark.parametrize( - 'command_args,command_opts,rpm_command', + ('command_args', 'command_opts', 'rpm_command'), params, ids=['isc_dhcp', 'infoblox_dhcp', 'infoblox_dns'], ) diff --git a/tests/foreman/destructive/test_ldap_authentication.py b/tests/foreman/destructive/test_ldap_authentication.py index 39f5a6b4f65..65ef31aa2cf 100644 --- a/tests/foreman/destructive/test_ldap_authentication.py +++ b/tests/foreman/destructive/test_ldap_authentication.py @@ -80,7 +80,7 @@ def set_certificate_in_satellite(server_type, sat, hostname=None): raise AssertionError(f'Failed to restart the httpd after applying {server_type} cert') -@pytest.fixture() +@pytest.fixture def ldap_tear_down(module_target_sat): """Teardown the all ldap settings user, usergroup and ldap delete""" yield @@ -92,14 +92,14 @@ def ldap_tear_down(module_target_sat): ldap_auth.delete() -@pytest.fixture() +@pytest.fixture def external_user_count(module_target_sat): """return the external auth source user count""" users = module_target_sat.api.User().search() - yield len([user for user in users if user.auth_source_name == 'External']) + return len([user for user in users if user.auth_source_name == 'External']) -@pytest.fixture() +@pytest.fixture def groups_teardown(module_target_sat): """teardown for groups created for external/remote groups""" yield @@ -112,7 +112,7 @@ def groups_teardown(module_target_sat): user_groups[0].delete() -@pytest.fixture() +@pytest.fixture def rhsso_groups_teardown(module_target_sat, default_sso_host): """Teardown the rhsso groups""" yield @@ -384,6 +384,7 @@ def test_external_new_user_login_and_check_count_rhsso( with module_target_sat.ui_session(login=False) as rhsso_session: with pytest.raises(NavigationTriesExceeded) as error: rhsso_session.rhsso_login.login(login_details) + with pytest.raises(NavigationTriesExceeded) as error: rhsso_session.task.read_all() assert error.typename == 'NavigationTriesExceeded' @@ -430,6 +431,7 @@ def test_login_failure_rhsso_user_if_internal_user_exist( with module_target_sat.ui_session(login=False) as rhsso_session: with pytest.raises(NavigationTriesExceeded) as error: rhsso_session.rhsso_login.login(login_details) + with pytest.raises(NavigationTriesExceeded) as error: rhsso_session.task.read_all() assert error.typename == 'NavigationTriesExceeded' @@ -875,7 +877,7 @@ def test_positive_negotiate_logout( @pytest.mark.parametrize( - 'parametrized_enrolled_sat,user_not_exists', + ('parametrized_enrolled_sat', 'user_not_exists'), [('IDM', settings.ipa.user), ('AD', f'{settings.ldap.username}@{settings.ldap.realm.lower()}')], indirect=True, ids=['IDM', 'AD'], @@ -931,7 +933,7 @@ def test_positive_autonegotiate( @pytest.mark.parametrize( - 'parametrized_enrolled_sat,user_not_exists', + ('parametrized_enrolled_sat', 'user_not_exists'), [('IDM', settings.ipa.user), ('AD', f'{settings.ldap.username}@{settings.ldap.realm.lower()}')], indirect=True, ids=['IDM', 'AD'], @@ -1013,7 +1015,7 @@ def test_positive_negotiate_manual_with_autonegotiation_disabled( ids=['sessions_enabled', 'sessions_disabled'], ) @pytest.mark.parametrize( - 'parametrized_enrolled_sat,user_not_exists', + ('parametrized_enrolled_sat', 'user_not_exists'), [('IDM', settings.ipa.user), ('AD', f'{settings.ldap.username}@{settings.ldap.realm.lower()}')], indirect=True, ids=['IDM', 'AD'], diff --git a/tests/foreman/destructive/test_ldapauthsource.py b/tests/foreman/destructive/test_ldapauthsource.py index fdbc2da11ba..58e3ceb3e84 100644 --- a/tests/foreman/destructive/test_ldapauthsource.py +++ b/tests/foreman/destructive/test_ldapauthsource.py @@ -34,20 +34,16 @@ def configure_hammer_session(sat, enable=True): sat.execute(f"echo ' :use_sessions: {'true' if enable else 'false'}' >> {HAMMER_CONFIG}") -@pytest.fixture() +@pytest.fixture def rh_sso_hammer_auth_setup(module_target_sat, default_sso_host, request): """rh_sso hammer setup before running the auth login tests""" configure_hammer_session(module_target_sat) client_config = {'publicClient': 'true'} default_sso_host.update_client_configuration(client_config) - - def rh_sso_hammer_auth_cleanup(): - """restore the hammer config backup file and rhsso client settings""" - module_target_sat.execute(f'mv {HAMMER_CONFIG}.backup {HAMMER_CONFIG}') - client_config = {'publicClient': 'false'} - default_sso_host.update_client_configuration(client_config) - - request.addfinalizer(rh_sso_hammer_auth_cleanup) + yield + module_target_sat.execute(f'mv {HAMMER_CONFIG}.backup {HAMMER_CONFIG}') + client_config = {'publicClient': 'false'} + default_sso_host.update_client_configuration(client_config) def test_rhsso_login_using_hammer( diff --git a/tests/foreman/destructive/test_ping.py b/tests/foreman/destructive/test_ping.py index 67818b6a74e..e683a84a2b6 100644 --- a/tests/foreman/destructive/test_ping.py +++ b/tests/foreman/destructive/test_ping.py @@ -29,7 +29,7 @@ def tomcat_service_teardown(request, module_target_sat): def _finalize(): assert module_target_sat.cli.Service.start(options={'only': 'tomcat.service'}).status == 0 - yield module_target_sat + return module_target_sat def test_negative_cli_ping_fail_status(tomcat_service_teardown): diff --git a/tests/foreman/maintain/test_health.py b/tests/foreman/maintain/test_health.py index 0dd4320d633..3793dad8b01 100644 --- a/tests/foreman/maintain/test_health.py +++ b/tests/foreman/maintain/test_health.py @@ -589,9 +589,8 @@ def test_positive_health_check_foreman_proxy_verify_dhcp_config_syntax(sat_maint result = sat_maintain.cli.Health.check( options={'label': 'foreman-proxy-verify-dhcp-config-syntax'} ) - assert ( - 'No scenario matching label' and 'foreman-proxy-verify-dhcp-config-syntax' in result.stdout - ) + assert 'No scenario matching label' + assert 'foreman-proxy-verify-dhcp-config-syntax' in result.stdout # Enable DHCP installer = sat_maintain.install( InstallerCommand('enable-foreman-proxy-plugin-dhcp-remote-isc', 'foreman-proxy-dhcp true') @@ -617,9 +616,8 @@ def test_positive_health_check_foreman_proxy_verify_dhcp_config_syntax(sat_maint result = sat_maintain.cli.Health.check( options={'label': 'foreman-proxy-verify-dhcp-config-syntax'} ) - assert ( - 'No scenario matching label' and 'foreman-proxy-verify-dhcp-config-syntax' in result.stdout - ) + assert 'No scenario matching label' + assert 'foreman-proxy-verify-dhcp-config-syntax' in result.stdout def test_positive_remove_job_file(sat_maintain): diff --git a/tests/foreman/sys/test_katello_certs_check.py b/tests/foreman/sys/test_katello_certs_check.py index f058328e2e4..3ce28168e46 100644 --- a/tests/foreman/sys/test_katello_certs_check.py +++ b/tests/foreman/sys/test_katello_certs_check.py @@ -188,7 +188,7 @@ def test_katello_certs_check_output_wildcard_inputs(self, cert_setup_teardown): result = target_sat.execute(command) self.validate_output(result, cert_data) - @pytest.mark.parametrize('error, cert_file, key_file, ca_file', invalid_inputs) + @pytest.mark.parametrize(('error', 'cert_file', 'key_file', 'ca_file'), invalid_inputs) @pytest.mark.tier1 def test_katello_certs_check_output_invalid_input( self, @@ -264,7 +264,7 @@ def test_negative_check_expiration_of_certificate(self, cert_setup_teardown): assert message == check break else: - assert False, f'Failed, Unable to find message "{message}" in result' + pytest.fail(f'Failed, Unable to find message "{message}" in result') target_sat.execute("date -s 'last year'") @pytest.mark.stubbed diff --git a/tests/foreman/ui/test_contenthost.py b/tests/foreman/ui/test_contenthost.py index 97cdef261fd..46ef82e5201 100644 --- a/tests/foreman/ui/test_contenthost.py +++ b/tests/foreman/ui/test_contenthost.py @@ -76,7 +76,7 @@ def vm(module_repos_collection_with_manifest, rhel7_contenthost, target_sat): module_repos_collection_with_manifest.setup_virtual_machine(rhel7_contenthost) rhel7_contenthost.add_rex_key(target_sat) rhel7_contenthost.run(r'subscription-manager repos --enable \*') - yield rhel7_contenthost + return rhel7_contenthost @pytest.fixture @@ -84,7 +84,7 @@ def vm_module_streams(module_repos_collection_with_manifest, rhel8_contenthost, """Virtual machine registered in satellite""" module_repos_collection_with_manifest.setup_virtual_machine(rhel8_contenthost) rhel8_contenthost.add_rex_key(satellite=target_sat) - yield rhel8_contenthost + return rhel8_contenthost def set_ignore_facts_for_os(value=False): @@ -1006,7 +1006,8 @@ def test_module_stream_actions_on_content_host(session, default_location, vm_mod ) assert module_stream[0]['Name'] == FAKE_2_CUSTOM_PACKAGE_NAME assert module_stream[0]['Stream'] == stream_version - assert 'Enabled' and 'Installed' in module_stream[0]['Status'] + assert 'Enabled' + assert 'Installed' in module_stream[0]['Status'] # remove Module Stream result = session.contenthost.execute_module_stream_action( diff --git a/tests/foreman/ui/test_contentview_old.py b/tests/foreman/ui/test_contentview_old.py index 173243835e9..cfc135c3c9c 100644 --- a/tests/foreman/ui/test_contentview_old.py +++ b/tests/foreman/ui/test_contentview_old.py @@ -2063,7 +2063,8 @@ def test_positive_update_inclusive_filter_package_version(session, module_org, t cv.name, VERSION, 'name = "{}" and version = "{}"'.format(package_name, '0.71') ) assert len(packages) == 1 - assert packages[0]['Name'] == package_name and packages[0]['Version'] == '0.71' + assert packages[0]['Name'] == package_name + assert packages[0]['Version'] == '0.71' packages = session.contentview.search_version_package( cv.name, VERSION, 'name = "{}" and version = "{}"'.format(package_name, '5.21') ) @@ -2084,7 +2085,8 @@ def test_positive_update_inclusive_filter_package_version(session, module_org, t cv.name, new_version, 'name = "{}" and version = "{}"'.format(package_name, '5.21') ) assert len(packages) == 1 - assert packages[0]['Name'] == package_name and packages[0]['Version'] == '5.21' + assert packages[0]['Name'] == package_name + assert packages[0]['Version'] == '5.21' @pytest.mark.skip_if_open('BZ:2086957') @@ -2125,7 +2127,8 @@ def test_positive_update_exclusive_filter_package_version(session, module_org, t cv.name, VERSION, 'name = "{}" and version = "{}"'.format(package_name, '5.21') ) assert len(packages) == 1 - assert packages[0]['Name'] == package_name and packages[0]['Version'] == '5.21' + assert packages[0]['Name'] == package_name + assert packages[0]['Version'] == '5.21' packages = session.contentview.search_version_package( cv.name, VERSION, 'name = "{}" and version = "{}"'.format(package_name, '0.71') ) @@ -2146,7 +2149,8 @@ def test_positive_update_exclusive_filter_package_version(session, module_org, t cv.name, new_version, 'name = "{}" and version = "{}"'.format(package_name, '0.71') ) assert len(packages) == 1 - assert packages[0]['Name'] == package_name and packages[0]['Version'] == '0.71' + assert packages[0]['Name'] == package_name + assert packages[0]['Version'] == '0.71' @pytest.mark.skip_if_open('BZ:2086957') @@ -2516,7 +2520,8 @@ def test_positive_update_filter_affected_repos(session, module_org, target_sat): cv.name, VERSION, 'name = "{}" and version = "{}"'.format(repo1_package_name, '4.2.8') ) assert len(packages) == 1 - assert packages[0]['Name'] == repo1_package_name and packages[0]['Version'] == '4.2.8' + assert packages[0]['Name'] == repo1_package_name + assert packages[0]['Version'] == '4.2.8' packages = session.contentview.search_version_package( cv.name, VERSION, 'name = "{}" and version = "{}"'.format(repo1_package_name, '4.2.9') ) @@ -2529,7 +2534,8 @@ def test_positive_update_filter_affected_repos(session, module_org, target_sat): 'name = "{}" and version = "{}"'.format(repo2_package_name, '3.10.232'), ) assert len(packages) == 1 - assert packages[0]['Name'] == repo2_package_name and packages[0]['Version'] == '3.10.232' + assert packages[0]['Name'] == repo2_package_name + assert packages[0]['Version'] == '3.10.232' @pytest.mark.tier3 @@ -3040,10 +3046,8 @@ def test_positive_search_module_streams_in_content_view(session, module_org, tar f'name = "{module_stream}" and stream = "{module_version}"', ) assert len(module_streams) == 1 - assert ( - module_streams[0]['Name'] == module_stream - and module_streams[0]['Stream'] == module_version - ) + assert module_streams[0]['Name'] == module_stream + assert module_streams[0]['Stream'] == module_version @pytest.mark.tier2 diff --git a/tests/foreman/ui/test_discoveryrule.py b/tests/foreman/ui/test_discoveryrule.py index e529578efca..d61d5067f85 100644 --- a/tests/foreman/ui/test_discoveryrule.py +++ b/tests/foreman/ui/test_discoveryrule.py @@ -155,7 +155,7 @@ def test_negative_delete_rule_with_non_admin_user( location=[module_location], ).create() with Session(user=reader_user.login, password=reader_user.password) as session: - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 - TODO Adarsh determine better exception session.discoveryrule.delete(dr.name) dr_val = session.discoveryrule.read_all() assert dr.name in [rule['Name'] for rule in dr_val] diff --git a/tests/foreman/ui/test_errata.py b/tests/foreman/ui/test_errata.py index 755a69172dc..632fcefad32 100644 --- a/tests/foreman/ui/test_errata.py +++ b/tests/foreman/ui/test_errata.py @@ -155,12 +155,12 @@ def errata_status_installable(): _set_setting_value(errata_status_installable, original_value) -@pytest.fixture(scope='function') +@pytest.fixture def vm(module_repos_collection_with_setup, rhel7_contenthost, target_sat): """Virtual machine registered in satellite""" module_repos_collection_with_setup.setup_virtual_machine(rhel7_contenthost) rhel7_contenthost.add_rex_key(satellite=target_sat) - yield rhel7_contenthost + return rhel7_contenthost @pytest.mark.e2e diff --git a/tests/foreman/ui/test_host.py b/tests/foreman/ui/test_host.py index b76273263bf..ac44d35bf2d 100644 --- a/tests/foreman/ui/test_host.py +++ b/tests/foreman/ui/test_host.py @@ -64,7 +64,7 @@ def ui_user(ui_user, smart_proxy_location, module_target_sat): id=ui_user.id, default_location=smart_proxy_location, ).update(['default_location']) - yield ui_user + return ui_user @pytest.fixture @@ -133,7 +133,7 @@ def tracer_install_host(rex_contenthost, target_sat): rex_contenthost.create_custom_repos( **{f'rhel{rhelver}_os': settings.repos[f'rhel{rhelver}_os']} ) - yield rex_contenthost + return rex_contenthost @pytest.mark.e2e @@ -750,9 +750,9 @@ def test_positive_check_permissions_affect_create_procedure( ] with Session(test_name, user=user.login, password=user_password) as session: for host_field in host_fields: + values = {host_field['name']: host_field['unexpected_value']} + values.update(host_field.get('other_fields_values', {})) with pytest.raises(NoSuchElementException) as context: - values = {host_field['name']: host_field['unexpected_value']} - values.update(host_field.get('other_fields_values', {})) session.host.helper.read_create_view(values) error_message = str(context.value) assert host_field['unexpected_value'] in error_message diff --git a/tests/foreman/ui/test_jobinvocation.py b/tests/foreman/ui/test_jobinvocation.py index 62ab4ed5ef4..bb773841ef6 100644 --- a/tests/foreman/ui/test_jobinvocation.py +++ b/tests/foreman/ui/test_jobinvocation.py @@ -29,7 +29,7 @@ def module_rhel_client_by_ip(module_org, smart_proxy_location, rhel7_contenthost target_sat.api_factory.update_vm_host_location( rhel7_contenthost, location_id=smart_proxy_location.id ) - yield rhel7_contenthost + return rhel7_contenthost @pytest.mark.tier4 diff --git a/tests/foreman/ui/test_ldap_authentication.py b/tests/foreman/ui/test_ldap_authentication.py index e1983767e77..b72d1bbcd8f 100644 --- a/tests/foreman/ui/test_ldap_authentication.py +++ b/tests/foreman/ui/test_ldap_authentication.py @@ -59,7 +59,7 @@ def set_certificate_in_satellite(server_type, target_sat, hostname=None): raise AssertionError(f'Failed to restart the httpd after applying {server_type} cert') -@pytest.fixture() +@pytest.fixture def ldap_usergroup_name(): """Return some random usergroup name, and attempt to delete such usergroup when test finishes. @@ -71,7 +71,7 @@ def ldap_usergroup_name(): user_groups[0].delete() -@pytest.fixture() +@pytest.fixture def ldap_tear_down(): """Teardown the all ldap settings user, usergroup and ldap delete""" yield @@ -83,14 +83,14 @@ def ldap_tear_down(): ldap_auth.delete() -@pytest.fixture() +@pytest.fixture def external_user_count(): """return the external auth source user count""" users = entities.User().search() - yield len([user for user in users if user.auth_source_name == 'External']) + return len([user for user in users if user.auth_source_name == 'External']) -@pytest.fixture() +@pytest.fixture def groups_teardown(): """teardown for groups created for external/remote groups""" yield @@ -101,7 +101,7 @@ def groups_teardown(): user_groups[0].delete() -@pytest.fixture() +@pytest.fixture def rhsso_groups_teardown(default_sso_host): """Teardown the rhsso groups""" yield @@ -109,7 +109,7 @@ def rhsso_groups_teardown(default_sso_host): default_sso_host.delete_rhsso_group(group_name) -@pytest.fixture() +@pytest.fixture def multigroup_setting_cleanup(default_ipa_host): """Adding and removing the user to/from ipa group""" sat_users = settings.ipa.groups @@ -119,7 +119,7 @@ def multigroup_setting_cleanup(default_ipa_host): default_ipa_host.remove_user_from_usergroup(idm_users[1], sat_users[0]) -@pytest.fixture() +@pytest.fixture def ipa_add_user(default_ipa_host): """Create an IPA user and delete it""" test_user = gen_string('alpha') diff --git a/tests/foreman/ui/test_partitiontable.py b/tests/foreman/ui/test_partitiontable.py index 393a2ca634f..e36d448698d 100644 --- a/tests/foreman/ui/test_partitiontable.py +++ b/tests/foreman/ui/test_partitiontable.py @@ -167,7 +167,7 @@ def test_positive_delete_with_lock_and_unlock(session): ) assert session.partitiontable.search(name)[0]['Name'] == name session.partitiontable.lock(name) - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 - TODO determine better exception session.partitiontable.delete(name) session.partitiontable.unlock(name) session.partitiontable.delete(name) diff --git a/tests/foreman/ui/test_provisioningtemplate.py b/tests/foreman/ui/test_provisioningtemplate.py index 579ca711f7b..62b9169a729 100644 --- a/tests/foreman/ui/test_provisioningtemplate.py +++ b/tests/foreman/ui/test_provisioningtemplate.py @@ -27,7 +27,7 @@ def template_data(): return DataFile.OS_TEMPLATE_DATA_FILE.read_text() -@pytest.fixture() +@pytest.fixture def clone_setup(target_sat, module_org, module_location): name = gen_string('alpha') content = gen_string('alpha') diff --git a/tests/foreman/ui/test_repository.py b/tests/foreman/ui/test_repository.py index 63b7df93577..8395d096967 100644 --- a/tests/foreman/ui/test_repository.py +++ b/tests/foreman/ui/test_repository.py @@ -227,8 +227,8 @@ def test_positive_create_as_non_admin_user_with_cv_published(module_org, test_na with Session(test_name, user_login, user_password) as session: # ensure that the created user is not a global admin user # check administer->users page + pswd = gen_string('alphanumeric') with pytest.raises(NavigationTriesExceeded): - pswd = gen_string('alphanumeric') session.user.create( { 'user.login': gen_string('alphanumeric'), @@ -774,7 +774,8 @@ def test_positive_reposet_disable(session, target_sat, function_entitlement_mani ) ] ) - assert results and all([result == 'Syncing Complete.' for result in results]) + assert results + assert all([result == 'Syncing Complete.' for result in results]) session.redhatrepository.disable(repository_name) assert not session.redhatrepository.search( f'name = "{repository_name}"', category='Enabled' @@ -825,7 +826,8 @@ def test_positive_reposet_disable_after_manifest_deleted( ) ] ) - assert results and all([result == 'Syncing Complete.' for result in results]) + assert results + assert all([result == 'Syncing Complete.' for result in results]) # Delete manifest sub.delete_manifest(data={'organization_id': org.id}) # Verify that the displayed repository name is correct @@ -904,7 +906,8 @@ def test_positive_delete_rhel_repo(session, module_entitlement_manifest_org, tar ) ] ) - assert results and all([result == 'Syncing Complete.' for result in results]) + assert results + assert all([result == 'Syncing Complete.' for result in results]) session.repository.delete(product_name, repository_name) assert not session.redhatrepository.search( f'name = "{repository_name}"', category='Enabled' diff --git a/tests/foreman/ui/test_rhc.py b/tests/foreman/ui/test_rhc.py index 6fa17a18589..2ffe7b11e12 100644 --- a/tests/foreman/ui/test_rhc.py +++ b/tests/foreman/ui/test_rhc.py @@ -64,7 +64,7 @@ def module_rhc_org(module_target_sat): return org -@pytest.fixture() +@pytest.fixture def fixture_setup_rhc_satellite( request, module_target_sat, diff --git a/tests/foreman/ui/test_settings.py b/tests/foreman/ui/test_settings.py index ade4cd9afbe..923d542443d 100644 --- a/tests/foreman/ui/test_settings.py +++ b/tests/foreman/ui/test_settings.py @@ -83,10 +83,10 @@ def test_positive_update_restrict_composite_view(session, setting_update, repo_s session.contentview.promote( composite_cv.name, 'Version 1.0', repo_setup['lce'].name ) - assert ( - 'Administrator -> Settings -> Content page using the ' - 'restrict_composite_view flag.' in str(context.value) - ) + assert ( + 'Administrator -> Settings -> Content page using the ' + 'restrict_composite_view flag.' in str(context.value) + ) else: result = session.contentview.promote( composite_cv.name, 'Version 1.0', repo_setup['lce'].name @@ -139,7 +139,7 @@ def test_negative_validate_foreman_url_error_message(session, setting_update): invalid_value = [invalid_value for invalid_value in invalid_settings_values()][0] with pytest.raises(AssertionError) as context: session.settings.update(f'name = {property_name}', invalid_value) - assert 'Value is invalid: must be integer' in str(context.value) + assert 'Value is invalid: must be integer' in str(context.value) @pytest.mark.tier2 @@ -509,7 +509,7 @@ def test_negative_update_hostname_with_empty_fact(session, setting_update): with session: with pytest.raises(AssertionError) as context: session.settings.update(property_name, new_hostname) - assert 'can\'t be blank' in str(context.value) + assert 'can\'t be blank' in str(context.value) @pytest.mark.run_in_one_thread diff --git a/tests/foreman/ui/test_subscription.py b/tests/foreman/ui/test_subscription.py index 2196eabb60b..13878f24ab9 100644 --- a/tests/foreman/ui/test_subscription.py +++ b/tests/foreman/ui/test_subscription.py @@ -397,7 +397,8 @@ def test_positive_view_vdc_guest_subscription_products( f'subscription_name = "{VDC_SUBSCRIPTION_NAME}" ' f'and name = "{virt_who_hypervisor_host["name"]}"' ) - assert content_hosts and content_hosts[0]['Name'] == virt_who_hypervisor_host['name'] + assert content_hosts + assert content_hosts[0]['Name'] == virt_who_hypervisor_host['name'] # ensure that hypervisor guests subscription provided products list is not empty and # that the product is in provided products. provided_products = session.subscription.provided_products( diff --git a/tests/foreman/virtwho/api/test_esx.py b/tests/foreman/virtwho/api/test_esx.py index 1e0396d4ce5..e7544047d7e 100644 --- a/tests/foreman/virtwho/api/test_esx.py +++ b/tests/foreman/virtwho/api/test_esx.py @@ -383,10 +383,9 @@ def test_positive_remove_env_option( env_error = ( f"option {{\'{option}\'}} is not exist or not be enabled in {{\'{config_file}\'}}" ) - try: + with pytest.raises(Exception) as exc_info: # noqa: PT011 - TODO determine better exception get_configure_option({option}, {config_file}) - except Exception as VirtWhoError: - assert env_error == str(VirtWhoError) + assert str(exc_info.value) == env_error # Check /var/log/messages should not display warning message env_warning = f"Ignoring unknown configuration option \"{option}\"" result = target_sat.execute(f'grep "{env_warning}" /var/log/messages') diff --git a/tests/foreman/virtwho/api/test_esx_sca.py b/tests/foreman/virtwho/api/test_esx_sca.py index 3a967cbded1..3ac780254f0 100644 --- a/tests/foreman/virtwho/api/test_esx_sca.py +++ b/tests/foreman/virtwho/api/test_esx_sca.py @@ -431,10 +431,9 @@ def test_positive_remove_env_option( env_error = ( f"option {{\'{option}\'}} is not exist or not be enabled in {{\'{config_file}\'}}" ) - try: + with pytest.raises(Exception) as exc_info: # noqa: PT011 - TODO determine better exception get_configure_option({option}, {config_file}) - except Exception as VirtWhoError: - assert env_error == str(VirtWhoError) + assert str(exc_info.value) == env_error # Check /var/log/messages should not display warning message env_warning = f"Ignoring unknown configuration option \"{option}\"" result = target_sat.execute(f'grep "{env_warning}" /var/log/messages') diff --git a/tests/foreman/virtwho/api/test_nutanix.py b/tests/foreman/virtwho/api/test_nutanix.py index d9ddc34938f..ae2726cf610 100644 --- a/tests/foreman/virtwho/api/test_nutanix.py +++ b/tests/foreman/virtwho/api/test_nutanix.py @@ -250,10 +250,9 @@ def test_positive_ahv_internal_debug_option( config_file = get_configure_file(virtwho_config_api.id) option = 'ahv_internal_debug' env_error = f"option {option} is not exist or not be enabled in {config_file}" - try: + with pytest.raises(Exception) as exc_info: # noqa: PT011 - TODO determine better exception get_configure_option("ahv_internal_debug", config_file) - except Exception as VirtWhoError: - assert env_error == str(VirtWhoError) + assert str(exc_info.value) == env_error # check message exist in log file /var/log/rhsm/rhsm.log message = 'Value for "ahv_internal_debug" not set, using default: False' assert check_message_in_rhsm_log(message) == message diff --git a/tests/foreman/virtwho/cli/test_esx.py b/tests/foreman/virtwho/cli/test_esx.py index fe2b1827bf6..c604fc6f3f2 100644 --- a/tests/foreman/virtwho/cli/test_esx.py +++ b/tests/foreman/virtwho/cli/test_esx.py @@ -38,7 +38,7 @@ ) -@pytest.fixture() +@pytest.fixture def form_data(target_sat, default_org): form = { 'name': gen_string('alpha'), @@ -56,7 +56,7 @@ def form_data(target_sat, default_org): return form -@pytest.fixture() +@pytest.fixture def virtwho_config(form_data, target_sat): virtwho_config = target_sat.cli.VirtWhoConfig.create(form_data)['general-information'] yield virtwho_config @@ -446,10 +446,9 @@ def test_positive_remove_env_option(self, default_org, form_data, virtwho_config env_error = ( f"option {{\'{option}\'}} is not exist or not be enabled in {{\'{config_file}\'}}" ) - try: + with pytest.raises(Exception) as exc_info: # noqa: PT011 - TODO determine better exception get_configure_option({option}, {config_file}) - except Exception as VirtWhoError: - assert env_error == str(VirtWhoError) + assert str(exc_info.value) == env_error # Check /var/log/messages should not display warning message env_warning = f"Ignoring unknown configuration option \"{option}\"" result = target_sat.execute(f'grep "{env_warning}" /var/log/messages') diff --git a/tests/foreman/virtwho/cli/test_esx_sca.py b/tests/foreman/virtwho/cli/test_esx_sca.py index df15cce8105..d8ec7c71d9d 100644 --- a/tests/foreman/virtwho/cli/test_esx_sca.py +++ b/tests/foreman/virtwho/cli/test_esx_sca.py @@ -36,7 +36,7 @@ ) -@pytest.fixture() +@pytest.fixture def form_data(target_sat, module_sca_manifest_org): form = { 'name': gen_string('alpha'), @@ -54,7 +54,7 @@ def form_data(target_sat, module_sca_manifest_org): return form -@pytest.fixture() +@pytest.fixture def virtwho_config(form_data, target_sat): virtwho_config = target_sat.cli.VirtWhoConfig.create(form_data)['general-information'] yield virtwho_config @@ -545,10 +545,9 @@ def test_positive_remove_env_option( env_error = ( f"option {{\'{option}\'}} is not exist or not be enabled in {{\'{config_file}\'}}" ) - try: + with pytest.raises(Exception) as exc_info: # noqa: PT011 - TODO determine better exception get_configure_option({option}, {config_file}) - except Exception as VirtWhoError: - assert env_error == str(VirtWhoError) + assert str(exc_info.value) == env_error # Check /var/log/messages should not display warning message env_warning = f"Ignoring unknown configuration option \"{option}\"" result = target_sat.execute(f'grep "{env_warning}" /var/log/messages') diff --git a/tests/foreman/virtwho/cli/test_hyperv.py b/tests/foreman/virtwho/cli/test_hyperv.py index 1fa31db9f00..35e90d61eb1 100644 --- a/tests/foreman/virtwho/cli/test_hyperv.py +++ b/tests/foreman/virtwho/cli/test_hyperv.py @@ -29,7 +29,7 @@ ) -@pytest.fixture() +@pytest.fixture def form_data(target_sat, default_org): form = { 'name': gen_string('alpha'), @@ -47,7 +47,7 @@ def form_data(target_sat, default_org): return form -@pytest.fixture() +@pytest.fixture def virtwho_config(form_data, target_sat): virtwho_config = target_sat.cli.VirtWhoConfig.create(form_data)['general-information'] yield virtwho_config diff --git a/tests/foreman/virtwho/cli/test_hyperv_sca.py b/tests/foreman/virtwho/cli/test_hyperv_sca.py index e3909489e21..6d60e285c9d 100644 --- a/tests/foreman/virtwho/cli/test_hyperv_sca.py +++ b/tests/foreman/virtwho/cli/test_hyperv_sca.py @@ -29,7 +29,7 @@ ) -@pytest.fixture() +@pytest.fixture def form_data(target_sat, module_sca_manifest_org): form = { 'name': gen_string('alpha'), @@ -47,7 +47,7 @@ def form_data(target_sat, module_sca_manifest_org): return form -@pytest.fixture() +@pytest.fixture def virtwho_config(form_data, target_sat): virtwho_config = target_sat.cli.VirtWhoConfig.create(form_data)['general-information'] yield virtwho_config diff --git a/tests/foreman/virtwho/cli/test_kubevirt.py b/tests/foreman/virtwho/cli/test_kubevirt.py index c6d38de60dd..e003294de87 100644 --- a/tests/foreman/virtwho/cli/test_kubevirt.py +++ b/tests/foreman/virtwho/cli/test_kubevirt.py @@ -29,7 +29,7 @@ ) -@pytest.fixture() +@pytest.fixture def form_data(target_sat, default_org): form = { 'name': gen_string('alpha'), @@ -45,7 +45,7 @@ def form_data(target_sat, default_org): return form -@pytest.fixture() +@pytest.fixture def virtwho_config(form_data, target_sat): virtwho_config = target_sat.cli.VirtWhoConfig.create(form_data)['general-information'] yield virtwho_config diff --git a/tests/foreman/virtwho/cli/test_kubevirt_sca.py b/tests/foreman/virtwho/cli/test_kubevirt_sca.py index 99e4335c9f6..9746d80c34b 100644 --- a/tests/foreman/virtwho/cli/test_kubevirt_sca.py +++ b/tests/foreman/virtwho/cli/test_kubevirt_sca.py @@ -27,7 +27,7 @@ ) -@pytest.fixture() +@pytest.fixture def form_data(target_sat, module_sca_manifest_org): form = { 'name': gen_string('alpha'), @@ -43,7 +43,7 @@ def form_data(target_sat, module_sca_manifest_org): return form -@pytest.fixture() +@pytest.fixture def virtwho_config(form_data, target_sat): virtwho_config = target_sat.cli.VirtWhoConfig.create(form_data)['general-information'] yield virtwho_config diff --git a/tests/foreman/virtwho/cli/test_libvirt.py b/tests/foreman/virtwho/cli/test_libvirt.py index 1f5b034b473..5cd4280e4f3 100644 --- a/tests/foreman/virtwho/cli/test_libvirt.py +++ b/tests/foreman/virtwho/cli/test_libvirt.py @@ -29,7 +29,7 @@ ) -@pytest.fixture() +@pytest.fixture def form_data(target_sat, default_org): form = { 'name': gen_string('alpha'), @@ -46,7 +46,7 @@ def form_data(target_sat, default_org): return form -@pytest.fixture() +@pytest.fixture def virtwho_config(form_data, target_sat): virtwho_config = target_sat.cli.VirtWhoConfig.create(form_data)['general-information'] yield virtwho_config diff --git a/tests/foreman/virtwho/cli/test_libvirt_sca.py b/tests/foreman/virtwho/cli/test_libvirt_sca.py index b29ffaf667f..b1a359c0095 100644 --- a/tests/foreman/virtwho/cli/test_libvirt_sca.py +++ b/tests/foreman/virtwho/cli/test_libvirt_sca.py @@ -27,7 +27,7 @@ ) -@pytest.fixture() +@pytest.fixture def form_data(target_sat, module_sca_manifest_org): form = { 'name': gen_string('alpha'), @@ -44,7 +44,7 @@ def form_data(target_sat, module_sca_manifest_org): return form -@pytest.fixture() +@pytest.fixture def virtwho_config(form_data, target_sat): virtwho_config = target_sat.cli.VirtWhoConfig.create(form_data)['general-information'] yield virtwho_config diff --git a/tests/foreman/virtwho/cli/test_nutanix.py b/tests/foreman/virtwho/cli/test_nutanix.py index 9b9437d0386..ed9ad20ce49 100644 --- a/tests/foreman/virtwho/cli/test_nutanix.py +++ b/tests/foreman/virtwho/cli/test_nutanix.py @@ -31,7 +31,7 @@ ) -@pytest.fixture() +@pytest.fixture def form_data(target_sat, default_org): form = { 'name': gen_string('alpha'), @@ -51,7 +51,7 @@ def form_data(target_sat, default_org): return form -@pytest.fixture() +@pytest.fixture def virtwho_config(form_data, target_sat): virtwho_config = target_sat.cli.VirtWhoConfig.create(form_data)['general-information'] yield virtwho_config @@ -260,10 +260,9 @@ def test_positive_ahv_internal_debug_option( config_file = get_configure_file(virtwho_config['id']) option = 'ahv_internal_debug' env_error = f"option {option} is not exist or not be enabled in {config_file}" - try: + with pytest.raises(Exception) as exc_info: # noqa: PT011 - TODO determine better exception get_configure_option("ahv_internal_debug", config_file) - except Exception as VirtWhoError: - assert env_error == str(VirtWhoError) + assert str(exc_info.value) == env_error # check message exist in log file /var/log/rhsm/rhsm.log message = 'Value for "ahv_internal_debug" not set, using default: False' assert check_message_in_rhsm_log(message) == message diff --git a/tests/foreman/virtwho/cli/test_nutanix_sca.py b/tests/foreman/virtwho/cli/test_nutanix_sca.py index 59ba58f6f60..44876700c23 100644 --- a/tests/foreman/virtwho/cli/test_nutanix_sca.py +++ b/tests/foreman/virtwho/cli/test_nutanix_sca.py @@ -29,7 +29,7 @@ ) -@pytest.fixture() +@pytest.fixture def form_data(target_sat, module_sca_manifest_org): sca_form = { 'name': gen_string('alpha'), @@ -48,7 +48,7 @@ def form_data(target_sat, module_sca_manifest_org): return sca_form -@pytest.fixture() +@pytest.fixture def virtwho_config(form_data, target_sat): virtwho_config = target_sat.cli.VirtWhoConfig.create(form_data)['general-information'] yield virtwho_config diff --git a/tests/foreman/virtwho/conftest.py b/tests/foreman/virtwho/conftest.py index 0bd09647bf6..8e422b22940 100644 --- a/tests/foreman/virtwho/conftest.py +++ b/tests/foreman/virtwho/conftest.py @@ -36,7 +36,7 @@ def module_user(request, module_target_sat, default_org, default_location): logger.warning('Unable to delete session user: %s', str(err)) -@pytest.fixture() +@pytest.fixture def session(test_name, module_user): """Session fixture which automatically initializes (but does not start!) airgun UI session and correctly passes current test name to it. Uses shared @@ -84,7 +84,7 @@ def module_user_sca(request, module_target_sat, module_org, module_location): logger.warning('Unable to delete session user: %s', str(err)) -@pytest.fixture() +@pytest.fixture def session_sca(test_name, module_user_sca): """Session fixture which automatically initializes (but does not start!) airgun UI session and correctly passes current test name to it. Uses shared diff --git a/tests/foreman/virtwho/ui/test_esx.py b/tests/foreman/virtwho/ui/test_esx.py index 2715febb34f..75652da9bd6 100644 --- a/tests/foreman/virtwho/ui/test_esx.py +++ b/tests/foreman/virtwho/ui/test_esx.py @@ -752,10 +752,9 @@ def test_positive_remove_env_option( env_error = ( f"option {{\'{option}\'}} is not exist or not be enabled in {{\'{config_file}\'}}" ) - try: + with pytest.raises(Exception) as exc_info: # noqa: PT011 - TODO determine better exception get_configure_option({option}, {config_file}) - except Exception as VirtWhoError: - assert env_error == str(VirtWhoError) + assert str(exc_info.value) == env_error # Check /var/log/messages should not display warning message env_warning = f"Ignoring unknown configuration option \"{option}\"" result = target_sat.execute(f'grep "{env_warning}" /var/log/messages') diff --git a/tests/foreman/virtwho/ui/test_esx_sca.py b/tests/foreman/virtwho/ui/test_esx_sca.py index f8eb03fea98..63c4c55a16b 100644 --- a/tests/foreman/virtwho/ui/test_esx_sca.py +++ b/tests/foreman/virtwho/ui/test_esx_sca.py @@ -327,10 +327,9 @@ def test_positive_remove_env_option( env_error = ( f"option {{\'{option}\'}} is not exist or not be enabled in {{\'{config_file}\'}}" ) - try: + with pytest.raises(Exception) as exc_info: # noqa: PT011 - TODO determine better exception get_configure_option({option}, {config_file}) - except Exception as VirtWhoError: - assert env_error == str(VirtWhoError) + assert str(exc_info.value) == env_error # Check /var/log/messages should not display warning message env_warning = f"Ignoring unknown configuration option \"{option}\"" result = target_sat.execute(f'grep "{env_warning}" /var/log/messages') diff --git a/tests/foreman/virtwho/ui/test_nutanix.py b/tests/foreman/virtwho/ui/test_nutanix.py index 8bd1a3b23c7..652f3354559 100644 --- a/tests/foreman/virtwho/ui/test_nutanix.py +++ b/tests/foreman/virtwho/ui/test_nutanix.py @@ -236,10 +236,9 @@ def test_positive_ahv_internal_debug_option( # ahv_internal_debug does not set in virt-who-config-X.conf option = 'ahv_internal_debug' env_error = f"option {option} is not exist or not be enabled in {config_file}" - try: + with pytest.raises(Exception) as exc_info: # noqa: PT011 - TODO determine better exception get_configure_option("ahv_internal_debug", config_file) - except Exception as VirtWhoError: - assert env_error == str(VirtWhoError) + assert str(exc_info.value) == env_error # check message exist in log file /var/log/rhsm/rhsm.log message = 'Value for "ahv_internal_debug" not set, using default: False' assert check_message_in_rhsm_log(message) == message diff --git a/tests/foreman/virtwho/ui/test_nutanix_sca.py b/tests/foreman/virtwho/ui/test_nutanix_sca.py index 42de668055e..eb2d7d889ad 100644 --- a/tests/foreman/virtwho/ui/test_nutanix_sca.py +++ b/tests/foreman/virtwho/ui/test_nutanix_sca.py @@ -205,10 +205,9 @@ def test_positive_ahv_internal_debug_option( # ahv_internal_debug does not set in virt-who-config-X.conf option = 'ahv_internal_debug' env_error = f"option {option} is not exist or not be enabled in {config_file}" - try: + with pytest.raises(Exception) as exc_info: # noqa: PT011 - TODO determine better exception get_configure_option("ahv_internal_debug", config_file) - except Exception as VirtWhoError: - assert env_error == str(VirtWhoError) + assert str(exc_info.value) == env_error # check message exist in log file /var/log/rhsm/rhsm.log message = 'Value for "ahv_internal_debug" not set, using default: False' assert check_message_in_rhsm_log(message) == message diff --git a/tests/robottelo/conftest.py b/tests/robottelo/conftest.py index df6419a4f24..d8ffb1ad75b 100644 --- a/tests/robottelo/conftest.py +++ b/tests/robottelo/conftest.py @@ -13,13 +13,13 @@ def align_to_satellite(): pass -@pytest.fixture(scope='function') +@pytest.fixture def dummy_test(request): """This should be indirectly parametrized to provide dynamic dummy_tests to exec_test""" return request.param -@pytest.fixture(scope='function') +@pytest.fixture def exec_test(request, dummy_test): """Create a temporary file with the string provided by dummy_test, and run it with pytest.main diff --git a/tests/robottelo/test_cli.py b/tests/robottelo/test_cli.py index 78b0f6f0cf8..706a1d47785 100644 --- a/tests/robottelo/test_cli.py +++ b/tests/robottelo/test_cli.py @@ -301,7 +301,7 @@ def test_exists_with_option_and_no_empty_return(self, lst_method): assert 1 == response @mock.patch('robottelo.cli.base.Base.command_requires_org') - def test_info_requires_organization_id(self, _): + def test_info_requires_organization_id(self, _): # noqa: PT019 - not a fixture """Check info raises CLIError with organization-id is not present in options """ diff --git a/tests/robottelo/test_datafactory.py b/tests/robottelo/test_datafactory.py index 04e081a9b39..b93d401ed89 100644 --- a/tests/robottelo/test_datafactory.py +++ b/tests/robottelo/test_datafactory.py @@ -13,7 +13,7 @@ class TestFilteredDataPoint: """Tests for :meth:`robottelo.utils.datafactory.filtered_datapoint` decorator""" - @pytest.fixture(scope="function") + @pytest.fixture def run_one_datapoint(self, request): # Modify run_one_datapoint on settings singleton based on the indirect param # default to false when not parametrized diff --git a/tests/robottelo/test_decorators.py b/tests/robottelo/test_decorators.py index ff333fbb7e1..0f8ac441ce9 100644 --- a/tests/robottelo/test_decorators.py +++ b/tests/robottelo/test_decorators.py @@ -9,7 +9,7 @@ class TestCacheable: """Tests for :func:`robottelo.utils.decorators.cacheable`.""" - @pytest.fixture(scope="function") + @pytest.fixture def make_foo(self): mocked_object_cache_patcher = mock.patch.dict('robottelo.utils.decorators.OBJECT_CACHE') mocked_object_cache_patcher.start() diff --git a/tests/robottelo/test_func_locker.py b/tests/robottelo/test_func_locker.py index ed010e56076..ad4ab5c74aa 100644 --- a/tests/robottelo/test_func_locker.py +++ b/tests/robottelo/test_func_locker.py @@ -193,7 +193,7 @@ def simple_function_not_locked(): class TestFuncLocker: - @pytest.fixture(scope="function", autouse=True) + @pytest.fixture(autouse=True) def count_and_pool(self): global counter_file counter_file.write('0') @@ -371,7 +371,9 @@ def test_recursive_lock_function(self, count_and_pool, recursive_function): """Ensure that recursive calls to locked function is detected using lock_function decorator""" res = count_and_pool.apply_async(recursive_function, ()) - with pytest.raises(func_locker.FunctionLockerError, match=r'.*recursion detected.*'): + with pytest.raises( # noqa: PT012 + func_locker.FunctionLockerError, match=r'.*recursion detected.*' + ): try: res.get(timeout=5) except multiprocessing.TimeoutError: diff --git a/tests/robottelo/test_func_shared.py b/tests/robottelo/test_func_shared.py index 8ab9fb2f06d..7cc635e1aa0 100644 --- a/tests/robottelo/test_func_shared.py +++ b/tests/robottelo/test_func_shared.py @@ -163,13 +163,13 @@ def scope(self): # generate a new namespace scope = gen_string('alpha', 10) set_default_scope(scope) - yield scope + return scope - @pytest.fixture(scope='function', autouse=True) + @pytest.fixture(autouse=True) def enable(self): enable_shared_function(True) - @pytest.fixture(scope='function') + @pytest.fixture def pool(self): pool = multiprocessing.Pool(DEFAULT_POOL_SIZE) yield pool diff --git a/tests/robottelo/test_issue_handlers.py b/tests/robottelo/test_issue_handlers.py index 090e031b6f7..4da0b6df011 100644 --- a/tests/robottelo/test_issue_handlers.py +++ b/tests/robottelo/test_issue_handlers.py @@ -342,8 +342,8 @@ def test_bz_should_not_deselect(self): @pytest.mark.parametrize('issue', ["BZ123456", "XX:123456", "KK:89456", "123456", 999999]) def test_invalid_handler(self, issue): """Assert is_open w/ invalid handlers raise AttributeError""" + issue_deselect = should_deselect(issue) with pytest.raises(AttributeError): - issue_deselect = should_deselect(issue) is_open(issue) assert issue_deselect is None diff --git a/tests/upgrades/test_activation_key.py b/tests/upgrades/test_activation_key.py index 7e7cdf9de21..e58c06fee13 100644 --- a/tests/upgrades/test_activation_key.py +++ b/tests/upgrades/test_activation_key.py @@ -26,7 +26,7 @@ class TestActivationKey: operated/modified. """ - @pytest.fixture(scope='function') + @pytest.fixture def activation_key_setup(self, request, target_sat): """ The purpose of this fixture is to setup the activation key based on the provided @@ -45,7 +45,7 @@ def activation_key_setup(self, request, target_sat): content_view=cv, organization=org, name=f"{request.param}_ak" ).create() ak_details = {'org': org, "cv": cv, 'ak': ak, 'custom_repo': custom_repo} - yield ak_details + return ak_details @pytest.mark.pre_upgrade @pytest.mark.parametrize( diff --git a/tests/upgrades/test_classparameter.py b/tests/upgrades/test_classparameter.py index c22d39c48b1..f113f7ab235 100644 --- a/tests/upgrades/test_classparameter.py +++ b/tests/upgrades/test_classparameter.py @@ -51,7 +51,7 @@ class TestScenarioPositivePuppetParameterAndDatatypeIntact: """ @pytest.fixture(scope="class") - def _setup_scenario(self, class_target_sat): + def setup_scenario(self, class_target_sat): """Import some parametrized puppet classes. This is required to make sure that we have smart class variable available. Read all available smart class parameters for imported puppet class to @@ -100,7 +100,7 @@ def _validate_value(self, data, sc_param): @pytest.mark.pre_upgrade @pytest.mark.parametrize('count', list(range(1, 10))) def test_pre_puppet_class_parameter_data_and_type( - self, class_target_sat, count, _setup_scenario, save_test_data + self, class_target_sat, count, setup_scenario, save_test_data ): """Puppet Class parameters with different data type are created @@ -116,7 +116,7 @@ def test_pre_puppet_class_parameter_data_and_type( :expectedresults: The parameters are updated with different data types """ - save_test_data(_setup_scenario) + save_test_data(setup_scenario) data = _valid_sc_parameters_data()[count - 1] sc_param = class_target_sat.api.SmartClassParameters().search( query={'search': f'parameter="api_classparameters_scp_00{count}"'} @@ -130,9 +130,10 @@ def test_pre_puppet_class_parameter_data_and_type( self._validate_value(data, sc_param) @pytest.mark.post_upgrade(depend_on=test_pre_puppet_class_parameter_data_and_type) + @pytest.mark.usefixtures('_clean_scenario') @pytest.mark.parametrize('count', list(range(1, 10))) def test_post_puppet_class_parameter_data_and_type( - self, count, _clean_scenario, class_pre_upgrade_data, class_target_sat + self, count, class_pre_upgrade_data, class_target_sat ): """Puppet Class Parameters value and type is intact post upgrade diff --git a/tests/upgrades/test_client.py b/tests/upgrades/test_client.py index 7cb4ce6fe7c..4e1f1720d57 100644 --- a/tests/upgrades/test_client.py +++ b/tests/upgrades/test_client.py @@ -29,7 +29,7 @@ @pytest.fixture def client_for_upgrade(module_target_sat, rex_contenthost, module_org): rex_contenthost.create_custom_repos(fake_yum=settings.repos.yum_1.url) - yield rex_contenthost + return rex_contenthost class TestScenarioUpgradeOldClientAndPackageInstallation: diff --git a/tests/upgrades/test_host.py b/tests/upgrades/test_host.py index 72a4465eea9..a53a36814ff 100644 --- a/tests/upgrades/test_host.py +++ b/tests/upgrades/test_host.py @@ -90,7 +90,7 @@ def class_host( image=module_gce_finishimg, root_pass=gen_string('alphanumeric'), ).create() - yield host + return host def google_host(self, googleclient): """Returns the Google Client Host object to perform the assertions"""