简体   繁体   English

ScopeMismatch 当我尝试进行 setup_teardown pytest function

[英]ScopeMismatch when i try to make setup_teardown pytest function

My goal is to create a fixture that will run once at the beginning of the class function test and initialize the attributes I need in self.我的目标是创建一个 fixture,它将在 class function 测试开始时运行一次,并初始化我需要的属性。 To do this, I created a fixture with the scope of the class and applied it directly to the class. To solve the compatibility problem of pytest with asynchronous code, pytest-asyncio was used.为此,我用 class 的 scope 创建了一个 fixture,并直接应用到 class。为了解决 pytest 与异步代码的兼容性问题,使用了 pytest-asyncio。

My minimally reproducible example:我的最小可重现示例:

import pytest


@pytest.fixture(scope="class")
async def setup_teardown(request):
    request.cls.test_number = '123'
    yield
    # ...


@pytest.mark.asyncio
@pytest.mark.usefixtures("setup_teardown")
class Test_BaseFunctional():

    async def test_my_number(self):
        assert self.test_number == '123'

But i'm receiving:但我收到:

ScopeMismatch: You tried to access the function scoped fixture event_loop with a class scoped request object, involved factories:
tests/issue.py:4:  def setup_teardown(request)

I tried many ways, from time to time I got a large-scale non-working code, and in the end I returned to this minimal example in the hope of help from you, dear friends.尝试了很多方法,时不时会出现大规模的无法运行的代码,最后又回到了这个最小的例子,希望对各位小伙伴有所帮助。

The reason was in pytest-asyncio fixtures realization.原因在于 pytest-asyncio fixtures 的实现。 They has scope "function" which not implicated with higher-level fixtures, such as the scope "class".它们具有 scope “功能”,不涉及更高级别的固定装置,例如 scope “类”。 In this case, we just need to redefine event_loop fixture to eliminate ScopeMismatch.在这种情况下,我们只需重新定义 event_loop fixture 即可消除 ScopeMismatch。

@pytest.fixture(scope="class")
def event_loop():
    policy = asyncio.get_event_loop_policy()
    loop = policy.new_event_loop()
    yield loop
    loop.close()

You can put this code into coftest.py file.您可以将此代码放入 coftest.py 文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM