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

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