pytest只是通过模块中的我的CLI测试,而下一个未能进行订购。为什么会发生这种情况?

发布于 2025-02-11 19:58:28 字数 8359 浏览 0 评论 0原文

pytest版本:pytest == 7.1.2

typer版本:typer == 0.4.1

我有这个测试文件

import pytest
from mimicbot import (
    __app_name__,
    cli,
    config,
)
import typer
from typer.testing import CliRunner, Result
from configparser import ConfigParser
from pathlib import Path 

default_path = Path(config.APP_DIR_PATH)
default_config = default_path / "config.ini"

@pytest.fixture
def mock_config_path(tmp_path):
    tmp_config_path = tmp_path / "config.ini"
    config.init_app(tmp_path)
    # copy a file from path default_config and paste it to tmp_config_path
    tmp_config_path.write_text(default_config.read_text())
    return tmp_config_path


class TestMine:
    # Must have an initialized mimicbot config to the default parameters
    def test_successful_mine(self, mock_config_path, tmp_path):
        parsed_config = ConfigParser()
        parsed_config.read(str(mock_config_path))
        runner = CliRunner()
        result = runner.invoke(cli.app, ["mine", "-ap", tmp_path])

        data_path = tmp_path / "data" / parsed_config.get("discord", "guild") / parsed_config.get("general", "session")
        messages_path = data_path / "messages.csv"

        assert "Successfully mined data." in result.stdout
        assert result.exit_code == 0
        assert messages_path.exists()
    
    def test_failed_mine_api_key(self, mock_config_path, tmp_path):
        parsed_config = ConfigParser()
        parsed_config.read(str(mock_config_path))
        parsed_config.set("discord", "api_key", "xxFAKExx")
        with open(str(mock_config_path), "w") as config_file:
            parsed_config.write(config_file)

        runner = CliRunner()
        result = runner.invoke(cli.app, ["mine", "-ap", tmp_path])

        assert "Error: API_KEY_ERROR" in result.stdout
        assert result.exit_code == 1

,我正在运行这两个测试,这些测试依赖于等待CLI执行。 CLI取决于一个函数,该功能需要几秒钟才能运行。

没有任何我订购这两个测试的方法,我总是得到相同的结果:第一个(顺序)通过,而以下一个失败。

运行以前的文件时,我会得到以下追溯。

====================================== =================================== ,插件1.0.0 rootdir:c:\ projects \ mimicbot \ mimicbotwrapper,configfile:pytest.ini插件: ASYNCIO-0.18.3 ASYNCIO:MODE =自动收集8个项目

tests \ test_init.py ......
[75%] tests \ test_mine.py .f
[100%]

=============================================失败= ========================================== _________________________________ TestMine.test_failed_mine_api_key _________________________________

self =< tests.test_mine.testmine对象在0x00000230bb8c3bb0> mock_config_path = WindowsPath('c:/users/1Seba/appdata/local/temp/pytest-of-1seba/pytest-67/test_failed_mine_api_ekey0/config.ini') tmp_path = WindowsPath('c:/users/1seba/appdata/local/local/temp/pytest of-1seba/pytest-67/test_failed_mine_api_key0')

  def test_failed_mine_api_key(self,mock_config_path,tmp_path):
    parsed_config = configparser()
    parsed_config.Read(str(mock_config_path))
    parsed_config.set(“ discord”,“ api_key”,“ xxfakexx”)
    使用打开(str(mock_config_path),“ w”)作为config_file:
        parsed_config.write(config_file)

    Runner = Clirunner()
    结果= runner.invoke(cli.app,[“ mine”,“ -ap”,tmp_path])
 
 断言“错误:api_key_error”结果。
 

''=<结果runtimeerror('事件循环已关闭')> .stdout

tests \ test_mine.py:51:assertionError =========================================================================== =============================== tests/test_mine.py :: testmine :: test_failed_mine_api_key
c:\ projects \ mimicbot \ mimicbotwrapper \ env \ lib \ site-packages \ discord \ client.py:229: 弃用:没有当前事件循环 self.loop = asyncio.get_event_loop()如果循环是没有其他循环

