Skip to content
Snippets Groups Projects
test_snmp_handling.py 1.97 KiB
import json
import os

import jsonschema
import pytest

from inventory_provider import snmp

import inventory_provider

TEST_DATA_DIRNAME = os.path.realpath(os.path.join(
    inventory_provider.__path__[0],
    "..",
    "test",
    "data"))


@pytest.fixture
def snmp_walk_responses():
    test_data_filename = os.path.join(TEST_DATA_DIRNAME, "snmp-walk.json")
    with open(test_data_filename) as f:
        return json.loads(f.read())


def test_snmp_interfaces(mocker, data_config, snmp_walk_responses):

    expected_result_schema = {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "array",
        "items": {
            "type": "object",
            "properties": {
                "v4Address": {"type": "string"},
                "v4Mask": {"type": "string"},
                "v4InterfaceName": {"type": "string"},
                "v6Address": {"type": "string"},
                "v6Mask": {"type": "string"},
                "v6InterfaceName": {"type": "string"},
                "index": {"type": "string"}
            },
            "required": ["index"],
            "additionalProperties": False
        }
    }

    def _mocked_walk(agent_hostname, community, base_oid):
        return [e for e in snmp_walk_responses
                if e['oid'].startswith(base_oid)]

    mocker.patch(
        'inventory_provider.snmp.walk',
        _mocked_walk)

    interfaces = snmp.get_router_interfaces(
        'ignored', 'ignored', {'oids': data_config['oids']})
    interfaces = list(interfaces)

    jsonschema.validate(interfaces, expected_result_schema)
    assert interfaces, "interface list isn't empty"
    for ifc in interfaces:
        if 'v4Address' in ifc \
                and 'v4Mask' in ifc \
                and 'v4InterfaceName' in ifc:
            continue
        if 'v6Address' in ifc \
                and 'v6Mask' in ifc \
                and 'v6InterfaceName' in ifc:
            continue
        assert False, "address details not found in interface dict"