Prerequisite: pytest and pytest-html need to be installed (to generate html test reports)
pip install pytest 和 pip install pytest-html
(1) Install pytest in pycharm: pip install pytest
(2) Install the test report package that comes with pytest: pip install pytest-html
1: Naming rules
Pytest单元测试中的类名和方法名必须是以test开头,执行中只能找到test开头的类和方法,
比unittest更加严谨
Unittest:Setup, setupclass , teardown , teardownclass
Pytest: setup, setup_class and teardown, teardown_class functions (same as unittest execution)
Run at the beginning and end of the test method, that is: running a test function will run setup and teardown once
Run at the beginning and end of the test method, but only execute setup_class and teardown_class once no matter how many test functions
2: Pytest generates its own html test report
Prerequisite: You need to download the pytest-html module (python's own module for generating test reports)
pip install pytest-html
Case number one
pytest.main("module.py")【Run under the specified module, run all classes and test cases beginning with test】
pytest.main(["--html=./report.html","模块.py"])
case two
Run the specified module, specify the class, specify the use case, separate with a colon, and generate a test report
pytest.main([‘--html=./report.html’,‘模块.py::类::test_a_001'])
case three
Execute pytest.main() directly [Automatically search for files starting with test or py files ending with test in the current directory ]
pytest.main([‘--html=./report.html’])
Pytest call statement
pytst.main(['-x','--html=./report.html','t12est000.py'])
注释:
-x出现一条测试用例失败就退出测试
-s:显示print内容
Expansion: Skip
Use @pytest.mark.skip() to skip the use case (function)
@pytest.mark.skip()
def test001(self):
assert 2==2
3: How Pytest works
. 点号,表示用例通过
F 表示失败 Failure
E 表示用例中存在异常 Error
4: File reading
4.1: Read csv file
import csv #导入csv模块
class ReadCsv():
def read_csv(self):
item =[] #定义一个空列表
c = csv.reader(open("../commonDemo/test1.csv","r")) #得到csv文件对象
for csv_i in c:
item.append(csv_i) #将获取的数据添加到列表中
return item
r = ReadCsv()
print(r.read_csv())
4.2: Read xml file
from xml.dom import minidom
class Readxml():
def read_xml(self,filename,onename,twoname):
root =minidom.parse(filename)
firstnode =root.getElementsByTagName(onename)[0]
secondnode=firstnode.getElementsByTagName(twoname)[0].firstChild.data
return secondnode
5:allure
Allure is a lightweight and very flexible open source test reporting framework. It supports most testing frameworks, such as TestNG, Pytest, JUint, etc. It's simple to use and easy to integrate.
(1) First configure the environment variable of allure: add the installation path of allure in the system variable path
(2) Verify that allure is configured successfully
Configured successfully:
Configuration failed:
(3) Install allure in pycharm: pip install allure-pytest (generate allure test report)
pip install allure-pytest
allure-pytest is a plug-in for Pytest, through which we can generate the data required by Allure for generating test reports
5.1: Several common features of Allure
@allure.feature # 用于描述被测试产品需求
@allure.story # 用于描述feature的用户场景,即测试需求
with allure.step(): # 用于描述测试步骤,将会输出到报告中
allure.attach # 用于向测试报告中输入一些附加的信息,通常是一些测试数据,截图等
5.1.1:allure.feature
@allure.feature # 用于描述被测试产品需求
5.1.2:allure.story
@allure.story # 用于描述feature的用户场景,即测试需求
the case
Realize the user login function, the scenario is login success and login failure
import pytest,allure,os
class TestClass005():
@allure.feature("用户登录功能")#用于定义被测试的功能,被测产品的需求点
@allure.story("登录成功") #用于定义被测功能的用户场景,即子功能点
def test_success(self):
assert 1==1
@allure.feature("用户登录功能")#用于定义被测试的功能,被测产品的需求点
@allure.story("登录失败") #用于定义被测功能的用户场景,即子功能点
def test_fail(self):
assert 1==2
if __name__ == '__main__':
pytest.main(['--alluredir', 'report/result', 'test1.py']) #生成json类型的测试报告
split = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean' #将测试报告转为html格式
os.system(split) # system函数可以将字符串转化成命令在服务器上运行
Pytest and allure effect display
5.1.3:with allure.step()
用于描述测试步骤,将会输出到报告中
5.1.4:allure.attach
用于向测试报告中输入一些附加的信息,通常是一些测试数据,截图等
the case
Realize product information display, various car brands in the auto show
import pytest,os,allure
class TestShop():
@allure.feature("购物车")
@allure.story("产品展示")
def testshow(self):
with allure.step("查看哈吉利系列车信息"):
allure.attach("博越","吉利")
with allure.step("查看哈弗系列车信息"):
allure.attach("H7","哈弗")
if __name__ == '__main__':
pytest.main(['--alluredir', 'report/result', 'test_07.py'])
split = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean'
os.system(split)
Pytest and allure effect display
6: Data-driven
foreword
When designing use cases, some use cases are only different in the input of parameter data. For example, the operation process of the login function is the same. If the use case repeatedly writes the operation process, the amount of code will increase. Corresponding to this kind of test case with multiple sets of data, the data-driven design pattern can be used. A set of data corresponds to a test case, and the use case is automatically loaded and generated.
6.1 Brief introduction of parameterized
pytest一个应用比较广泛的数据驱动框架就是 parameterized:
pytest.mark.parametrize是pytest 的内置装饰器
数据驱动的数据源可以是函数外的数据集合、CSV 文件、Excel 表格、TXT 文件,以及数据库等多种形式。
@pytest.mark.parametrize() 装饰器接收两个参数:
第一个参数以字符串的形式存在,表示用例函数的参数,假如测试函数函数有多个参数,则以逗号分开。
第二个参数用于保存测试数据。
假如只有一组数据,则以列表的形式存在如[0,1],如果有多组数据,以列表嵌套元组的形式存在(如[(0,1), (1,2)])
important point:
a.如果只有一组数据,以列表的形式存在;
b.如果有多组数据,以列表嵌套元组的形式存在(如 [0,1] 或者 [(0,1), (1,2)])
(1) A set of data
import pytest
from calcdemo.calc import Calc
c = Calc()
class TestCalcClass():
@pytest.mark.parametrize("num",[1,2])
def test001(self,num):
print(num)
if __name__ == '__main__':
pytest.main(["-s","test003.py"])
结果:
1
2
Multiple sets of data
import pytest
from calcdemo.calc import Calc
c = Calc()
class TestCalcClass():
@pytest.mark.parametrize("num1,num2",[(1,2),(3,4),(5,6)])
def test001(self,num1,num2):
print(num1,num2)
if __name__ == '__main__':
pytest.main(["-s","test003.py"])
输出:
1 2
3 4
5 6