从文章标题能够看出,就是初始化和释放的操做,根据个人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
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一块儿分享。