p

    Philip MacMenamin

    9 months ago
    Hi, is there a standard way to test a Task raises an Exception?
    Anna Geller

    Anna Geller

    9 months ago
    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

    Philip MacMenamin

    9 months ago
    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:
    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:
    prefect.TaskRunner | FAIL signal raised: FAIL('Expecting file: does_not_exist, not found in input_dir')
    But, the test fails:
    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.
    Anna Geller

    Anna Geller

    9 months ago
    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