From ad1de5d3dad066d00da1310802ba83580a87fe13 Mon Sep 17 00:00:00 2001 From: Aaron Loo Date: Thu, 18 Oct 2018 16:42:57 -0700 Subject: [PATCH] ordered hashes, for nicer diffs --- detect_secrets/core/baseline.py | 6 ++++++ tests/core/baseline_test.py | 32 ++++++++++++++++++++++++++++++++ tests/main_test.py | 7 +++---- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/detect_secrets/core/baseline.py b/detect_secrets/core/baseline.py index 1f16d048b..964e7fcd4 100644 --- a/detect_secrets/core/baseline.py +++ b/detect_secrets/core/baseline.py @@ -235,6 +235,12 @@ def format_baseline_for_output(baseline): :type baseline: dict :rtype: str """ + for filename, secret_list in baseline['results'].items(): + baseline['results'][filename] = sorted( + secret_list, + key=lambda x: (x['line_number'], x['hashed_secret'],), + ) + return json.dumps( baseline, indent=2, diff --git a/tests/core/baseline_test.py b/tests/core/baseline_test.py index 66f428fbe..6111bd012 100644 --- a/tests/core/baseline_test.py +++ b/tests/core/baseline_test.py @@ -1,11 +1,13 @@ from __future__ import absolute_import +import json import random import mock import pytest from detect_secrets.core import baseline +from detect_secrets.core.baseline import format_baseline_for_output from detect_secrets.core.baseline import get_secrets_not_in_baseline from detect_secrets.core.baseline import merge_baseline from detect_secrets.core.baseline import merge_results @@ -512,3 +514,33 @@ def get_secret(): 'line_number': random_number, 'type': 'Test Type', } + + +class TestFormatBaselineForOutput(object): + + def test_sorts_by_line_number_then_hash(self): + output_string = format_baseline_for_output({ + 'results': { + 'filename': [ + { + 'hashed_secret': 'a', + 'line_number': 3, + }, + { + 'hashed_secret': 'z', + 'line_number': 2, + }, + { + 'hashed_secret': 'f', + 'line_number': 3, + }, + ], + }, + }) + + ordered_hashes = list(map( + lambda x: x['hashed_secret'], + json.loads(output_string)['results']['filename'], + )) + + assert ordered_hashes == ['z', 'a', 'f'] diff --git a/tests/main_test.py b/tests/main_test.py index 63ffe9870..d99e394a2 100644 --- a/tests/main_test.py +++ b/tests/main_test.py @@ -35,10 +35,9 @@ def mock_merge_baseline(): with mock.patch( 'detect_secrets.main.baseline.merge_baseline', ) as m: - # This return value doesn't matter, because we're not testing - # for it. It just needs to be a dictionary, so it can be properly - # JSON dumped. - m.return_value = {} + # This return value needs to have the `results` key, so that it can + # formatted appropriately for output. + m.return_value = {'results': {}} yield m