Pytest Fixture(一)

2023-03-13,

Fixture 是一些函数,pytest 会在执行测试函数之前(或之后)加载运行它们。我们可以用它做一些事情,比如数据库的链接操作之类的

import pytest

@pytest.fixture()
def post_code():
return '010' def test_postcode(post_code):
assert post_code == '010'

  

执行结果

预处理和后处理

很多时候需要在测试前进行预处理(如新建数据库连接),并在测试完成进行清理(关闭数据库连接)。

当有大量重复的这类操作,最佳实践是使用固件来自动化所有预处理和后处理。

Pytest 使用 yield 关键词将固件分为两部分,yield 之前的代码属于预处理,会在测试前执行;yield 之后的代码属于后处理,将在测试完成后执行。

以下测试模拟数据库查询,使用 Fixture来模拟数据库的连接关闭:

import pytest

@pytest.fixture()
def db():
print('Connection success')
yield
print(' closed') def search_user(user_id):
d = {
'0001': 'lowen'
}
return d[user_id] def test_search(db):
assert search_user('0001') == 'lowen'

 

结果

成功前后标识前后有数据库的连接和关闭操作

Pytest Fixture(一)的相关教程结束。

《Pytest Fixture(一).doc》

下载本文的Word格式文档,以方便收藏与打印。