tests/test_mine.py :: testmine :: test_failed_mine_api_key
c:\ projects \ mimicbot \ mimicbotwrapper \ env \ lib \ lib \ site-packages_pytest \ unraisableException.py:78: pytestunraisableExceptionWarning:在:<功能中忽略了例外 _proactorbasepipetransport

追溯(最近的最新通话): 文件“ C:\ Python310 \ lib \ asyncio \ proactor_events.py”,第116行,in del self.close() 文件“ c:\ python310 \ lib \ asyncio \ proactor_events.py”,第108行, self._loop.call_soon(self._call_connection_lost,无) 文件“ C:\ python310 \ lib \ asyncio \ base_events.py”,第745行,在call_soon中 self._check_closed() 文件“ c:c:\ python310 \ lib \ asyncio \ base_events.py”,第510行,in _check_closed RAIND TIMETERERR(“事件循环已关闭”)RuntimeError:事件循环已关闭

  warnings.warn(pytest.pytestunraisableExceptionWarning(msg))
 

- docs: https://docs.pytest .org/en/stable/how-to/capture-warnings.html ============================================================ ===============================失败测试/test_mine.py :: testmine :: test_failed_mine_api_key-- assertionError:断言'错误:api _... ================================ 1 失败,7通过,3.24s中的3个警告============================================================ 系统:1:Runtime Warning:Coroutine'Client.run..runner'是 从未等待

,那么测试的订购(文件开始)被翻转时,我会得到以下追溯:

====================================== =================================== ,插件1.0.0 rootdir:c:\ projects \ mimicbot \ mimicbotwrapper,configfile:pytest.ini插件: ASYNCIO-0.18.3 ASYNCIO:MODE =自动收集8个项目

tests \ test_init.py ......
[75%] tests \ test_mine.py .f
[100%]

=============================================失败= ========================================== __________________________________ testmine.test_successful_mine __________________________________________________________

self =< tests.test_mine.testmine对象在0x000001ab03a9e410> mock_config_path = WindowsPath('c:/users/1seba/appdata/local/temp/pytest-of-1seba/pytest-68/test_successful_mine0/config.ini') tmp_path = WindowsPath('c:/users/1seba/appdata/local/local/temp/pytest of-1seba/pytest-68/test_successful_mine0')

  def test_successful_mine(self,mock_config_path,tmp_path):
    parsed_config = configparser()
    parsed_config.Read(str(mock_config_path))
    Runner = Clirunner()
    结果= runner.invoke(cli.app,[“ mine”,“ -ap”,tmp_path])

    data_path = tmp_path /“ data” / parsed_config.get(“ discord”,“ guild”) / parsed_config.get(“常规”,“ session”)
    messages_path = data_path /“ messages.csv”
 
 断言“成功挖掘的数据”。结果。分类e自言自语:断言“成功挖掘的数据”。在'e + 
 

其中''=<结果runtimeerror('事件循环已关闭')> .stdout

tests \ test_mine.py:48:OssertionError =========================================================================== ================================= tests/test_mine.py :: testmine :: test_successful_mine
c:\ projects \ mimicbot \ mimicbotwrapper \ env \ lib \ site-packages \ discord \ client.py:229: 弃用:没有当前事件循环 self.loop = asyncio.get_event_loop()如果循环是没有其他循环

tests/test_mine.py :: testmine :: test_successful_mine
c:\ projects \ mimicbot \ mimicbotwrapper \ env \ lib \ lib \ site-packages_pytest \ unraisableException.py:78: pytestunraisableExceptionWarning:在:<功能中忽略了例外 _proactorbasepipetransport

追溯(最近的最新通话): 文件“ C:\ Python310 \ lib \ asyncio \ proactor_events.py”,第116行,in del self.close() 文件“ c:\ python310 \ lib \ asyncio \ proactor_events.py”,第108行, self._loop.call_soon(self._call_connection_lost,无) 文件“ C:\ python310 \ lib \ asyncio \ base_events.py”,第745行,在call_soon中 self._check_closed() 文件“ c:c:\ python310 \ lib \ asyncio \ base_events.py”,第510行,in _check_closed RAIND TIMETERERR(“事件循环已关闭”)RuntimeError:事件循环已关闭

  warnings.warn(pytest.pytestunraisableExceptionWarning(msg))
 

