Helper functions to quickly write tests in notebooks
All the helpers here wrap test(a,b,cmp): an assert cmp(a,b) that shows both values when the comparison fails, rather than a bare AssertionError. The named comparisons are test_eq, test_ne, test_eq_type (equal and same type), test_close (within eps, default 1e-5), test_is, test_shuffled (equal ignoring order), test_stdout (what f prints), and test_warns.
Simple test functions
To check that code fails as expected, use test_fail(f, contains=..., exc=...) for a callable, or expect_fail as a context manager, which also accepts regex:
with expect_fail(contains="foo"): raiseException("foobar")with expect_fail(ValueError): raiseValueError()# `msg` is included when the check fails: no exception raised, or `contains` not foundwith expect_fail(AssertionError, 'no boom'):with expect_fail(msg='no boom'): 1+1with expect_fail(AssertionError, 'wrong text'):with expect_fail(contains='foo', msg='wrong text'): raiseException('bar')# `regex` is like `contains`, but a regular expressionwith expect_fail(regex=r'fo+bar'): raiseException('foobar')with expect_fail(AssertionError, 'wrong pat'):with expect_fail(regex=r'^bar', msg='wrong pat'): raiseException('foobar')
cmp can be any callable, and fastcore’s curried operators (in_, gt, is_, and friends from fastcore.basics) make good ones: test(x, valid, in_) beats a bare assert x in valid by showing both values when it fails:
from fastcore.basics import in_
test(2, [1,2,3], in_)test('b', 'abc', in_)
all_equal
def all_equal( a, b):
Compares whether a and b are the same length and have the same contents
test_eq compares with equals, which works by content across types: generators are consumed, and lists, tuples, sets, dicts, numpy arrays, torch tensors, and DataFrames all compare their contents, including mixed cases like an array against a plain list:
Context manager that tests if an exception is raised. Deprecated: use expect_fail instead
def _tst_1(): assertFalse, "This is a test"def _tst_2(): raiseSyntaxErrorwith ExceptionExpected(): _tst_1()with ExceptionExpected(ex=AssertionError, regex="This is a test"): _tst_1()with ExceptionExpected(ex=SyntaxError): _tst_2()