pytest测试框架

一、命名规则

1.模块名必须以test_开头或者以_test结尾
2.测试类必须以Test开头,并且不能有init方法
3.测试方法必须以test开头

二、运行方式

1.主函数模式

(1)运行所有:pytest.main()
(2)指定模块:pytest.main(['-vs','test_login.py'])
(3)指定目录:pytest.main(['-vs', ,'./interface_testcase'])
(4)通过nodeid指定用例运行:nodeid由模块名,分隔符,类名,方法名,函数名组成
pytest.main(['-vs','./interface_testcase/test_interface.py::TestInterface::test_01_zhihu'])

2.命令行模式
(1)运行所有:pytest
(2)指定模块:pytest -vs test_login.py
(3)指定目录:pytest -vs ./interface_testcase
(4)pytest -vs ./interface_testcase/test_interface.py::TestInterface::test_01_zhihu

3.通过pytest.ini配置文件运行,
(1)放置在根目录
(2)编码,ANSI
(3)作用:改变pytest默认行为
(4)运行规则:

[pytest]
addopts = -vs
testpaths = ./appautotest
python_files = test_*.py
python_classes = Test*
python_functions = test
markers =
    usermanage:用户管理模块
    schedulemanage:日程管理模块

参数详解:
-s:表示输出调试信息,包括print打印信息
-v:显示更详细信息
-vs:组合使用
-n 3:多线程执行
--reruns 3:失败重试
-x:一个用例报错,测试停止
--maxfail=2:两个用例失败,测试停止
-k:跟进方法的部分字符串指定测试用例

2.测试用例执行顺序

1.@pytest.mark.run指定执行顺序

@pytest.mark.run(order=1)

3.分组执行

配置文件markers指定组名

#在pytest.ini 配置文件中指定
@pytest.mark.usermanage

pytest -m "usermanage or ..."

4.跳过执行

#无条件跳过
    @pytest.mark.skip(reason="")

#有条件跳过
    @pytest.mark.skipif(age >= 19, reason="" )

5.生成测试报告

#默认测试报告 指定文件路径
addopts = -vs --html ./appautotest/reporter

6.前后置操作

setup和teardown的前后置操作,有一定的局限性,只能在每个function和class执行;

    # 打开软件
    def setup(self):
        d.app_start('cn.styd.management_app')

  # 关闭软件
    def teardown(self):      
        d.app_stop("cn.styd.management_app")

    def setup_class(self):
        print("start")

    def teardown_class(self):
        print("end")

相比较装饰器fixture显得更加灵活,定义一个方法,加上装饰器@pytest.fixture,该装饰器有以下几个参数

#  作用域``"function"`` (default), ``"class"``, ``"module"``
# scope="function",
#  参数类型 list, set, list(字典),set(字典),类似于参数化传递
# params=['1', '2', '3'],
# 是否自动执行,默认false,当为true时功能和setup,teardown类似,每个方法都会执行
# autouse=False,
# ids=None,
# 别名
# name=None




@pytest.fixture(scope='function', autouse=False, params=['1', '2', '3'])
def my_fixture():
    # 前置操作

    d.app_start('cn.styd.management_app')

    # 后置操作
    yield
    d.app_stop('cn.styd.management_app')


class TestMember:
    def test_sales_sea_pool_num_correct(self, my_fixture):
        # 可以接受fixture传递的参数
        print("这是执行的第" + str(my_fixture) + '次')
        assert in_total_num == out_total_num

7.生成allure测试报告

addopts = -vs --alluredir ./temp  # temp目录下生成.json的临时报告
testpaths = ./appautotest
python_files = *_test.py
python_classes = Test*
python_functions = test
import os
import pytest
if __name__ == '__main__':
    pytest.main()
#j将./temp目录下的临时报告,生成正式报告至reporter目下,--clean同时清空reporter目录
    os.system('allure generate ./temp -o ./reporter --clean')

问题:allure 命令在cmd中可以执行成功,在pycharm中运行报错,无法将“allure”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后重试。

解决:cmd中可执行,证明环境变量肯定是设置了的,当时path的allure的路径设置的是D盘,实在没有找到什么原因,就试着换成C盘,结果解决了。具体原因需要再找找

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容