Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_init(self):
with self.subTest(text='init has not raised any exceptions'):
func = deal.pre(lambda x: x > 0)
with self.subTest(text='validator'):
func = deal.pre(lambda x: x > 0)(lambda x: x)
with pytest.raises(deal.PreContractError):
func(-2)
with self.subTest(text='message'):
func = deal.pre(lambda x: x > 0, message='TEST')(lambda x: x)
try:
func(-2)
except AssertionError as e:
self.assertEqual(e.args[0], 'TEST')
with self.subTest(text='exception'):
func = deal.pre(lambda x: x > 0, exception=NameError)(lambda x: x)
with pytest.raises(NameError):
func(-2)
with self.subTest(text='exception with name'):
func = deal.pre(lambda x: x > 0, exception=NameError('TEST'))(lambda x: x)
with self.subTest(text='exception/exception'):
with pytest.raises(NameError):
func(-2)
with self.subTest(text='exception/message'):
@deal.pre(scheme, message='old message')
def func(name):
return name * 2
@deal.pre(lambda name: name != 'Oleg')
def func(name):
return name * 2
@deal.pre(lambda x: x > 0 or 'new message', message='old message')
def double(x):
return x * 2
@deal.pre(lambda a, b: a > 0)
@deal.pre(lambda a, b: b > 0, message='b must be positive')
def div(a: int, b: int) -> float:
assert isinstance(a, int)
assert isinstance(b, int)
assert a > 0
assert b > 0
return a / b
def test_main(self):
func = deal.pre(lambda x: x > 0)(lambda x: x)
with self.subTest(text='good'):
self.assertEqual(func(4), 4)
with self.subTest(text='error'):
with pytest.raises(deal.PreContractError):
func(-2)
def test_contract_returns_message():
func = deal.pre(lambda x: x > 0 or 'TEST')(lambda x: x)
assert func(4) == 4
with pytest.raises(deal.PreContractError):
func(-2)
try:
func(-2)
except deal.PreContractError as e:
assert e.args[0] == 'TEST'
def test_correct_exceptions_raised_on_contract_fail():
func = deal.pre(lambda x: x > 0)(lambda x: x)
with pytest.raises(deal.PreContractError):
func(-2)
func = deal.pre(lambda x: x > 0, message='TEST')(lambda x: x)
try:
func(-2)
except AssertionError as e:
assert e.args[0] == 'TEST'
func = deal.pre(lambda x: x > 0, exception=NameError)(lambda x: x)
with pytest.raises(NameError):
func(-2)
func = deal.pre(lambda x: x > 0, exception=NameError('TEST'))(lambda x: x)
with pytest.raises(NameError):
func(-2)
try:
func(-2)
except NameError as e:
assert e.args[0] == 'TEST'
def test_debug(self):
func = deal.pre(lambda x: x > 0, debug=True)(lambda x: x * 2)
deal.switch(debug=False)
with self.subTest(text='good'):
func(-2)
deal.switch(debug=True)
with self.subTest(text='error'):
with pytest.raises(deal.PreContractError):
func(-2)
@deal.pre(lambda self, x: x > 0)
def method2(self, y):
return self.y