Skip to content

Commit

Permalink
test: Added tests for rhc connect option
Browse files Browse the repository at this point in the history
- Tests to connect using basic auth
- Tetst to connect using activation key
- Tests for incorrect credentials and --server option
- Test to verify rhc-worker-playbook installation on rhc connect
  • Loading branch information
archana-redhat authored and Lorquas committed Jun 11, 2024
1 parent adbdac0 commit 30787ff
Show file tree
Hide file tree
Showing 4 changed files with 231 additions and 0 deletions.
Empty file added integration-tests/__init__.py
Empty file.
1 change: 1 addition & 0 deletions integration-tests/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
git+https://github.com/ptoscano/pytest-client-tools@main
pyyaml
sh
156 changes: 156 additions & 0 deletions integration-tests/test_connect.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
"""
This Python module contains integration tests for rhc.
It uses pytest-client-tools Python module.More information about this
module could be found: https://github.com/ptoscano/pytest-client-tools/
"""

import contextlib
import time
import logging
import pytest
from datetime import datetime
import sh

from utils import (
rhcd_service_is_active,
prepare_args_for_connect,
check_rhcd_journalctl,
)

logger = logging.getLogger(__name__)


@pytest.mark.parametrize("auth", ["basic", "activation-key"])
def test_connect(external_candlepin, rhc, test_config, auth):
"""Test if RHC can connect to CRC using basic auth and activation key,
Also verify that rhcd service is in active state afterward.
"""
with contextlib.suppress(Exception):
rhc.disconnect()
command_args = prepare_args_for_connect(test_config, auth=auth)
command = ["connect"] + command_args
result = rhc.run(*command)
assert rhc.is_registered
assert rhcd_service_is_active()
assert "Connected to Red Hat Subscription Management" in result.stdout
assert "Connected to Red Hat Insights" in result.stdout
assert "Activated the Remote Host Configuration daemon" in result.stdout
assert "Successfully connected to Red Hat!" in result.stdout


@pytest.mark.parametrize(
"credentials,server",
[
( # username and password: valid, server: invalid
{"username": "candlepin.username", "password": "candlepin.password"},
"http://non-existent.server",
),
( # organization and activation-key: valid, server: invalid
{
"organization": "candlepin.org",
"activation-key": "candlepin.activation_keys",
},
"http://non-existent.server",
),
( # password and server: valid, username: invalid
{"username": "non-existent-user", "password": "candlepin.password"},
None,
),
( # activation-key and server: valid, organization: invalid
{
"organization": "non-existent-org",
"activation-key": "candlepin.activation_keys",
},
None,
),
( # username and server: valid, password: invalid
{"username": "candlepin.username", "password": "xpto123"},
None,
),
( # organization and server: valid, activation-key: invalid
{"organization": "candlepin.org", "activation-key": "xpto123"},
None,
),
# invalid combination of parameters
(
{
"username": "candlepin.username",
"activation-key": "candlepin.activation_keys",
},
None,
),
(
{
"activation-key": "candlepin.activation_keys",
"password": "candlepin.password",
},
None,
),
],
)
def test_connect_wrong_parameters(
external_candlepin, rhc, test_config, credentials, server
):
"""Test if RHC handles invalid credentials properly"""
# An attempt to bring system in disconnected state in case it is not.
with contextlib.suppress(Exception):
rhc.disconnect()
command_args = prepare_args_for_connect(
test_config, credentials=credentials, server=server
)
command = ["connect"] + command_args
result = rhc.run(*command, check=False)
assert result.returncode == 1
assert not rhcd_service_is_active()


@pytest.mark.parametrize("auth", ["basic", "activation-key"])
def test_rhc_worker_playbook_install_after_rhc_connect(
external_candlepin, rhc, test_config, auth
):
"""
Test that rhc-worker-playbook is installed after rhc-connect,
Also log the total time taken to install the package
test_steps:
1- run 'rhc connect'
2- monitor rhcd logs to see when package-manager-worker installs 'rhc-worker-playbook'
3- validate rhc-worker-playbook is installed
"""
with contextlib.suppress(Exception):
sh.yum("remove", "rhc-worker-playbook", "-y")

success_message = "Registered rhc-worker-playbook"
with contextlib.suppress(Exception):
rhc.disconnect()

start_date_time = datetime.now().strftime(
"%Y-%m-%d %H:%M:%S"
) # current date and time for observing rhcd logs
command_args = prepare_args_for_connect(test_config, auth=auth)
command = ["connect"] + command_args
rhc.run(*command, check=False)
assert rhc.is_registered

# Verifying if rhc-worker-playbook was installed successfully
t_end = time.time() + 60 * 5 # maximum time to wait for installation
while time.time() < t_end:
installed_status = check_rhcd_journalctl(
str_to_check=success_message,
since_datetime=start_date_time,
must_exist_in_log=True,
)
if installed_status:
break
assert (
installed_status
), "rhc connect is expected to install rhc_worker_playbook package"

total_runtime = datetime.now() - datetime.strptime(
start_date_time, "%Y-%m-%d %H:%M:%S"
)
pkg_version = sh.rpm("-qa", "rhc-worker-playbook")
logger.info(f"successfully installed rhc_worker_playbook package {pkg_version}")
logger.info(
f"time taken to start rhcd service and install "
f"rhc_worker_playbook : {total_runtime} s"
)
74 changes: 74 additions & 0 deletions integration-tests/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import sh


def rhcd_service_is_active():
"""Method to verify if rhcd is in active/inactive state
:return: True if rhcd in active state else False
"""
try:
stdout = sh.systemctl("is-active rhcd".split()).strip()
return stdout == "active"
except sh.ErrorReturnCode_3:
return False


def check_rhcd_journalctl(str_to_check, since_datetime=None, must_exist_in_log=True):
"""This method helps in verifying strings in rhcd logs
:param str_to_check: string to be searched in logs
:param since_datetime: start time for logs
:param must_exist_in_log: True if str_to_check should exist in log else false
:return: True/False
"""
if since_datetime:
rhcd_logs = sh.journalctl("-u", "rhcd", "--since", since_datetime)
else:
rhcd_logs = sh.journalctl("-u", "rhcd")

if must_exist_in_log:
return str_to_check in rhcd_logs
else:
return str_to_check not in rhcd_logs


def prepare_args_for_connect(
test_config, auth: str = None, credentials: dict = None, server: str = None
):
"""Method to create arguments to be passed in 'rhc connect' command
This method expects either auth type or custom credentials
"""
args = []
if credentials:
for k, v in credentials.items():
try:
value = test_config.get(v)
value = value[0] if isinstance(value, list) else value
except KeyError:
value = v
if value:
args.extend([f"--{k}", value])

elif auth:
if auth == "basic":
args.extend(
[
"--username",
test_config.get("candlepin.username"),
"--password",
test_config.get("candlepin.password"),
]
)

elif auth == "activation-key":
args.extend(
[
"--activation-key",
test_config.get("candlepin.activation_keys")[0],
"--organization",
test_config.get("candlepin.org"),
]
)

if server:
args.extend(["--server", server])

return args

0 comments on commit 30787ff

Please sign in to comment.