【pytest】安装、编写用例、运行用例

安装pytest:

命令行:pip install pytest

Pycharm:File | Settings | Project: xxx| Project Interpreter,点击 + 号,搜索 pyteset,点击左下角 install package

编写测试用例:

测试用例编写规则:

1. 测试用例文件名(.py文件)必须以 “test_” 开头或者以 “test” 结尾;

2. 测试类的类名必须以 “Test” 开头,且测试类不能有 __init__() 方法;

3. 测试方法的方法名必须以 “test" 开头;

# test_moduleName.py  测试模块名

class TestClassName:
    """测试类"""

    def test_func_name(self):
        """测试方法"""
        # 用例内容
        pass

运行测试用例:

命令行参数:

运行指定的测试用例:

  1.  pytest :                                                                   执行所有符合 pytest 用例编写规则的所有测试用例;
  2.  pytest testPackages :                                             执行 testPackages 包中所有的测试用例;
  3.  pytest test_moduleName.py :                                执行 testPackages 模块中所有的测试用例;
  4.  pytest test_moduleName.py::TestClassName :     执行 testPackages 模块 TestClassName 类中所有的测试方法;
  5.  pytest test_moduleName.py::TestClassName ::test_func_name :只执行 test_func_name 用例;

通过 -m 运行标记测试用例:

  1.  pyetst -m xxx :运行所有标记为 xxx 的测试用例,可以标记测试类或测试方法,并且支持 and、or、not 等表达式;

通过 -k模糊匹配 运行测试用例:

  1.  pytest -k 'xxx' :运行名字包含 xxx 的测试方法或测试类,也支持 and、or、not 等表达式;

通过python代码的方式运行:

pytest.main(args, plugins) :

  •     args 参数:    相当于命令行使用的参数,多个参数以列表的方式提交,列表内的每个元素代表一个命令行参数;
  •     plugins 参数:运行pytest 时使用的插件,也可以是列表(同 args 参数);
# main.py

import pytest

# 相当于命令行:pytest -m smoke -s -v
# 未使用 plugins 参数
pytest.main([
    '-m smoke',  # 运行标记为 smoke 的用例
    '-s',        # 显示标准输出
    '-v'         # 显示详细报告
])
  • 注意事项 :调用pytest.main()将会导入所有测试用例及其导入的其他模块;由于python导入系统的缓存机制,从同一进程后续调用pytest.main()不会反映调用之间对这些文件的更改;因此,不建议从同一进程(例如,为了重新运行测试)多次调用pytest.main();
发布了44 篇原创文章 · 获赞 23 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/waitan2018/article/details/104021131
今日推荐