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