- docs: https://docs.pytest .org/en/stable/how-to/capture-warnings.html ============================================================ ==============================失败测试/test_mine.py :: testmine :: test_successful_mine -assertionerror: 断言'成功mi ... ============================ 1失败,7 通过,2.23s中的3个警告=============================== Runtime Warning:Coroutine'Client.run..runner'从来都不是 等待

,两个文件都以相同的方式失败,似乎在两个文件上都发生了同样的问题。

我还尝试将测试移动到分开文件(我认为废话解决方案),并且也以相同的方式失败。

有什么问题? 我该如何解决?

提前致谢!

pytest version: pytest==7.1.2

typer version: typer==0.4.1

I have this test file

import pytest
from mimicbot import (
    __app_name__,
    cli,
    config,
)
import typer
from typer.testing import CliRunner, Result
from configparser import ConfigParser
from pathlib import Path 

default_path = Path(config.APP_DIR_PATH)
default_config = default_path / "config.ini"

@pytest.fixture
def mock_config_path(tmp_path):
    tmp_config_path = tmp_path / "config.ini"
    config.init_app(tmp_path)
    # copy a file from path default_config and paste it to tmp_config_path
    tmp_config_path.write_text(default_config.read_text())
    return tmp_config_path


class TestMine:
    # Must have an initialized mimicbot config to the default parameters
    def test_successful_mine(self, mock_config_path, tmp_path):
        parsed_config = ConfigParser()
        parsed_config.read(str(mock_config_path))
        runner = CliRunner()
        result = runner.invoke(cli.app, ["mine", "-ap", tmp_path])

        data_path = tmp_path / "data" / parsed_config.get("discord", "guild") / parsed_config.get("general", "session")
        messages_path = data_path / "messages.csv"

        assert "Successfully mined data." in result.stdout
        assert result.exit_code == 0
        assert messages_path.exists()
    
    def test_failed_mine_api_key(self, mock_config_path, tmp_path):
        parsed_config = ConfigParser()
        parsed_config.read(str(mock_config_path))
        parsed_config.set("discord", "api_key", "xxFAKExx")
        with open(str(mock_config_path), "w") as config_file:
            parsed_config.write(config_file)

        runner = CliRunner()
        result = runner.invoke(cli.app, ["mine", "-ap", tmp_path])

        assert "Error: API_KEY_ERROR" in result.stdout
        assert result.exit_code == 1

I am running those two tests which depend on waiting for the cli to execute. The cli depends on a function which takes a couple seconds to run.

Reguardless of how I order the two tests I always get the same result: the first one (sequentially) passes while the following one fails.

When running the former file I get the following traceback.

======================================== test session starts ======================================== platform win32 -- Python 3.10.2, pytest-7.1.2, pluggy-1.0.0 rootdir: C:\Projects\MimicBot\mimicbotwrapper, configfile: pytest.ini plugins:
asyncio-0.18.3 asyncio: mode=auto collected 8 items

tests\test_init.py ......
[ 75%] tests\test_mine.py .F
[100%]

============================================= FAILURES ==============================================
_________________________________ TestMine.test_failed_mine_api_key _________________________________

self = <tests.test_mine.TestMine object at 0x00000230BB8C3BB0>
mock_config_path =
WindowsPath('C:/Users/1seba/AppData/Local/Temp/pytest-of-1seba/pytest-67/test_failed_mine_api_key0/config.ini')
tmp_path =
WindowsPath('C:/Users/1seba/AppData/Local/Temp/pytest-of-1seba/pytest-67/test_failed_mine_api_key0')

def test_failed_mine_api_key(self, mock_config_path, tmp_path):
    parsed_config = ConfigParser()
    parsed_config.read(str(mock_config_path))
    parsed_config.set("discord", "api_key", "xxFAKExx")
    with open(str(mock_config_path), "w") as config_file:
        parsed_config.write(config_file)

    runner = CliRunner()
    result = runner.invoke(cli.app, ["mine", "-ap", tmp_path])
  assert "Error: API_KEY_ERROR" in result.stdout E       AssertionError: assert 'Error: API_KEY_ERROR' in '' E        +  where

'' = <Result RuntimeError('Event loop is closed')>.stdout

