File size: 3,439 Bytes
9d57416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""Validator for the explicitly used JSON Schema subset (standard library).

Unknown keywords fail; this is not a general JSON Schema implementation.
Used to validate real segment payloads and the generated Python/TS contract.
"""
import json
import math
from pathlib import Path

SCHEMA_PATH = Path(__file__).with_name('contract.schema.json')


def validate(value, schema=None, root=None, path='$'):
    if schema is None:
        root = schema = json.loads(SCHEMA_PATH.read_text())
    root = root or schema
    known = {'$schema', '$ref', '$defs', 'type', 'const', 'enum', 'properties', 'required',
             'additionalProperties', 'items', 'minItems', 'maxItems', 'minimum', 'maximum',
             'exclusiveMinimum', 'anyOf'}
    # description 只是注释,不约束值;不放行它,带 description 的定义(如 ObserverSplit)一碰到真值就断言
    assert set(schema) - {'description'} <= known, 'unsupported schema keywords'
    if '$ref' in schema:
        return validate(value, root['$defs'][schema['$ref'].split('/')[-1]], root, path)
    if 'const' in schema and value != schema['const']:
        raise ValueError(path + ': const mismatch')
    if 'enum' in schema and value not in schema['enum']:
        raise ValueError(path + ': enum mismatch')
    if 'anyOf' in schema:
        for candidate in schema['anyOf']:
            try:
                validate(value, candidate, root, path)
                return
            except ValueError:
                pass
        raise ValueError(path + ': anyOf mismatch')
    if 'type' in schema:
        kinds = schema['type'] if isinstance(schema['type'], list) else [schema['type']]
        def matches(kind):
            return {'object': isinstance(value, dict), 'array': isinstance(value, list),
                    'string': isinstance(value, str), 'boolean': type(value) is bool,
                    'null': value is None, 'integer': type(value) is int,
                    'number': type(value) in (int, float) and math.isfinite(value)}[kind]
        if not any(matches(kind) for kind in kinds):
            raise ValueError(path + ': wrong type')
    if isinstance(value, dict):
        for name in schema.get('required', []):
            if name not in value:
                raise ValueError(path + ': missing ' + name)
        properties = schema.get('properties', {})
        for name, item in value.items():
            if name in properties:
                validate(item, properties[name], root, path + '.' + name)
            elif schema.get('additionalProperties') is False:
                raise ValueError(path + ': unexpected ' + name)
            elif isinstance(schema.get('additionalProperties'), dict):
                validate(item, schema['additionalProperties'], root, path + '.' + name)
    if isinstance(value, list):
        if len(value) < schema.get('minItems', 0) or len(value) > schema.get('maxItems', math.inf):
            raise ValueError(path + ': wrong array length')
        for i, item in enumerate(value):
            validate(item, schema.get('items', {}), root, path + '[' + str(i) + ']')
    if type(value) in (int, float):
        if value < schema.get('minimum', -math.inf) or value > schema.get('maximum', math.inf):
            raise ValueError(path + ': out of bounds')
        if 'exclusiveMinimum' in schema and value <= schema['exclusiveMinimum']:
            raise ValueError(path + ': exclusive minimum')