2022-03-03 10:16:02 +00:00
|
|
|
"""Pytest conftest fixtures."""
|
2024-01-24 11:50:39 +00:00
|
|
|
import logging
|
2022-03-06 12:48:40 +00:00
|
|
|
import os
|
|
|
|
import sys
|
2024-01-24 11:50:39 +00:00
|
|
|
from contextlib import contextmanager
|
2022-03-03 10:16:02 +00:00
|
|
|
|
|
|
|
import pytest
|
2024-01-24 11:50:39 +00:00
|
|
|
from _pytest.logging import LogCaptureHandler
|
2022-03-03 10:16:02 +00:00
|
|
|
|
|
|
|
from prometheuspvesd.utils import Singleton
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
|
|
def reset_singletons():
|
|
|
|
Singleton._instances = {}
|
2022-03-06 12:48:40 +00:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
|
|
def reset_os_environment():
|
2024-01-24 11:50:39 +00:00
|
|
|
os.environ.clear()
|
2022-03-06 12:48:40 +00:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
|
|
def reset_sys_argv():
|
|
|
|
sys.argv = ["prometheus-pve-sd"]
|
2024-01-24 11:50:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
@contextmanager
|
|
|
|
def local_caplog_fn(level=logging.INFO, name="prometheuspvesd"):
|
|
|
|
"""
|
|
|
|
Context manager that captures records from non-propagating loggers.
|
|
|
|
|
|
|
|
After the end of the 'with' statement, the log level is restored to its original
|
|
|
|
value. Code adapted from https://github.com/pytest-dev/pytest/issues/3697#issuecomment-790925527.
|
|
|
|
|
|
|
|
:param int level: The level.
|
|
|
|
:param logging.Logger logger: The logger to update.
|
|
|
|
"""
|
|
|
|
|
|
|
|
logger = logging.getLogger(name)
|
|
|
|
|
|
|
|
old_level = logger.level
|
|
|
|
logger.setLevel(level)
|
|
|
|
|
|
|
|
handler = LogCaptureHandler()
|
|
|
|
logger.addHandler(handler)
|
|
|
|
|
|
|
|
try:
|
|
|
|
yield handler
|
|
|
|
finally:
|
|
|
|
logger.setLevel(old_level)
|
|
|
|
logger.removeHandler(handler)
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def local_caplog():
|
|
|
|
"""Fixture that yields a context manager for capturing records from non-propagating loggers."""
|
|
|
|
|
|
|
|
yield local_caplog_fn
|