Hi, is there a standard way to test a Task raises ...
# ask-community
p
Hi, is there a standard way to test a Task raises an Exception?
a
yes, I think so. Check out the tests/ directory in the main prefect repository, e.g. https://github.com/PrefectHQ/prefect/blob/4c9100485f5c2ab4a0b26376cf6419d585a45a9e/tests/tasks/prefect/test_flow_run.py#L187
p
I guess I'm not following what's going on here, is this the simplest way to see if a Task raises and Exception?
I tried something like:
Copy code
def test_single_file_not_found_gens_exception(monkeypatch):
     with pytest.raises(signals.FAIL):                                                                   
         flow.run(input_dir=os.getcwd() + "/test/input_files/",
                 file_name="does_not_exist")
I can run the test, and see:
Copy code
prefect.TaskRunner | FAIL signal raised: FAIL('Expecting file: does_not_exist, not found in input_dir')
But, the test fails:
Copy code
DID NOT RAISE <class 'prefect.engine.signals.FAIL'>
So, I thought maybe I should test the Task rather than run the flow.
I guess I can just ask the final state if it's failed.
def test_single_file_not_found_gens_exception(mock_nfs_mount):
state = flow.run(input_dir=os.getcwd() + "/test/input_files/",
file_name="does_not_exist")
assert state.is_failed()
It would nice if there was a clear example how you can test run a task, or a flow, to generate an exception.
a
That’s correct, I would also test it in a way that my test asserts specific state. You can find more examples here: https://docs.prefect.io/core/idioms/testing-flows.html
👍 1