Merge pull request #486 from OddCoincidence/assert-raises

Reuse and improve ergonomics of assert_raises utility
This commit is contained in:
Windel Bouwman
2019-02-17 07:59:34 +01:00
committed by GitHub
20 changed files with 129 additions and 373 deletions

View File

@@ -1,17 +1,8 @@
from testutils import assert_raises
assert divmod(11, 3) == (3, 2)
assert divmod(8,11) == (0, 8)
assert divmod(0.873, 0.252) == (3.0, 0.11699999999999999)
try:
divmod(5, 0)
except ZeroDivisionError:
pass
else:
assert False, "Expected divmod by zero to throw ZeroDivisionError"
try:
divmod(5.0, 0.0)
except ZeroDivisionError:
pass
else:
assert False, "Expected divmod by zero to throw ZeroDivisionError"
assert_raises(ZeroDivisionError, lambda: divmod(5, 0), 'divmod by zero')
assert_raises(ZeroDivisionError, lambda: divmod(5.0, 0.0), 'divmod by zero')

View File

@@ -1,17 +1,9 @@
from testutils import assert_raises
assert format(5, "b") == "101"
try:
format(2, 3)
except TypeError:
pass
else:
assert False, "TypeError not raised when format is called with a number"
assert_raises(TypeError, lambda: format(2, 3), 'format called with number')
assert format({}) == "{}"
try:
format({}, 'b')
except TypeError:
pass
else:
assert False, "TypeError not raised when format_spec not empty for dict"
assert_raises(TypeError, lambda: format({}, 'b'), 'format_spec not empty for dict')

View File

@@ -1,9 +1,6 @@
from testutils import assert_raises
assert hex(16) == '0x10'
assert hex(-16) == '-0x10'
try:
hex({})
except TypeError:
pass
else:
assert False, "TypeError not raised when ord() is called with a dict"
assert_raises(TypeError, lambda: hex({}), 'ord() called with dict')

View File

@@ -1,3 +1,5 @@
from testutils import assert_raises
# simple values
assert max(0, 0) == 0
assert max(1, 0) == 1
@@ -14,32 +16,17 @@ assert max({
}) == "b"
assert max([1, 2], default=0) == 2
assert max([], default=0) == 0
try:
max([])
except ValueError:
pass
else:
assert False, "ValueError was not raised"
assert_raises(ValueError, lambda: max([]))
# key parameter
assert max(1, 2, -3, key=abs) == -3
assert max([1, 2, -3], key=abs) == -3
# no argument
try:
max()
except TypeError:
pass
else:
assert False, "TypeError was not raised"
assert_raises(TypeError, lambda: max())
# one non-iterable argument
try:
max(1)
except TypeError:
pass
else:
assert False, "TypeError was not raised"
assert_raises(TypeError, lambda: max(1))
# custom class
@@ -64,9 +51,4 @@ class MyNotComparable():
pass
try:
max(MyNotComparable(), MyNotComparable())
except TypeError:
pass
else:
assert False, "TypeError was not raised"
assert_raises(TypeError, lambda: max(MyNotComparable(), MyNotComparable()))

View File

@@ -1,3 +1,5 @@
from testutils import assert_raises
# simple values
assert min(0, 0) == 0
assert min(1, 0) == 0
@@ -14,32 +16,18 @@ assert min({
}) == "a"
assert min([1, 2], default=0) == 1
assert min([], default=0) == 0
try:
min([])
except ValueError:
pass
else:
assert False, "ValueError was not raised"
assert_raises(ValueError, lambda: min([]))
# key parameter
assert min(1, 2, -3, key=abs) == 1
assert min([1, 2, -3], key=abs) == 1
# no argument
try:
min()
except TypeError:
pass
else:
assert False, "TypeError was not raised"
assert_raises(TypeError, lambda: min())
# one non-iterable argument
try:
min(1)
except TypeError:
pass
else:
assert False, "TypeError was not raised"
assert_raises(TypeError, lambda: min(1))
# custom class
@@ -64,9 +52,4 @@ class MyNotComparable():
pass
try:
min(MyNotComparable(), MyNotComparable())
except TypeError:
pass
else:
assert False, "TypeError was not raised"
assert_raises(TypeError, lambda: min(MyNotComparable(), MyNotComparable()))

