我有一个非常简单的测试数据库设置(pytest-asyncio 0.23.5.port1,pytest 8.1.1):
conftest.py
import asyncio
import os
from pathlib import Path
import pytest
from alembic import command
from alembic.config import Config
from sqlalchemy_utils import database_exists, create_database, drop_database
from app.main.conf import settings
from app.main.database import session_factory, engine
@pytest.fixture(scope="session")
def event_loop():
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
@pytest.fixture(scope="session")
def alembic_config():
base_dir = Path(__file__).resolve().parent.parent
alembic_cfg = Config(os.path.join(base_dir, "alembic.ini"))
yield alembic_cfg
@pytest.fixture(scope="session")
def db(alembic_config):
url = settings.DB.sync_url
if database_exists(url):
raise ValueError(
f"База данных для тестов {settings.DB.NAME} уже существует. "
f"Удалите ее и перезапустите тесты."
)
create_database(url)
command.upgrade(alembic_config, "head")
yield
drop_database(url)
@pytest.fixture
async def session(db):
async with engine.begin() as connection:
session = session_factory(bind=connection)
yield session
await session.close()
await connection.rollback()
pyproject.toml:
[tool.pytest.ini_options]
testpaths = [
"src/tests",
]
pythonpath = ["src"]
required_plugins = [
"pytest-asyncio",
"pytest-cov",
"pytest-mock",
]
asyncio_mode = "auto"
env = [
"DB_DATABASE=nkz-profiles-new-tests"
]
测试:
from sqlalchemy import select
from app.models import Country
async def test_1(session):
stmt = select(Country)
result = await session.scalars(stmt)
assert list(result.all()) == []
async def test_create(session):
country = Country(name="12w", code="cacsas")
session.add(country)
await session.commit()
async def test_2(session):
stmt = select(Country)
result = await session.scalars(stmt)
assert list(result.all()) == []
当我运行测试时 pytest-asyncio 生成警告:
src/tests/usecases/libs/list_document_types/test_view.py::test_1
/Users/alber.aleksandrov/PycharmProjects/nkz-profiles-new/.venv/lib/python3.11/site-packages/pytest_asyncio/plugin.py:769: DeprecationWarning:pytest-asyncio 提供的 event_loop 固定装置 已被重新定义于
/Users/alber.aleksandrov/PycharmProjects/nkz-profiles-new/src/tests/conftest.py:14 用自定义实现替换 event_loop 固定装置是 已弃用,并将导致将来出现错误。如果你想 请求一个范围不是函数的异步事件循环
范围,在标记 asyncio 标记时使用“scope”参数 测试。如果要返回不同类型的事件循环,请使用 event_loop_policy 固定装置。
如何修复我的代码以跳过此警告?
在pytest.ini中添加:
filterwarnings = 忽略::DeprecationWarning