|
8 | 8 | schema = json.load((Path(__file__).parent / 'profiles-schema.json').open()) |
9 | 9 |
|
10 | 10 |
|
| 11 | +class Check(object): |
| 12 | + def __init__(self, config): |
| 13 | + if type(config) == str: |
| 14 | + match config: |
| 15 | + case "json": |
| 16 | + self.method = parseJSON |
| 17 | + case "xml": |
| 18 | + self.method = parseXML |
| 19 | + case _: |
| 20 | + # TODO: allow to reference another profile |
| 21 | + raise Exception(f"Unknown check: {config}") |
| 22 | + elif "schema" in config and "language" in config: |
| 23 | + match config["language"]: |
| 24 | + case "xsd": |
| 25 | + pass # TODO: load as local file or from URL with cache |
| 26 | + case "jsonschema": |
| 27 | + pass # TODO |
| 28 | + case _: |
| 29 | + raise Exception(f"Unsupported schema language: {config['language']}") |
| 30 | + |
| 31 | + else: |
| 32 | + raise Exception(f"Unkown check: {json.dumps(config)}") |
| 33 | + |
| 34 | + def execute(self, data): |
| 35 | + self.method(data) |
| 36 | + |
| 37 | + |
11 | 38 | class Validator(object): |
12 | 39 | def __init__(self, profiles, **config): |
13 | 40 | validateJSON(profiles, schema) |
14 | 41 |
|
15 | | - # TODO: check if id is unique |
16 | | - self.profiles = dict([(p["id"], p) for p in profiles]) |
17 | | - # TODO: compile checks of profiles |
| 42 | + checks = {p["id"]: p.get("checks", []) for p in profiles} |
| 43 | + if len(checks) != len(profiles): |
| 44 | + raise ValueError("Profiles must have unique ids") |
18 | 45 |
|
19 | | - # self.reports = config.get('reports', None) |
| 46 | + self.profiles = {} |
| 47 | + for p in profiles: |
| 48 | + id = p["id"] |
20 | 49 |
|
21 | | - def profile(self, id): |
22 | | - "Returns public metadata of a profile or None." |
23 | | - p = self.profiles[id] |
24 | | - fields = ['id', 'title', 'description', 'url'] |
25 | | - return {key: p[key] for key in fields if key in p} |
| 50 | + # TODO: support reference to profile as check |
| 51 | + checks[id] = [Check(c) for c in checks[id]] |
26 | 52 |
|
27 | | - def profiles_metadata(self): |
28 | | - "List of profiles reduced to their their public metadata" |
29 | | - return [self.profile(id) for id in self.profiles] |
| 53 | + about = ['id', 'title', 'description', 'url'] |
| 54 | + self.profiles[id] = {key: p[key] for key in about if p.get(key, False)} |
| 55 | + |
| 56 | + self.checks = checks |
| 57 | + |
| 58 | + def profile(self, id) -> dict: |
| 59 | + return self.profiles[id] |
30 | 60 |
|
31 | 61 | def execute(self, profile, data=None, file=None): |
32 | 62 | if file: |
33 | 63 | data = Path(file).read_bytes() |
34 | | - |
35 | | - checks = self.profiles[profile]['checks'] |
36 | | - for check in checks: |
37 | | - if check == "json": |
38 | | - parseJSON(data) |
39 | | - elif check == "xml": |
40 | | - parseXML(data) |
| 64 | + for check in self.checks[profile]: |
| 65 | + check.execute(data) |
0 commit comments