在使用pytest做断言的时候,遇到了报错
Fixture "token" called directly. Fixtures are not meant to be called directly,
but are created automatically when test functions request them as parameters.
conftest文件的@pytest.fixture中scope选择的是session
这个是目录层级
运行pytest之后就会报错,请教一下这是为什么
该回答内容部分引用GPT,GPT_Pro更好的解决问题
在使用pytest做断言的时候,如果发生报错,很可能是由于conftest.py文件中定义的fixture函数设置有问题,或者调用函数方式有误。Fixture是pytest中用于支持初始化和清理测试环境的一种特性,其作用是把测试中常用的重复性代码抽取出来,便于重复使用。
在这个报错中,可能是因为conftest.py文件中@pytest.fixture的scope设置为session,导致fixture函数不能直接被调用。scope的作用是控制fixture在测试中的生存时间,session表示fixture只会在整个测试会话只执行一次,在不同测试函数中都可以使用相同的变量。因此,当使用者直接调用fixture函数时,就会出现Fixture "token" called directy Fixtures are not meantto be called directy
but are created automatically when test functions requestthem as parameters。
正确的使用fixture函数的方式是:在测试函数上方加上@pytest.mark.usefixtures(fixture_name)装饰器,然后将要使用的fixture函数作为参数传入即可。具体代码如下:
@pytest.mark.usefixtures("token")
def test_function():
# do something here
fixture函数也可以传入参数,当函数名和参数都传入@pytest.mark.usefixtures装饰器时,就会以fixture_name(parameter)的形式调用。例如:
@pytest.mark.usefixtures("token(parameter)")
def test_function():
# do something here
如果回答有帮助,望采纳。