Skip to content

Unit Test

Marius Rieder edited this page Feb 22, 2021 · 3 revisions

Boilerplate to implement pytest unit tests for Checkmk Extensions

Agent Based (tests/unit/agent_based/test_{{ MODULENAME }}.py)

#!/usr/bin/env python3
# -*- encoding: utf-8; py-indent-offset: 4 -*-

import pytest
from cmk.base.plugins.agent_based.agent_based_api.v1 import (
    Result,
    Service,
    State,
)
from cmk.base.plugins.agent_based import {{ MODULENAME }}

EXAMPLE_STRING_TABLE = [
    # Example input from the Agent
]
EXAMPLE_SECTION = {
    # Example parsed section
}


@pytest.mark.parametrize('string_table, result', [
    ([], {}),
    (
        EXAMPLE_STRING_TABLE,
        EXAMPLE_SECTION
    ),
])
def test_parse_{{ MODULENAME }}(string_table, result):
    assert {{ MODULENAME }}.parse_{{ MODULENAME }}(string_table) == result


@pytest.mark.parametrize('params, section, result', [
    ([], {}, []),
    (
        [],
        EXAMPLE_SECTION,
        [Service(item='{{ DISCOVERED_SERVICE }}')]
    ),
])
def test_discovery_{{ MODULENAME }}(params, section, result):
    assert list({{ MODULENAME }}.discovery_{{ MODULENAME }}(params, section)) == result


@pytest.mark.parametrize('item, params, section, result', [
    (
        'ITEM',
        {},
        EXAMPLE_SECTION
        [
            Result(state=State.OK, summary='Happy'),
        ]
    ),
])
def test_check_{{ MODULENAME }}(item, params, section, result):
    assert list({{ MODULENAME }}.check_{{ MODULENAME }}(item, params, section)) == result

Wato Plugins (tests/unit/web/plugin/wato/test_{{ MODULENAME }}.py)

#!/usr/bin/env python3
# -*- encoding: utf-8; py-indent-offset: 4 -*-

import pytest  # type: ignore[import]
import {{ MODULENAME }}


@pytest.fixture
def vs():
    return {{ MODULENAME }}._parameter_valuespec_{{ VSNAME }}()

@pytest.mark.parametrize('data', [
    ({'states': []}),
])
def test_validate_datatype(self, vs, data):
    assert vs.validate_datatype(data, '') is None

@pytest.mark.parametrize('input, output', [
    ({'states': []}, {'states': {}}),
])
def test_transform_value(self, vs, input, output):
    assert vs.transform_value(input) == output

Requirement (tests/unit/web/conftest.py)

#!/usr/bin/env python3
# -*- encoding: utf-8; py-indent-offset: 4 -*-

import sys
from pathlib import Path
sys.path.append(str(Path(*Path(__file__).parts[:-4], 'web', 'plugins', 'wato')))