Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add page about "How to test notebooks" #40

Open
haraldschilly opened this issue Jun 12, 2023 · 1 comment
Open

add page about "How to test notebooks" #40

haraldschilly opened this issue Jun 12, 2023 · 1 comment
Labels
enhancement New feature or request

Comments

@haraldschilly
Copy link
Contributor

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 :-)

@haraldschilly haraldschilly added the enhancement New feature or request label Jun 12, 2023
@westurner
Copy link

westurner commented Jun 19, 2023

  • https://github.com/chmp/ipytest is one way to run pytest within jupyter notebooks.
  • pytest functions conventionally start with def test_.
  • There are many ways to make assertions of types and values in pytest test functions:
    • 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_())
  • It's possible to call unittest assertion functions without a 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 #

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants