Skip to content

Commit

Permalink
Merge pull request #7 from Momnt-Technologies/aray-finalFix
Browse files Browse the repository at this point in the history
fix: fixing the loggers to handle both types of json outputs
  • Loading branch information
mbonig authored Aug 8, 2024
2 parents 4f36431 + af2a2ef commit 2786b85
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
Binary file added src/handlers/__pycache__/index.cpython-311.pyc
Binary file not shown.
27 changes: 26 additions & 1 deletion src/handlers/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import logging
import os
import subprocess
from typing import Dict, Optional

logger = logging.getLogger()
logger.setLevel(logging.INFO)
Expand Down Expand Up @@ -33,6 +34,23 @@ def handler(event, context):

return kubectl(event["commands"])

def parse_json(json_str: str) -> Optional[Dict]:
try:
return json.loads(json_str)
except json.JSONDecodeError:
json_objects = []

try:
for line in json_str.strip().split('\n'):
try:
json_objects.append(json.loads(line))
except json.JSONDecodeError as e:
logger.error(f"Failed to parse line: {line}, error: {e}")

except (TypeError, AttributeError) as e:
logger.error("Failed to parse json: %s" % e)

return json_objects

def kubectl(commands):
maxAttempts = 3
Expand All @@ -49,7 +67,14 @@ def kubectl(commands):
logger.info(f"Decoded output: {decoded_output}")

if isinstance(decoded_output, str):
logger.info(f"Converted json output: {json.loads(decoded_output)}")
parsed_json = parse_json(decoded_output)
if isinstance(parsed_json, list):
for item in parsed_json:
logger.info(f"{item}")

else:
logger.info(f"Converted json output: {parsed_json}")

else:
logger.info(f"Could not convert to json, different data type returned: {type(decoded_output)}")

Expand Down
21 changes: 21 additions & 0 deletions src/handlers/index_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from index import parse_json

def test_parse_json():
json_str = '{"key": "value"}'
assert parse_json(json_str) == {"key": "value"}
print("base case assert passed")

json_str = '{"key": "value"}\n{"key": "value"}'
assert parse_json(json_str) == [{"key": "value"}, {"key": "value"}]
print("multiple logs in one message assert passed")

json_str = '{"key": "value"}\n{"key": "value"'
assert parse_json(json_str) == [{"key": "value"}]
print("incomplete log assert passed")

json_str = '{"key": "value"}\n{"key": "value"}\n{"key": "value"}'
assert parse_json(json_str) == [{"key": "value"}, {"key": "value"}, {"key": "value"}]
print("more than 2 logs assert passed")

if __name__ == "__main__":
test_parse_json()

0 comments on commit 2786b85

Please sign in to comment.