test_elx_schemas.py 1.51 KB
Newer Older
Pinar Alper's avatar
Pinar Alper committed
1
2
3
from unittest import TestCase
from json import loads
from jsonschema import validate
Vilem Ded's avatar
Vilem Ded committed
4
from jsonschema.exceptions import SchemaError
Pinar Alper's avatar
Pinar Alper committed
5
6
import os

Vilem Ded's avatar
Vilem Ded committed
7
8
9
10
11
# Fixtures
dirname = os.path.dirname(__file__)
testdata_dir = os.path.abspath(os.path.join(dirname, "data/"))
schema_dir = os.path.abspath(os.path.join(dirname,"../../metadata_tools/resources/"))
schema_testdata_filename_map = [
12
13
     ('elu-dataset.json', 'datasets.json'),
    #('elu-project.json', 'projects.json'),
Vilem Ded's avatar
Vilem Ded committed
14
15
    ('elu-institution.json', 'partners.json')
    ]
Pinar Alper's avatar
Pinar Alper committed
16
17
18



Vilem Ded's avatar
Vilem Ded committed
19
class TestJSONSchemas(TestCase):
Pinar Alper's avatar
Pinar Alper committed
20
21

    def test_validation(self):
Vilem Ded's avatar
Vilem Ded committed
22
23
24
25
26
27
28
29
30
31
32
33
34
        for schema_filename, dataset_filename in schema_testdata_filename_map:
            schema_filepath = os.path.abspath(os.path.join(schema_dir, schema_filename))
            schemaFile = open(os.path.join(schema_dir, schema_filename), encoding='utf-8')

            data_filepath = os.path.abspath(os.path.join(testdata_dir, dataset_filename))
            dataFile = open(data_filepath, encoding='utf-8')

            schema = loads(schemaFile.read())
            data = loads(dataFile.read())['items']

            for item in data:
                try:
                    validate(item, schema)
35

Vilem Ded's avatar
Vilem Ded committed
36
37
38
39
40
41
42
                except SchemaError:
                   self.fail(f"JSONSchema {schema_filepath} is not valid - SchemaError.")
                except:
                    self.fail(f"JSONSchema {schema_filepath} is not valid - failed on test data {data_filepath}")
                finally:
                    dataFile.close()
                    schemaFile.close()