1import yaml 2import pprint 3import sys 4 5def _load_code(expression): 6 return eval(expression) 7 8def myconstructor1(constructor, tag, node): 9 seq = constructor.construct_sequence(node) 10 return {tag: seq } 11 12def 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 26class Multi1(yaml.FullLoader): 27 pass 28class Multi2(yaml.FullLoader): 29 pass 30 31def test_multi_constructor(input_filename, code_filename, verbose=False): 32 with open(input_filename, 'rb') as file: 33 input = file.read().decode('utf-8') 34 with open(code_filename, 'rb') as file: 35 native = _load_code(file.read()) 36 37 # default multi constructor for ! and !! tags 38 Multi1.add_multi_constructor('!', myconstructor1) 39 Multi1.add_multi_constructor('tag:yaml.org,2002:', myconstructor1) 40 41 data = yaml.load(input, Loader=Multi1) 42 if verbose: 43 print('Multi1:') 44 print(data) 45 print(native) 46 assert(data == native) 47 48 49 # default multi constructor for all tags 50 Multi2.add_multi_constructor(None, myconstructor2) 51 52 data = yaml.load(input, Loader=Multi2) 53 if verbose: 54 print('Multi2:') 55 print(data) 56 print(native) 57 assert(data == native) 58 59 60test_multi_constructor.unittest = ['.multi', '.code'] 61 62if __name__ == '__main__': 63 import test_appliance 64 test_appliance.run(globals()) 65 66