blob: 41b67e5e9d595663b771ba580244a4ae7353c666 [file] [log] [blame]
Inaky Perez-Gonzalez662dde62017-07-24 10:24:35 -07001#! /usr/bin/python
2#
3# Zephyr's Sanity Check library
4#
5# Set of code that other projects can also import to do things on
6# Zephyr's sanity check testcases.
7
8import logging
9import os
10import yaml
11
12log = logging.getLogger("scl")
13
14#
15#
16def yaml_load(filename):
17 """
18 Safely load a YAML document
19
20 Follows recomendations from
21 https://security.openstack.org/guidelines/dg_avoid-dangerous-input-parsing-libraries.html.
22
23 :param str filename: filename to load
24 :raises yaml.scanner: On YAML scan issues
25 :raises: any other exception on file access erors
26 :return: dictionary representing the YAML document
27 """
28 try:
29 with open(filename, 'r') as f:
30 return yaml.safe_load(f)
31 except yaml.scanner.ScannerError as e: # For errors parsing schema.yaml
32 mark = e.problem_mark
33 cmark = e.context_mark
34 log.error("%s:%d:%d: error: %s (note %s context @%s:%d:%d %s)",
35 mark.name, mark.line, mark.column, e.problem,
36 e.note, cmark.name, cmark.line, cmark.column, e.context)
37 raise
38
39# If pykwalify is installed, then the validate functionw ill work --
40# otherwise, it is a stub and we'd warn about it.
41try:
42 import pykwalify.core
43 # Don't print error messages yourself, let us do it
44 logging.getLogger("pykwalify.core").setLevel(50)
45
46 def _yaml_validate(data, schema):
47 if not schema:
48 return
49 c = pykwalify.core.Core(source_data = data, schema_data = schema)
50 c.validate(raise_exception = True)
51
52except ImportError as e:
53 log.warning("can't import pykwalify; won't validate YAML (%s)", e)
54 def _yaml_validate(data, schema):
55 pass
56
57def yaml_load_verify(filename, schema):
58 """
59 Safely load a testcase/sample yaml document and validate it
60 against the YAML schema, returing in case of success the YAML data.
61
62 :param str filename: name of the file to load and process
63 :param dict schema: loaded YAML schema (can load with :func:`yaml_load`)
64
65 # 'document.yaml' contains a single YAML document.
66 :raises yaml.scanner.ScannerError: on YAML parsing error
67 :raises pykwalify.errors.SchemaError: on Schema violation error
68 """
69 # 'document.yaml' contains a single YAML document.
70 y = yaml_load(filename)
71 _yaml_validate(y, schema)
72 return y