新版 pytest setup
时间: 2023-10-14 19:07:58 浏览: 47
最新版的 pytest 已经移除了 `setup` 和 `teardown` 函数,取而代之的是更加灵活和易用的 `fixtures` 功能。`fixtures` 可以在测试运行前后执行一些必要的操作,例如初始化测试数据、连接数据库等。举例来说,如果要在测试中使用一个名为 `my_fixture` 的 `fixture`,可以这样定义:
```python
@pytest.fixture
def my_fixture():
# setup
yield
# teardown
```
其中 `yield` 语句前面的部分是 `setup` 操作,后面的部分是 `teardown` 操作。在测试函数中,可以通过函数参数的方式来使用这个 `fixture`:
```python
def test_something(my_fixture):
# test code here
```
在上面的例子中,`my_fixture` 会在 `test_something` 运行之前先执行 `setup` 操作,然后在测试运行完之后再执行 `teardown` 操作。