Skip to content

Commit 9bbceae

Browse files
committed
Initial implementation of JSON validation with schema in GenericJsonParser
1 parent 2816e8a commit 9bbceae

File tree

2 files changed

+419
-17
lines changed

2 files changed

+419
-17
lines changed

InteractiveHtmlBom/ecad/genericjson.py

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import io
22
import json
3+
from jsonschema import validate, ValidationError
34

45
from .common import EcadParser, Component
56

@@ -8,36 +9,47 @@ class GenericJsonParser(EcadParser):
89
COMPATIBLE_SPEC_VERSIONS = [1]
910

1011
def get_generic_json_pcb(self):
12+
from os import path
1113
with io.open(self.file_name, 'r') as f:
12-
return json.load(f)
14+
pcb = json.load(f)
1315

14-
def _verify(self, pcb):
16+
if '_spec_version' not in pcb:
17+
raise ValidationError("'_spec_version' is a required property")
1518

16-
"""Spot check the pcb object."""
17-
if 'pcbdata' not in pcb:
18-
self.logger.error('No pcbdata object')
19-
return False
20-
p = pcb['pcbdata']
19+
if pcb['_spec_version'] not in self.COMPATIBLE_SPEC_VERSIONS:
20+
raise ValidationError("Unsupported _spec_version ({})"
21+
.format(pcb['_spec_version']))
2122

22-
if 'components' not in pcb:
23-
self.logger.error('No components object')
24-
return False
25-
c = pcb['components']
23+
schema_dir = path.join(path.dirname(__file__), 'schema')
24+
if pcb['_spec_version'] == 1:
25+
schema_file_name = path.join(schema_dir,
26+
'genericjsonpcbdata_v{}.schema'
27+
.format(pcb['_spec_version']))
2628

27-
if pcb['_spec_version'] not in self.COMPATIBLE_SPEC_VERSIONS:
28-
self.logger.error('Unsupported spec version ({})'
29-
.format(pcb['_spec_version']))
30-
return False
29+
with io.open(schema_file_name, 'r') as f:
30+
schema = json.load(f)
3131

32-
if 'footprints' not in p or len(p['footprints']) != len(c):
32+
validate(instance=pcb, schema=schema)
33+
34+
return pcb
35+
36+
def _verify(self, pcb):
37+
38+
"""Spot check the pcb object."""
39+
40+
if len(pcb['pcbdata']['footprints']) != len(pcb['components']):
3341
self.logger.error("length of components list doesn't match"
3442
" length of footprints list")
3543
return False
3644

3745
return True
3846

3947
def parse(self):
40-
pcb = self.get_generic_json_pcb()
48+
try:
49+
pcb = self.get_generic_json_pcb()
50+
except ValidationError as e:
51+
self.logger.error(e.message)
52+
return None, None
4153

4254
if not self._verify(pcb):
4355
self.logger.error('File {} does not appear to be valid generic'

0 commit comments

Comments
 (0)