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返回

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值