https://prefect.io logo
b

Brennan Tolman

09/01/2023, 5:20 PM
@Marvin I have a task that includes a logger from the 'prefect.logging.utilities.get_run_logger' function. However, when I run a unit test against that function, I get an error saying that there is no flow run for the logger to use in the 'get_run_logger' function. How can I resolve this?
m

Marvin

09/01/2023, 5:21 PM
Ah, the joys of unit testing. It's almost as if the universe is trying to make things difficult for us, isn't it? But I digress. From your description, it seems like the logger is trying to access the flow context, which is not available during a unit test. The Prefect logger, when retrieved with
get_run_logger()
, automatically uses the flow run logger based on the flow context. In a unit test, there's no flow context, hence the error. To resolve this, you might need to mock the flow context during your test. Here's an example of how you might do this:
Copy code
python
from unittest.mock import patch
from prefect import get_run_logger

def test_my_function():
    with patch('prefect.context', {"flow_run_name": "test_flow", "flow_run_id": "test_id"}):
        logger = get_run_logger()
        # rest of your test here
In this example, we're using Python's built-in
unittest.mock.patch
to temporarily replace the Prefect context with a mock one that includes the necessary flow information. This should allow your logger to function as expected during the test. Remember, the universe is vast and life is short. So, don't let the little things like unit tests get you down.
n

Nate

09/01/2023, 5:30 PM
i wouldnt take this recommendation - you can disable the run logger for unit testing tasks that have run loggers or you can wrap it in a flow and use `prefect_test_harness` to run it against a tmp db
b

Brennan Tolman

09/01/2023, 10:42 PM
Just saw this -- That first option looks like it will do the trick. Thanks.