diff options
author | Matěj Cepl <mcepl@redhat.com> | 2011-11-29 19:50:16 +0100 |
---|---|---|
committer | Matěj Cepl <mcepl@redhat.com> | 2011-11-29 19:52:39 +0100 |
commit | ccc7c6a3b36a3c7d096b12e62e63334374dd897c (patch) | |
tree | 53374df591efa222586321d040fdac647443a67c | |
parent | 2f56bd116a0b29aef3d3475ad4d70d6935a41727 (diff) | |
download | json_diff-ccc7c6a3b36a3c7d096b12e62e63334374dd897c.tar.gz |
Make scripts pylint and PEP8 compliant.1.1.0
New version 1.1.0.
-rwxr-xr-x | json_diff.py | 72 | ||||
-rw-r--r-- | setup.py | 5 | ||||
-rw-r--r-- | test_json_diff.py | 43 | ||||
-rw-r--r-- | test_strings.py | 4 |
4 files changed, 81 insertions, 43 deletions
diff --git a/json_diff.py b/json_diff.py index 4522ceb..8322fd9 100755 --- a/json_diff.py +++ b/json_diff.py @@ -8,19 +8,20 @@ Copyright (c) 2011, Red Hat Corp. 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 @@ -30,11 +31,12 @@ import logging 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", @@ -69,6 +71,7 @@ td { %s """ + def is_scalar(value): """ Primitive version, relying on the fact that JSON cannot @@ -76,12 +79,17 @@ def is_scalar(value): """ 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> @@ -90,6 +98,7 @@ class HTMLFormatter(object): 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): @@ -102,13 +111,15 @@ class HTMLFormatter(object): 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: @@ -125,9 +136,12 @@ class HTMLFormatter(object): 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 @@ -139,7 +153,8 @@ class Comparator(object): 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) @@ -203,6 +218,7 @@ class Comparator(object): 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): @@ -228,15 +244,16 @@ class Comparator(object): 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: @@ -246,12 +263,12 @@ class Comparator(object): 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": {}, @@ -322,8 +339,8 @@ if __name__ == "__main__": 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") @@ -331,19 +348,20 @@ if __name__ == "__main__": 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()))
\ No newline at end of file + print(outs.encode(locale.getpreferredencoding())) @@ -9,9 +9,10 @@ setup( 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.""", diff --git a/test_json_diff.py b/test_json_diff.py index 21cd7af..2c97974 100644 --- a/test_json_diff.py +++ b/test_json_diff.py @@ -17,15 +17,19 @@ from test_strings import ARRAY_DIFF, ARRAY_NEW, ARRAY_OLD, \ 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), @@ -34,13 +38,16 @@ class OurTestCase(unittest.TestCase): 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({}, {}) @@ -97,7 +104,8 @@ class TestHappyPath(OurTestCase): 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"), @@ -106,16 +114,24 @@ class TestHappyPath(OurTestCase): 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, @@ -127,13 +143,16 @@ class TestadPath(OurTestCase): 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",)}) diff --git a/test_strings.py b/test_strings.py index 31ab50f..4108a15 100644 --- a/test_strings.py +++ b/test_strings.py @@ -24,7 +24,7 @@ SIMPLE_NEW = u""" } """ -SIMPLE_DIFF = u""" +SIMPLE_DIFF = u""" { "_append": { "d": "přidáno" @@ -228,4 +228,4 @@ ARRAY_DIFF = u""" } } } -"""
\ No newline at end of file +""" |