解决pytest.mark.dependency的scope为package报AttributeError: ‘NoneType‘ object has no attribute..

在上一篇文章中,我们执行scope='package’时报如下错:

D:\pythonProject\dependency\dep\dep2>pytest -sv
======================================================================== test session starts ========================================================================
platform win32 -- Python 3.7.6, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- d:\python3.7.6\python.exe
cachedir: .pytest_cache
rootdir: D:\pythonProject\dependency\dep\dep2
plugins: allure-pytest-2.9.41, dependency-0.5.1
collected 6 items                                                                                                                                                    

test_dep_01.py::Testna::test_01 function test_01
PASSED
test_dep_01.py::Testna::test_02 function test_02
PASSED
test_dep_02.py::test_02 function test_02
PASSED
test_dep_02.py::Testdep1::test_01 class test_01
PASSED
test_dep_02.py::Testdep1::test_02 ERROR
test_dep_02.py::test_01 function test_01
PASSED

============================================================================== ERRORS ===============================================================================
________________________________________________________________ ERROR at setup of Testdep1.test_02 _________________________________________________________________

item = <Function test_02>

    def pytest_runtest_setup(item):
        """Check dependencies if this item is marked "dependency".
        Skip if any of the dependencies has not been run successfully.
        """
        marker = item.get_closest_marker("dependency")
        if marker is not None:
            depends = marker.kwargs.get('depends')
            if depends:
                scope = marker.kwargs.get('scope', 'module')
                manager = DependencyManager.getManager(item, scope=scope)
>               manager.checkDepend(depends, item)
E               AttributeError: 'NoneType' object has no attribute 'checkDepend'

D:\python3.7.6\lib\site-packages\pytest_dependency.py:179: AttributeError
====================================================================== short test summary info ======================================================================
ERROR test_dep_02.py::Testdep1::test_02 - AttributeError: 'NoneType' object has no attribute 'checkDepend'
==================================================================== 5 passed, 1 error in 0.10s =====================================================================

