Pytest 源码分析

测试脚本 test_demo.py

import pytest

class TestDemo():
    def test_01(self):
        print 111111

    def test_02(self):
        print 2222222
 
if __name__ == '__main__':
    pytest.main() #执行测试

运行该测试脚本,会发生什么?运行原理是?
首先会

import pytest

通过pytest.py 文件,发现主要是:
①将_pytest中导入后续所需要的包和模块
②从_pytest中compat.py 导入该方法 _setup_collect_fakemodule,并运行该方法_setup_collect_fakemodule。

# -*- coding: utf-8 -*-
# PYTHON_ARGCOMPLETE_OK
"""
pytest: unit and functional testing with Python.
"""
# else we are imported
from _pytest import __version__
from _pytest.assertion import register_assert_rewrite
from _pytest.config import cmdline
from _pytest.config import hookimpl
.......
.......

if __name__ == "__main__":
    # if run as a script or by 'python -m pytest'
    # we trigger the below "else" condition by the following import
    import pytest

    raise SystemExit(pytest.main())
else:

    from _pytest.compat import _setup_collect_fakemodule

    _setup_collect_fakemodule()

step2 :
看一下compat.py文件中的_setup_collect_fakemodule方法

def _setup_collect_fakemodule():
    from types import ModuleType
    import pytest

    pytest.collect = ModuleType("pytest.collect")
    pytest.collect.__all__ = []  # used for setns
    for attribute in COLLECT_FAKEMODULE_ATTRIBUTES:
        setattr(pytest.collect, attribute, getattr(pytest, attribute))

pytest.main()
main() 函数就是_pytest/config/init.py 中定义的全局函数 main() 函数


def main(args=None, plugins=None):
    """ return exit code, after performing an in-process test run.

    :arg args: list of command line arguments.

    :arg plugins: list of plugin objects to be auto-registered during
                  initialization.
    """
    from _pytest.main import EXIT_USAGEERROR

    try:
        try:
            config = _prepareconfig(args, plugins)
        except ConftestImportFailure as e:
            exc_info = ExceptionInfo(e.excinfo)
            tw = py.io.TerminalWriter(sys.stderr)
            tw.line(
                "ImportError while loading conftest '{e.path}'.".format(e=e), red=True
            )
            exc_info.traceback = exc_info.traceback.filter(filter_traceback)
            exc_repr = (
                exc_info.getrepr(style="short", chain=False)
                if exc_info.traceback
                else exc_info.exconly()
            )
            formatted_tb = safe_str(exc_repr)
            for line in formatted_tb.splitlines():
                tw.line(line.rstrip(), red=True)
            return 4
        else:
            try:
                return config.hook.pytest_cmdline_main(config=config)
            finally:
                config._ensure_unconfigure()
    except UsageError as e:
        tw = py.io.TerminalWriter(sys.stderr)
        for msg in e.args:
            tw.line("ERROR: {}\n".format(msg), red=True)
        return EXIT_USAGEERROR

通过获取config 对象;后通过执行config.hook.pytest_cmdline_main执行测试

config = _prepareconfig(args, plugins)

通过_prepareconfig函数,该函数返回的就是config对象,该对象通过函数pluginmanager.hook.pytest_cmdline_parse返回

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
pytest源码是一个用于收集和执行测试用例的工具。它可以通过指定相关配置和命令来定制测试的收集过程。在给定的引用中,我们可以看到一些关于如何收集用例的配置。 在中,pytest.ini文件中的addopts选项指定了一些命令行选项,如"-vs"表示输出详细信息,"-m"后面的"smoke"表示只运行标记为"smoke"的测试用例。testpaths指定了测试用例的路径,python_files、python_classes和python_functions则分别指定了测试文件、测试类和测试函数的命名规则。 在中,我们看到了一个示例测试用例函数test_new(),它用于测试一个加法操作。在这个例子中,我们可以看到使用了pytest.main()函数来执行测试用例,并通过传递命令行参数来定制测试执行过程。 所以,根据给定的引用内容,pytest源码可以根据配置文件和命令行参数来收集和执行测试用例。通过配置文件中的相关选项,可以指定要收集的测试文件、类和函数的命名规则,并可以通过命令行参数来进一步定制测试执行的方式。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Pytest框架测试用例规则和运行方式](https://blog.csdn.net/weixin_37600187/article/details/128332154)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [【温故知新】pytest框架执行用例并打印日志和报告](https://blog.csdn.net/qq_17195161/article/details/126322450)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值