Skip to content

Commit

Permalink
feat(converter): fix format object util when is array list
Browse files Browse the repository at this point in the history
  • Loading branch information
muffoltz committed Jan 28, 2025
1 parent f12c99c commit 9ff3e61
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 23 deletions.
28 changes: 14 additions & 14 deletions converter/converter/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ def get_sender(edxl_json: Dict[str, Any]) -> str:
def delete_paths(data: Dict[str, Any], paths: List[str]) -> None:
"""
Safely deletes keys in a dictionary based on dot-separated paths.
Args:
data: Dictionary to modify
paths: List of dot-separated paths (e.g., "a.b.c")
"""
def delete_recursively(d: Dict[str, Any], keys: List[str]) -> None:
if not keys or not isinstance(d, dict):
return

key = keys[0]
if len(keys) == 1:
# Delete target key if it exists
Expand All @@ -41,51 +41,51 @@ def add_space_before_uppercase(text):
def format_object(obj: Any, indent: int = 0) -> str:
"""
Recursively formats an object into a readable string.
Args:
obj: Object to format
indent: Current indentation level (for recursion)
Returns:
Formatted string representation with proper indentation and structure
"""
indent_str = " " * indent

if hasattr(obj, '__dict__'): # Object with attributes
attributes = vars(obj)
if not attributes:
return f"{indent_str}No attributes to display."

formatted_lines = []

# Add class name at root level
if indent == 0:
formatted_lines.append(f"{indent_str}{add_space_before_uppercase(obj.__class__.__name__)}:")

for field, value in attributes.items():
if value is None: # Skip None values
continue

if hasattr(value, '__dict__'): # Nested object
formatted_lines.append(f"{indent_str}- {field.replace('_', ' ').title()}:")
formatted_lines.append(format_object(value, indent=indent + 1))
else: # Primitive value
formatted_lines.append(f"{indent_str}- {field.replace('_', ' ').title()}: {value}")

return "\n".join(formatted_lines)

# Handle collections
if isinstance(obj, list):
return "\n".join(f"{indent_str}- {format_object(item, indent + 1)}" for item in obj)
return "\n".join(f"{indent_str}- {format_object(item, indent + 1).strip()}" for item in obj)
elif isinstance(obj, dict):
formatted_lines = []
for key, value in obj.items():
formatted_lines.append(f"{indent_str}- {key.replace('_', ' ').title()}:")
formatted_lines.append(format_object(value, indent + 1))
return "\n".join(formatted_lines)

# Base case for primitives
return f"{indent_str}{obj}"
return f"{indent_str}{obj}"


def add_object_to_initial_alert_notes(output_json, note_text):
Expand Down
17 changes: 8 additions & 9 deletions converter/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,10 @@ def test_format_object_primitive():
assert format_object("test") == "test"
assert format_object(123) == "123"

# ToDo: improve list handling and tests
# def test_format_object_list():
# result = format_object(["a", "b", "c"])
# expected = "- a\n- b\n- c"
# assert result == expected
def test_format_object_list():
result = format_object(["a", "b", "c"])
expected = "- a\n- b\n- c"
assert result == expected

def test_format_object_dict():
data = {"key1": "value1", "key2": "value2"}
Expand All @@ -31,7 +30,7 @@ def test_format_object_dict():
def test_format_object_nested():
victim = ExampleTestVictim("PLUSIEURS", "GRAVE")
incident = ExampleTestIncident("Accident", "School", victim)

result = format_object(incident)
expected = (
"Example Test Incident:\n"
Expand All @@ -54,10 +53,10 @@ def test_delete_paths():
},
"f": 4
}

paths = ["a.b.c", "f"]
delete_paths(data, paths)

assert "c" not in data["a"]["b"]
assert "f" not in data
assert data["a"]["b"]["d"] == 2
Expand All @@ -70,7 +69,7 @@ def test_delete_paths_missing():
def test_delete_paths_cleanup():
data = {"a": {"b": {"c": 1}}}
delete_paths(data, ["a.b.c"])
assert data == {} # Empty dictionaries should be cleaned up
assert data == {} # Empty dictionaries should be cleaned up

def test_add_note_to_existing_notes():
output_json = {
Expand Down

0 comments on commit 9ff3e61

Please sign in to comment.