如果你還想從頭學起Pytest,可以看看這個系列的文章哦!
https://www.cnblogs.com/poloyy/category/1690628.html
前言
用過unittest的童鞋都知道,有兩個前置方法,兩個后置方法;分別是
- setup()
- setupClass()
- teardown()
- teardownClass()
Pytest也貼心的提供了類似setup、teardown的方法,並且還超過四個,一共有十種
- 模塊級別:setup_module、teardown_module
- 函數級別:setup_function、teardown_function,不在類中的方法
- 類級別:setup_class、teardown_class
- 方法級別:setup_method、teardown_method
- 方法細化級別:setup、teardown
代碼
用過unittest的童鞋,對這個前置、后置方法應該不陌生了,我們直接來看代碼和運行結果
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = __Time__ = 2020-04-06 11:40 __Author__ = 小菠蘿測試筆記 __Blog__ = https://www.cnblogs.com/poloyy/ """ import pytest def setup_module(): print("=====整個.py模塊開始前只執行一次:打開瀏覽器=====") def teardown_module(): print("=====整個.py模塊結束后只執行一次:關閉瀏覽器=====") def setup_function(): print("===每個函數級別用例開始前都執行setup_function===") def teardown_function(): print("===每個函數級別用例結束后都執行teardown_function====") def test_one(): print("one") def test_two(): print("two") class TestCase(): def setup_class(self): print("====整個測試類開始前只執行一次setup_class====") def teardown_class(self): print("====整個測試類結束后只執行一次teardown_class====") def setup_method(self): print("==類里面每個用例執行前都會執行setup_method==") def teardown_method(self): print("==類里面每個用例結束后都會執行teardown_method==") def setup(self): print("=類里面每個用例執行前都會執行setup=") def teardown(self): print("=類里面每個用例結束后都會執行teardown=") def test_three(self): print("three")
def test_four(self): print("four") if __name__ == '__main__': pytest.main(["-q", "-s", "-ra", "setup_teardown.py"])
執行結果

