chore: add unit tests for PrometheusSD class (#162)

This commit is contained in:
Robert Kaussow 2022-03-06 13:48:40 +01:00 committed by GitHub
parent 2ab1ad34e0
commit c6b63909d0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 224 additions and 5 deletions

View File

@ -8,7 +8,7 @@ local PythonVersion(pyversion='3.7') = {
'pip install poetry poetry-dynamic-versioning -qq', 'pip install poetry poetry-dynamic-versioning -qq',
'poetry config experimental.new-installer false', 'poetry config experimental.new-installer false',
'poetry install', 'poetry install',
'poetry run pytest', 'poetry run pytest --cov-append',
'poetry version', 'poetry version',
'poetry run prometheus-pve-sd --help', 'poetry run prometheus-pve-sd --help',
], ],

View File

@ -254,7 +254,7 @@ class Config():
except jsonschema.exceptions.ValidationError as e: except jsonschema.exceptions.ValidationError as e:
schema_error = "Failed validating '{validator}' in schema{schema}\n{message}".format( schema_error = "Failed validating '{validator}' in schema{schema}\n{message}".format(
validator=e.validator, validator=e.validator,
schema=format_as_index(list(e.relative_schema_path)[:-1]), schema=format_as_index(list(e.relative_schema_path)[:-1], 0),
message=e.message message=e.message
) )
raise prometheuspvesd.exception.ConfigError("Configuration error", schema_error) raise prometheuspvesd.exception.ConfigError("Configuration error", schema_error)

View File

@ -0,0 +1 @@
"""Init pytest unit tests."""

View File

@ -0,0 +1,4 @@
---
exclude_vmid:
- 100
- "101"

View File

View File

@ -0,0 +1 @@
"""Init pytest fixtures."""

View File

