From f908c0e8e1daaab5566844509b8ed358e9f12cbb Mon Sep 17 00:00:00 2001 From: Lyndsy Simon Date: Wed, 21 Nov 2018 13:16:04 -0600 Subject: [PATCH] Add JSONFormatter --- columnist/formatters/__init__.py | 1 + columnist/formatters/json.py | 11 ++++++ tests/test_formatters.py | 59 ++++++++++++++++++++++++++------ 3 files changed, 60 insertions(+), 11 deletions(-) create mode 100644 columnist/formatters/json.py diff --git a/columnist/formatters/__init__.py b/columnist/formatters/__init__.py index 0ab21af..4d7294c 100644 --- a/columnist/formatters/__init__.py +++ b/columnist/formatters/__init__.py @@ -1 +1,2 @@ from .csv import CSVFormatter # noqa: F401 +from .json import JSONFormatter # noqa: F401 diff --git a/columnist/formatters/json.py b/columnist/formatters/json.py new file mode 100644 index 0000000..c40a78b --- /dev/null +++ b/columnist/formatters/json.py @@ -0,0 +1,11 @@ +import json + +from .base import Formatter + + +class JSONFormatter(Formatter): + def to_file(self, destination, **options): + destination.write(self.to_string(**options)) + + def to_string(self, **options): + return json.dumps(list(self.report.rows())) diff --git a/tests/test_formatters.py b/tests/test_formatters.py index 6bcd0a0..e0c513b 100644 --- a/tests/test_formatters.py +++ b/tests/test_formatters.py @@ -1,10 +1,12 @@ import datetime +import json import pytest from columnist import column from columnist import Report from columnist.formatters import CSVFormatter +from columnist.formatters import JSONFormatter from tests.db import Model @@ -25,18 +27,19 @@ class MockReport(Report): ) -class TestCSVFormatter: - @pytest.fixture - def records(self, db): - records = ( - Model(alpha='foo'), - Model(alpha='bar'), - Model(alpha='foo'), - ) - db.add_all(records) - db.commit() - return records +@pytest.fixture +def records(db): + records = ( + Model(alpha='foo'), + Model(alpha='bar'), + Model(alpha='foo'), + ) + db.add_all(records) + db.commit() + return records + +class TestCSVFormatter: @pytest.fixture def expected(self): today = datetime.datetime.now().strftime('%Y-%m-%d') @@ -64,3 +67,37 @@ class TestCSVFormatter: in fp.readlines() ] assert output == expected + + +class TestJSONFormatter: + @pytest.fixture + def expected(self): + today = datetime.datetime.now().strftime('%Y-%m-%d') + return [ + { + 'alpha_is_foo': True, + 'Date Created': today, + }, + { + 'alpha_is_foo': False, + 'Date Created': today, + }, + { + 'alpha_is_foo': True, + 'Date Created': today, + }, + ] + + def test_to_string(self, records, expected): + report = MockReport() + + output = JSONFormatter(report).to_string() + assert json.loads(output) == expected + + def test_to_file(self, records, expected, tmpdir): + output_file = tmpdir.mkdir('test').join('output.json') + with open(output_file, 'w') as fp: + JSONFormatter(MockReport()).to_file(fp) + with open(output_file, 'r') as fp: + output = json.load(fp) + assert output == expected -- 2.45.2