Skip to content
Snippets Groups Projects
Verified Commit 8faf0407 authored by Daniel Shahaf's avatar Daniel Shahaf Committed by Mattia Rizzolo
Browse files

json: detect order-only differences and print them nicely


Closes: #839538
Signed-off-by: Mattia Rizzolo's avatarMattia Rizzolo <mattia@debian.org>
parent fa076223
No related branches found
No related tags found
No related merge requests found
......@@ -17,6 +17,7 @@
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <http://www.gnu.org/licenses/>.
from collections import OrderedDict
import re
import json
......@@ -34,18 +35,26 @@ class JSONFile(File):
with open(file.path) as f:
try:
file.parsed = json.load(f)
file.parsed = json.load(f, object_pairs_hook=OrderedDict)
except json.JSONDecodeError:
return False
return True
def compare_details(self, other, source=None):
return [Difference.from_text(self.dumps(self), self.dumps(other),
self.path, other.path)]
difference = Difference.from_text(self.dumps(self), self.dumps(other),
self.path, other.path)
if difference:
return [difference]
difference = Difference.from_text(self.dumps(self, sort_keys=False),
self.dumps(other, sort_keys=False),
self.path, other.path,
comment="ordering differences only")
return [difference]
@staticmethod
def dumps(file):
def dumps(file, sort_keys=True):
if not hasattr(file, 'parsed'):
return ""
return json.dumps(file.parsed, indent=4, sort_keys=True)
return json.dumps(file.parsed, indent=4, sort_keys=sort_keys)
......@@ -25,6 +25,8 @@ from utils import data, load_fixture, assert_non_existing
json1 = load_fixture(data('test1.json'))
json2 = load_fixture(data('test2.json'))
json3a = load_fixture(data('order1a.json'))
json3b = load_fixture(data('order1b.json'))
def test_identification(json1):
assert isinstance(json1, JSONFile)
......@@ -43,3 +45,8 @@ def test_diff(differences):
def test_compare_non_existing(monkeypatch, json1):
assert_non_existing(monkeypatch, json1)
def test_ordering_differences(json3a, json3b):
diff = json3a.compare(json3b)
assert diff.details[0]._comments == ['ordering differences only']
assert diff.details[0].unified_diff == open(data('order1.diff')).read()
@@ -1,4 +1,4 @@
{
- "hello": 42,
- "world": 43
+ "world": 43,
+ "hello": 42
}
{ "hello": 42, "world": 43 }
{ "world": 43, "hello": 42 }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment