[PYTHON] Unit test Databricks Notebook

Introduction

Unit test the following Notebook

MyNotebook


def hoge(i):
  return 'hoge'*i

def fuga(i):
  return 'fuga'*i

Creating a test notebook

Create a test NotebookMyNotebookTest in the same folder as NotebookMyNotebook

MyNotebookTest


# Cmd1 
%run "./MyNotebook"

# Cmd2
import unittest

class MyNotebookTests(unittest.TestCase):
  
  def test_hoge(self):
    self.assertEqual(hoge(3), 'hogehogehoge')
    self.assertNotEqual(hoge(2), 'hoge')

  def test_fuga(self):
    self.assertEqual(fuga(3), 'fugafugafuga')
    self.assertNotEqual(fuga(2), 'fuga')

suite = unittest.TestLoader().loadTestsFromTestCase(MyNotebookTests)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)

As a point to create

--Run the % run command first with Cmd 1 to run the notebook under test.

%run "./MyUnittest"

--Write test cases using unittest which is a python test framework in Cmd 2 or later.

Execution result

Confirm that the test is OK as follows

test_fuga (__main__.MyNotebookTests) ... ok
test_hoge (__main__.MyNotebookTests) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
Out[50]: <unittest.runner.TextTestResult run=2 errors=0 failures=0>

Recommended Posts

Unit test Databricks Notebook
numpy unit test
python unit test template
Flask unit test environment (test_client)
Unit test flask with pytest
Databricks
test
Unit test log output with python
Use Jupyter Notebook as a unit test and manual creation tool
Django Tutorial (Blog App Creation) ④ --Unit Test