Skip to content

Commit

Permalink
Merge pull request #769 from vorticity/fix-yaml-ordering
Browse files Browse the repository at this point in the history
Set default yaml.dump sort_keys to False to respect dictionary order
  • Loading branch information
lafrech committed May 12, 2022
2 parents 34d342c + 329bba9 commit 242844f
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,4 @@ Contributors (chronological)
- François Magimel `<https://github.com/Linkid>`_
- Stefan van der Walt `<https://github.com/stefanv>`_
- `<https://github.com/kasium>`_
- Edwin Erdmanis `@vorticity <https://github.com/vorticity>`_
7 changes: 5 additions & 2 deletions src/apispec/yaml_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@


def dict_to_yaml(dic: dict, yaml_dump_kwargs: typing.Any | None = None) -> str:
if yaml_dump_kwargs is None:
yaml_dump_kwargs = {}
"""Serializes a dictionary to YAML."""
yaml_dump_kwargs = yaml_dump_kwargs or {}

# By default, don't sort alphabetically to respect schema field ordering
yaml_dump_kwargs.setdefault("sort_keys", False)
return yaml.dump(dic, **yaml_dump_kwargs)


Expand Down
13 changes: 13 additions & 0 deletions tests/test_yaml_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,16 @@ def test_load_operations_from_docstring_empty_docstring(docstring):
def test_dict_to_yaml_unicode():
assert yaml_utils.dict_to_yaml({"가": "나"}) == '"\\uAC00": "\\uB098"\n'
assert yaml_utils.dict_to_yaml({"가": "나"}, {"allow_unicode": True}) == "가: 나\n"


def test_dict_to_yaml_keys_are_not_sorted_by_default():
assert yaml_utils.dict_to_yaml({"herp": 1, "derp": 2}) == "herp: 1\nderp: 2\n"


def test_dict_to_yaml_keys_can_be_sorted_with_yaml_dump_kwargs():
assert (
yaml_utils.dict_to_yaml(
{"herp": 1, "derp": 2}, yaml_dump_kwargs={"sort_keys": True}
)
== "derp: 2\nherp: 1\n"
)

0 comments on commit 242844f

Please sign in to comment.