python pytest 前置后置

有些函数需要连接数据库,可以把连接数据库和断开数据的操作放在,指定的函数里.
这样每次测试函数的时候,都调取这个链接数据库的函数即可

# test_db.py

@pytest.fixture()
def db():
    print('Connection successful')

    yield

    print('Connection closed')


def search_user(user_id):
    d = {
        '001': 'xiaoming'
    }
    return d[user_id]


def test_search(db):
    assert search_user('001') == 'xiaoming'

参考:
https://learning-pytest.readthedocs.io/zh/latest/doc/fixture/setup-and-teardown.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章