【问题标题】:Parameterizing tests with pytest使用 pytest 参数化测试
【发布时间】:2017-08-22 19:35:51
【问题描述】:

我正在学习使用 pyest 进行参数化测试。在关注the relevant pytest documentation之后,我想出了这个简单的例子:

import unittest

import pytest


@pytest.fixture(autouse=True, params=['foo', 'bar'])
def foo(request):
    print('fixture')
    print(request.param)


class Foo(unittest.TestCase):
    def setUp(self):
        print('unittest setUp()')

    def test(self):
        print('test')

这会产生以下错误:

Failed: The requested fixture has no parameter defined for the current test.
E               
E               Requested fixture 'foo' defined in:
E               tests/fixture.py:7

第 7 行是def foo(request):

是什么导致了这个错误,我该如何解决?

【问题讨论】:

  • 我通常使用@pytest.mark.parametrise('request', ['foo', 'bar'])。它不能回答你的问题,但它可以作为一个快速修复(其中request 是参数的名称)
  • @Artyer 感谢您的建议。我链接的文档没有这个,所以我仍然有兴趣了解我做错了什么。
  • 我认为问题就像错误中提到的那样,您没有定义参数,正如@Artyer 在他的示例中所说,他正在命名“请求”然后传递值。在您的代码中,您将请求参数传递给 foo 函数,但由于您没有在夹具内定义,因此没有参数
  • @GenaroMorales 我的示例与docs.pytest.org/en/latest/fixture.html#parametrizing-fixtures 文档中给出的示例有何不同?
  • 使用自动使用意味着类中的所有测试方法都将使用这个fixture,如果你删除了你将只在具有请求参数的方法中使用该fixture并且该方法将通过跨度>

标签: python pytest fixtures parameterized-tests


【解决方案1】:

fixture 的目标是将对象传递给测试用例,但您创建的 fixture 不会返回或产生任何东西。

那么我不确定你是否可以将对象传递给 unittest TestCase 方法,我认为它可能会与 self 参数产生一些冲突。

另一方面,它可以使用一个简单的功能:

@pytest.fixture(autouse=True, params=['foo', 'bar'])
def foo(request):
    print('fixture')
    print(request.param)
    yield request.param

# class Foo(unittest.TestCase):
#     def setUp(self):
#         print('unittest setUp()')
# 
#     def _test(self):
#         print('test')

def test_fixture(foo):
    assert foo == 'foo'

>>>  1 failed, 1 passed in 0.05 seconds
# test 1 run with foo : OK
# test 2 run with bar : FAILED

编辑:

确实:Why cant unittest.TestCases see my py.test fixtures?

【讨论】:

  • 我在 pytest 中重写了我的单元测试测试。感谢您提供的链接,它促使我朝着这个方向前进。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-15
  • 2018-02-24
  • 2023-01-20
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
相关资源
最近更新 更多