2019-12-19 16:19:41 +01:00
|
|
|
import glob
|
|
|
|
import json
|
|
|
|
import pytest
|
|
|
|
import yaml
|
|
|
|
from jsonschema import validate
|
2019-12-19 17:08:51 +01:00
|
|
|
from jsonschema.exceptions import ValidationError
|
2019-12-19 16:19:41 +01:00
|
|
|
|
|
|
|
|
|
|
|
def _get_definition_files():
|
|
|
|
"""
|
|
|
|
Return a list of all definition files.
|
|
|
|
"""
|
2019-12-26 21:36:28 +01:00
|
|
|
return [f for f in glob.glob("device-types/*/*", recursive=True)]
|
2019-12-19 16:19:41 +01:00
|
|
|
|
|
|
|
|
|
|
|
# Initialize schema
|
|
|
|
with open("tests/schema.json") as schema_file:
|
|
|
|
schema = json.loads(schema_file.read())
|
|
|
|
|
|
|
|
|
2019-12-19 17:14:27 +01:00
|
|
|
def test_environment():
|
|
|
|
"""
|
|
|
|
Run basic sanity checks on the environment to ensure tests are running correctly.
|
|
|
|
"""
|
|
|
|
# Validate that definition files exist
|
|
|
|
assert _get_definition_files(), "No definition files found!"
|
|
|
|
|
|
|
|
# Validate that the schema exists
|
|
|
|
assert schema, "Schema definition is empty!"
|
|
|
|
|
|
|
|
|
2019-12-19 16:19:41 +01:00
|
|
|
@pytest.mark.parametrize("file_path", _get_definition_files())
|
|
|
|
def test_definition(file_path):
|
|
|
|
"""
|
2019-12-30 16:11:25 +01:00
|
|
|
Validate each DeviceType definition file using the provided JSON schema.
|
2019-12-19 16:19:41 +01:00
|
|
|
"""
|
2019-12-26 21:36:28 +01:00
|
|
|
# Check file extension
|
|
|
|
assert file_path.split('.')[-1] in ('yaml', 'yml'), f"Invalid file extension: {file_path}"
|
|
|
|
|
2019-12-19 16:19:41 +01:00
|
|
|
# Read file
|
|
|
|
with open(file_path) as definition_file:
|
2019-12-30 16:11:25 +01:00
|
|
|
content = definition_file.read()
|
|
|
|
|
|
|
|
# Check for trailing newline
|
|
|
|
assert content[-1] == '\n', "Missing trailing newline"
|
|
|
|
|
|
|
|
# Load YAML data
|
|
|
|
definition = yaml.load(content, Loader=yaml.SafeLoader)
|
2019-12-19 16:19:41 +01:00
|
|
|
|
|
|
|
# Run validation
|
2019-12-19 17:08:51 +01:00
|
|
|
try:
|
|
|
|
validate(definition, schema=schema)
|
|
|
|
except ValidationError as e:
|
2020-11-24 19:25:06 +01:00
|
|
|
pytest.fail(f"{file_path} failed validation: {e}", False)
|