https://prefect.io logo
#prefect-community
Title
# prefect-community
b

Ben Muller

11/04/2022, 2:40 AM
Hey Prefect, I have a task in 2,0 that I want to test, in that task I use the
get_run_logger()
. In order to test that function I am using
.fn()
but I can not test it because
get_run_logger()
failed every time because
E           prefect.exceptions.MissingContextError: There is no active flow or task run context.
Besides possibly using an optional kwarg in every single task that I have, how can I get around this to test my tasks logic properly?
1
I can obviously mock it, but is this what is intended?
n

Nate

11/04/2022, 3:19 AM
hi @Ben Muller - you can disable the logger
Copy code
from prefect.logging import disable_run_logger

def test_some_flow():
   with disable_run_logger():
     call_some_flow_that_uses_logger.fn()
b

Ben Muller

11/04/2022, 3:21 AM
huh
that doesnt really do what I want
if I run a pytest you want me to manually add that every time i run the test?
n

Nate

11/04/2022, 3:24 AM
i wrote it wrong at first, but updated - I'm just suggesting calling
your_flow.fn()
within the
disable_run_logger
context manager block in tests
1
b

Ben Muller

11/04/2022, 3:25 AM
ahhhh
yeah that is great
ty
I can also mock it, kind of similar
c

Cole Murray

11/04/2022, 3:40 AM
Hey Ben, Our approach to this is to separate the “class task” from the prefect function task. Our code typically takes this form:
Copy code
@task
def some_task_here(something: str):
  some_task = SomeTask() # can move outside of this function to avoid instantiation each time if desired
  some_task.run(something)
This makes it quite easy to test your code, as it lives outside of prefect context.
👍 1
w.r.t. the logger, we inject this as a parameter into our class, allowing us to also swap for the standard lib logger if needed. This can then be trivially mocked at test time
b

Ben Muller

11/04/2022, 3:42 AM
Thanks Cole, I actually did this quite a bit in 1.0 but now moving to 2.0 it felt like a bit of a mistake tbh, lead to a lot of duplication in my code base. Appreciate you weighing in and helping out 🙂
👍 2
2 Views