File size: 2,291 Bytes
1120183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Strict loader validation with explicit, lossless JSON collection conversion.

Never use default=str or discard unknown/nonempty missing/unexpected/error data.
The original failed run remains unchanged. This helper is for new candidates.
"""
from collections.abc import Mapping

FIELDS = ('missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs')


def json_value(value):
    if value is None or type(value) in (str, bool, int):
        return value
    if type(value) is float:
        import math
        if not math.isfinite(value):
            raise TypeError('Nonfinite loading diagnostic')
        return value
    if isinstance(value, Mapping):
        if not all(type(k) is str for k in value):
            raise TypeError('Loading diagnostic mapping requires string keys')
        return {k: json_value(v) for k, v in value.items()}
    if isinstance(value, (tuple, list)):
        return [json_value(v) for v in value]
    if isinstance(value, (set, frozenset)):
        import json
        result = [json_value(v) for v in value]
        return sorted(result, key=lambda v: json.dumps(v, sort_keys=True, allow_nan=False))
    raise TypeError('Unsupported loading diagnostic type: ' + type(value).__name__)


def strict_loading_report(info):
    if not isinstance(info, Mapping):
        raise TypeError('Loading information must be a mapping')
    if set(info) - set(FIELDS):
        raise ValueError('Unknown loading diagnostic fields; explicit review required')
    missing_fields = [k for k in FIELDS if k not in info]
    if missing_fields:
        raise ValueError('Loading diagnostic fields absent: ' + ','.join(missing_fields))
    report = {
        'source_collection_types': {k: type(info[k]).__name__ for k in FIELDS},
        'loading_information': json_value(info),
        'strict_fields': list(FIELDS),
    }
    for key in FIELDS:
        value = info[key]
        if not isinstance(value, (list, tuple, set, frozenset, Mapping)):
            raise TypeError('Unknown loading-status collection: ' + key)
        if len(value):
            # Diagnostic conversion must never turn a failed strict load into PASS.
            raise ValueError('Complete published body strict load failed: ' + key)
    report['strict_load_passed'] = True
    return report