Skip to content

Commit 30c232b

Browse files
author
czheo
committed
add exceptions to To.step check
1 parent 335d773 commit 30c232b

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

syntax_sugar/infix.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,15 @@ def step(self):
4848

4949
@step.setter
5050
def step(self, value):
51-
if value == 0 or not value /is_a/ int:
52-
raise TypeError('Interval must be an integer different from 0')
51+
if not value /is_a/ int:
52+
raise TypeError('Step must be int')
53+
elif value == 0:
54+
raise ValueError('Step cannot be zero')
55+
elif self.start < self.end and value < 0:
56+
raise ValueError('Increasing range with negative step')
57+
elif self.start > self.end and value > 0:
58+
raise ValueError('Decreasing range with positive step')
59+
5360
self._step = value
5461

5562
def __mul__(self, rhs):

tests/test_infix.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
1+
from pytest import raises
12
import random
23
from syntax_sugar import *
4+
from syntax_sugar.infix import To
35

46
def test_int_to_int():
7+
assert list(1 /to/ 1) == [1]
8+
assert list(2 /to/ 1) == [2, 1]
59
for i in range(100):
610
start, end = random.randint(1, 1e3), random.randint(1, 1e3)
711
end += start
@@ -11,6 +15,8 @@ def test_int_to_int():
1115
assert list(start /to/ end) == list(range(start, end - 1, -1))
1216

1317
def test_int_to_int_with_step():
18+
assert list(1 /to/ 1 /by/ 2) == [1]
19+
assert list(2 /to/ 1 /by/ 2) == [2]
1420
for i in range(100):
1521
start, end = random.randint(1, 1e3), random.randint(1, 1e3)
1622
step = random.randint(1, 10)
@@ -47,6 +53,22 @@ def test_str_to_str_with_step():
4753
assert str('v' /to/ 'd' /by/ -3) == 'vspmjgd'
4854
assert str('v' /to/ 'd' /by/ 3) == 'vspmjgd'
4955

56+
def test_bad_step():
57+
to_obj = To(1, 2)
58+
for bad_step in ["x", [], 1.5]:
59+
with raises(TypeError):
60+
to_obj.step = bad_step
61+
62+
with raises(ValueError):
63+
to_obj.step = 0
64+
65+
with raises(ValueError):
66+
to_obj.step = -1
67+
68+
to_obj = To(2, 1)
69+
with raises(ValueError):
70+
to_obj.step = 1
71+
5072
def test_take():
5173
assert 1 /to/ INF /take/ 5 == [1,2,3,4,5]
5274

0 commit comments

Comments
 (0)