【问题标题】:Parametrize pytest fixture参数化 pytest 夹具
【发布时间】:2015-10-07 18:09:32
【问题描述】:

据我从有关 pytest 夹具参数化的文档中了解到 - 它使用给定的参数创建夹具的副本,从而调用每个需要具有不同副本的夹具的测试。

我的需求有点不同。假设有一个fixture:

@pytest.fixture
def sample_foo():
    return Foo(file_path='file/path/test.json')

def test1(sample_foo):
    pass

def test2(sample_foo):
    pass

问题是测试test1test2 需要类Foo 的相同实例,但file_path 的值不同

所以现在我这样做了:

def build_foo(path):
   return Foo(file_path=path)

 def test1():
     sample_foo = build_foo('file/path/some.json')

 def test2():
     sample_foo = build_foo('file/path/another.json')

这看起来有点像代码重复。我可以为每个文件创建一个单独的装置,但这看起来更糟。看起来每个测试都需要它自己的唯一文件,所以也许可以通过查看请求夹具的测试函数的名称来确定文件的名称来解决这个问题。但这不能保证。

【问题讨论】:

  • 你能告诉我测试是否太不同了吗?或者唯一的区别是 Foo() 实例之间?取决于这几种方法是可能的
  • @AlexanderPetrovich 这取决于。当前 json 文件包含来自 HTTP 服务器的一系列示例响应。因此,当我在内部测试 Foo 的任何功能时,它会执行一些 http 请求。响应来自这个 json。

标签: python pytest


【解决方案1】:

你需要fixture parameters

可以对夹具函数进行参数化,在这种情况下它们将被多次调用,每次执行一组依赖测试,即。 e.依赖于此夹具的测试。

def build_foo(path):
   return Foo(file_path=path)

@pytest.fixture(params=["file/path/some.json", "file/path/another.json"])
def file_path(request):
    return request.param

def test(file_path):    
    sample_foo = build_foo(file_path) 

也许你可以直接

def test(file_path):    
    sample_foo = Foo(file_path) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2022-12-08
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    相关资源
    最近更新 更多