Skip to content

Commit

Permalink
Extracted private function as helper, created unit test to reproduce …
Browse files Browse the repository at this point in the history
…the bug and fixed the issue.
  • Loading branch information
tomeksabala committed May 20, 2022
1 parent db747aa commit f754a1f
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 16 deletions.
13 changes: 13 additions & 0 deletions ckanext/scheming/tests/test_unaids_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import pytest

from ckanext.scheming.unaids_helpers import comma_swap_formatter


@pytest.mark.parametrize("input,expected",
[("no_commas", "no_commas"),
("comma,split", "split comma"),
("Tanzania, Republic of", "Republic of Tanzania")
])
def test_comma_swap_formatter(input, expected):
actual = comma_swap_formatter(input)
assert actual == expected
15 changes: 15 additions & 0 deletions ckanext/scheming/unaids_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,18 @@ def get_resource_field(dataset_type, resource_type, field_name):
return field
except IndexError:
return {}


def comma_swap_formatter(input):
"""
Swaps the parts of a string around a single comma.
Use to format e.g. "Tanzania, Republic of" as "Republic of Tanzania"
"""
if input.count(',') == 1:
parts = input.split(',')
stripped_parts = list(map(lambda x: x.strip(), parts))
reversed_parts = reversed(stripped_parts)
joined_parts = " ".join(reversed_parts)
return joined_parts
else:
return input
18 changes: 2 additions & 16 deletions ckanext/scheming/unaids_validators.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from ckanext.scheming.unaids_helpers import comma_swap_formatter
from ckanext.scheming.validation import scheming_validator
from ckan.logic.validators import package_name_validator
import slugify
Expand Down Expand Up @@ -89,7 +90,7 @@ def autogenerate(field, schema):
formatters = {
"lower": __lower_formatter,
"slugify": slugify.slugify,
"comma_swap": __comma_swap_formatter
"comma_swap": comma_swap_formatter
}
f_list = []
for f in template_formatters:
Expand Down Expand Up @@ -122,18 +123,3 @@ def validator(key, data, errors, context):

def __lower_formatter(input):
return input.lower()


def __comma_swap_formatter(input):
"""
Swaps the parts of a string around a single comma.
Use to format e.g. "Tanzania, Republic of" as "Republic of Tanzania"
"""
if input.count(',') == 1:
parts = input.split(',')
stripped_parts = map(lambda x: x.strip(), parts)
reversed_parts = reversed(stripped_parts)
joined_parts = " ".join(reversed_parts)
return joined_parts
else:
return input

0 comments on commit f754a1f

Please sign in to comment.