truncate.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. """Utilities for truncating assertion output.
  2. Current default behaviour is to truncate assertion explanations at
  3. terminal lines, unless running with an assertions verbosity level of at least 2 or running on CI.
  4. """
  5. from __future__ import annotations
  6. from _pytest.compat import running_on_ci
  7. from _pytest.config import Config
  8. from _pytest.nodes import Item
  9. DEFAULT_MAX_LINES = 8
  10. DEFAULT_MAX_CHARS = DEFAULT_MAX_LINES * 80
  11. USAGE_MSG = "use '-vv' to show"
  12. def truncate_if_required(explanation: list[str], item: Item) -> list[str]:
  13. """Truncate this assertion explanation if the given test item is eligible."""
  14. should_truncate, max_lines, max_chars = _get_truncation_parameters(item)
  15. if should_truncate:
  16. return _truncate_explanation(
  17. explanation,
  18. max_lines=max_lines,
  19. max_chars=max_chars,
  20. )
  21. return explanation
  22. def _get_truncation_parameters(item: Item) -> tuple[bool, int, int]:
  23. """Return the truncation parameters related to the given item, as (should truncate, max lines, max chars)."""
  24. # We do not need to truncate if one of conditions is met:
  25. # 1. Verbosity level is 2 or more;
  26. # 2. Test is being run in CI environment;
  27. # 3. Both truncation_limit_lines and truncation_limit_chars
  28. # .ini parameters are set to 0 explicitly.
  29. max_lines = item.config.getini("truncation_limit_lines")
  30. max_lines = int(max_lines if max_lines is not None else DEFAULT_MAX_LINES)
  31. max_chars = item.config.getini("truncation_limit_chars")
  32. max_chars = int(max_chars if max_chars is not None else DEFAULT_MAX_CHARS)
  33. verbose = item.config.get_verbosity(Config.VERBOSITY_ASSERTIONS)
  34. should_truncate = verbose < 2 and not running_on_ci()
  35. should_truncate = should_truncate and (max_lines > 0 or max_chars > 0)
  36. return should_truncate, max_lines, max_chars
  37. def _truncate_explanation(
  38. input_lines: list[str],
  39. max_lines: int,
  40. max_chars: int,
  41. ) -> list[str]:
  42. """Truncate given list of strings that makes up the assertion explanation.
  43. Truncates to either max_lines, or max_chars - whichever the input reaches
  44. first, taking the truncation explanation into account. The remaining lines
  45. will be replaced by a usage message.
  46. """
  47. # Check if truncation required
  48. input_char_count = len("".join(input_lines))
  49. # The length of the truncation explanation depends on the number of lines
  50. # removed but is at least 68 characters:
  51. # The real value is
  52. # 64 (for the base message:
  53. # '...\n...Full output truncated (1 line hidden), use '-vv' to show")'
  54. # )
  55. # + 1 (for plural)
  56. # + int(math.log10(len(input_lines) - max_lines)) (number of hidden line, at least 1)
  57. # + 3 for the '...' added to the truncated line
  58. # But if there's more than 100 lines it's very likely that we're going to
  59. # truncate, so we don't need the exact value using log10.
  60. tolerable_max_chars = (
  61. max_chars + 70 # 64 + 1 (for plural) + 2 (for '99') + 3 for '...'
  62. )
  63. # The truncation explanation add two lines to the output
  64. tolerable_max_lines = max_lines + 2
  65. if (
  66. len(input_lines) <= tolerable_max_lines
  67. and input_char_count <= tolerable_max_chars
  68. ):
  69. return input_lines
  70. # Truncate first to max_lines, and then truncate to max_chars if necessary
  71. if max_lines > 0:
  72. truncated_explanation = input_lines[:max_lines]
  73. else:
  74. truncated_explanation = input_lines
  75. truncated_char = True
  76. # We reevaluate the need to truncate chars following removal of some lines
  77. if len("".join(truncated_explanation)) > tolerable_max_chars and max_chars > 0:
  78. truncated_explanation = _truncate_by_char_count(
  79. truncated_explanation, max_chars
  80. )
  81. else:
  82. truncated_char = False
  83. if truncated_explanation == input_lines:
  84. # No truncation happened, so we do not need to add any explanations
  85. return truncated_explanation
  86. truncated_line_count = len(input_lines) - len(truncated_explanation)
  87. if truncated_explanation[-1]:
  88. # Add ellipsis and take into account part-truncated final line
  89. truncated_explanation[-1] = truncated_explanation[-1] + "..."
  90. if truncated_char:
  91. # It's possible that we did not remove any char from this line
  92. truncated_line_count += 1
  93. else:
  94. # Add proper ellipsis when we were able to fit a full line exactly
  95. truncated_explanation[-1] = "..."
  96. return [
  97. *truncated_explanation,
  98. "",
  99. f"...Full output truncated ({truncated_line_count} line"
  100. f"{'' if truncated_line_count == 1 else 's'} hidden), {USAGE_MSG}",
  101. ]
  102. def _truncate_by_char_count(input_lines: list[str], max_chars: int) -> list[str]:
  103. # Find point at which input length exceeds total allowed length
  104. iterated_char_count = 0
  105. for iterated_index, input_line in enumerate(input_lines):
  106. if iterated_char_count + len(input_line) > max_chars:
  107. break
  108. iterated_char_count += len(input_line)
  109. # Create truncated explanation with modified final line
  110. truncated_result = input_lines[:iterated_index]
  111. final_line = input_lines[iterated_index]
  112. if final_line:
  113. final_line_truncate_point = max_chars - iterated_char_count
  114. final_line = final_line[:final_line_truncate_point]
  115. truncated_result.append(final_line)
  116. return truncated_result