xref: /freebsd/contrib/libucl/python/tests/test_validation.py (revision 242b24828472137ec4411826b86e753d49bd2c39)
1from .compat import unittest
2import ucl
3import json
4import os.path
5import glob
6import re
7
8TESTS_SCHEMA_FOLDER = '../tests/schema/*.json'
9
10comment_re = re.compile('\/\*((?!\*\/).)*?\*\/', re.DOTALL | re.MULTILINE)
11def json_remove_comments(content):
12    return comment_re.sub('', content)
13
14class ValidationTest(unittest.TestCase):
15    def validate(self, jsonfile):
16        def perform_test(schema, data, valid, description):
17            msg = '%s (valid=%r)' % (description, valid)
18            if valid:
19                self.assertTrue(ucl.validate(schema, data), msg)
20            else:
21                with self.assertRaises(ucl.SchemaError):
22                    ucl.validate(schema, data)
23                    self.fail(msg) # fail() will be called only if SchemaError is not raised
24
25        with open(jsonfile) as f:
26            try:
27                # data = json.load(f)
28                data = json.loads(json_remove_comments(f.read()))
29            except ValueError as e:
30                raise self.skipTest('Failed to load JSON: %s' % str(e))
31
32            for testgroup in data:
33                for test in testgroup['tests']:
34                    perform_test(testgroup['schema'], test['data'],
35                        test['valid'], test['description'])
36
37    @classmethod
38    def setupValidationTests(cls):
39        """Creates each test dynamically from a folder"""
40        def test_gen(filename):
41            def run_test(self):
42                self.validate(filename)
43            return run_test
44
45        for jsonfile in glob.glob(TESTS_SCHEMA_FOLDER):
46            testname = os.path.splitext(os.path.basename(jsonfile))[0]
47            setattr(cls, 'test_%s' % testname, test_gen(jsonfile))
48
49
50ValidationTest.setupValidationTests()
51