Add test case to test diffing function

This commit is contained in:
Joey Pinhas 2019-08-23 14:14:10 -04:00
parent 780f20249f
commit b28837a038
2 changed files with 79 additions and 3 deletions

View file

@ -1,10 +1,10 @@
from __future__ import print_function from __future__ import print_function
import argparse import argparse
import difflib
import io import io
import json import json
import sys import sys
import difflib
from collections import OrderedDict from collections import OrderedDict
from typing import List from typing import List
from typing import Mapping from typing import Mapping
@ -56,7 +56,7 @@ def parse_topkeys(s): # type: (str) -> List[str]
return s.split(',') 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') source_lines = ''.join(source).split('\n')
target_lines = ''.join(target).split('\n') target_lines = ''.join(target).split('\n')
d = difflib.Differ() d = difflib.Differ()
@ -132,7 +132,7 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
print('File {} is not pretty-formatted'.format(json_file)) print('File {} is not pretty-formatted'.format(json_file))
if args.show_expected: if args.show_expected:
print(get_diff(contents, pretty_contents)) print(get_diff(contents, list(pretty_contents)))
if args.autofix: if args.autofix:
_autofix(json_file, pretty_contents) _autofix(json_file, pretty_contents)

View file

@ -3,6 +3,7 @@ import shutil
import pytest import pytest
from six import PY2 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 main
from pre_commit_hooks.pretty_format_json import parse_num_to_int from pre_commit_hooks.pretty_format_json import parse_num_to_int
from testing.util import get_resource_path from testing.util import get_resource_path
@ -105,3 +106,78 @@ def test_top_sorted_get_pretty_format():
def test_badfile_main(): def test_badfile_main():
ret = main([get_resource_path('ok_yaml.yaml')]) ret = main([get_resource_path('ok_yaml.yaml')])
assert ret == 1 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