Skip to content

Commit

Permalink
testlibs: fix deep_sort for list case
Browse files Browse the repository at this point in the history
First deep_sort the inner elements of a list and finally sort the list
itself using sorted.

Signed-off-by: Chris Aslanoglou <chris.aslanoglou@gmail.com>
  • Loading branch information
chris-asl committed Jan 18, 2018
1 parent 9824bd9 commit 7234ac3
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 11 deletions.
13 changes: 2 additions & 11 deletions hepcrawl/testlib/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,13 @@ def get_crawler_instance(crawler_host, *args, **kwargs):


def deep_sort(element):
"""Dummy deep-sort json dicts (lists, dicts, stirngs, bools and integers).
"""
if isinstance(element, str):
return element

"""Dummy deep-sort json dicts (lists, dicts, stirngs, bools and integers)."""
if isinstance(element, dict):
for key, value in element.items():
element[key] = deep_sort(value)

return element

if isinstance(element, list):
new_element = []
for item in sorted(element):
new_element.append(deep_sort(item))

return new_element
return sorted([deep_sort(item) for item in element])

return element
77 changes: 77 additions & 0 deletions tests/unit/test_testlib_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# -*- coding: utf-8 -*-
#
# This file is part of hepcrawl.
# Copyright (C) 2015, 2016, 2017 CERN.
#
# hepcrawl is a free software; you can redistribute it and/or modify it
# under the terms of the Revised BSD License; see LICENSE file for
# more details.

from __future__ import absolute_import, division, print_function, unicode_literals

from hepcrawl.testlib.utils import deep_sort


def test_deep_sort_with_dict_in_list():
element = [{'b': {'name': 'bb'}}, {'a': {'name': 'aa'}}]
expected_element = [{'a': {'name': 'aa'}}, {'b': {'name': 'bb'}}]

result = deep_sort(expected_element)
assert result == expected_element


def test_deep_sort_with_query_parser_output():
element = {
"bool": {
"filter": {
"bool": {
"should": [
{
"term": {
"authors.name_variations": "j ellis"
}
},
{
"term": {
"authors.name_variations": "ellis j"
}
}
]
}
},
"must": {
"match": {
"authors.full_name": "ellis, j"
}
}
}
}

expected_element = {
"bool": {
"filter": {
"bool": {
"should": [
{
"term": {
"authors.name_variations": "ellis j"
}
},
{
"term": {
"authors.name_variations": "j ellis"
}
}
]
}
},
"must": {
"match": {
"authors.full_name": "ellis, j"
}
}
}
}

result = deep_sort(expected_element)
assert result == expected_element

0 comments on commit 7234ac3

Please sign in to comment.