1、pytest 简述
pytest是python的单元测试框架,类似于python自带的unittest测试框架。
相比unittest使用简洁、效率更高。
-
pytest通过装饰器@pytest.mark.parametrize来实现参数化
-
pytest支持很多插件,比如失败重新执行、控制用例执行顺序、测试报告插件
-
pytest 通过pytest-html生成html格式报告,或者通过allure生成方案
-
执行测试过程中可以将某些测试跳过,或者对某些预期失败的case标记为失败
-
方便和持续集成工具集成
1.1、pytest示例:
import pytest
def test_a():
print("aaa")
assert 1
def test_b():
print('bbb')
assert 0
if __name__ == '__main__':
pytest.main(['./test.py'])
- 不需要创建测试类,直接编写测试函数也ok
- 测试函数名,必须以test开头
- ‘./test.py’是test文件的相对地址
1.2、setup和teardown函数
- 模块级别,对整个py文件起作用
setup_module / teardown_module - 类级别,对测试类作用
setup_class/teardown_class - 函数级别,对测试用例作用(不在测试类中)
setup_function / teardown_function - 方法级别,对测试类中的测试用例作用(在测试类中)
setup_method /teardown_method
如下:
在测试类Test执行前,先执行setup_class(初始化浏览器的一些操作),在测试类Test执行后,再执行teardown_class(关闭浏览器操作)
此例还可用在连接数据、库获得数据库权柄,以及关闭数据库连接的场景中
import pytest
class Test(object):
@classmethod
def setup_class(cls):
print("初始化浏览器")
cls.driver=webdriver.Chrome()
cls.driver.maximize_window()
time.sleep(2)
cls.driver.get("http://www.baidu.com")
@classmethod
def teardown_class(cls):
cls.driver.close()
print("关闭浏览器")
def test_in01(self):
self.driver.find_element_by_id(