Skip to content

Commit

Permalink
Find built charm by glob
Browse files Browse the repository at this point in the history
  • Loading branch information
Deezzir committed Nov 21, 2024
1 parent 0e5cc37 commit edd1c0a
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 57 deletions.
26 changes: 7 additions & 19 deletions tests/functional/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,13 @@

log = logging.getLogger(__name__)

BASES = {
"[email protected]": "focal",
"[email protected]": "jammy",
"[email protected]": "noble",
}


def pytest_addoption(parser):
parser.addoption(
"--base",
type=str.lower,
default="[email protected]",
choices=BASES.keys(),
choices=["[email protected]", "[email protected]", "[email protected]"],
help="Set base for the applications.",
)

Expand Down Expand Up @@ -157,18 +151,12 @@ def required_resources(resources: list[Resource], provided_collectors: set) -> l


@pytest.fixture()
def charm_path(base: str) -> Path:
def charm_path(base: str, architecture: str) -> Path:
"""Fixture to determine the charm path based on the base."""
env_charm_path = f"CHARM_PATH_{BASES[base].upper()}"
path = os.getenv(env_charm_path)
glob_path = f"hardware-observer_*{base.replace('@', '-')}-{architecture}*.charm"
paths = list(Path(".").glob(glob_path))

if not path:
raise EnvironmentError(
f"Environment variable '{env_charm_path}' is not set for base '{base}'."
)
if not Path(path).exists():
raise FileNotFoundError(
f"The path specified in '{env_charm_path}' ({path}) does not exist."
)
if not paths:
raise FileNotFoundError(f"The path for the charm for {base}-{architecture} is not found.")

return Path(path)
return os.getcwd() / paths[0]
78 changes: 40 additions & 38 deletions tests/functional/test_charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
from tenacity import AsyncRetrying, RetryError, stop_after_attempt, wait_fixed
from utils import (
RESOURCES_DIR,
HardwareExporterConfigError,
MetricsFetchError,
assert_metrics,
get_hardware_exporter_config,
get_metrics_output,
run_command_on_unit,
)
Expand Down Expand Up @@ -241,20 +243,20 @@ async def test_config_changed_port(self, app, unit, ops_test):
ops_test.model.wait_for_idle(apps=[APP_NAME]),
)

cmd = "cat /etc/hardware-exporter-config.yaml"
results = await run_command_on_unit(ops_test, unit.name, cmd)
assert results.get("return-code") == 0
config = yaml.safe_load(results.get("stdout").strip())
try:
config = await get_hardware_exporter_config(ops_test, unit.name)
except HardwareExporterConfigError:
pytest.fail("Not able to obtain hardware-exporter config!")
assert config["port"] == int(new_port)

await app.reset_config(["hardware-exporter-port"])

async def test_no_redfish_config(self, unit, ops_test):
"""Test that there is no Redfish options because it's not available on lxd machines."""
cmd = "cat /etc/hardware-exporter-config.yaml"
results = await run_command_on_unit(ops_test, unit.name, cmd)
assert results.get("return-code") == 0
config = yaml.safe_load(results.get("stdout").strip())
try:
config = await get_hardware_exporter_config(ops_test, unit.name)
except HardwareExporterConfigError:
pytest.fail("Not able to obtain hardware-exporter config!")
assert config.get("redfish_host") is None
assert config.get("redfish_username") is None
assert config.get("redfish_client_timeout") is None
Expand All @@ -267,10 +269,10 @@ async def test_config_changed_log_level(self, app, unit, ops_test):
ops_test.model.wait_for_idle(apps=[APP_NAME]),
)

cmd = "cat /etc/hardware-exporter-config.yaml"
results = await run_command_on_unit(ops_test, unit.name, cmd)
assert results.get("return-code") == 0
config = yaml.safe_load(results.get("stdout").strip())
try:
config = await get_hardware_exporter_config(ops_test, unit.name)
except HardwareExporterConfigError:
pytest.fail("Not able to obtain hardware-exporter config!")
assert config["level"] == new_log_level

await app.reset_config(["exporter-log-level"])
Expand All @@ -283,10 +285,10 @@ async def test_config_changed_collect_timeout(self, app, unit, ops_test):
ops_test.model.wait_for_idle(apps=[APP_NAME]),
)

cmd = "cat /etc/hardware-exporter-config.yaml"
results = await run_command_on_unit(ops_test, unit.name, cmd)
assert results.get("return-code") == 0
config = yaml.safe_load(results.get("stdout").strip())
try:
config = await get_hardware_exporter_config(ops_test, unit.name)
except HardwareExporterConfigError:
pytest.fail("Not able to obtain hardware-exporter config!")
assert config["collect_timeout"] == int(new_collect_timeout)

