從文章標題能夠看出,就是初始化和釋放的操做,根據個人java習慣來學習pytest,我的感受沒差太多,理解上也不是很難。javascript
哦,對了,差點跑題了,這個框架是基於Python語言的,在學習的時候不免總會用java的類比思想來學習,下面言歸正傳哈。java
咱們還從 unittest與pytest來對比學習吧微信
unittest有兩個前置方法,兩個後置方法,分別是:框架
我的始終以爲unittest和Junit像極了。ide
固然,Pytest也提供了相似setup、teardown的方法,分別是:函數
我總感受學習pytest像是在學習testng同樣,難道是個人錯覺嗎,啊啊啊啊,不能吧。學習
unittest的setupClass和teardownClass,須要配合@classmethod裝飾器一塊兒使用,也就是咱們java說的註解呀,這塊是翻譯給java學Python的同窗的,可忽略哈。示例代碼以下:測試
# -*- coding: utf-8 -*-# @Time : 2020/10/21 20:09# @Author : longrong.lang # @FileName: test_setup_teardown_unittest.py # @Software: PyCharm # @Cnblogs :https://www.cnblogs.com/longronglang''' unittest代碼示例'''import unittestclass TestUnitTest(unittest.TestCase): @classmethod def setUpClass(cls): print("全部用例執行前執行") def setUp(self): print("每一個用例開始前執行") def tearDown(self): print("每一個用例結束後執行") @classmethod def tearDownClass(cls): print("全部用例執行後執行") def testA(self): '''用例A''' print("用例A執行了") self.assertEquals(1, 1) def testB(self): '''用例B''' print("用例B執行了") self.assertTrue(True)if __name__ == "__main__": unittest.main()
能夠看出執行順序爲:this
setUpClass setUp testA tearDown setUp testB tearDown tearDownClass 用例之間按用例名稱ASCII碼的順序加載,數字與字母順序爲0~9,A~Z,a~z, 因此testA會在testB以前運行。
函數級的setup_function、teardown_function只對函數用例生效,並且不在類中使用spa
依舊仍是把類和函數都有的狀況放在一塊兒,示例代碼以下:
# -*- coding: utf-8 -*-# @Time : 2020/10/21 20:27# @Author : longrong.lang # @FileName: test_setup_teardown_pytest.py # @Software: PyCharm # @Cnblogs :https://www.cnblogs.com/longronglang''' pyetest示例'''import pytest def setup_module(): print("setup_module():在模塊最以前執行,且只執行一次")def teardown_module(): print("teardown_module:在模塊以後執行,且只執行一次")def setup_function(): print("setup_function():每一個方法以前執行")def teardown_function(): print("teardown_function():每一個方法以後執行")def test_1(): print("正在執行用例1") x = "this" assert 'h' in x def test_2(): print("正在執行用例2") assert 1 == 1class TestClass(object): def setup_class(self): print("setup_class(self):每一個類以前執行一次,只執行一次") def teardown_class(self): print("teardown_class(self):每一個類以後執行一次,只執行一次") def test_A(self): print("正在執行用例A") x = "this" assert 'h' in x def test_B(self): print("正在執行B") assert 1 == 1if __name__ == "__main__": pytest.main(["-q", "test_setup_teardown_pytest.py"])
能夠看出來,互不影響,執行順序爲:
setup_module()setup_function()test_1teardown_function()setup_function()test_2teardown_function()setup_class(self)test_A test_Bteardown_class(self)teardown_module
main方法中的-q,爲pytest打印測試用例的執行結果級別。
如不清楚,請移步到《Pytest學習(一)- 入門及基礎》。
本文分享自微信公衆號 - 軟件測試君(backlight2018),做者:糖小幽
原文出處及轉載信息見文內詳細說明,若有侵權,請聯繫 yunjia_community@tencent.com 刪除。
原始發表時間:2020-10-22
本文參與騰訊雲自媒體分享計劃,歡迎正在閱讀的你也加入,一塊兒分享。