Loading...
Loading...
This skill should be used when the user asks to "write pytest tests", "set up pytest best practices", "configure pytest", "write fixtures", or needs guidance on pytest testing patterns and project structure.
npx skill4agent add the-perfect-developer/the-perfect-opencode pytestsrcpyproject.toml
src/
mypkg/
__init__.py
app.py
tests/
conftest.py
test_app.pyimportlibpyproject.toml[tool.pytest.ini_options]
addopts = ["--import-mode=importlib"]
testpaths = ["tests"]pip install -e .test_*.py*_test.pytest_Test__init__conftest.pyassertdef test_addition():
assert 1 + 1 == 2
def test_with_message():
result = compute()
assert result > 0, f"Expected positive, got {result}"pytest.approxdef test_floats():
assert 0.1 + 0.2 == pytest.approx(0.3)pytest.raisesdef test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
def test_exception_message():
with pytest.raises(ValueError, match=r"invalid value"):
parse_value("bad")conftest.pyimport pytest
@pytest.fixture
def user():
return {"name": "Alice", "role": "admin"}
def test_user_role(user):
assert user["role"] == "admin"addfinalizer@pytest.fixture
def db_connection():
conn = create_connection()
yield conn # test runs here
conn.close() # teardown| Scope | Lifetime | Use case |
|---|---|---|
| Per test (default) | Mutable state, cheap to create |
| Per test class | Shared state within a class |
| Per test file | Expensive setup shared across a module |
| Entire test run | Database connections, containers |
@pytest.fixture(scope="session")
def app_config():
return load_config("test.env")@pytest.fixture
def created_user(admin_client):
user = admin_client.create_user(name="test")
yield user
admin_client.delete_user(user) # always runs@pytest.fixture
def make_order():
orders = []
def _make(product, qty):
order = Order(product=product, qty=qty)
orders.append(order)
return order
yield _make
for o in orders: o.cancel()
def test_two_orders(make_order):
o1 = make_order("book", 1)
o2 = make_order("pen", 5)
assert o1.product != o2.productconftest.pyconftest.pytests/unit/conftest.py@pytest.mark.parametrize@pytest.mark.parametrize("value,expected", [
(2, 4),
(3, 9),
(-1, 1),
])
def test_square(value, expected):
assert square(value) == expectedpytest.param@pytest.mark.parametrize("n", [
0,
pytest.param(-1, marks=pytest.mark.xfail(reason="negative not supported")),
])
def test_sqrt(n):
assert sqrt(n) >= 0@pytest.fixture(params=["sqlite", "postgres"])
def db(request):
return create_db(request.param)pyproject.toml[tool.pytest.ini_options]
markers = [
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
"integration: requires external services",
"unit: fast, isolated tests",
][tool.pytest.ini_options]
addopts = ["--strict-markers"]@pytest.mark.slow
def test_heavy_computation(): ...
# Module-level
pytestmark = pytest.mark.integrationpyproject.toml[tool.pytest.ini_options]
addopts = [
"--import-mode=importlib",
"--strict-markers",
"--strict-config",
"-ra", # show summary of all non-passing tests
]
testpaths = ["tests"]
markers = [
"slow: deselect with '-m \"not slow\"'",
"integration: requires live services",
][tool.pytest.ini_options]
strict = trueskipif@pytest.mark.skipif(sys.platform == "win32", reason="POSIX only")
def test_symlinks(): ...xfailstrict=True@pytest.mark.xfail(reason="issue #42: parser bug", strict=False)
def test_parser_edge_case(): ...unittest.mockdef test_env_override(monkeypatch):
monkeypatch.setenv("API_KEY", "test-key")
assert get_api_key() == "test-key"
def test_function_patch(monkeypatch):
monkeypatch.setattr("mymodule.fetch", lambda url: {"ok": True})
assert fetch_data() == {"ok": True}monkeypatchtmp_pathpathlib.Pathtempfiledef test_writes_file(tmp_path):
out = tmp_path / "result.txt"
write_report(out)
assert out.read_text() == "done"| Goal | Tool |
|---|---|
| Assert equality | |
| Assert float equality | |
| Assert exception raised | |
| Assert warning emitted | |
| Skip conditionally | |
| Document known failure | |
| Run test N times with data | |
| Shared setup/teardown | |
| Patch objects/env | |
| Temp files | |
references/fixtures.mdreferences/configuration.mdpyproject.tomlpytest.ini