我可以在conftest.py中定义除固定装置之外的函数吗

LIN*_*OHN 6 python testing pytest

我可以在conftest.py中定义除固定装置之外的函数吗

如果我有一个函数 add() ,在conftest.py中定义

我可以使用 test_add.py 文件中的函数仅调用 add()

Ant*_*nko 6

两种可能的方式

  1. 您可以从 conftest.py 导入函数 add ,或者将其移至更合适的位置。(例如 utils.py)

  2. 您可以创建返回函数的装置并在测试中使用它。像这样的东西。

测试.py

import pytest


@pytest.fixture
def add():
    def inner_add(x, y):
        return x + y
    return inner_add
Run Code Online (Sandbox Code Playgroud)

测试全部.py

def test_all(add):
    assert add(1, 2) == 3
Run Code Online (Sandbox Code Playgroud)

我无法想象什么时候这将是一个好的解决方案。但我确信它存在。