From af76e55aef698a6e40e4c13c2ac8cd7924d9d4ab Mon Sep 17 00:00:00 2001 From: Alex Hall Date: Fri, 10 May 2019 18:46:05 +0200 Subject: [PATCH] Truncate long variables in the middle --- pysnooper/utils.py | 10 ++++++++-- tests/test_pysnooper.py | 18 ++++++++++++++++-- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/pysnooper/utils.py b/pysnooper/utils.py index 576f655..458d602 100644 --- a/pysnooper/utils.py +++ b/pysnooper/utils.py @@ -54,11 +54,17 @@ def get_shortish_repr(item): except Exception: r = 'REPR FAILED' r = r.replace('\r', '').replace('\n', '') - if len(r) > MAX_VARIABLE_LENGTH: - r = '{truncated_r}...'.format(truncated_r=r[:MAX_VARIABLE_LENGTH]) + r = truncate(r, MAX_VARIABLE_LENGTH) return r +def truncate(string, max_length): + if len(string) > max_length: + left = (max_length - 3) // 2 + right = max_length - 3 - left + string = u'{}...{}'.format(string[:left], string[-right:]) + return string + def ensure_tuple(x): if isinstance(x, six.string_types): diff --git a/tests/test_pysnooper.py b/tests/test_pysnooper.py index 4142708..c1112fc 100644 --- a/tests/test_pysnooper.py +++ b/tests/test_pysnooper.py @@ -6,6 +6,7 @@ import textwrap import threading import types +from pysnooper.utils import truncate from python_toolbox import sys_tools, temp_file_tools import pytest @@ -384,15 +385,16 @@ def test_long_variable(): result = my_function() assert result == list(range(1000)) output = output_capturer.string_io.getvalue() + regex = r'^\[0, 1, 2, .*\.\.\..*, 997, 998, 999\]$' assert_output( output, ( CallEntry('def my_function():'), LineEntry('foo = list(range(1000))'), - VariableEntry('foo', value_regex=r'''^\[0, 1, 2, .*\.\.\.$'''), + VariableEntry('foo', value_regex=regex), LineEntry(), ReturnEntry(), - ReturnValueEntry(value_regex=r'''^\[0, 1, 2, .*\.\.\.$''') + ReturnValueEntry(value_regex=regex) ) ) @@ -918,3 +920,15 @@ def test_with_block_depth(): ReturnValueEntry('20'), ) ) + + +def test_truncate(): + max_length = 20 + for i in range(max_length * 2): + string = i * 'a' + truncated = truncate(string, max_length) + if len(string) <= max_length: + assert string == truncated + else: + assert truncated == 'aaaaaaaa...aaaaaaaaa' + assert len(truncated) == max_length