Skip to content

Commit

Permalink
Ensure our histogram uses a non-zero step
Browse files Browse the repository at this point in the history
When all allocations are the same size, we were falling back to the size
of the smallest allocation as our step for generating histogram buckets.
When the smallest allocation was zero bytes, that would lead to
a division by zero and an exception.

Fix this by falling back to 1 instead of the size of the smallest
allocation. This will never lead to a zero division error, and still
puts every element in the same bucket because they're all equal
(otherwise we wouldn't have needed the fallback).

Signed-off-by: Matt Wozniski <[email protected]>
  • Loading branch information
godlygeek authored and pablogsal committed Mar 7, 2024
1 parent 9adee4a commit ef5514c
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/news/113.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix the generation of histograms when the tests performed zero-byte allocations.
2 changes: 1 addition & 1 deletion src/pytest_memray/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def histogram(
[0, 0, 0, 0, 1, 0, 0, 1, 3, 2]
"""
step = ((high - low) / bins) or low
step = ((high - low) / bins) or low or 1
dist = collections.Counter((x - low) // step for x in iterable)
return [dist[b] for b in range(bins)]

Expand Down
23 changes: 23 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from pytest_memray.utils import WriteEnabledDirectoryAction
from pytest_memray.utils import parse_memory_string
from pytest_memray.plugin import cli_hist


@pytest.mark.parametrize(
Expand Down Expand Up @@ -123,3 +124,25 @@ def test_write_enabled_dir_cannot_create(
w_dir_check(path)
finally:
tmp_path.chmod(tmp_path.stat().st_mode | write)


def test_histogram_with_zero_byte_allocations():
# GIVEN
allocations = [0, 100, 990, 1000, 50000]

# WHEN
histogram = cli_hist(allocations, bins=5)

# THEN
assert histogram == "▄ ▄ █ ▄"


def test_histogram_with_only_zero_byte_allocations():
# GIVEN
allocations = [0, 0, 0, 0]

# WHEN
histogram = cli_hist(allocations, bins=5)

# THEN
assert histogram == "█ "

0 comments on commit ef5514c

Please sign in to comment.