Unit testing best practices for Prefect flows, subflows and tasks

This Discourse topic is waiting for a contributor! Add your content as a comment, and we’ll review and consolidate it.

Thanks for helping us grow this knowledge base! :heart:

I really like these prompts; thanks for setting them up!

To answer “Unit testing tasks,” this is how I typically do it:


from prefect import task

def divide_task(x, y):
    return x / y


import pytest
from module import divide_task

def test_divide_task():
    assert divide_task.fn(1, 2) == 0.5  # fn calls underlying function

def test_divide_task_error():
    with pytest.raises(ZeroDivisionError):
        divide_task.fn(1, 0)

Then run in the command line.
pytest .

There’s another way of writing it, but I think this might be too verbose.

import pytest
from prefect import flow
from module import divide_task

def test_divide_task():
    def test_flow():
        return divide_task(1, 2)
    task_state = test_flow().result()
    actual = task_state.result()
    assert actual == 0.5 

Also, there’s docs here Testing - Prefect 2.0

1 Like

You are amazing, I didn’t even plan to share it until Tuesday (until then I plan to refine this content plan even more) and you are already contributing :pray:

1 Like