python - 从 Pytest fixture 中调用自定义函数

标签 python pytest fixtures

我想在 conftest.py 中编写一个 Pytest 固定装置,该装置在其内部调用一个函数,该函数默认情况下不执行任何操作,但可以在测试模块中重新定义。

#conftest.py

def within_foo():
    pass

@pytest.fixture
def foo():
    if some_condition():
        within_foo()
    something_else()


# test_foo.py

def within_foo():
    print('this should be printed when running test_foo')

def test_foo(foo):
    pass

有没有一种干净的方法来实现这个?

最佳答案

您可以通过继承来实现这一点。为所有测试创建一个基类,然后您可以决定要在哪些测试中覆盖 within_foo()

class BaseTest:

    @pytest.fixture
    def foo(self):
        self.within_foo()

    def within_foo(self):
        pass

@pytest.mark.testing
class TestSomething(BaseTest):

    def within_foo(self):
        print('this should be printed when running test_foo')

    def test_foo(self, foo):
        pass

@pytest.mark.testing
class TestSomethingElse(BaseTest):

    def test_foo_again(self, foo):
        print('test_foo_again')

输出

========================== 2 passed in 0.08 seconds ===========================
this should be printed when running test_foo
.test_foo

.test_foo_again

关于python - 从 Pytest fixture 中调用自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59983900/

相关文章:

python - 如何告诉 pytest-dependency 暂时忽略测试依赖项?

python - pytest-randomly - 检测测试耦合

ruby-on-rails - 使用 Rails Minitest,测试如何通过但在重新测试时失败?

ruby-on-rails - 如何在 Rails 中测试文件上传以进行集成测试?

python - 在将 Selenium WebDriver 与 Python 结合使用时处理 Firefox 不响应?

python - 使用 pytest 参数化测试

python - wxpython 的 Intellisense 之类的小部件是什么

ruby-on-rails - 在 Ruby on Rails 中使用固定装置播种数据是否危险

python - 如何使用 keras 计算具有 4 个神经元的输出的类权重?

python - 为什么这个 python 列表需要这么多内存?