Skip to content

Commit e37cac9

Browse files
committed
Fix html5lib#37: Preserve order of attributes on serialization.
This doesn't do anything about the fact that none of our treebuilders preserve attribute order: it merely avoids the serializer reordering them from the order it receives them in. This changes the serializer tests to use an OrderedDict to get alphabetical order so they continue to meet their expectations.
1 parent b4a8a6f commit e37cac9

File tree

2 files changed

+7
-4
lines changed

2 files changed

+7
-4
lines changed

html5lib/serializer/htmlserializer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ def serialize(self, treewalker, encoding=None):
226226
in_cdata = True
227227
elif in_cdata:
228228
self.serializeError(_("Unexpected child element of a CDATA element"))
229-
for (attr_namespace, attr_name), attr_value in sorted(token["data"].items()):
229+
for (attr_namespace, attr_name), attr_value in token["data"].items():
230230
# TODO: Add namespace support here
231231
k = attr_name
232232
v = attr_value

html5lib/tests/test_serializer.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import absolute_import, division, unicode_literals
22

33
import unittest
4+
from collections import OrderedDict
45
from .support import get_data_files
56

67
try:
@@ -73,9 +74,11 @@ def _convertAttrib(self, attribs):
7374
"""html5lib tree-walkers use a dict of (namespace, name): value for
7475
attributes, but JSON cannot represent this. Convert from the format
7576
in the serializer tests (a list of dicts with "namespace", "name",
76-
and "value" as keys) to html5lib's tree-walker format."""
77-
attrs = {}
78-
for attrib in attribs:
77+
and "value" as keys) to html5lib's tree-walker format. Tests expect
78+
attributes to be ordered alphabetically, so use an OrderedDict to
79+
ensure this."""
80+
attrs = OrderedDict()
81+
for attrib in sorted(attribs, key=lambda x: (x["namespace"], x["name"])):
7982
name = (attrib["namespace"], attrib["name"])
8083
assert(name not in attrs)
8184
attrs[name] = attrib["value"]

0 commit comments

Comments
 (0)