Skip to content

Commit

Permalink
Properly handle out of bounds percentiles
Browse files Browse the repository at this point in the history
  • Loading branch information
dylanjw committed Aug 1, 2018
1 parent 9ec88d8 commit c138ded
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
14 changes: 11 additions & 3 deletions tests/core/utilities/test_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,21 @@ def test_percentiles_out_of_one_hundred(p, expected):
assert percentile(values, p) == expected


def test_percentiles_with_single_values():
def test_percentiles_with_no_values():
with pytest.raises(InsufficientData):
percentile([0], 1)
percentile([], 1)


def test_percentiles_with_out_of_bounds_fractions():
assert 1 == percentile([1, 2, 3, 4], percentile=10)
assert 1 == percentile([1, 2, 3, 4], percentile=15)
assert 1 == percentile([1, 2, 3, 4], percentile=20)
assert 1 == percentile([1, 2, 3, 4], percentile=25)
assert 1 > percentile([1, 2, 3, 4], percentile=30)


@given(
values=st.lists(elements=st.integers(), min_size=3, max_size=200),
values=st.lists(elements=st.integers(), min_size=1, max_size=200),
p=st.integers(max_value=100, min_value=0))
def test_fuzz_test_percentiles(values, p):
if not values:
Expand Down
6 changes: 4 additions & 2 deletions web3/utils/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
def percentile(values=None, percentile=None):
"""Calculates a simplified weighted average percentile
"""
if values in [None, tuple(), []] or len(values) <= 6:
raise InsufficientData("Expected a sequence of at least 6 integers, got {0}".format(values))
if values in [None, tuple(), []] or len(values) < 1:
raise InsufficientData("Expected a sequence of at least 1 integers, got {0}".format(values))
if percentile is None:
raise ValueError("Expected a percentile choice, got {0}".format(percentile))

Expand All @@ -16,6 +16,8 @@ def percentile(values=None, percentile=None):
rank = len(values) * percentile / 100
if rank > 0:
index = rank - 1
if index < 0:
return sorted_values[0]
else:
index = rank

Expand Down

0 comments on commit c138ded

Please sign in to comment.