前言:

  上一篇pytest文档2 -- 用例的执行规则已经介绍了如何在cmd执行pytest用例,平常我们写代码在pycharm比较多

写完用例后,需要调试看看,是否正常运行,如果每次跑cmd执行,太麻烦,所以很有必要学习如何在pycharm里卖弄运行pytest用例

Pycharm运行的三种方式:

1、以xx.py脚本方式直接执行,当写的代码里面没有用到unittest 和pytest框架时,并且脚本名称不是以test开头命名的,此时pycharm’ 会以xx.py脚本方式运行

2、当脚本名为test_xx.py时,用到unitest框架,此时运行代码,pycharm会自动识别到以unittest方式运行

3、以pytest方式运行,需要改该工程默认的运行器,file->setting->Tools->Python Integrated Tools ->项目名称-> Default test runner -->选择 py.test

备注:pytest 是可以兼容unittest框架代码的。

 

pycharm 写pytest代码

1、在pycharm里面写pytest用例,要先导入pytest

# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : Test_class.py
# Time       :2021/11/16 19:39
# Author     :author Richard_kong
# version    :python 3.8
# Description:
"""
import pytest

class TestClass():
    def test_one(self):
        x = 'this'
        assert 'h' in x

    def test_two(self):
        x = 'hello'
        assert hasattr(x,'check')

    def test_three(self):
        a = 'hello'
        b = 'hello world'

        assert a in b


if __name__ == '__main__':
    pytest.main(['-s', 'test_class.py'])

  运行结果 .F. 点代表测试通过,F代表Fail的意思, pytest.main() 里面要传递的是 list,多个参数放在list中就不会有告警

pytest.main(['-q','test_class'])

pytest.main()的含义:

  每个项目都有入口文件用来启动项目,但是在自动化项目里,特别是unitest框架 在项目新建一个main.py 或者run_all.py文件 使用python main.py或者python run_all.py执行测试用例。

在pytest框架也有一个入口,那就是pytest.main(),可以作为用例执行入口,下面对pytest.main()进行讲解:

  

def main(
    args: Optional[Union[List[str], py.path.local]] = None,
    plugins: Optional[Sequence[Union[str, _PluggyPlugin]]] = None,
) -> Union[int, ExitCode]:
    """Perform an in-process test run.

    :param args: List of command line arguments.
    :param plugins: List of plugin objects to be auto-registered during initialization.

    :returns: An exit code.
    """
    try:
        try:
            config = _prepareconfig(args, plugins)
        except ConftestImportFailure as e:
            exc_info = ExceptionInfo(e.excinfo)
            tw = TerminalWriter(sys.stderr)
            tw.line(f"ImportError while loading conftest '{e.path}'.", red=True)
            exc_info.traceback = exc_info.traceback.filter(
                filter_traceback_for_conftest_import_failure
            )
            exc_repr = (
                exc_info.getrepr(style="short", chain=False)
                if exc_info.traceback
                else exc_info.exconly()
            )
            formatted_tb = str(exc_repr)
            for line in formatted_tb.splitlines():
                tw.line(line.rstrip(), red=True)
            return ExitCode.USAGE_ERROR
        else:
            try:
                ret: Union[ExitCode, int] = config.hook.pytest_cmdline_main(
                    config=config
                )
                try:
                    return ExitCode(ret)
                except ValueError:
                    return ret
            finally:
                config._ensure_unconfigure()
    except UsageError as e:
        tw = TerminalWriter(sys.stderr)
        for msg in e.args:
            tw.line(f"ERROR: {msg}\n", red=True)
        return ExitCode.USAGE_ERROR

  重点参数说明:args

param args: List of command line arguments
翻译:参数args:就是参数传入 以 列表的方式传入
main()命令行参数详情
-s: 显示程序中的print/logging输出
-v:丰富信息魔术,输出更详细的用例执行信息
-q:安静模式,不输出环境信息
-x:出现一条测试用例失败就退出测试。调试阶段非常有用
-k:可以使用 and not or 等逻辑运算符,区分:匹配方法(文件名、类名、函数名)

当不传入参数时,相当于执行命令 pytest **.py  来执行测试用例

当 输入参数 -s -v -x时 相当于命令行输入 pytest -s -v -x
pytest.main(['-s','-v','-x'])

Pycharm设置pytest
1、新建一个工程后,左上角file -> setting -> tools-> python  integrated Tools->项目名称-> Default test runer -> 选择py.test

pytest 输出如何保存到日志中 pytest怎么运行_用例

 

 

改完之后,再重新建个脚本(注意是先改项目运行方式,再写代码才能出来),接下来右键运行就能出来pytest运行了

pytest 输出如何保存到日志中 pytest怎么运行_pytest 输出如何保存到日志中_02

 

 pytest是可以兼容unitest脚本的,之前写的unittest用例也可以使用pytest框架来运行