Alex Ilyin
02/11/2025, 8:55 PMMarvin
02/11/2025, 8:55 PMprefect_test_harness
context manager or fixture from the prefect.testing.utilities
module. This allows you to run flows and tasks against a temporary local SQLite database, making it suitable for testing purposes. Here's a concise example:
python
from prefect import flow
from prefect.blocks.core import Block
from prefect.testing.utilities import prefect_test_harness
# Define a custom block
class MyBlock(Block):
value: int
# Example flow using the block
@flow
def my_flow():
block = MyBlock.load("my-block")
return block.value
# Test function using prefect_test_harness
def test_my_flow():
with prefect_test_harness():
# Save a mock block value
mock_block = MyBlock(value=42)
mock_block.save("my-block")
# Run the flow and assert the result
assert my_flow() == 42
This example demonstrates how to define a block, save a mock value, and test a flow using the mock. For more details, refer to the Prefect testing guide.Alex Ilyin
02/11/2025, 10:37 PMMarvin
02/11/2025, 10:37 PMpython
import pytest
from prefect.blocks.core import Block
from prefect.testing.utilities import prefect_test_harness
# Define a custom block
class MyBlock(Block):
value: int
@pytest.fixture(scope="function")
def mock_my_block():
with prefect_test_harness():
# Save a mock block value
mock_block = MyBlock(value=42)
mock_block.save("my-block")
yield
# Example flow using the block
from prefect import flow
@flow
def my_flow():
block = MyBlock.load("my-block")
return block.value
# Test function using the fixture
def test_my_flow(mock_my_block):
assert my_flow() == 42
### Explanation:
- Fixture Definition: The mock_my_block
fixture uses prefect_test_harness
to set up a temporary testing environment and saves a mock block.
- Scope: The fixture is scoped to "function", meaning it's applied to each test function that uses it.
- Usage: In the test function, simply include mock_my_block
as an argument to automatically use the fixture.
This setup allows you to reuse the fixture across multiple tests, ensuring consistent mock block values.