簡體   English   中英

Pytest asyncio 未啟動簡單的異步測試

[英]Pytest asyncio not launching simple async test

使用 Pytest 和 asyncio 我正在嘗試執行異步測試:

async def count(self):
    return "2"

async def test_foo(self):
    x = []
    x.append(await asyncio.gather(self.count(), self.count(), self.count()))
    print(x)

如果在不使用 pytest 的情況下啟動此代碼,它會返回:

[['2', '2', '2']]

使用 Pytest 它似乎沒有在函數內執行任何操作。 它返回此警告:

 RuntimeWarning: coroutine 'TestClass.test_foo' was never awaited
    method()

任何想法?

您應該使用pytest.mark.asyncio標記。

使用此標記標記您的測試協程,pytest 將使用 event_loop 夾具提供的事件循環將其作為異步任務執行。

例如

import asyncio
import pytest


class TestClass:
    async def count(self):
        return "2"

    @pytest.mark.asyncio
    async def test_foo(self):
        x = []
        x.append(await asyncio.gather(self.count(), self.count(), self.count()))
        print(x)
        assert x == [['2', '2', '2']]

單元測試結果:

⚡  coverage run -m pytest -s /Users/dulin/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/66546652/test_example.py && coverage report -m --include="src/*"
============================================================================================================================================ test session starts ============================================================================================================================================
platform darwin -- Python 3.9.2, pytest-5.3.1, py-1.8.0, pluggy-0.13.1
rootdir: /Users/dulin/workspace/github.com/mrdulin/python-codelab
plugins: asyncio-0.10.0
collected 1 item                                                                                                                                                                                                                                                                                            

src/stackoverflow/66546652/test_example.py [['2', '2', '2']]
.

============================================================================================================================================= 1 passed in 0.03s =============================================================================================================================================
Name                                         Stmts   Miss  Cover   Missing
--------------------------------------------------------------------------
src/stackoverflow/66546652/test_example.py      11      0   100%

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM