CertSafari
    Databricks Certified Machine Learning Professional· Lessons

    Domain 2 · Lesson 6/11

    Unit testing notebook functions in Databricks

    Validation Testing

    12 min read
    8.8% of exam
    5 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Write notebook functions that return one predictable, single-typed result so they can be unit tested
    • Run pytest or unittest assertions against notebook functions and have a failure stop the cell
    • Choose between keeping functions and tests in one notebook, in separate notebooks, or in workspace files, and give the Databricks recommendation for each language

    Key concept

    Unit test — A unit test calls one self-contained piece of code, usually a function, with known inputs and asserts that it returns the expected output. Because it checks so little, it runs fast enough to run on every change, so mistakes in notebook code surface before they reach a pipeline.

    1.Writing functions that can be unit tested

    A unit test only works if the function under test has one right answer for a given input. Databricks supports unit testing in Python, R, Scala and SQL notebooks, using pytest, testthat, ScalaTest and SQL user-defined functions respectively. In every language the test does the same thing: it calls a function with inputs whose correct result you already know, and asserts on what comes back.

    The function has to be designed for that. It should return a single predictable outcome of a single data type. A function that checks whether a column exists should return True or False, not False when the column is missing and the column itself when it is present. A function that counts rows should return a non-negative whole number, never a count in one case and False in another. When the return type changes from call to call, every test has to branch on the type first, and a bug that returns the wrong kind of value can slip through.

    A function with one boolean result per call, from a myfunctions.py file kept in a Git folderpython
    # Does the specified column exist in the given DataFrame?
    def columnExists(dataFrame, columnName):
      if columnName in dataFrame.columns:
        return True
      else:
        return False

    Unit tests should run against data you control, not production tables. This matters most for functions that add, remove or change data, because a test that writes to a production table can damage it. The usual approach is to build a small fake DataFrame that resembles the production data closely, with an explicit schema, and pass that to the function. For an imputation function that fills missing values with the column mean, for example, the test builds a few rows with known gaps, so the mean is known in advance and can be asserted exactly.

    Databricks recommends writing and running unit tests in a notebook rather than in the web terminal. The terminal can run some commands, but it has more limitations, including no support for Spark. Most data functions take a Spark DataFrame, so that limitation matters.

    Checkpoint 1 of 6· Fill the gap

    This helper from myfunctions.py is meant to be easy to unit test. Which value belongs in the blank so that every call returns one predictable result of a single data type?

    # Does the specified column exist in the given DataFrame?
    def columnExists(dataFrame, columnName):
      if columnName in dataFrame.columns:
        return True
      else:
        return  ? 

    Sources1

    2.Running assertions from a notebook

    The simplest test sits right next to the code it checks. Libraries such as Python's built-in unittest run inside a notebook cell. The last line is what turns the test into a gate. unittest.main(..., exit=False) reports results without stopping the notebook, so the assert on wasSuccessful() is what makes the cell fail when any test fails.

    A function and its unittest case run in the same notebook; the final assert fails the cell if any test failspython
    def reverse(s):
        return s[::-1]
    
    import unittest
    
    class TestHelpers(unittest.TestCase):
        def test_reverse(self):
            self.assertEqual(reverse('abc'), 'cba')
    
    r = unittest.main(argv=[''], verbosity=2, exit=False)
    assert r.result.wasSuccessful(), 'Test failed; see logs above'

    pytest follows the same pattern. A notebook installs pytest with %pip install pytest, calls pytest.main(...) on the test files, and asserts that the return code is 0. That assert matters as much as the unittest one: without it the notebook, or the job running it, reports success even when tests failed. Test failures appear in the cell's output area, and they still show up if you hide the cell's results.

    When tests live in their own Python files, the file and function names decide what runs. Databricks uses pytest's naming conventions to discover tests, both in pytest runs and in the workspace's Tests pane. A file named transform_checks.py, or a function named check_null_input, is never collected. pytest does not report such a test as failed, because it never runs it.

    Names pytest and the Databricks Tests pane recognise as tests
    What is discoveredNaming rule
    Test filestest_*.py or *_test.py
    Test functions outside a classtest-prefixed functions or methods
    Tests inside a classtest-prefixed methods in a Test-prefixed class without an __init__ method
    Static and class methodsMethods decorated with @staticmethod or @classmethod inside Test-prefixed classes

    Opening a valid test file in the workspace shows a Tests icon in the left sidebar. From there you can run every test, rerun only the failed tests, or run one test from an inline glyph. A failed test also places a failure marker on the line that raised the error. To keep test code in the same notebook without running it on every production run, a widget can switch modes: dbutils.widgets.dropdown("Mode", "Test", ["Test", "Normal"]) runs the asserts in Test mode and the real logic in Normal mode. Tests can also run on a schedule as a notebook job that emails a chosen address.

    Checkpoint 2 of 6· Check yourself

    A Git folder holds utils_test.py, which defines two top-level functions: test_pivot_and_clean and check_null_input. Both contain assert statements. What happens when a notebook runs pytest.main on this file?

    Sources234

    3.Where functions and their tests should live

    Notebook teams usually organise functions and tests in one of three ways, and each trades easy upkeep against reuse. The question is how many places can call the function. A function defined in a notebook cell exists only for that notebook and anything that %runs it. A function in a Python module can be imported by notebooks, test files and jobs alike.

    Three ways to organise functions and unit tests
    ApproachBenefitsChallenges
    Functions and tests in files outside notebooks (Python modules in a Git folder or workspace files)Callable from notebooks and from outside them; test frameworks are built to run tests outside notebooks; workspace tools discover, run and track Python testsNot supported for Scala notebooks; more files to track and maintain
    Functions in one notebook, tests in a separate notebookFunctions are easier to reuse across notebooksMore notebooks to maintain; functions cannot be used outside notebooks and are harder to test outside them
    Functions and tests in the same notebookOne notebook to track and maintainFunctions are harder to reuse across notebooks, cannot be used outside notebooks, and are harder to test outside them

    A single notebook is easy to keep track of, and that is its only advantage. Its helper functions are tied to that notebook, so another notebook that needs compute_feature_ratio has to copy it, and the copies drift apart. A function that may be needed elsewhere, by a scheduled job, a second notebook or a pytest suite, should go into a Python module such as myfunctions.py, and every caller should import it. Pulling shared code out of a notebook into a module like transforms.py is the standard refactor, because it makes the functions both reusable and easier to test.

    Separate notebooks are a middle option. The test notebook starts with %run ./shared-code-notebook, which runs the functions notebook and brings its definitions into scope, and later cells run the tests. Functions can then be reused by any notebook that runs them, but they still exist only inside notebooks. A plain pytest file cannot import a notebook as a module.

    The recommendation depends on the language. Python and R notebooks should keep functions and tests outside notebooks, in files. Scala notebooks cannot use that approach, so they keep functions in one notebook and tests in another. SQL notebooks store functions as SQL user-defined functions in a schema and call both the UDFs and their tests from SQL notebooks. One example is a SELECT if(...) that prints PASS or FAIL.

    Checkpoint 3 of 6· Match them up

    A lead is choosing how the team should organise helper functions and their unit tests. Match each approach to the trade-off it brings.

    Tap a term, then the definition that fits it.

    Checkpoint 4 of 6· Exam question

    A data scientist has written a compute_feature_ratio function directly inside a Databricks Python notebook cell. The team wants to add a pytest suite that asserts the function returns the expected value for a set of known inputs, and they also want other notebooks and a scheduled job to be able to call the same function without duplicating the code. What should they do first?

    Checkpoint 5 of 6· Exam question

    An ML engineering team is deciding how to organize functions and their unit tests for a Scala-based feature transformation pipeline running on Databricks. Databricks documentation notes that Scala notebooks cannot use the same pattern recommended for Python and R. Which organizing approach should the team use instead?

    Checkpoint 6 of 6· Exam question

    A team keeps every helper function and its pytest cases inside a single Databricks notebook so that one file tracks both the logic and its tests together. Which consequence follows directly from this organizing choice?

    Sources125

    Sources

    (5)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “To get the best unit testing results, a function should return a single predictable outcome and be of a single data type.”
      ↩︎ Writing functions that can be unit tested
      “you should run unit tests against non-production data”
      ↩︎ Writing functions that can be unit tested
      “Databricks recommends writing and running your unit tests in a notebook.”
      ↩︎ Writing functions that can be unit tested
      “For Python and R notebooks, Databricks recommends storing functions and their unit tests outside of notebooks.”
      ↩︎ Where functions and their tests should live
      “Unit testing checks self-contained units of code, such as functions, early and often”
      ↩︎ Key concept
      “Challenges: This approach is not supported for Scala notebooks.”
      ↩︎ Exam trap 1
      “These functions can be more difficult to reuse across notebooks.”
      ↩︎ Exam trap 3
      “For Scala notebooks, Databricks recommends including functions in one notebook and their unit tests in a separate notebook.”
      ↩︎ Prediction
      “Store functions in one notebook and their unit tests in a separate notebook.. Benefits: These functions are easier to reuse across notebooks.”
      ↩︎ Checkpoint
    2. 2.
      “Test failures appear in the output area of the cell.”
      ↩︎ Running assertions from a notebook
      “You can use widgets to distinguish test invocations from normal invocations in a single notebook.”
      ↩︎ Running assertions from a notebook
      “When you use %run, test code is included in a separate notebook that you call from another notebook.”
      ↩︎ Where functions and their tests should live
    3. 3.
      “Fail the cell execution if there are any test failures.”
      ↩︎ Running assertions from a notebook
    4. 4.
      “Databricks follows pytest naming conventions to detect test files, classes and cases.”
      ↩︎ Running assertions from a notebook
      “Databricks follows pytest naming conventions to detect test files, classes and cases.”
      ↩︎ Exam trap 2
      “test-prefixed functions or methods outside of a class”
      ↩︎ Checkpoint
    5. 5.
      “This enables you to use these functions with other similar notebooks”
      ↩︎ Where functions and their tests should live

    Continue to part 2 of 2

    Unit and integration tests across dev, staging and production

    Spotted a mistake, or was something unclear? Tell us.