View File

@@ -1,8 +1,6 @@
from testutils import assert_raises
fd = open('README.md')
assert 'RustPython' in fd.read()
try:
open('DoesNotExist')
assert False
except FileNotFoundError:
pass
assert_raises(FileNotFoundError, lambda: open('DoesNotExist'))

View File

@@ -1,23 +1,9 @@
from testutils import assert_raises
assert ord("a") == 97
assert ord("é") == 233
assert ord("🤡") == 129313
try:
ord()
except TypeError:
pass
else:
assert False, "TypeError not raised when ord() is called with no argument"
try:
ord("")
except TypeError:
pass
else:
assert False, "TypeError not raised when ord() is called with an empty string"
try:
ord("ab")
except TypeError:
pass
else:
assert False, "TypeError not raised when ord() is called with more than one character"
assert_raises(TypeError, lambda: ord(), "ord() is called with no argument")
assert_raises(TypeError, lambda: ord(""), "ord() is called with an empty string")
assert_raises(TypeError, lambda: ord("ab"), "ord() is called with more than one character")

View File

@@ -1,20 +1,4 @@
def assert_raises(expr, exc_type):
"""
Helper function to assert `expr` raises an exception of type `exc_type`
Args:
expr: Callable
exec_type: Exception
Returns:
None
Raises:
Assertion error on failure
"""
try:
expr(None)
except exc_type:
assert True
else:
assert False
from testutils import assert_raises
assert range(2**63+1)[2**63] == 9223372036854775808
@@ -29,15 +13,10 @@ assert range(4, 10).index(6) == 2
assert range(4, 10, 2).index(6) == 1
assert range(10, 4, -2).index(8) == 1
# index raises value error on out of bounds
assert_raises(lambda _: range(10).index(-1), ValueError)
assert_raises(lambda _: range(10).index(10), ValueError)
# index raises value error if out of step
assert_raises(lambda _: range(4, 10, 2).index(5), ValueError)
# index raises value error if needle is not an int
assert_raises(lambda _: range(10).index('foo'), ValueError)
assert_raises(ValueError, lambda: range(10).index(-1), 'out of bounds')
assert_raises(ValueError, lambda: range(10).index(10), 'out of bounds')
assert_raises(ValueError, lambda: range(4, 10, 2).index(5), 'out of step')
assert_raises(ValueError, lambda: range(10).index('foo'), 'not an int')
# count tests
assert range(10).count(2) == 1

View File

@@ -1,3 +1,4 @@
from testutils import assert_raises
a = []
assert a[:] == []
@@ -18,12 +19,7 @@ assert b[-10:1] == [1]
assert b[0:0] == []
assert b[1:0] == []
try:
_ = b[::0]
except ValueError:
pass
else:
assert False, "Zero step slice should raise ValueError"
assert_raises(ValueError, lambda: b[::0], 'zero step slice')
assert b[::-1] == [2, 1]
assert b[1::-1] == [2, 1]

View File

