Skip to content
This repository has been archived by the owner on Sep 7, 2023. It is now read-only.

Commit

Permalink
Generate valid json if multiple log entries are generated on same line
Browse files Browse the repository at this point in the history
  • Loading branch information
skshetry committed Aug 3, 2019
1 parent f679181 commit 6544e13
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
56 changes: 56 additions & 0 deletions tests/test_json_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,24 @@ def single_log_file():
return file


@pytest.fixture
def log_on_same_line():
"""Create a log file with multiple entries on same line."""
file = tempfile.NamedTemporaryFile(mode="w")
file.write('{"message": 1}{"message": 2}{"message": 3}')
file.seek(0)
return file


@pytest.fixture
def log_comma_separation_same_line():
"""Create a log file with multiple entries on same line, comma separated."""
file = tempfile.NamedTemporaryFile(mode="w")
file.write('{"message": 1},{"message": 2},{"message": 3}')
file.seek(0)
return file


@pytest.fixture
def empty_log_file():
"""Create a log file without any entries."""
Expand Down Expand Up @@ -110,3 +128,41 @@ def test_single_logfile(single_log_file):
else:
assert len(json_log["logs"]) == 1
assert json_log["logs"][0]["from"] == "[email protected]"


def test_logfile_log_entries_on_same_line(log_on_same_line):
"""Test with single log."""
output = ""
with open(log_on_same_line.name) as file:
for line in wrap_json_output(file):
output += line

try:
json_log = json.loads(output)
except ValueError:
assert False, "Invalid json generated."
else:
assert len(json_log["logs"]) == 3
assert json_log["logs"][0]["message"] == 1
assert json_log["logs"][1]["message"] == 2
assert json_log["logs"][2]["message"] == 3


def test_logfile_log_entries_on_same_line_with_comma_separation(
log_comma_separation_same_line
):
"""Test with single log."""
output = ""
with open(log_comma_separation_same_line.name) as file:
for line in wrap_json_output(file):
output += line

try:
json_log = json.loads(output)
except ValueError:
assert False, "Invalid json generated."
else:
assert len(json_log["logs"]) == 3
assert json_log["logs"][0]["message"] == 1
assert json_log["logs"][1]["message"] == 2
assert json_log["logs"][2]["message"] == 3
2 changes: 1 addition & 1 deletion zippy/utils/json_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ def wrap_json_output(input_file):
json_ending = "]}"

yield json_starting
yield ",".join(input_file.readlines())
yield ",".join(input_file.readlines()).replace("}{", "},{")
yield json_ending

0 comments on commit 6544e13

Please sign in to comment.