|
| 1 | +import yaml |
| 2 | +import pprint |
| 3 | +import sys |
| 4 | + |
| 5 | +def _load_code(expression): |
| 6 | + return eval(expression) |
| 7 | + |
| 8 | +def myconstructor1(constructor, tag, node): |
| 9 | + seq = constructor.construct_sequence(node) |
| 10 | + return {tag: seq } |
| 11 | + |
| 12 | +def myconstructor2(constructor, tag, node): |
| 13 | + seq = constructor.construct_sequence(node) |
| 14 | + string = '' |
| 15 | + try: |
| 16 | + i = tag.index('!') + 1 |
| 17 | + except: |
| 18 | + try: |
| 19 | + i = tag.rindex(':') + 1 |
| 20 | + except: |
| 21 | + pass |
| 22 | + if i >= 0: |
| 23 | + tag = tag[i:] |
| 24 | + return { tag: seq } |
| 25 | + |
| 26 | +class Multi1(yaml.FullLoader): |
| 27 | + pass |
| 28 | +class Multi2(yaml.FullLoader): |
| 29 | + pass |
| 30 | + |
| 31 | +def test_multi_constructor(input_filename, code_filename, verbose=False): |
| 32 | + input = open(input_filename, 'rb').read().decode('utf-8') |
| 33 | + native = _load_code(open(code_filename, 'rb').read()) |
| 34 | + |
| 35 | + # default multi constructor for ! and !! tags |
| 36 | + Multi1.add_multi_constructor('!', myconstructor1) |
| 37 | + Multi1.add_multi_constructor('tag:yaml.org,2002:', myconstructor1) |
| 38 | + |
| 39 | + data = yaml.load(input, Loader=Multi1) |
| 40 | + if verbose: |
| 41 | + print('Multi1:') |
| 42 | + print(data) |
| 43 | + print(native) |
| 44 | + assert(data == native) |
| 45 | + |
| 46 | + |
| 47 | + # default multi constructor for all tags |
| 48 | + Multi2.add_multi_constructor(None, myconstructor2) |
| 49 | + |
| 50 | + data = yaml.load(input, Loader=Multi2) |
| 51 | + if verbose: |
| 52 | + print('Multi2:') |
| 53 | + print(data) |
| 54 | + print(native) |
| 55 | + assert(data == native) |
| 56 | + |
| 57 | + |
| 58 | +test_multi_constructor.unittest = ['.multi', '.code'] |
| 59 | + |
| 60 | +if __name__ == '__main__': |
| 61 | + import test_appliance |
| 62 | + test_appliance.run(globals()) |
| 63 | + |
0 commit comments