Some renaming.
[pyyaml/python3.git] / tests / test_structure.py
blob754bc5ea609ac4d8d2f54da03d51183e3c246a8a
2 import test_appliance
4 from yaml.reader import Reader
5 from yaml.scanner import Scanner
6 from yaml.parser import *
8 class TestStructure(test_appliance.TestAppliance):
10 def _testStructure(self, test_name, data_filename, structure_filename):
11 node1 = None
12 node2 = eval(file(structure_filename, 'rb').read())
13 try:
14 parser = Parser(Scanner(Reader(file(data_filename, 'rb'))))
15 node1 = parser.parse()
16 node1 = [self._convert(n) for n in node1]
17 if len(node1) == 1:
18 node1 = node1[0]
19 self.failUnlessEqual(node1, node2)
20 except:
21 print
22 print "DATA:"
23 print file(data_filename, 'rb').read()
24 print "NODE1:", node1
25 print "NODE2:", node2
26 raise
28 def _convert(self, node):
29 if isinstance(node, ScalarNode):
30 return True
31 elif isinstance(node, SequenceNode):
32 sequence = []
33 for item in node.value:
34 sequence.append(self._convert(item))
35 return sequence
36 elif isinstance(node, MappingNode):
37 mapping = []
38 for key, value in node.value:
39 mapping.append((self._convert(key), self._convert(value)))
40 return mapping
41 elif isinstance(node, AliasNode):
42 return '*'
43 else:
44 return node
46 TestStructure.add_tests('testStructure', '.data', '.structure')
48 class TestParser(test_appliance.TestAppliance):
50 def _testParser(self, test_name, data_filename, canonical_filename):
51 documents1 = None
52 documents2 = None
53 try:
54 parser = Parser(Scanner(Reader(file(data_filename, 'rb'))))
55 documents1 = parser.parse()
56 canonical = test_appliance.CanonicalParser(canonical_filename, file(canonical_filename, 'rb').read())
57 documents2 = canonical.parse()
58 self._compare(documents1, documents2)
59 except:
60 print
61 print "DATA1:"
62 print file(data_filename, 'rb').read()
63 print "DATA2:"
64 print file(canonical_filename, 'rb').read()
65 print "DOCUMENTS1:", documents1
66 print "DOCUMENTS2:", documents2
67 raise
69 def _compare(self, value1, value2):
70 if value1 is None and hasattr(value2, 'tag') and value2.tag == 'tag:yaml.org,2002:null':
71 return
72 self.failUnlessEqual(type(value1), type(value2))
73 if isinstance(value1, list) or isinstance(value1, tuple):
74 self.failUnlessEqual(len(value1), len(value2))
75 for item1, item2 in zip(value1, value2):
76 self._compare(item1, item2)
77 else:
78 self.failUnlessEqual(value1.__class__.__name__, value2.__class__.__name__)
79 if isinstance(value1, SequenceNode) or isinstance(value1, MappingNode):
80 self._compare(value1.value, value2.value)
82 TestParser.add_tests('testParser', '.data', '.canonical')