‘‘‘ https://learning-pytest.readthedocs.io/zh/latest/index.html ‘‘‘
‘‘‘ 在pycharm终端输入 pip3 install pytest==5.4.3 验证是否安装是否成功? 再次输入pytest,出现python及pytest版本号,就说明安装成功了 ‘‘‘
‘‘‘ 1 当前目录搜索以test_开头或者_test结尾的文件 test_01.py login_test.py 2 测试函数以及测试方法是以test开头 def testlogin(): assert 1==1 不符合要求: def logintest(): assert 3==3 3 测试类必须是Test开头 class Test_Login(): def test_login_01(self): assert 2==2 不符合要求: class Login_Test(): def test_login_02(self): assert 4==4 ‘‘‘
‘‘‘ --help: -v:可以输出用例更加详细的执行信息 -s: 输出用例中的调试信息,比如print等打印信息 --collect-only:列出当前目录下所有的测试模块,测试类及测试函数 -k: 执行用例中包含“关键字”的用例 -m: 根据标记执行特定的测试用例(@pytest.mark.xxx加上装饰器>>>pytest -m xxx) and>>>@pytest.mark.login/@pytest.mark.exit这两个装饰器在同一个测试用例可以用and>>>pytest -m "login and exit" or>>>pytest -m "login or exit">>>执行包含login或exit的装饰器 not>>>pytest -m "login not exit">>>执行login但不包括exit的装饰器 -x: 用例失败后立刻停止,后续的用例也不执行了 --maxfail=num: 指定失败num次后停止(从上往下执行用例,如果失败num次就停止,小于num则继续运行剩下的用例) --durations=num: 当num等于0时,可以打印出所有用例接口所消耗时间;当num=3(不一定要等于3)时,打印出接口耗时最长的3条用例信息 requests库中,requests.get(url=‘xxx‘).elapsed.total_seconds(),可以统计出一个接口所消耗时间 -q: 简化控制台的输出 --tb=style(style可以是:no,line,short) 屏蔽测试用例执行输出的回溯信息,可以简化用例失败时的输出信息 运行指定的测试类:pytest test_cc/m1_test.py::TestClass -v 运行指定的测试方法:pytest test_cc/test_m2.py::test_three -v 学习博客地址:https://www.cnblogs.com/pipile/p/12696425.html ‘‘‘
‘‘‘ 单独运行一个包 pytest -v logins/ 单独运行一个模块 pytest -v logins/test_01.py 单独运行一个模块下的一个方法用例(单个def) pytest -v logins/test_01.py::test_login_01 单独运行一个模块下的一个类下的一个方法用例(class下的def) pytest -v logins/test_01.py::Test_Login::test_login_02 ‘‘‘
‘‘‘ assert是python中原生断言,但是pytest中的assert会帮你把错误信息找出来,加上-v参数可以看到更详细的错误信息 in判断(成员运算符,字符串也可以使用) ==判断(在python中,==是表示值和类型都要相等) eg: import requests import pytest def test_login(): dict1 = { ‘loginName‘:‘‘, ‘password‘:"123456", ‘rand‘: "1234", ‘randCode‘: "1234", ‘roleFrom‘: "1" } r = requests.post(url=‘http://82.157.33.124:2088/v1/manager/user/login‘, json=dict1) assert ‘账号不能为空‘ == r.json()[‘msg‘] ‘‘‘
‘‘‘ 跳过测试(@pytest.mark.skip(reason=‘说明原因‘)) import pytest @pytest.mark.skip(reason=‘该功能暂时取消,此测试用例忽略执行‘) def test_login_phone_001(): assert 1==1 @pytest.mark.skip(reason=‘该功能暂时取消,此测试用例忽略执行‘) def test_login_phone_002(): assert 2==2 def test_login_email_001(): assert 3==3 结果: test_01.py::test_login_phone_001 SKIPPED test_01.py::test_login_phone_002 SKIPPED test_01.py::test_login_email_001 PASSED 预期失败测试(@pytest.mark.xfail(reason=‘说明原因‘)) import pytest import requests @pytest.mark.xfail(reason=‘期望返回状态码200,实际是1001‘) def test_login(): dict1 = { ‘loginName‘:‘‘, ‘password‘:"123456", ‘rand‘: "1234", ‘randCode‘: "1234", ‘roleFrom‘: "1" } r = requests.post(url=‘http://82.157.33.124:2088/v1/manager/user/login‘, json=dict1) assert r.status_code==200 结果: test_01.py::test_login XPASS ‘‘‘
原文:https://www.cnblogs.com/xuewei95/p/15129727.html