1. 程式人生 > 其它 >【pytest】setup和teardown的詳細使用

【pytest】setup和teardown的詳細使用

setup和teardown的詳細使用 

Pytest也貼心的提供了類似setup、teardown的方法,並且還超過四個,一共有8種

  • 模組級別:setup_module、teardown_module
  • 函式級別:setup_function、teardown_function,不在類中的方法
  • 類級別:setup_class、teardown_class
  • 方法級別:setup_method、teardown_method

test_pytest02.py

程式碼:

import pytest

#按模組執行
def setup_module():
    print("=====整個.py模組開始前只執行一次:開啟瀏覽器=====")
def teardown_module():
    print("=====整個.py模組結束後只執行一次:關閉瀏覽器=====")

#按類執行
class Baidu(object):

    def setup_class(self):
        print("測試類下,所有test類執行前執行一次-")


    def teardown_class(self):
        print("測試類下,所有test類執行之後執行一次-")

    def setup_method(self):
        print("==類裡面每個用例執行前都會執行setup_method==")

    def teardown_method(self):
        print("==類裡面每個用例結束後都會執行teardown_method==")

    def test_three(self):
        print("three")

    def test_four(self):
        print("four")


if __name__ == '__main__':
    pytest.main(["-q", "-s", "-ra", "test_pytest02.py"])

 

執行結果: