<blockquote>
<p>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? </p>
</blockquote>
<p>可以对<code>indirect=True</code>使用测试参数化。
在pytest文档中:<a href="https://pytest.org/latest/example/parametrize.html#apply-indirect-on-particular-arguments" rel="noreferrer">Apply indirect on particular arguments</a>。
如图所示:<a href="https://stackoverflow.com/a/33879151/3858507">https://stackoverflow.com/a/33879151/3858507</a></p>
<hr/>
<blockquote>
<p>The fixture?</p>
</blockquote>
<p>另一个可能适合您的选项是使用某个fixture,该fixture使用参数化指定参数:</p>
<pre><code>@pytest.fixture(params=[3,4])
def number_of_passengers(request):
return request.param
</code></pre>
<p>然后从出租车和测试本身进入这个固定装置:</p>
<pre><code>@pytest.fixture
def taxi(number_of_passengers):
return Taxi(rear_seat=Passenger() * number_of_passengers)
def test_three_passengers_in_taxi(taxi, number_of_passengers)
assert taxi.has_passengers(number_of_passengers)
assert taxi.front_passenger_is_not_a_child()
</code></pre>
<p>如果您的测试和断言在您拥有的案例之间非常相似,那么这种方法是很好的。</p>
<hr/>
<blockquote>
<p>Or am I wasting time and is a fixture per test the way to go?</p>
</blockquote>
<p>我要说的是,您绝对不应该为每个测试函数创建fixture。为此,您可以将设置放在测试中。这实际上是一个可行的替代方案,在这种情况下,你必须作出不同的索赔案件的出租车。</p>
<hr/>
<p>最后一种可能的模式是出租车工厂。虽然对于您展示的示例,它并不十分有用,但如果需要多个参数,并且只有一些参数在更改,则可以创建类似于以下内容的装置:</p>
<pre><code>from functools import partial
@pytest.fixture
def taxi_factory():
return partial(Taxi, 1, 2, 3)
</code></pre>