Open haraldschilly opened 1 year ago
def test_
.x=None; if x is None: raise AssertionError(("x is None!", dict(x=x)))
assert
(the assert keyword)self.assert_(expr, msg)
(or unittest.TestCase().assert_()
)unittest.TestCase()
in every Jupyter notebook input cell:
import unittest
Test = unittest.TestCase()
def test_testcase_methods_as_function_calls_that_raise_AssertionErrors():
Test.assertTrue(True)
Test.assertEqual("123", "123")
with Test.assertRaises(ZeroDivisionError):
1/0
with Test.assertRaises(ValueError):
int("0x0")
# a simple test runner that runs callables that start with `test_` (like pytest and iirc nose)
testscope = {**globals(), **locals()}
for name, testfunc in ((k,v) for k,v in testscope.items() if k.startswith('test_') and callable(v)):
objstate = dict(name=name, func=testfunc, state='running')
print(('running', objstate))
try:
objstate['output'] = testfunc()
print(('completed', objstate))
except KeyboardInterrupt:
raise
except Exception as exc:
traceback.print_tb(exc.__traceback__)
pass #
unittest
has more helpful AssertionError messages:
>>> assert "123" == "1234"
AssertionError:
>>> unittest.TestCase().assertEqual("123", "1234")
AssertionError: '123' != '1234'
assert
statements are optimized out with python -O
and python -OO
, test assertions that use the assert
keyword will not run if the -O
or -OO
flags are passed to the python process that runs the tests.
def test_()
-style functions are more succint than class Test0(unittest.TestCase)
-style functionsself.
references to refactor is more work than copy/pasting def test_()
functions, in the average casetest_
unittest
can, toounittest.TestCase
testsunittest.TestCase
's setUp
and tearDown
methods
There are various ways how to test jupyter notebooks, especially for python and R. Document the various ways how this works on CoCalc, what's available, and at the same time make sure this actually works on CoCalc :-)
%%ipytest
magic