await app.reset_config(["collect-timeout"])
Expand Down Expand Up @@ -321,10 +323,10 @@ async def test_exporter_failed(self, app, unit, ops_test):

async def test_config_collector_enabled(self, app, unit, ops_test, provided_collectors):
"""Test whether provided collectors are present in exporter config."""
cmd = "cat /etc/hardware-exporter-config.yaml"
results = await run_command_on_unit(ops_test, unit.name, cmd)
assert results.get("return-code") == 0
config = yaml.safe_load(results.get("stdout").strip())
try:
config = await get_hardware_exporter_config(ops_test, unit.name)
except HardwareExporterConfigError:
pytest.fail("Not able to obtain hardware-exporter config!")
collectors_in_config = {
collector.replace("collector.", "") for collector in config.get("enable_collectors")
}
Expand All @@ -345,10 +347,10 @@ async def test_redfish_client_timeout_config(self, app, unit, ops_test, provided
ops_test.model.wait_for_idle(apps=[APP_NAME]),
)

cmd = "cat /etc/hardware-exporter-config.yaml"
results = await run_command_on_unit(ops_test, unit.name, cmd)
assert results.get("return-code") == 0
config = yaml.safe_load(results.get("stdout").strip())
try:
config = await get_hardware_exporter_config(ops_test, unit.name)
except HardwareExporterConfigError:
pytest.fail("Not able to obtain hardware-exporter config!")
assert config["redfish_client_timeout"] == int(new_timeout)

await app.reset_config(["collect-timeout"])
Expand Down Expand Up @@ -566,27 +568,27 @@ async def test_redfish_config(self, ops_test, app, unit, provided_collectors):
if "redfish" not in provided_collectors:
pytest.skip("redfish not in provided collectors, skipping test")
# initially Redfish is available and enabled
cmd = "cat /etc/hardware-exporter-config.yaml"
results_before = await run_command_on_unit(ops_test, unit.name, cmd)
assert results_before.get("return-code") == 0
config = yaml.safe_load(results_before.get("stdout").strip())
assert config.get("redfish_host") is not None
assert config.get("redfish_username") is not None
assert config.get("redfish_client_timeout") is not None
try:
config_before = await get_hardware_exporter_config(ops_test, unit.name)
except HardwareExporterConfigError:
pytest.fail("Not able to obtain hardware-exporter config!")
assert config_before.get("redfish_host") is not None
assert config_before.get("redfish_username") is not None
assert config_before.get("redfish_client_timeout") is not None

# Disable Redfish and see if the config is not present
await asyncio.gather(
app.set_config({"redfish-disable": "true"}),
ops_test.model.wait_for_idle(apps=[APP_NAME]),
)

cmd = "cat /etc/hardware-exporter-config.yaml"
results_after = await run_command_on_unit(ops_test, unit.name, cmd)
assert results_before.get("return-code") == 0
config = yaml.safe_load(results_after.get("stdout").strip())
assert config.get("redfish_host") is None
assert config.get("redfish_username") is None
assert config.get("redfish_client_timeout") is None
try:
config_after = await get_hardware_exporter_config(ops_test, unit.name)
except HardwareExporterConfigError:
pytest.fail("Not able to obtain hardware-exporter config!")
assert config_after.get("redfish_host") is None
assert config_after.get("redfish_username") is None
assert config_after.get("redfish_client_timeout") is None

await app.reset_config(["redfish-disable"])

Expand Down
16 changes: 16 additions & 0 deletions tests/functional/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from pathlib import Path
from typing import Optional

import yaml
from async_lru import alru_cache

RESOURCES_DIR = Path("./resources/")
Expand Down Expand Up @@ -44,6 +45,12 @@ class MetricsFetchError(Exception):
pass


class HardwareExporterConfigError(Exception):
"""Raise if something goes wrong when getting hardware-exporter config."""

pass


async def run_command_on_unit(ops_test, unit_name, command):
complete_command = ["exec", "--unit", unit_name, "--", *command.split()]
return_code, stdout, _ = await ops_test.juju(*complete_command)
Expand All @@ -54,6 +61,15 @@ async def run_command_on_unit(ops_test, unit_name, command):
return results


async def get_hardware_exporter_config(ops_test, unit_name) -> dict:
"""Return hardware-exporter config from endpoint on unit."""
command = "cat /etc/hardware-exporter/config.yaml"
results = await run_command_on_unit(ops_test, unit_name, command)
if results.get("return-code") > 0:
raise HardwareExporterConfigError
return yaml.safe_load(results.get("stdout"))


@alru_cache
async def get_metrics_output(ops_test, unit_name) -> Optional[dict[str, list[Metric]]]:
"""Return parsed prometheus metric output from endpoint on unit.
Expand Down

0 comments on commit edd1c0a

Please sign in to comment.