我可以将参数传递给pytest固定装置吗? [英] Can I pass arguments to pytest fixtures?

查看:64
本文介绍了我可以将参数传递给pytest固定装置吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所有测试的基准是,总会有一辆出租车,其中至少有一名乘客.我可以使用一些基本的固定装置轻松实现此设置:

The baseline of all my tests is that there will always be a taxi with at least one passenger in it. I can easily achieve this setup with some basic fixtures:

from blah import Passenger, Taxi

@pytest.fixture
def passenger():
    return Passenger()

@pytest.fixture
def taxi(passenger):
    return Taxi(rear_seat=passenger)

测试基线很简单:

def test_taxi_contains_passenger(taxi)
    assert taxi.has_passenger()

当我开始需要更复杂的测试设置时,我的问题浮出水面.在某些情况下,我需要出租车有一名以上的乘客,而在某些情况下,我需要定义乘客的属性.例如:

My issue crops up when I start needing more complicated test setup. There will be scenarios where I'll need the taxi to have more than one passenger and scenarios where I'll need to define passenger attributes. For example:

def test_three_passengers_in_taxi(taxi)
    assert taxi.has_passengers(3)
    assert taxi.front_passenger_is_not_a_child()

我可以通过具有用于特定测试的特定固定装置来解决此问题.对于以上测试,我将创建以下夹具:

I'm able to get around this problem by having specific fixtures for specific tests. For the above test, I would create the following fixture:

@pytest.fixture
def three_passenger_test_setup(taxi)
    taxi.add_front_seat_passenger(Passenger(child=False))
    taxi.add_rear_seat_passenger(Passenger())
    return taxi

我可以将上面的夹具传递到我的测试用例中,并且一切都很好,但是如果我走这条路,我可能会为每个测试最终获得一个夹具,并且感觉应该有一种更有效的方法来执行此操作.

I can pass the above fixture into my test case and everything is dandy, but if I go down this route I might end up with a fixture for every test and it feels like there should be a more efficient way of doing this.

是否有一种方法可以将参数传递给灯具,以便可以将这些参数用于创建灯具返回的对象?我应该参数化测试功能吗?治具?还是我在浪费时间,每次测试都可以使用固定装置吗?

Is there a way to pass arguments to a fixture so that those arguments can be used in creating the object the fixture returns? Should I be parameterizing the test function? The fixture? Or am I wasting time and is a fixture per test the way to go?

推荐答案

我们可以通过以下方法来做到这一点:使用在灯具内获取args并从灯具返回该方法的方法.

We can do this by using a method that takes args within a fixture and return the method from the fixture.

让我给你看一个例子

@pytest.fixture
def my_fixture():

  def _method(a, b):
    return a*b

  return _method

def test_me(my_fixture):
  result1 = my_fixture(2, 3)
  assert result1 == 6

  result2 = my_fixture(4, 5)
  assert result2 == 20

这篇关于我可以将参数传递给pytest固定装置吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