@ -1,8 +1,141 @@
"""Global pytest fixtures.""" """Global pytest fixtures."""
import environs
import pytest import pytest
@pytest.fixture
def builtins():
return {
"metrics.enabled": {
"default": True,
"env": "METRICS_ENABLED",
"type": environs.Env().bool
},
"metrics.address": {
"default": "127.0.0.1",
"env": "METRICS_ADDRESS",
"type": environs.Env().str
},
"metrics.port": {
"default": 8000,
"env": "METRICS_PORT",
"type": environs.Env().int
},
"config_file": {
"default": "",
"env": "CONFIG_FILE",
"type": environs.Env().str
},
"logging.level": {
"default": "WARNING",
"env": "LOG_LEVEL",
"file": True,
"type": environs.Env().str
},
"logging.format": {
"default": "console",
"env": "LOG_FORMAT",
"file": True,
"type": environs.Env().str
},
"output_file": {
"default": "dummy",
"env": "OUTPUT_FILE",
"file": True,
"type": environs.Env().str
},
"loop_delay": {
"default": 300,
"env": "LOOP_DELAY",
"file": True,
"type": environs.Env().int
},
"service": {
"default": False,
"env": "SERVICE",
"file": True,
"type": environs.Env().bool
},
"exclude_state": {
"default": [],
"env": "EXCLUDE_STATE",
"file": True,
"type": environs.Env().list
},
"exclude_vmid": {
"default": [],
"env": "EXCLUDE_VMID",
"file": True,
"type": environs.Env().list
},
"exclude_tags": {
"default": [],
"env": "EXCLUDE_TAGS",
"file": True,
"type": environs.Env().list
},
"pve.server": {
"default": "dummyserver",
"env": "PVE_SERVER",
"file": True,
"type": environs.Env().str
},
"pve.user": {
"default": "dummyuser",
"env": "PVE_USER",
"file": True,
"type": environs.Env().str
},
"pve.password": {
"default": "dummypass",
"env": "PVE_PASSWORD",
"file": True,
"type": environs.Env().str
},
"pve.auth_timeout": {
"default": 5,
"env": "PVE_AUTH_TIMEOUT",
"file": True,
"type": environs.Env().int
},
"pve.verify_ssl": {
"default": True,
"env": "PVE_VERIFY_SSL",
"file": True,
"type": environs.Env().bool
}
}
@pytest.fixture
def defaults():
return {
"exclude_state": [],
"exclude_tags": [],
"exclude_vmid": [],
"logging": {
"format": "console",
"level": "WARNING"
},
"loop_delay": 300,
"metrics": {
"address": "127.0.0.1",
"enabled": True,
"port": 8000
},
"output_file": "dummy",
"pve": {
"auth_timeout": 5,
"password": "dummypass",
"server": "dummyserver",
"user": "dummyuser",
"verify_ssl": True
},
"service": True,
}
@pytest.fixture @pytest.fixture
def qemus(): def qemus():
return [ return [

View File

@ -1,4 +1,6 @@
"""Pytest conftest fixtures.""" """Pytest conftest fixtures."""
import os
import sys
import pytest import pytest
@ -8,3 +10,13 @@ from prometheuspvesd.utils import Singleton
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def reset_singletons(): def reset_singletons():
Singleton._instances = {} Singleton._instances = {}
@pytest.fixture(autouse=True)
def reset_os_environment():
os.environ = {}
@pytest.fixture(autouse=True)
def reset_sys_argv():
sys.argv = ["prometheus-pve-sd"]

View File

@ -0,0 +1,68 @@
"""Test CLI class."""
import pytest
from proxmoxer import ProxmoxAPI
import prometheuspvesd.exception
from prometheuspvesd.cli import PrometheusSD
from prometheuspvesd.config import Config
from prometheuspvesd.discovery import Discovery
from prometheuspvesd.exception import APIError
from prometheuspvesd.logger import Log
pytest_plugins = [
"prometheuspvesd.test.fixtures.fixtures",
]
def test_cli_required_error(mocker, capsys):
mocker.patch.object(Discovery, "_auth", return_value=mocker.create_autospec(ProxmoxAPI))
mocker.patch.object(PrometheusSD, "_fetch", return_value=True)
with pytest.raises(SystemExit) as e:
PrometheusSD()
stdout, stderr = capsys.readouterr()
assert "Option 'pve.server' is required but not set" in stderr
assert e.value.code == 1
def test_cli_config_error(mocker, capsys):
mocker.patch(
"prometheuspvesd.config.SingleConfig.__init__",
side_effect=prometheuspvesd.exception.ConfigError("Dummy Config Exception")
)
mocker.patch.object(Discovery, "_auth", return_value=mocker.create_autospec(ProxmoxAPI))
mocker.patch.object(PrometheusSD, "_fetch", return_value=True)
with pytest.raises(SystemExit) as e:
PrometheusSD()
stdout, stderr = capsys.readouterr()
assert "Dummy Config Exception" in stderr
assert e.value.code == 1
def test_cli_log_error(mocker, capsys):
mocker.patch.object(Log, "update_logger", side_effect=ValueError("Dummy Logleve Exception"))
mocker.patch.object(Discovery, "_auth", return_value=mocker.create_autospec(ProxmoxAPI))
mocker.patch.object(PrometheusSD, "_fetch", return_value=True)
with pytest.raises(SystemExit) as e:
PrometheusSD()
stdout, stderr = capsys.readouterr()
assert "Dummy Logleve Exception" in stderr
assert e.value.code == 1
def test_cli_api_error(mocker, builtins, capsys):
mocker.patch.dict(Config.SETTINGS, builtins)
mocker.patch.object(Discovery, "_auth", side_effect=APIError("Dummy API Exception"))
mocker.patch.object(PrometheusSD, "_fetch", return_value=True)
with pytest.raises(SystemExit) as e:
PrometheusSD()
stdout, stderr = capsys.readouterr()
assert "Proxmoxer API error: Dummy API Exception" in stderr
assert e.value.code == 1

View File

@ -1,4 +1,4 @@
"""Test Autostop class.""" """Test Discovery class."""
import pytest import pytest
from proxmoxer import ProxmoxAPI from proxmoxer import ProxmoxAPI

View File

@ -78,7 +78,7 @@ sections = ["FUTURE", "STDLIB", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER"]
skip_glob = ["**/.env*", "**/env/*", "**/.venv/*", "**/docs/*"] skip_glob = ["**/.env*", "**/env/*", "**/.venv/*", "**/docs/*"]
[tool.pytest.ini_options] [tool.pytest.ini_options]
addopts = "prometheuspvesd --cov=prometheuspvesd --cov-report=xml:coverage.xml --cov-report=term --cov-append --no-cov-on-fail" addopts = "prometheuspvesd --cov=prometheuspvesd --cov-report=xml:coverage.xml --cov-report=term --no-cov-on-fail"
filterwarnings = [ filterwarnings = [
"ignore::FutureWarning", "ignore::FutureWarning",
"ignore:.*distutils.*:DeprecationWarning", "ignore:.*distutils.*:DeprecationWarning",

View File

@ -10,7 +10,7 @@
ignore = D102, D103, D105, D107, D202, W503 ignore = D102, D103, D105, D107, D202, W503
max-line-length = 99 max-line-length = 99
inline-quotes = double inline-quotes = double
exclude = .git, __pycache__, build, dist, test, *.pyc, *.egg-info, .cache, .eggs, env* exclude = .git, __pycache__, build, dist, *.pyc, *.egg-info, .cache, .eggs, env*
[yapf] [yapf]
based_on_style = google based_on_style = google