Skip to content

Commit

Permalink
Make scripts pylint and PEP8 compliant.
Browse files Browse the repository at this point in the history
New version 1.1.0.
  • Loading branch information
Matěj Cepl committed Nov 29, 2011
1 parent 2f56bd1 commit ccc7c6a
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 43 deletions.
72 changes: 45 additions & 27 deletions json_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,20 @@
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
try:
import json
Expand All @@ -30,11 +31,12 @@
from optparse import OptionParser

__author__ = "Matěj Cepl"
__version__ = "0.9.2"
__version__ = "1.1.0"

import locale

logging.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=logging.INFO)
logging.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s',
level=logging.INFO)

STYLE_MAP = {
u"_append": u"append_class",
Expand Down Expand Up @@ -69,19 +71,25 @@
%s
"""


def is_scalar(value):
"""
Primitive version, relying on the fact that JSON cannot
contain any more complicated data structures.
"""
return not isinstance(value, (list, tuple, dict))


class HTMLFormatter(object):
"""Special formatter to generate HTML page from diff dict.
"""

def __init__(self, diff_object):
self.diff = diff_object

def _generate_page(self, in_dict, title="json_diff result"):
"""A shell function to start recursive self._format_dict.
"""
out_str = out_str_template % (title, title,
self._format_dict(in_dict))
out_str += u"""</table>
Expand All @@ -90,6 +98,7 @@ def _generate_page(self, in_dict, title="json_diff result"):
return out_str

def _format_item(self, item, index, typch, level=0):
"""Function to unify formatting on the leaf node level."""
level_str = (u"<td>" + LEVEL_INDENT + u"</td>") * level

if is_scalar(item):
Expand All @@ -102,13 +111,15 @@ def _format_item(self, item, index, typch, level=0):
return out_str.strip()

def _format_array(self, diff_array, typch, level=0):
"""Recursively generate HTML for two different arrays."""
out_str = []
for index in range(len(diff_array)):
out_str.append(self._format_item(diff_array[index], index, typch, level))
out_str.append(self._format_item(diff_array[index], index, typch,
level))
return ("".join(out_str)).strip()

# doesn't have level and neither concept of it, much
def _format_dict(self, diff_dict, typch="unknown_change", level=0):
"""Recursively generate HTML for two different dicts."""
out_str = []
# For all STYLE_MAP keys which are present in diff_dict
for typechange in set(diff_dict.keys()) & INTERNAL_KEYS:
Expand All @@ -125,9 +136,12 @@ def _format_dict(self, diff_dict, typch="unknown_change", level=0):
def __unicode__(self):
return self._generate_page(self.diff)


class BadJSONError(ValueError):
"""Module should use its own exceptions."""
pass


class Comparator(object):
"""
Main workhorse, the object itself
Expand All @@ -139,7 +153,8 @@ def __init__(self, fn1=None, fn2=None, opts=None):
try:
self.obj1 = json.load(fn1)
except (TypeError, OverflowError, ValueError), exc:
raise BadJSONError("Cannot decode object from JSON.\n%s" % unicode(exc))
raise BadJSONError("Cannot decode object from JSON.\n%s" %
unicode(exc))
if fn2:
try:
self.obj2 = json.load(fn2)
Expand Down Expand Up @@ -203,6 +218,7 @@ def _filter_results(self, result):
return out_result

def _compare_elements(self, old, new):
"""Unify decision making on the leaf node level."""
res = None
# We want to go through the tree post-order
if isinstance(old, dict):
Expand All @@ -228,15 +244,16 @@ def _compare_elements(self, old, new):

return res


def _compare_scalars(self, old, new, name=None):
"""
Be careful with the result of this function. Negative answer from this function
is really None, not False, so deciding based on the return value like in
Be careful with the result of this function. Negative answer from this
function is really None, not False, so deciding based on the return
value like in
if self._compare_scalars(...):
leads to wrong answer (it should be if self._compare_scalars(...) is not None:)
leads to wrong answer (it should be
if self._compare_scalars(...) is not None:)
"""
# Explicitly excluded arguments
if old != new:
Expand All @@ -246,12 +263,12 @@ def _compare_scalars(self, old, new, name=None):

def _compare_arrays(self, old_arr, new_arr):
"""
simpler version of compare_dicts; just an internal method, becase
simpler version of compare_dicts; just an internal method, because
it could never be called from outside.
We have it guaranteed that both new_arr and old_arr are of type list.
"""
inters = min(len(old_arr), len(new_arr)) # this is the smaller length
inters = min(len(old_arr), len(new_arr)) # this is the smaller length

result = {
u"_append": {},
Expand Down Expand Up @@ -322,28 +339,29 @@ def compare_dicts(self, old_obj=None, new_obj=None):
description = "Generates diff between two JSON files."
parser = OptionParser(usage=usage)
parser.add_option("-x", "--exclude",
action="append", dest="exclude", metavar="ATTR", default=[],
help="attributes which should be ignored when comparing")
action="append", dest="exclude", metavar="ATTR", default=[],
help="attributes which should be ignored when comparing")
parser.add_option("-i", "--include",
action="append", dest="include", metavar="ATTR", default=[],
help="attributes which should be exclusively used when comparing")
parser.add_option("-a", "--ignore-append",
action="store_true", dest="ignore_append", metavar="BOOL", default=False,
help="ignore appended keys")
parser.add_option("-H", "--HTML",
action="store_true", dest="HTMLoutput", metavar="BOOL", default=False,
help="program should output to HTML report")
action="store_true", dest="HTMLoutput", metavar="BOOL", default=False,
help="program should output to HTML report")
(options, args) = parser.parse_args()

if len(args) != 2:
parser.error("Script requires two positional arguments, names for old and new JSON file.")
parser.error("Script requires two positional arguments, " + \
"names for old and new JSON file.")

diff = Comparator(open(args[0]), open(args[1]), options)
if options.HTMLoutput:
diff_res = diff.compare_dicts()
# we want to hardcode UTF-8 here, because that's what's in <meta> element
# of the generated HTML
# we want to hardcode UTF-8 here, because that's what's
# in <meta> element of the generated HTML
print(unicode(HTMLFormatter(diff_res)).encode("utf-8"))
else:
outs = json.dumps(diff.compare_dicts(), indent=4, ensure_ascii=False)
print(outs.encode(locale.getpreferredencoding()))
print(outs.encode(locale.getpreferredencoding()))
5 changes: 3 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@
author = 'Matěj Cepl',
author_email = 'mcepl@redhat.com',
url = 'https://gitorious.org/json_diff/mainline',
download_url = "http://mcepl.fedorapeople.org/scripts/json_diff-%s.tar.gz" % json_diff.__version__,
py_modules = ['json_diff', 'test_json_diff', 'test_strings'],
package_data = ['test/*'],
package_data = {
'json_diff': 'test/*'
},
long_description = """Compares two JSON files (http://json.org) and
generates a new JSON file with the result. Allows exclusion of some
keys from the comparison, or in other way to include only some keys.""",
Expand Down
43 changes: 31 additions & 12 deletions test_json_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,19 @@
NESTED_DIFF_IGNORING, \
SIMPLE_ARRAY_OLD, SIMPLE_DIFF, SIMPLE_DIFF_HTML, SIMPLE_NEW, SIMPLE_OLD


class OurTestCase(unittest.TestCase):
def _run_test(self, oldf, newf, difff, msg="", opts=None):
diffator = json_diff.Comparator(oldf, newf, opts)
diff = diffator.compare_dicts()
expected = json.load(difff)
self.assertEqual(json.dumps(diff, sort_keys=True), json.dumps(expected, sort_keys=True),
self.assertEqual(json.dumps(diff, sort_keys=True),
json.dumps(expected, sort_keys=True),
msg + "\n\nexpected = %s\n\nobserved = %s" %
(json.dumps(expected, sort_keys=True, indent=4, ensure_ascii=False),
json.dumps(diff, sort_keys=True, indent=4, ensure_ascii=False)))
(json.dumps(expected, sort_keys=True, indent=4,
ensure_ascii=False),
json.dumps(diff, sort_keys=True, indent=4,
ensure_ascii=False)))

def _run_test_strings(self, olds, news, diffs, msg="", opts=None):
self._run_test(StringIO(olds), StringIO(news), StringIO(diffs),
Expand All @@ -34,13 +38,16 @@ def _run_test_strings(self, olds, news, diffs, msg="", opts=None):
def _run_test_formatted(self, oldf, newf, difff, msg="", opts=None):
diffator = json_diff.Comparator(oldf, newf, opts)
diff = ("\n".join([line.strip() \
for line in unicode( \
json_diff.HTMLFormatter(diffator.compare_dicts())).split("\n")])).strip()
expected = ("\n".join([line.strip() for line in difff if line])).strip()
for line in unicode(\
json_diff.HTMLFormatter(diffator.compare_dicts())).\
split("\n")])).strip()
expected = ("\n".join([line.strip() for line in difff if line])).\
strip()
self.assertEqual(diff, expected, msg +
"\n\nexpected = %s\n\nobserved = %s" %
(expected, diff))


class TestBasicJSON(OurTestCase):
def test_empty(self):
diffator = json_diff.Comparator({}, {})
Expand Down Expand Up @@ -97,7 +104,8 @@ def test_realFile(self):
open("test/diff.json"), "Simply nested objects (from file) diff.")

def test_nested(self):
self._run_test_strings(NESTED_OLD, NESTED_NEW, NESTED_DIFF, "Nested objects diff.")
self._run_test_strings(NESTED_OLD, NESTED_NEW, NESTED_DIFF,
"Nested objects diff.")

def test_nested_formatted(self):
self._run_test_formatted(open("test/old.json"), open("test/new.json"),
Expand All @@ -106,16 +114,24 @@ def test_nested_formatted(self):

def test_nested_excluded(self):
self._run_test_strings(NESTED_OLD, NESTED_NEW, NESTED_DIFF_EXCL,
"Nested objects diff with exclusion.", exc=("nome",))
"Nested objects diff with exclusion.",
{'excluded_attrs': ("nome",)})

def test_nested_included(self):
self._run_test_strings(NESTED_OLD, NESTED_NEW, NESTED_DIFF_INCL,
"Nested objects diff.", inc=("nome",))
"Nested objects diff.", {'included_attrs': ("nome",)})

def test_nested_ignoring_append(self):
self._run_test_strings(NESTED_OLD, NESTED_NEW, NESTED_DIFF_IGNORING,
"Nested objects diff.", {'ignore_append': True})


class TestadPath(OurTestCase):
def test_no_JSON(self):
self.assertRaises(json_diff.BadJSONError,
json_diff.Comparator, StringIO(NO_JSON_OLD), StringIO(NO_JSON_NEW))
json_diff.Comparator, StringIO(NO_JSON_OLD),
StringIO(NO_JSON_NEW)
)

def test_bad_JSON_no_hex(self):
self.assertRaises(json_diff.BadJSONError, self._run_test_strings,
Expand All @@ -127,13 +143,16 @@ def test_bad_JSON_no_octal(self):
u'{"a": 01}', '{"a": 2}', u'{"_update": {"a": 2}}',
"Octal numbers not supported")


class TestPiglitData(OurTestCase):
# def test_piglit_results(self):
# self._run_test(open("test/old-testing-data.json"), open("test/new-testing-data.json"),
# self._run_test(open("test/old-testing-data.json"),
# open("test/new-testing-data.json"),
# open("test/diff-testing-data.json"), "Large piglit results diff.")

def test_piglit_result_only(self):
self._run_test(open("test/old-testing-data.json"), open("test/new-testing-data.json"),
self._run_test(open("test/old-testing-data.json"),
open("test/new-testing-data.json"),
open("test/diff-result-only-testing-data.json"),
"Large piglit reports diff (just resume field).",
{'included_attrs': ("result",)})
Expand Down
4 changes: 2 additions & 2 deletions test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
}
"""

SIMPLE_DIFF = u"""
SIMPLE_DIFF = u"""
{
"_append": {
"d": "přidáno"
Expand Down Expand Up @@ -228,4 +228,4 @@
}
}
}
"""
"""

0 comments on commit ccc7c6a

Please sign in to comment.