我正在编写selenium测试,包含一组类,每个类包含几个测试.每个类当前打开然后关闭Firefox,这有两个结果:
我可以通过添加睡眠来解决错误54,但它仍然会超级慢.
所以,我想要做的是在所有测试类中重用相同的Firefox实例.这意味着我需要在所有测试类之前运行一个方法,在所有测试类之后运行另一个方法.因此,'setup_class'和'teardown_class'是不够的.
我是测试新手,我偶然发现了 pytest 固定装置,但我不完全确定何时使用它们以及它们为什么有用。
例如,请参阅以下代码:
import pytest
@pytest.fixture
def input_value():
input = 39
return input
def test_divisible_by_3(input_value):
assert input_value % 3 == 0
def test_divisible_by_6(input_value):
assert input_value % 6 == 0
Run Code Online (Sandbox Code Playgroud)
这里pytest.fixture的作用是什么?为什么我们不能简单地创建一个被调用的函数input_value()
并在测试函数内运行该函数?例如:
import pytest
def input_value():
input = 39
return input
def test_divisible_by_3():
assert input_value() % 3 == 0
def test_divisible_by_6():
assert input_value() % 6 == 0
Run Code Online (Sandbox Code Playgroud)
为什么我们不能这样做?使用fixture有什么用?
假设我有一个测试函数,它将参数化record
作为字典,其中它的值之一是已经定义的固定装置。
例如,我们有一个固定装置:
@pytest.fixture
def a_value():
return "some_value"
Run Code Online (Sandbox Code Playgroud)
和测试功能:
@pytest.mark.parametrize("record", [{"a": a_value, "other": "other_value"},
{"a": a_value, "another": "another_value"}])
def test_record(record):
do_something(record)
Run Code Online (Sandbox Code Playgroud)
现在,我知道可以通过将夹具传递给测试函数并相应地更新记录来解决这个问题,例如:
@pytest.mark.parametrize("record", [{"other": "other_value"},
{"another": "another_value"}])
def test_record(a_value, record):
record["a"] = a_value
do_something(record)
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有一种方法可以在没有这种“解决方法”的情况下做到这一点,当我有许多已经定义的固定装置并且我只想在传递给函数的每个参数化记录中使用它们时。
我已经检查过这个问题,尽管它似乎并不完全适合我的情况。从那里的答案中找不到正确的用法。
pytest ×3
python ×2
decorator ×1
python-2.7 ×1
python-3.x ×1
selenium ×1
testing ×1
unit-testing ×1