Add test case to test diffing function
diff --git a/pre_commit_hooks/pretty_format_json.py b/pre_commit_hooks/pretty_format_json.py index 475bf1c..2e04064 100644 --- a/pre_commit_hooks/pretty_format_json.py +++ b/pre_commit_hooks/pretty_format_json.py
@@ -1,10 +1,10 @@ from __future__ import print_function import argparse +import difflib import io import json import sys -import difflib from collections import OrderedDict from typing import List from typing import Mapping @@ -56,7 +56,7 @@ return s.split(',') -def get_diff(source, target): +def get_diff(source, target): # type: (List[str], List[str]) -> str source_lines = ''.join(source).split('\n') target_lines = ''.join(target).split('\n') d = difflib.Differ() @@ -132,7 +132,7 @@ print('File {} is not pretty-formatted'.format(json_file)) if args.show_expected: - print(get_diff(contents, pretty_contents)) + print(get_diff(contents, list(pretty_contents))) if args.autofix: _autofix(json_file, pretty_contents)
diff --git a/tests/pretty_format_json_test.py b/tests/pretty_format_json_test.py index 3b7b9a2..bd84431 100644 --- a/tests/pretty_format_json_test.py +++ b/tests/pretty_format_json_test.py
@@ -3,6 +3,7 @@ import pytest from six import PY2 +from pre_commit_hooks.pretty_format_json import get_diff from pre_commit_hooks.pretty_format_json import main from pre_commit_hooks.pretty_format_json import parse_num_to_int from testing.util import get_resource_path @@ -105,3 +106,78 @@ def test_badfile_main(): ret = main([get_resource_path('ok_yaml.yaml')]) assert ret == 1 + + +def test_diffing_output(): + table_tests = [ + { + 'name': 'diff_test_1', + 'source': """ +{ + "key1": "val1", + "key2": 2, +"array_key": [1, 2, 3], + "object":{ + "bool_key": true + } +} +""", + 'target': """ +{ + "array_key": [ + 1, + 2, + 3 + ], + "key1": "val1", + "key2": 2, + "object": { + "bool_key": true + } +} +""", + 'expected': """ +{ ++ "array_key": [ ++ 1, ++ 2, ++ 3 ++ ], +- "key1": "val1", +? -- + ++ "key1": "val1", +- "key2": 2, +? -- -- + ++ "key2": 2, +- "array_key": [1, 2, 3], +- "object":{ +? ------ + ++ "object": { +? + + +- "bool_key": true +? ---- + ++ "bool_key": true +- } ++ } + } +""", + }, + { + 'name': 'diff_test_2', + 'source': '', + 'target': '', + 'expected': '', + }, + + ] + for test in table_tests: + s = list(test['source']) + t = list(test['target']) + expected = test['expected'].strip() + actual = get_diff(s, t).strip() + assert actual == expected