@@ -1,55 +1,11 @@
try:
5 / 0
except ZeroDivisionError:
pass
else:
assert False, 'Expected ZeroDivisionError'
from testutils import assert_raises
try:
5 / -0.0
except ZeroDivisionError:
pass
else:
assert False, 'Expected ZeroDivisionError'
assert_raises(ZeroDivisionError, lambda: 5 / 0)
assert_raises(ZeroDivisionError, lambda: 5 / -0.0)
assert_raises(ZeroDivisionError, lambda: 5 / (2-2))
assert_raises(ZeroDivisionError, lambda: 5 % 0)
assert_raises(ZeroDivisionError, lambda: 5 // 0)
assert_raises(ZeroDivisionError, lambda: 5.3 // (-0.0))
assert_raises(ZeroDivisionError, lambda: divmod(5, 0))
try:
5 / (2-2)
except ZeroDivisionError:
pass
else:
assert False, 'Expected ZeroDivisionError'
try:
5 % 0
except ZeroDivisionError:
pass
else:
assert False, 'Expected ZeroDivisionError'
try:
5 // 0
except ZeroDivisionError:
pass
else:
assert False, 'Expected ZeroDivisionError'
try:
5.3 // (-0.0)
except ZeroDivisionError:
pass
else:
assert False, 'Expected ZeroDivisionError'
try:
divmod(5, 0)
except ZeroDivisionError:
pass
else:
assert False, 'Expected ZeroDivisionError'
try:
raise ZeroDivisionError('Is an ArithmeticError subclass?')
except ArithmeticError:
pass
else:
assert False, 'Expected ZeroDivisionError'
assert issubclass(ZeroDivisionError, ArithmeticError)

View File

@@ -1,3 +1,5 @@
from testutils import assert_raises
# 2.456984346552728
res = 10**500 / (4 * 10**499 + 7 * 10**497 + 3 * 10**494)
assert 2.456984 <= res <= 2.456985
@@ -8,20 +10,10 @@ assert 95.238095 <= res <= 95.238096
assert 10**500 / (2*10**(500-308)) == 5e307
assert 10**500 / (10**(500-308)) == 1e308
try:
10**500 / (10**(500-309))
except OverflowError:
pass
else:
assert False, 'Expected overflow on too big result'
assert_raises(OverflowError, lambda: 10**500 / (10**(500-309)), 'too big result')
# a bit more than f64::MAX = 1.7976931348623157e+308_f64
assert (2 * 10**308) / 2 == 1e308
# when dividing too big int by a float, the operation should fail
try:
(2 * 10**308) / 2.0
except OverflowError:
pass
else:
assert False, 'Expected overflow on division of a big int by a float'
assert_raises(OverflowError, lambda: (2 * 10**308) / 2.0, 'division of big int by float')

View File

@@ -1,22 +1,6 @@
import math
def assert_raises(expr, exc_type):
"""
Helper function to assert `expr` raises an exception of type `exc_type`
Args:
expr: Callable
exec_type: Exception
Returns:
None
Raises:
Assertion error on failure
"""
try:
expr(None)
except exc_type:
assert True
else:
assert False
from testutils import assert_raises
1 + 1.1
@@ -79,8 +63,8 @@ assert float('2.99e-23') == 2.99e-23
assert float(b'3.14') == 3.14
assert float(b'2.99e-23') == 2.99e-23
assert_raises(lambda _: float('foo'), ValueError)
assert_raises(lambda _: float(2**10000), OverflowError)
assert_raises(ValueError, lambda: float('foo'))
assert_raises(OverflowError, lambda: float(2**10000))
# check that magic methods are implemented for ints and floats

View File

@@ -1,21 +1,12 @@
from testutils import assert_raises
def no_args():
pass
no_args()
try:
no_args('one_arg')
except TypeError:
pass
else:
assert False, 'no TypeError raised: 1 arg to no_args'
try:
no_args(kw='should fail')
except TypeError:
pass
else:
assert False, 'no TypeError raised: kwarg to no_args'
assert_raises(TypeError, lambda: no_args('one_arg'), '1 arg to no_args')
assert_raises(TypeError, lambda: no_args(kw='should fail'), 'kwarg to no_args')
def one_arg(arg):
@@ -24,40 +15,20 @@ def one_arg(arg):
one_arg('one_arg')
assert "arg" == one_arg(arg="arg")
try:
one_arg()
except TypeError:
pass
else:
assert False, 'no TypeError raised: no args to one_arg'
assert_raises(TypeError, lambda: one_arg(), 'no args to one_arg')
assert_raises(TypeError,
lambda: one_arg(wrong_arg='wont work'),
'incorrect kwarg to one_arg')
assert_raises(TypeError,
lambda: one_arg('one_arg', 'two_arg'),
'two args to one_arg')
assert_raises(TypeError,
lambda: one_arg('one_arg', extra_arg='wont work'),
'no TypeError raised: extra kwarg to one_arg')
try:
one_arg(wrong_arg='wont work')
except TypeError:
pass
else:
assert False, 'no TypeError raised: incorrect kwarg to one_arg'
try:
one_arg('one_arg', 'two_arg')
except TypeError:
pass
else:
assert False, 'no TypeError raised: two args to one_arg'
try:
one_arg('one_arg', extra_arg='wont work')
except TypeError:
pass
else:
assert False, 'no TypeError raised: extra kwarg to one_arg'
try:
one_arg('one_arg', arg='duplicate')
except TypeError:
pass
else:
assert False, 'no TypeError raised: same pos and kwarg to one_arg'
assert_raises(TypeError,
lambda: one_arg('one_arg', arg='duplicate'),
'same pos and kwarg to one_arg')
def one_default_arg(arg="default"):
@@ -67,12 +38,9 @@ assert 'default' == one_default_arg()
assert 'arg' == one_default_arg('arg')
assert 'kwarg' == one_default_arg(arg='kwarg')
try:
one_default_arg('one_arg', 'two_arg')
except TypeError:
pass
else:
assert False, 'no TypeError raised: two args to one_default_arg'
assert_raises(TypeError,
lambda: one_default_arg('one_arg', 'two_arg'),
'two args to one_default_arg')
def one_normal_one_default_arg(pos, arg="default"):
@@ -81,19 +49,13 @@ def one_normal_one_default_arg(pos, arg="default"):
assert ('arg', 'default') == one_normal_one_default_arg('arg')
assert ('arg', 'arg2') == one_normal_one_default_arg('arg', 'arg2')
try:
one_normal_one_default_arg()
except TypeError:
pass
else:
assert False, 'no TypeError raised: no args to one_normal_one_default_arg'
assert_raises(TypeError,
lambda: one_normal_one_default_arg(),
'no args to one_normal_one_default_arg')
try:
one_normal_one_default_arg('one', 'two', 'three')
except TypeError:
pass
else:
assert False, 'no TypeError raised: three args to one_normal_one_default_arg'
assert_raises(TypeError,
lambda: one_normal_one_default_arg('one', 'two', 'three'),
'three args to one_normal_one_default_arg')
def two_pos(a, b):

View File

@@ -1,3 +1,5 @@
from testutils import assert_raises
x = [1, 2, 3]
assert x[0] == 1
assert x[1] == 2
@@ -16,12 +18,7 @@ assert x * 2 == [1, 2, 3, 1, 2, 3], "list __mul__ by 2 failed"
# index()
assert ['a', 'b', 'c'].index('b') == 1
assert [5, 6, 7].index(7) == 2
try:
['a', 'b', 'c'].index('z')
except ValueError:
pass
else:
assert False, "ValueError was not raised"
assert_raises(ValueError, lambda: ['a', 'b', 'c'].index('z'))
x = [[1,0,-3], 'a', 1]
y = [[3,2,1], 'z', 2]
@@ -33,12 +30,7 @@ assert x > y, "list __gt__ failed"
assert [1,2,'a'].pop() == 'a', "list pop failed"
try:
[].pop()
except IndexError:
pass
else:
assert False, "IndexError was not raised"
assert_raises(IndexError, lambda: [].pop())
recursive = []
recursive.append(recursive)
@@ -61,12 +53,7 @@ x = ['a', 'b', 'c']
x.insert(-100, 'z')
assert x == ['z', 'a', 'b', 'c']
try:
x.insert(100000000000000000000, 'z')
except OverflowError:
pass
else:
assert False, "OverflowError was not raised"
assert_raises(OverflowError, lambda: x.insert(100000000000000000000, 'z'))
x = [[], 2, {}]
y = x.copy()
@@ -82,9 +69,4 @@ a.remove(1)
assert len(a) == 2
assert not 1 in a
try:
a.remove(10)
except ValueError:
pass
else:
assert False, "Remove not exist element should raise ValueError"
assert_raises(ValueError, lambda: a.remove(10), 'Remove not exist element')

View File

@@ -1,3 +1,5 @@
from testutils import assert_raises
# test lists
assert 3 in [1, 2, 3]
assert 3 not in [1, 2]
@@ -19,12 +21,7 @@ assert b"5" <= b"5"
assert b"4" > b"2"
assert not b"1" >= b"2"
assert b"10" >= b"10"
try:
bytes() > 2
except TypeError:
pass
else:
assert False, "TypeError not raised"
assert_raises(TypeError, lambda: bytes() > 2)
# test tuple
assert 1 in (1, 2)
@@ -53,12 +50,7 @@ class MyNotContainingClass():
pass
try:
1 in MyNotContainingClass()
except TypeError:
pass
else:
assert False, "TypeError not raised"
assert_raises(TypeError, lambda: 1 in MyNotContainingClass())
class MyContainingClass():

View File

@@ -1,18 +1,9 @@
from testutils import assert_raises
print(2 + 3)
try:
print('test', end=4)
except TypeError:
pass
else:
assert False, 'Expected TypeError on wrong type passed to end'
try:
print('test', sep=['a'])
except TypeError:
pass
else:
assert False, 'Expected TypeError on wrong type passed to sep'
assert_raises(TypeError, lambda: print('test', end=4), 'wrong type passed to end')
assert_raises(TypeError, lambda: print('test', sep=['a']), 'wrong type passed to sep')
try:
print('test', end=None, sep=None, flush=None)

View File

@@ -1,3 +1,5 @@
from testutils import assert_raises
assert set([1,2]) == set([1,2])
assert not set([1,2,3]) == set([1,2])
@@ -69,19 +71,8 @@ assert set([1,2,3]).symmetric_difference(set([5,6])) == set([1,2,3,5,6])
assert set([1,2,3]) ^ set([4,5]) == set([1,2,3,4,5])
assert set([1,2,3]) ^ set([1,2,3,4,5]) == set([4,5])
try:
set([[]])
except TypeError:
pass
else:
assert False, "TypeError was not raised"
try:
set().add([])
except TypeError:
pass
else:
assert False, "TypeError was not raised"
assert_raises(TypeError, lambda: set([[]]))
assert_raises(TypeError, lambda: set().add([]))
a = set([1, 2, 3])
assert a.discard(1) is None

View File

@@ -1,13 +1,11 @@
import os
from testutils import assert_raises
assert os.open('README.md', 0) > 0
try:
os.open('DOES_NOT_EXIST', 0)
assert False
except FileNotFoundError:
pass
assert_raises(FileNotFoundError, lambda: os.open('DOES_NOT_EXIST', 0))
assert os.O_RDONLY == 0

View File

@@ -1,20 +1,4 @@
def assert_raises(expr, exc_type):
"""
Helper function to assert `expr` raises an exception of type `exc_type`
Args:
expr: Callable
exec_type: Exception
Returns:
None
Raises:
Assertion error on failure
"""
try:
expr(None)
except exc_type:
assert True
else:
assert False
from testutils import assert_raises
#
# Tests
@@ -23,15 +7,15 @@ assert 8 >> 3 == 1
assert 8 << 3 == 64
# Left shift raises type error
assert_raises(lambda _: 1 << 0.1, TypeError)
assert_raises(lambda _: 1 << "abc", TypeError)
assert_raises(TypeError, lambda: 1 << 0.1)
assert_raises(TypeError, lambda: 1 << "abc")
# Right shift raises type error
assert_raises(lambda _: 1 >> 0.1, TypeError)
assert_raises(lambda _: 1 >> "abc", TypeError)
assert_raises(TypeError, lambda: 1 >> 0.1)
assert_raises(TypeError, lambda: 1 >> "abc")
# Left shift raises value error on negative
assert_raises(lambda _: 1 << -1, ValueError)
assert_raises(ValueError, lambda: 1 << -1)
# Right shift raises value error on negative
assert_raises(lambda _: 1 >> -1, ValueError)
assert_raises(ValueError, lambda: 1 >> -1)

View File

@@ -0,0 +1,20 @@
def assert_raises(exc_type, expr, msg=None):
"""
Helper function to assert `expr` raises an exception of type `exc_type`.
Args:
expr: Callable
exec_type: Exception
Returns:
None
Raises:
Assertion error on failure
"""
try:
expr()
except exc_type:
pass
else:
failmsg = f'{exc_type.__name__} was not raised'
if msg is not None:
failmsg += f': {msg}'
assert False, failmsg