Skip to content

Commit de98b57

Browse files
authored
Fix query db in containerized envs (#22140)
* Update query_db function to support containerized envs * update test_health.py * ruff format * move Install method import to top level * remove local imports * add db_user arg to query_db() * replace with self.install_method with settings.server.install_method
1 parent 2d6a4b5 commit de98b57

7 files changed

Lines changed: 48 additions & 59 deletions

File tree

robottelo/hosts.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@
5454
RHSSO_USER_UPDATE,
5555
SATELLITE_VERSION,
5656
)
57-
from robottelo.enums import NetworkType
57+
from robottelo.enums import InstallMethod, NetworkType
5858
from robottelo.exceptions import (
5959
CapsuleHostError,
6060
CLIFactoryError,
@@ -1805,7 +1805,6 @@ def detect_install_method(self):
18051805
:return: InstallMethod enum value
18061806
:rtype: InstallMethod
18071807
"""
1808-
from robottelo.enums import InstallMethod
18091808

18101809
# Runtime override
18111810
if hasattr(self, '_install_method_override'):
@@ -1855,7 +1854,6 @@ def get_service_names(self):
18551854
:rtype: list
18561855
"""
18571856
from robottelo.constants import InstallationServices
1858-
from robottelo.enums import InstallMethod
18591857

18601858
if self.install_method == InstallMethod.FOREMANCTL:
18611859
return InstallationServices.FOREMANCTL_SERVICES
@@ -2271,7 +2269,6 @@ def install_satellite(
22712269
:param foremanctl_parameters: Parameters list for foremanctl deploy
22722270
:return: Installation result
22732271
"""
2274-
from robottelo.enums import InstallMethod
22752272
from robottelo.utils.installer import InstallerCommand
22762273

22772274
# Determine method
@@ -2324,13 +2321,14 @@ def install_satellite(
23242321

23252322
return result
23262323

2327-
def query_db(self, query, db='foreman', output_format='json'):
2324+
def query_db(self, query, db='foreman', output_format='json', db_user='foreman'):
23282325
"""Execute a PostgreSQL query and return the result.
23292326
23302327
Args:
23312328
query: SQL query to execute
23322329
db: Database name (default: 'foreman')
23332330
output_format: Output format - 'json' for JSON array, raw output otherwise
2331+
db_user: Database user (default: 'foreman')
23342332
23352333
Returns:
23362334
list of dicts if output_format='json', str otherwise
@@ -2345,7 +2343,10 @@ def _execute_db_query(cmd):
23452343
raise CLIReturnCodeError(result.status, result.stderr, f'"{cmd}" failed')
23462344
return result
23472345

2348-
base_cmd = f'sudo -u postgres psql -d {db}'
2346+
if settings.server.install_method == InstallMethod.FOREMANCTL:
2347+
base_cmd = f'podman exec postgresql psql -U {db_user} -d {db}'
2348+
else:
2349+
base_cmd = f'sudo -u postgres psql -d {db}'
23492350

23502351
if output_format == 'json':
23512352
cmd = f'{base_cmd} -A -t -c "SELECT json_agg(row_to_json(t)) FROM ({query}) t"'

tests/foreman/api/test_contentview.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2723,11 +2723,12 @@ def test_repository_rpms_id_type(target_sat):
27232723
27242724
:CaseImportance: Medium
27252725
"""
2726-
db_out = target_sat.execute(
2727-
'sudo -u postgres psql -d foreman -c "select * from pg_sequences where sequencename=\'katello_repository_rpms_id_seq\';"'
2726+
db_out = target_sat.query_db(
2727+
"select * from pg_sequences where sequencename='katello_repository_rpms_id_seq'",
2728+
output_format='raw',
27282729
)
2729-
assert 'bigint' in db_out.stdout
2730-
assert 'integer' not in db_out.stdout
2730+
assert 'bigint' in db_out
2731+
assert 'integer' not in db_out
27312732

27322733

27332734
def test_negative_readonly_user_actions(

tests/foreman/api/test_notifications.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -233,15 +233,15 @@ def long_running_task(target_sat):
233233
},
234234
)
235235
sql_date_2_days_ago = "now() - INTERVAL '2 days'"
236-
result = target_sat.execute(
237-
"su - postgres -c \"psql foreman postgres <<EOF\n"
236+
query = (
238237
"UPDATE foreman_tasks_tasks "
239238
f"SET start_at = {sql_date_2_days_ago}, "
240-
f" started_at = {sql_date_2_days_ago}, "
241-
f" state_updated_at = {sql_date_2_days_ago} "
242-
f"WHERE id=\'{job['task']['id']}\';\nEOF\n\" "
243-
) # fmt: skip # skip formatting to avoid breaking the SQL query
244-
assert 'UPDATE 1' in result.stdout, f'Failed to age task {job["task"]["id"]}: {result.stderr}'
239+
f"started_at = {sql_date_2_days_ago}, "
240+
f"state_updated_at = {sql_date_2_days_ago} "
241+
f"WHERE id='{job['task']['id']}'"
242+
)
243+
result = target_sat.query_db(query, output_format='raw')
244+
assert 'UPDATE 1' in result, f'Failed to age task {job["task"]["id"]}'
245245

246246
yield job
247247

tests/foreman/api/test_repository.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1377,13 +1377,14 @@ def test_positive_sync_repo_null_contents_changed(self, module_sca_manifest_org,
13771377
releasever=None,
13781378
)
13791379
target_sat.api.Repository(id=repo_id).sync()
1380-
prod_log_out = target_sat.execute(
1381-
'sudo -u postgres psql -d foreman -c "select class,execution_plan_uuid,input '
1382-
'from dynflow_actions where input LIKE \'%"contents_changed":null%\''
1383-
' AND class = \'Actions::Katello::Repository::Sync\';"'
1380+
assert (
1381+
target_sat.query_db(
1382+
"select class,execution_plan_uuid,input "
1383+
"from dynflow_actions where input LIKE '%\"contents_changed\":null%'"
1384+
" AND class = 'Actions::Katello::Repository::Sync'"
1385+
)
1386+
== []
13841387
)
1385-
assert prod_log_out.status == 0
1386-
assert "(0 rows)" in prod_log_out.stdout
13871388

13881389
def test_positive_validate_async_operation_response(self, module_sca_manifest_org, target_sat):
13891390
"""Verify that RefreshDistribution action properly tracks Pulp tasks via AsyncOperationResponse.

tests/foreman/cli/test_oscap.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -619,16 +619,8 @@ def test_positive_associate_scap_policy_with_hostgroups(self, scap_content, modu
619619
pytest.fail("failed to list policies")
620620
assert name in [policy['name'] for policy in result]
621621
# check for orphaned entries
622-
db_out = module_target_sat.execute(
623-
'sudo -u postgres psql -d foreman -c "select * from foreman_openscap_assets"'
624-
)
625-
assert db_out.status == 0
626-
assert "(0 rows)" in db_out.stdout
627-
db_out = module_target_sat.execute(
628-
'sudo -u postgres psql -d foreman -c "select * from foreman_openscap_asset_policies"'
629-
)
630-
assert db_out.status == 0
631-
assert "(0 rows)" in db_out.stdout
622+
assert module_target_sat.query_db('select * from foreman_openscap_assets') == []
623+
assert module_target_sat.query_db('select * from foreman_openscap_asset_policies') == []
632624

633625
def test_positive_associate_scap_policy_with_hostgroup_via_ansible(
634626
self, scap_content, module_target_sat

tests/foreman/maintain/test_health.py

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -667,24 +667,20 @@ def test_positive_health_check_corrupted_roles(sat_maintain, request):
667667

668668
@request.addfinalizer
669669
def _finalize():
670-
resource_type = r"'\''Host'\''"
671-
sat_maintain.execute(
672-
f'''sudo su - postgres -c "psql -d foreman -c 'UPDATE permissions SET
673-
resource_type = {resource_type} WHERE name = {permission_name};'"'''
670+
sat_maintain.query_db(
671+
"UPDATE permissions SET resource_type = 'Host' WHERE name = 'console_hosts'",
672+
output_format='raw',
674673
)
675674
sat_maintain.cli.Role.delete(options={'name': role_name})
676675

677676
# Check the filter created to verify the role, resource type, and permissions assigned.
678677
sat_maintain.cli.Filter.create(
679678
options={'role': role_name, 'permissions': ['view_hosts', 'console_hosts']}
680679
)
681-
permission_name = r"'\''console_hosts'\''"
682-
resource_type = rf"'\''{resource_type}'\''"
683-
setup = sat_maintain.execute(
684-
f'''sudo su - postgres -c "psql -d foreman -c 'UPDATE permissions SET
685-
resource_type = {resource_type} WHERE name = {permission_name};'"'''
680+
sat_maintain.query_db(
681+
f"UPDATE permissions SET resource_type = '{resource_type}' WHERE name = 'console_hosts'",
682+
output_format='raw',
686683
)
687-
assert setup.status == 0
688684
result = sat_maintain.cli.Filter.list(options={'search': role_name}, output_format='yaml')
689685
# Shows the filter id which comprises of role id hence asserting 2 here
690686
assert result.count('Id') == 2
@@ -758,13 +754,11 @@ def test_positive_health_check_duplicate_permissions(sat_maintain):
758754
:BZ: 1849110, 1884024
759755
"""
760756
# Verify if check failed because of duplicate permissions
761-
name = r"'\''view_ansible_variables'\''"
762-
resource_type = r"'\''AnsibleVariable'\''"
763-
result = sat_maintain.execute(
764-
f'''sudo su - postgres -c "psql -d foreman -c 'INSERT INTO permissions(name, resource_type)
765-
VALUES({name}, {resource_type});'"'''
757+
sat_maintain.query_db(
758+
"INSERT INTO permissions(name, resource_type) "
759+
"VALUES('view_ansible_variables', 'AnsibleVariable')",
760+
output_format='raw',
766761
)
767-
assert result.status == 0
768762
result = sat_maintain.cli.Health.check({'label': 'duplicate-permissions', 'assumeyes': True})
769763
assert result.status == 0
770764
assert 'FAIL' in result.stdout

tests/foreman/ui/test_host.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4531,19 +4531,19 @@ def test_positive_search_by_report_origin_shows_all_hosts(target_sat):
45314531
timestamp = '2025-05-16 16:16:16'
45324532
report_count = 25
45334533

4534-
target_sat.execute(
4535-
'su - postgres -c "psql -d foreman -c \\"'
4534+
target_sat.query_db(
45364535
f"INSERT INTO reports (host_id, origin, reported_at) "
4537-
f"SELECT {host1.id}, 'Puppet', '{timestamp}'::timestamp + (i || ' seconds')::interval "
4538-
f"FROM generate_series(1, {report_count}) AS i"
4539-
'\\""'
4536+
f"SELECT {host1.id}, 'Puppet', '{timestamp}'::timestamp "
4537+
f"+ (i || ' seconds')::interval "
4538+
f"FROM generate_series(1, {report_count}) AS i",
4539+
output_format='raw',
45404540
)
4541-
target_sat.execute(
4542-
'su - postgres -c "psql -d foreman -c \\"'
4541+
target_sat.query_db(
45434542
f"INSERT INTO reports (host_id, origin, reported_at) "
4544-
f"SELECT {host2.id}, 'Puppet', '{timestamp}'::timestamp + (i || ' seconds')::interval "
4545-
f"FROM generate_series(1, 2) AS i"
4546-
'\\""'
4543+
f"SELECT {host2.id}, 'Puppet', '{timestamp}'::timestamp "
4544+
f"+ (i || ' seconds')::interval "
4545+
f"FROM generate_series(1, 2) AS i",
4546+
output_format='raw',
45474547
)
45484548

45494549
with target_sat.ui_session() as session:

0 commit comments

Comments
 (0)