website/docs/pytest.mdx
{/*
Pyrefly includes built-in support for pytest, the popular Python testing framework. This support focuses on fixtures and IDE workflows for navigating, annotating, and running tests.
Note: Pyrefly's pytest support is automatic when a file imports
pytest. Some IDE features also depend on selecting a Python interpreter where pytest is installed.
We welcome your feedback and suggestions. Please share your thoughts and ideas by opening an issue on GitHub.
pytest is a Python testing framework where tests are usually functions or
methods named test_*. Its fixture system lets tests request reusable setup
objects by naming fixture parameters.
import pytest
@pytest.fixture
def username() -> str:
return "Ada"
def test_user(username):
assert username == "Ada"
In this example, pytest injects the username fixture into the test function
based on the parameter name.
Pyrefly recognizes pytest imports and fixture decorators without requiring a plugin or manual configuration. It:
@pytest.fixture, @pytest.fixture(...),
and imported fixture aliases such as from pytest import fixture.Pyrefly understands pytest's fixture-by-name convention, so IDE navigation works across fixture definitions and fixture parameters in the same module.
import pytest
@pytest.fixture
def database_url() -> str:
return "sqlite://"
def test_connection(database_url):
assert database_url.startswith("sqlite")
Go-to-definition on the database_url parameter in test_connection jumps to
the fixture definition. Find-references on the fixture name includes parameters
that request that fixture.
Pyrefly also handles fixture aliases:
from pytest import fixture as reusable
@reusable
def user_id() -> int:
return 42
def test_lookup(user_id):
assert user_id > 0
Pyrefly can infer fixture return types and offer quick fixes that make those types explicit.
import pytest
@pytest.fixture
def enabled():
return True
def test_feature(enabled):
assert enabled
In the editor, these quick fixes appear as code actions:
Add pytest fixture type annotation, which updates the fixture to
def enabled() -> bool:.Add pytest fixture parameter type annotation, which updates the test
to def test_feature(enabled: bool):.In supported editors, Pyrefly shows runnable CodeLens actions above pytest tests. For example, a test method can be run using a pytest node id such as:
python -m pytest path/to/test_file.py::TestClass::test_method
This feature uses the Python interpreter selected for the workspace. If Pyrefly cannot import pytest from that interpreter, select the correct interpreter or install pytest in the active environment.
You do not need to enable a Pyrefly plugin or add Pyrefly-specific configuration for pytest support.
pytest in the Python environment used by your editor.pyrefly.