tests\test_mine.py:51: AssertionError
========================================= warnings summary ========================================== tests/test_mine.py::TestMine::test_successful_mine
tests/test_mine.py::TestMine::test_failed_mine_api_key
C:\Projects\MimicBot\mimicbotwrapper\env\lib\site-packages\discord\client.py:229:
DeprecationWarning: There is no current event loop
self.loop = asyncio.get_event_loop() if loop is None else loop

tests/test_mine.py::TestMine::test_failed_mine_api_key
C:\Projects\MimicBot\mimicbotwrapper\env\lib\site-packages_pytest\unraisableexception.py:78:
PytestUnraisableExceptionWarning: Exception ignored in: <function
_ProactorBasePipeTransport.del at 0x00000230AE62E830>

Traceback (most recent call last):
File "C:\Python310\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Python310\lib\asyncio\base_events.py", line 745, in call_soon
self._check_closed()
File "C:\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed

warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
====================================== short test summary info ====================================== FAILED tests/test_mine.py::TestMine::test_failed_mine_api_key -
AssertionError: assert 'Error: API_...============================== 1
failed, 7 passed, 3 warnings in 5.24s ==============================
sys:1: RuntimeWarning: coroutine 'Client.run..runner' was
never awaited

Then when the ordering (beginning of file to end) of the tests is flipped, I get the following traceback:

======================================== test session starts ======================================== platform win32 -- Python 3.10.2, pytest-7.1.2, pluggy-1.0.0 rootdir: C:\Projects\MimicBot\mimicbotwrapper, configfile: pytest.ini plugins:
asyncio-0.18.3 asyncio: mode=auto collected 8 items

tests\test_init.py ......
[ 75%] tests\test_mine.py .F
[100%]

============================================= FAILURES ==============================================
___________________________________ TestMine.test_successful_mine ___________________________________

self = <tests.test_mine.TestMine object at 0x000001AB03A9E410>
mock_config_path =
WindowsPath('C:/Users/1seba/AppData/Local/Temp/pytest-of-1seba/pytest-68/test_successful_mine0/config.ini')
tmp_path =
WindowsPath('C:/Users/1seba/AppData/Local/Temp/pytest-of-1seba/pytest-68/test_successful_mine0')

def test_successful_mine(self, mock_config_path, tmp_path):
    parsed_config = ConfigParser()
    parsed_config.read(str(mock_config_path))
    runner = CliRunner()
    result = runner.invoke(cli.app, ["mine", "-ap", tmp_path])

    data_path = tmp_path / "data" / parsed_config.get("discord", "guild") / parsed_config.get("general", "session")
    messages_path = data_path / "messages.csv"
  assert "Successfully mined data." in result.stdout E       AssertionError: assert 'Successfully mined data.' in '' E        + 

where '' = <Result RuntimeError('Event loop is closed')>.stdout

tests\test_mine.py:48: AssertionError
========================================= warnings summary ========================================== tests/test_mine.py::TestMine::test_failed_mine_api_key
tests/test_mine.py::TestMine::test_successful_mine
C:\Projects\MimicBot\mimicbotwrapper\env\lib\site-packages\discord\client.py:229:
DeprecationWarning: There is no current event loop
self.loop = asyncio.get_event_loop() if loop is None else loop

tests/test_mine.py::TestMine::test_successful_mine
C:\Projects\MimicBot\mimicbotwrapper\env\lib\site-packages_pytest\unraisableexception.py:78:
PytestUnraisableExceptionWarning: Exception ignored in: <function
_ProactorBasePipeTransport.del at 0x000001AB7681E830>

Traceback (most recent call last):
File "C:\Python310\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Python310\lib\asyncio\base_events.py", line 745, in call_soon
self._check_closed()
File "C:\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed

warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
====================================== short test summary info ====================================== FAILED tests/test_mine.py::TestMine::test_successful_mine - AssertionError:
assert 'Successfully mi...============================== 1 failed, 7
passed, 3 warnings in 2.23s ============================== sys:1:
RuntimeWarning: coroutine 'Client.run..runner' was never
awaited

In the end it seems like the same issue is happening on both files as they fail in the same manner.

I have also tried moving the tests to separate files (crap solution in my opinion) and that also failed in the same way.

What could be the problem?
How could I resolve it?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文