fix: snake case converter corner cases

This commit is contained in:
Thomas Leonard 2023-08-08 14:28:53 +02:00
parent 93cb33d359
commit 9ee127e3d5
2 changed files with 28 additions and 4 deletions

View File

@ -10,8 +10,8 @@ def to_camel_case(snake_str):
return components[0] + "".join(x.capitalize() if x else "_" for x in components[1:])
# From this response in Stackoverflow
# http://stackoverflow.com/a/1176023/1072990
def to_snake_case(name):
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
if not name:
return name
# Replace every capitalized letter (except the first one) by its lower case variant with an underscore before.
return (name[0] + re.sub("([A-Z])", r"_\1", name[1:])).lower()

View File

@ -3,6 +3,7 @@ from ..str_converters import to_camel_case, to_snake_case
def test_snake_case():
assert to_snake_case("") == ""
assert to_snake_case("snakesOnAPlane") == "snakes_on_a_plane"
assert to_snake_case("SnakesOnAPlane") == "snakes_on_a_plane"
assert to_snake_case("SnakesOnA_Plane") == "snakes_on_a__plane"
@ -10,10 +11,33 @@ def test_snake_case():
assert to_snake_case("snakes_on_a__plane") == "snakes_on_a__plane"
assert to_snake_case("IPhoneHysteria") == "i_phone_hysteria"
assert to_snake_case("iPhoneHysteria") == "i_phone_hysteria"
assert to_snake_case("_IPhoneHysteria") == "__i_phone_hysteria"
assert to_snake_case("_File__") == "__file__"
assert to_snake_case("potato01") == "potato01"
assert to_camel_case("a") == "a"
assert to_snake_case("A") == "a"
assert to_snake_case("_A") == "__a"
assert to_snake_case("_A0") == "__a0"
assert to_snake_case("AAA") == "a_a_a"
def test_camel_case():
assert to_camel_case("") == ""
assert to_camel_case("snakesOnAPlane") == "snakesOnAPlane"
assert to_camel_case("snakesOn_a_plane") == "snakesOnAPlane"
assert to_camel_case("snakes_On_a_plane") == "snakesOnAPlane"
assert to_camel_case("snakes_on_a_plane") == "snakesOnAPlane"
assert to_camel_case("snakes_on_a__plane") == "snakesOnA_Plane"
assert to_camel_case("i_phone_hysteria") == "iPhoneHysteria"
assert to_camel_case("_i_phone_hysteria") == "IPhoneHysteria"
assert to_camel_case("__i_phone_hysteria") == "_IPhoneHysteria"
assert to_camel_case("field_i18n") == "fieldI18n"
assert to_camel_case("__file__") == "_File__"
assert to_camel_case("potato01") == "potato01"
assert to_camel_case("potato_0_1") == "potato01"
assert to_camel_case("a") == "a"
assert to_camel_case("A") == "A"
assert to_camel_case("_a") == "A"
assert to_camel_case("__a") == "_A"
assert to_camel_case("__a0") == "_A0"
assert to_camel_case("a_a_a") == "aAA"