明明设置的@pytest.mark.dependency(depends=[“test_dep_01.py::Testna::test_01”]中的方法也已经执行了,为什么还报错了?

解决方法是:在dep2目录下增加__init__.py文件即可。 _init_.py文件内容是空的。关于_init__.py文件的作用后面我们再介绍。

A module that was compiled using NumPy 1.x cannot be run in NumPy 2.0.0 as it may crash. To support both 1.x and 2.x versions of NumPy, modules must be compiled with NumPy 2.0. Some module may need to rebuild instead e.g. with 'pybind11>=2.12'. If you are a user of the module, the easiest solution will be to downgrade to 'numpy<2' or try to upgrade the affected module. We expect that some modules will need time to support NumPy 2. Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "F:\anaconda\Lib\site-packages\ipykernel_launcher.py", line 17, in <module> app.launch_new_instance() File "F:\anaconda\Lib\site-packages\traitlets\config\application.py", line 1075, in launch_instance app.start() File "F:\anaconda\Lib\site-packages\ipykernel\kernelapp.py", line 701, in start self.io_loop.start() File "F:\anaconda\Lib\site-packages\tornado\platform\asyncio.py", line 205, in start self.asyncio_loop.run_forever() File "F:\anaconda\Lib\asyncio\windows_events.py", line 322, in run_forever super().run_forever() File "F:\anaconda\Lib\asyncio\base_events.py", line 641, in run_forever self._run_once() File "F:\anaconda\Lib\asyncio\base_events.py", line 1987, in _run_once handle._run() File "F:\anaconda\Lib\asyncio\events.py", line 88, in _run self._context.run(self._callback, *self._args) File "F:\anaconda\Lib\site-packages\ipykernel\kernelbase.py", line 534, in dispatch_queue await self.process_one() File "F:\anaconda\Lib\site-packages\ipykernel\kernelbase.py", line 523, in process_one await dispatch(*args) File "F:\anaconda\Lib\site-packages\ipykernel\kernelbase.py", line 429, in dispatch_shell await result File "F:\anaconda\Lib\site-packages\ipykernel\kernelbase.py", line 767, in execute_request reply_content = await reply_content File "F:\anaconda\Lib\site-packages\ipykernel\ipkernel.py", line 429, in do_execute res = shell.run_cell( File "F:\anaconda\Lib\site-packages\ipykernel\zmqshell.py", line 549, in run_cell return super().run_cell(*args, **kwargs) File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3075, in run_cell result = self._run_cell( File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3130, in _run_cell result = runner(coro) File "F:\anaconda\Lib\site-packages\IPython\core\async_helpers.py", line 129, in _pseudo_sync_runner coro.send(None) File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3334, in run_cell_async has_raised = await self.run_ast_nodes(code_ast.body, cell_name, File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3517, in run_ast_nodes if await self.run_code(code, result, async_=asy): File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3577, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "C:\Users\张宇\AppData\Local\Temp\ipykernel_25812\3580470148.py", line 2, in <module> import pandas as pd File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\__init__.py", line 61, in <module> from pandas.core.api import ( File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\api.py", line 28, in <module> from pandas.core.arrays import Categorical File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\arrays\__init__.py", line 1, in <module> from pandas.core.arrays.arrow import ArrowExtensionArray File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\arrays\arrow\__init__.py", line 5, in <module> from pandas.core.arrays.arrow.array import ArrowExtensionArray File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\arrays\arrow\array.py", line 52, in <module> from pandas.core import ( File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\ops\__init__.py", line 8, in <module> from pandas.core.ops.array_ops import ( File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\ops\array_ops.py", line 56, in <module> from pandas.core.computation import expressions File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\computation\expressions.py", line 21, in <module> from pandas.core.computation.check import NUMEXPR_INSTALLED File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\computation\check.py", line 5, in <module> ne = import_optional_dependency("numexpr", errors="warn") File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\compat\_optional.py", line 135, in import_optional_dependency module = importlib.import_module(name) File "F:\anaconda\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "F:\anaconda\Lib\site-packages\numexpr\__init__.py", line 24, in <module> from numexpr.interpreter import MAX_THREADS, use_vml, __BLOCK_SIZE1__ --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) AttributeError: _ARRAY_API not found A module that was compiled using NumPy 1.x cannot be run in NumPy 2.0.0 as it may crash. To support both 1.x and 2.x versions of NumPy, modules must be compiled with NumPy 2.0. Some module may need to rebuild instead e.g. with 'pybind11>=2.12'. If you are a user of the module, the easiest solution will be to downgrade to 'numpy<2' or try to upgrade the affected module. We expect that some modules will need time to support NumPy 2. Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "F:\anaconda\Lib\site-packages\ipykernel_launcher.py", line 17, in <module> app.launch_new_instance() File "F:\anaconda\Lib\site-packages\traitlets\config\application.py", line 1075, in launch_instance app.start() File "F:\anaconda\Lib\site-packages\ipykernel\kernelapp.py", line 701, in start self.io_loop.start() File "F:\anaconda\Lib\site-packages\tornado\platform\asyncio.py", line 205, in start self.asyncio_loop.run_forever() File "F:\anaconda\Lib\asyncio\windows_events.py", line 322, in run_forever super().run_forever() File "F:\anaconda\Lib\asyncio\base_events.py", line 641, in run_forever self._run_once() File "F:\anaconda\Lib\asyncio\base_events.py", line 1987, in _run_once handle._run() File "F:\anaconda\Lib\asyncio\events.py", line 88, in _run self._context.run(self._callback, *self._args) File "F:\anaconda\Lib\site-packages\ipykernel\kernelbase.py", line 534, in dispatch_queue await self.process_one() File "F:\anaconda\Lib\site-packages\ipykernel\kernelbase.py", line 523, in process_one await dispatch(*args) File "F:\anaconda\Lib\site-packages\ipykernel\kernelbase.py", line 429, in dispatch_shell await result File "F:\anaconda\Lib\site-packages\ipykernel\kernelbase.py", line 767, in execute_request reply_content = await reply_content File "F:\anaconda\Lib\site-packages\ipykernel\ipkernel.py", line 429, in do_execute res = shell.run_cell( File "F:\anaconda\Lib\site-packages\ipykernel\zmqshell.py", line 549, in run_cell return super().run_cell(*args, **kwargs) File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3075, in run_cell result = self._run_cell( File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3130, in _run_cell result = runner(coro) File "F:\anaconda\Lib\site-packages\IPython\core\async_helpers.py", line 129, in _pseudo_sync_runner coro.send(None) File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3334, in run_cell_async has_raised = await self.run_ast_nodes(code_ast.body, cell_name, File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3517, in run_ast_nodes if await self.run_code(code, result, async_=asy): File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3577, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "C:\Users\张宇\AppData\Local\Temp\ipykernel_25812\3580470148.py", line 2, in <module> import pandas as pd File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\__init__.py", line 61, in <module> from pandas.core.api import ( File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\api.py", line 28, in <module> from pandas.core.arrays import Categorical File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\arrays\__init__.py", line 1, in <module> from pandas.core.arrays.arrow import ArrowExtensionArray File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\arrays\arrow\__init__.py", line 5, in <module> from pandas.core.arrays.arrow.array import ArrowExtensionArray File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\arrays\arrow\array.py", line 66, in <module> from pandas.core.arrays.masked import BaseMaskedArray File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\arrays\masked.py", line 61, in <module> from pandas.core import ( File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\core\nanops.py", line 52, in <module> bn = import_optional_dependency("bottleneck", errors="warn") File "C:\Users\张宇\AppData\Roaming\Python\Python312\site-packages\pandas\compat\_optional.py", line 135, in import_optional_dependency module = importlib.import_module(name) File "F:\anaconda\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "F:\anaconda\Lib\site-packages\bottleneck\__init__.py", line 7, in <module> from .move import (move_argmax, move_argmin, move_max, move_mean, move_median, --------------------------------------------------------------------------- ImportError Traceback (most recent call last) File ~\AppData\Roaming\Python\Python312\site-packages\numpy\core\_multiarray_umath.py:44, in __getattr__(attr_name) 39 # Also print the message (with traceback). This is because old versions 40 # of NumPy unfortunately set up the import to replace (and hide) the 41 # error. The traceback shouldn't be needed, but e.g. pytest plugins 42 # seem to swallow it and we should be failing anyway... 43 sys.stderr.write(msg + tb_msg) ---> 44 raise ImportError(msg) 46 ret = getattr(_multiarray_umath, attr_name, None) 47 if ret is None: ImportError: A module that was compiled using NumPy 1.x cannot be run in NumPy 2.0.0 as it may crash. To support both 1.x and 2.x versions of NumPy, modules must be compiled with NumPy 2.0. Some module may need to rebuild instead e.g. with 'pybind11>=2.12'. If you are a user of the module, the easiest solution will be to downgrade to 'numpy<2' or try to upgrade the affected module. We expect that some modules will need time to support NumPy 2. A module that was compiled using NumPy 1.x cannot be run in NumPy 2.0.0 as it may crash. To support both 1.x and 2.x versions of NumPy, modules must be compiled with NumPy 2.0. Some module may need to rebuild instead e.g. with 'pybind11>=2.12'. If you are a user of the module, the easiest solution will be to downgrade to 'numpy<2' or try to upgrade the affected module. We expect that some modules will need time to support NumPy 2. Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "F:\anaconda\Lib\site-packages\ipykernel_launcher.py", line 17, in <module> app.launch_new_instance() File "F:\anaconda\Lib\site-packages\traitlets\config\application.py", line 1075, in launch_instance app.start() File "F:\anaconda\Lib\site-packages\ipykernel\kernelapp.py", line 701, in start self.io_loop.start() File "F:\anaconda\Lib\site-packages\tornado\platform\asyncio.py", line 205, in start self.asyncio_loop.run_forever() File "F:\anaconda\Lib\asyncio\windows_events.py", line 322, in run_forever super().run_forever() File "F:\anaconda\Lib\asyncio\base_events.py", line 641, in run_forever self._run_once() File "F:\anaconda\Lib\asyncio\base_events.py", line 1987, in _run_once handle._run() File "F:\anaconda\Lib\asyncio\events.py", line 88, in _run self._context.run(self._callback, *self._args) File "F:\anaconda\Lib\site-packages\ipykernel\kernelbase.py", line 534, in dispatch_queue await self.process_one() File "F:\anaconda\Lib\site-packages\ipykernel\kernelbase.py", line 523, in process_one await dispatch(*args) File "F:\anaconda\Lib\site-packages\ipykernel\kernelbase.py", line 429, in dispatch_shell await result File "F:\anaconda\Lib\site-packages\ipykernel\kernelbase.py", line 767, in execute_request reply_content = await reply_content File "F:\anaconda\Lib\site-packages\ipykernel\ipkernel.py", line 429, in do_execute res = shell.run_cell( File "F:\anaconda\Lib\site-packages\ipykernel\zmqshell.py", line 549, in run_cell return super().run_cell(*args, **kwargs) File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3075, in run_cell result = self._run_cell( File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3130, in _run_cell result = runner(coro) File "F:\anaconda\Lib\site-packages\IPython\core\async_helpers.py", line 129, in _pseudo_sync_runner coro.send(None) File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3334, in run_cell_async has_raised = await self.run_ast_nodes(code_ast.body, cell_name, File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3517, in run_ast_nodes if await self.run_code(code, result, async_=asy): File "F:\anaconda\Lib\site-packages\IPython\core\interactiveshell.py", line 3577, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "C:\Users\张宇\AppData\Local\Temp\ipykernel_25812\3580470148.py", line 3, in <module> import matplotlib.pyplot as plt File "F:\anaconda\Lib\site-packages\matplotlib\__init__.py", line 161, in <module> from . import _api, _version, cbook, _docstring, rcsetup File "F:\anaconda\Lib\site-packages\matplotlib\rcsetup.py", line 27, in <module> from matplotlib.colors import Colormap, is_color_like File "F:\anaconda\Lib\site-packages\matplotlib\colors.py", line 57, in <module> from matplotlib import _api, _cm, cbook, scale File "F:\anaconda\Lib\site-packages\matplotlib\scale.py", line 22, in <module> from matplotlib.ticker import ( File "F:\anaconda\Lib\site-packages\matplotlib\ticker.py", line 143, in <module> from matplotlib import transforms as mtransforms File "F:\anaconda\Lib\site-packages\matplotlib\transforms.py", line 49, in <module> from matplotlib._path import ( --------------------------------------------------------------------------- ImportError Traceback (most recent call last) File ~\AppData\Roaming\Python\Python312\site-packages\numpy\core\_multiarray_umath.py:44, in __getattr__(attr_name) 39 # Also print the message (with traceback). This is because old versions 40 # of NumPy unfortunately set up the import to replace (and hide) the 41 # error. The traceback shouldn't be needed, but e.g. pytest plugins 42 # seem to swallow it and we should be failing anyway... 43 sys.stderr.write(msg + tb_msg) ---> 44 raise ImportError(msg) 46 ret = getattr(_multiarray_umath, attr_name, None) 47 if ret is None: ImportError: A module that was compiled using NumPy 1.x cannot be run in NumPy 2.0.0 as it may crash. To support both 1.x and 2.x versions of NumPy, modules must be compiled with NumPy 2.0. Some module may need to rebuild instead e.g. with 'pybind11>=2.12'. If you are a user of the module, the easiest solution will be to downgrade to 'numpy<2' or try to upgrade the affected module. We expect that some modules will need time to support NumPy 2.
09-06
<think>我们面对的问题是:在使用`pytest.mark.asyncio`装饰异步测试函数`test_bidi_connection`时,出现了`AttributeError("'RunContext' object has no attribute 'runner'")`错误。 根据错误信息,这通常与pytest的上下文对象中缺少`runner`属性有关。结合引用[1]中提到的插件入口点,我们可以推测问题可能与pytest插件有关,特别是与异步插件(如pytest-asyncio)的版本或配置有关。 ### 错误分析 1. **插件兼容性问题**:较旧版本的pytest-asyncio可能不支持当前pytest运行环境,导致`RunContext`对象缺少`runner`属性。 2. **多重装饰器冲突**:如果同时使用了其他装饰器(如`pytest.mark.parametrize`),可能会与`pytest.mark.asyncio`产生冲突。 3. **pytest运行模式**:某些pytest插件(如pytest-xdist)在并行执行时可能对异步测试支持不足。 ### 解决方案 #### 步骤1:升级相关库 ```bash pip install --upgrade pytest pytest-asyncio ``` #### 步骤2:调整异步事件循环策略 在测试文件或`conftest.py`中添加以下代码,显式设置事件循环策略: ```python import pytest import asyncio # 在conftest.py中设置事件循环策略 @pytest.fixture(scope="session") def event_loop(): # 创建新的事件循环 loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) yield loop loop.close() ``` #### 步骤3:确保异步测试装饰器顺序正确 将`@pytest.mark.asyncio`放在最靠近函数的位置(即在内层): ```python # ✅ 正确:装饰器顺序 @pytest.mark.parametrize("param", [1, 2]) @pytest.mark.asyncio # 放在参数化装饰器下方 async def test_example(param): await asyncio.sleep(0.1) ``` #### 步骤4:使用pytest.ini配置异步事件循环 创建`pytest.ini`文件并配置: ```ini [pytest] asyncio_mode = auto ``` #### 步骤5:验证完整测试代码 ```python import pytest from selenium import webdriver from selenium.webdriver.firefox.options import Options # 注意装饰器顺序:先参数化,再asyncio @pytest.mark.asyncio async def test_bidi_connection(): options = Options() options.set_capability("webSocketUrl", True) # 启用BiDi[^1] driver = webdriver.Firefox(options=options) # 异步上下文管理连接 async with driver.bidi_connection() as conn: session = conn.session # 必须await异步命令 result = await session.execute("Browser.getVersion", {}) assert "Firefox" in result["userAgent"] driver.quit() ``` ### 错误原因总结 $$ \text{AttributeError} \Rightarrow \begin{cases} \text{1. pytest-asyncio插件版本过旧} \\ \text{2. 事件循环未正确配置} \\ \text{3. 装饰器顺序冲突} \end{cases} $$ ### 环境验证 | 组件 | 推荐版本 | 检查命令 | |------|----------|----------| | pytest | ≥7.0 | `pytest --version` | | pytest-asyncio | ≥0.20 | `pip show pytest-asyncio` | | asyncio | Python内置 | `python -c "import asyncio; print(asyncio.__version__)"` | ### 相关问题 1. 如何解决pytest异步测试中的`Event loop is closed`错误? 2. 在参数化异步测试时需要注意哪些问题? 3. 如何配置pytest-xdist以支持异步测试? 4. 调试异步测试时有哪些实用技巧? 5. 如何在pytest中复用同一个浏览器实例进行多个异步测试? 通过以上步骤,应能解决`'RunContext' object has no attribute 'runner'`错误。如果问题仍然存在,请提供完整的错误堆栈信息以便进一步分析。 </think>### 解决 `pytest.mark.asyncio` 调用时出现 `AttributeError("'RunContext' object has no attribute 'runner'")` 的错误 这个错误通常是由于 pytest-asyncio 插件版本兼容性问题或事件循环配置不当导致的。以下是逐步解决方案: #### 🔧 解决方案 1:升级 pytest-asyncio 并配置事件循环(推荐) ```python # conftest.py 中添加事件循环配置 import pytest import asyncio @pytest.fixture(scope="session") def event_loop(): """覆盖默认事件循环配置""" loop = asyncio.get_event_loop_policy().new_event_loop() yield loop loop.close() ``` ```python # 测试文件 import pytest from selenium import webdriver # 确保使用最新语法 ✅ @pytest.mark.asyncio async def test_bidi_connection(): driver = webdriver.Firefox() # 显式创建异步上下文 async with driver.bidi_connection() as connection: session = connection.session result = await session.execute("Browser.getVersion", {}) assert "Firefox" in result["userAgent"] driver.quit() ``` **关键修复点**: 1. **升级依赖**: ```bash pip install --upgrade pytest pytest-asyncio # pytest-asyncio ≥0.18.0 修复了此问题 ``` 2. **事件循环配置**:在 `conftest.py` 中显式定义事件循环fixture[^1] 3. **使用 `async with` 语法**:确保正确管理异步资源 #### ️ 解决方案 2:调整异步模式设置 在 `pytest.ini` 中添加配置: ```ini [pytest] asyncio_mode = auto # 自动处理异步上下文 ✅ ``` 或在测试文件中直接设置: ```python import pytest pytestmark = pytest.mark.asyncio # 模块级标记 async def test_bidi_connection(): # 测试代码... ``` #### 📦 版本兼容性参考表 | 依赖 | 修复版本 | 安装命令 | |------|----------|----------| | `pytest-asyncio` | ≥0.18.0 | `pip install pytest-asyncio==0.21` | | `pytest` | ≥7.0.0 | `pip install pytest==7.4.0` | | `asyncio` | Python≥3.7 | 内置 | #### 💻 替代方案:自定义异步运行器 ```python # conftest.py def pytest_configure(config): config.option.asyncio_mode = "auto" @pytest.hookimpl def pytest_sessionstart(session): """自定义运行上下文初始化""" session.runner = asyncio.new_event_loop() ``` --- ### 🔍 错误原因深度分析 $$ \text{AttributeError} \propto \frac{\text{过时的pytest-asyncio}}{\text{缺少事件循环配置}} \times \text{Pytest兼容性} $$ 错误根源: 1. **插件版本过旧**:pytest-asyncio<0.18 在最新 Pytest 中存在兼容问题 2. **上下文管理冲突**:`RunContext` 未正确初始化异步运行环境[^1] 3. **事件循环缺失**:未显式定义事件循环生命周期管理 --- ### ✅ 验证解决方案 1. 创建 `conftest.py` 添加事件循环fixture 2. 升级包:`pip install pytest-asyncio==0.21` 3. 运行测试:`pytest -v --asyncio-mode=auto` --- ### ❓ 相关问题 1. 如何在不同Python版本(3.7-3.11)中保持pytest-asyncio的兼容性? 2. 使用pytest-xdist并行执行异步测试时如何避免事件循环冲突? 3. 如何为Selenium BiDi自定义异步事件超时设置? 4. 在Docker环境中运行pytest异步测试的特殊配置要求? 5. 如何捕获和处理异步测试中的异常堆栈信息?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

永远不要矫情

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值