朝阳区手机网站制作服务,企业年金一般交多少钱,免费网页游戏平台,微推客1. cacheprovider插件 1.1. --lf, --last-failed#xff1a;只执行上一轮失败的用例1.2. --ff, --failed-first#xff1a;先执行上一轮失败的用例#xff0c;再执行其它的1.3. --nf, --new-first#xff1a;先执行新加的或修改的用例#xff0c;再执行其它的1.4. --cache…1. cacheprovider插件 1.1. --lf, --last-failed只执行上一轮失败的用例1.2. --ff, --failed-first先执行上一轮失败的用例再执行其它的1.3. --nf, --new-first先执行新加的或修改的用例再执行其它的1.4. --cache-clear先清除所有缓存再执行用例1.5. 如果上一轮没有失败的用例 2. config.cache对象3. Stepwise
pytest会将本轮测试的执行状态写入到.pytest_cache文件夹这个行为是由自带的cacheprovider插件来实现的 注意 pytest默认将测试执行的状态写入到根目录中的.pytest_cache文件夹我们也可以通过在pytest.ini中配置cache_dir选项来自定义缓存的目录它可以是相对路径也可以是绝对路径 相对路径指的是相对于pytest.ini文件所在的目录例如我们把这一章的缓存和源码放在一起 在src/chapter-12/pytest.ini中添加如下配置 [pytest]
cache_dir .pytest-cache这样即使我们在项目的根目录下执行src/chapter-12/中的用例也只会在pytest-chinese-doc/src/chapter-12/.pytest_cache中生成缓存而不再是pytest-chinese-doc/.pytest_cache中 pytest-chinese-doc (5.1.3)
λ pytest src/chapter-121. cacheprovider插件
在介绍这个插件之前我们先看一个简单例子
# src/chapter-12/test_failed.pyimport pytestpytest.mark.parametrize(num, [1, 2])
def test_failed(num):assert num 1# src\chapter-12\test_pass.pydef test_pass():assert 1我们有两个简单的测试模块首先我们来执行一下它们
λ pytest -q src/chapter-12/
.F. [100%] FAILURES
____________________________ test_failed[2] _____________________________num 2pytest.mark.parametrize(num, [1, 2])def test_failed(num):assert num 1
E assert 2 1src\chapter-12\test_failed.py:27: AssertionError
1 failed, 2 passed in 0.08s可以看到一共收集到三个测试用例其中有一个失败另外两个成功的并且两个执行成功的用例分属不同的测试模块
同时pytest也在src/chapter-12/的目录下生成缓存文件夹.pytest_cache具体的目录结构如下所示
src
├───chapter-12
│ │ pytest.ini # 配置了 cache_dir .pytest-cache
│ │ test_failed.py
│ │ test_pass.py
│ │
│ └───.pytest-cache
│ │ .gitignore
│ │ CACHEDIR.TAG
│ │ README.md
│ │
│ └───v
│ └───cache
│ lastfailed
│ nodeids
│ stepwise现在我们就结合上面的组织结构具体介绍一下cacheprovider插件的功能
1.1. --lf, --last-failed只执行上一轮失败的用例
缓存中的lastfailed文件记录了上次失败的用例ID我们可以通过一下--cache-show命令查看它的内容 --cache-show命令也是cacheprovider提供的新功能它不会导致任何用例的执行 λ pytest src/chapter-12/ -q --cache-show lastfailed
cachedir: D:\Personal Files\Projects\pytest-chinese-doc\src\chapter-12\.pytest-cache
--------------------- cache values for lastfailed ---------------------
cache\lastfailed contains:{test_failed.py::test_failed[2]: True}no tests ran in 0.01s我们可以看到它记录了一个用例为上次失败的测试用例的IDtest_failed.py::test_failed[2]
下次执行时当我们使用--lf选项pytest在收集阶段只会选择这个失败的用例而忽略其它的
λ pytest --lf --collect-only src/chapter-12/test session starts
platform win32 -- Python 3.7.3, pytest-5.1.3, py-1.8.0, pluggy-0.13.0
cachedir: .pytest-cache
rootdir: D:\Personal Files\Projects\pytest-chinese-doc\src\chapter-12, inifile: pytest.ini
collected 2 items / 1 deselected / 1 selected
Module test_failed.pyFunction test_failed[2]
run-last-failure: rerun previous 1 failure (skipped 2 files) 1 deselected in 0.02s 我们仔细观察一下上面的回显有一句话可能会让我们有点困惑collected 2 items / 1 deselected / 1 selected可我们明明有三个用例怎么会只收集到两个呢
实际上--lf复写了用例收集阶段的两个钩子方法pytest_ignore_collect(path, config)和pytest_collection_modifyitems(session, config, items)
我们来先看看pytest_ignore_collect(path, config)如果它的结果返回True就忽略path路径中的用例
# _pytest/cacheprovider.pydef last_failed_paths(self):Returns a set with all Paths()s of the previously failed nodeids (cached).try:return self._last_failed_pathsexcept AttributeError:rootpath Path(self.config.rootdir)result {rootpath / nodeid.split(::)[0] for nodeid in self.lastfailed}result {x for x in result if x.exists()}self._last_failed_paths resultreturn resultdef pytest_ignore_collect(self, path):Ignore this file path if we are in --lf mode and it is not in the list ofpreviously failed files.if self.active and self.config.getoption(lf) and path.isfile():last_failed_paths self.last_failed_paths()if last_failed_paths:skip_it Path(path) not in self.last_failed_paths()if skip_it:self._skipped_files 1return skip_it可以看到如果当前收集的文件不在上一次失败的路径集合内就会忽略这个文件所以这次执行就不会到test_pass.py中收集用例了故而只收集到两个用例并且pytest.ini也在忽略的名单上所以实际上是跳过两个文件(skipped 2 files)
至于pytest_collection_modifyitems(session, config, items)钩子方法我们在下一节和--ff命令一起看
1.2. --ff, --failed-first先执行上一轮失败的用例再执行其它的
我们先通过实践看看这个命令的效果再去分析它的实现
λ pytest --collect-only -s --ff src/chapter-12/test session starts
platform win32 -- Python 3.7.3, pytest-5.1.3, py-1.8.0, pluggy-0.13.0
cachedir: .pytest-cache
rootdir: D:\Personal Files\Projects\pytest-chinese-doc\src\chapter-12, inifile: pytest.ini
collected 3 items
Module test_failed.pyFunction test_failed[2]Function test_failed[1]
Module test_pass.pyFunction test_pass
run-last-failure: rerun previous 1 failure first no tests ran in 0.02s 我们可以看到一共收集到三个测试用例和正常的收集顺序相比上一轮失败的test_failed.py::test_failed[2]用例在最前面将优先执行
实际上-ff只复写了钩子方法pytest_collection_modifyitems(session, config, items)它可以过滤或者重新排序收集到的用例
# _pytest/cacheprovider.pydef pytest_collection_modifyitems(self, session, config, items):...if self.config.getoption(lf):items[:] previously_failedconfig.hook.pytest_deselected(itemspreviously_passed)else: # --failedfirstitems[:] previously_failed previously_passed...可以看到如果使用的是lf就把之前成功的用例状态置为deselected这轮执行就会忽略它们如果使用的是-ff只是将之前失败的用例顺序调到前面
另外我们也可以看到lf的优先级要高于ff所以它们同时使用的话ff是不起作用的
1.3. --nf, --new-first先执行新加的或修改的用例再执行其它的
缓存中的nodeids文件记录了上一轮执行的所有的用例
λ pytest src/chapter-12 --cache-show nodeidstest session starts
platform win32 -- Python 3.7.3, pytest-5.1.3, py-1.8.0, pluggy-0.13.0
cachedir: .pytest-cache
rootdir: D:\Personal Files\Projects\pytest-chinese-doc\src\chapter-12, inifile: pytest.ini
cachedir: D:\Personal Files\Projects\pytest-chinese-doc\src\chapter-12\.pytest-cache
---------------------- cache values for nodeids -----------------------
cache\nodeids contains:[test_failed.py::test_failed[1],test_failed.py::test_failed[2],test_pass.py::test_pass] no tests ran in 0.01s 我们看到上一轮共执行了三个测试用例
现在我们在test_pass.py中新加一个用例并修改一下test_failed.py文件中的用例但是不添加新用例
# src\chapter-12\test_pass.pydef test_pass():assert 1def test_new_pass():assert 1现在我们再来执行一下收集命令
λ pytest --collect-only -s --nf src/chapter-12/test session starts
platform win32 -- Python 3.7.3, pytest-5.1.3, py-1.8.0, pluggy-0.13.0
cachedir: .pytest-cache
rootdir: D:\Personal Files\Projects\pytest-chinese-doc\src\chapter-12, inifile: pytest.ini
collected 4 items
Module test_pass.pyFunction test_new_pass
Module test_failed.pyFunction test_failed[1]Function test_failed[2]
Module test_pass.pyFunction test_pass no tests ran in 0.03s 可以看到新加的用例顺序在最前面其次修改过的测试用例紧接其后最后才是旧的用例这个行为在源码中有所体现
# _pytest/cacheprovider.pydef pytest_collection_modifyitems(self, session, config, items):if self.active:new_items OrderedDict()other_items OrderedDict()for item in items:if item.nodeid not in self.cached_nodeids:new_items[item.nodeid] itemelse:other_items[item.nodeid] itemitems[:] self._get_increasing_order(new_items.values()) self._get_increasing_order(other_items.values())self.cached_nodeids [x.nodeid for x in items if isinstance(x, pytest.Item)]def _get_increasing_order(self, items):return sorted(items, keylambda item: item.fspath.mtime(), reverseTrue)item.fspath.mtime()代表用例所在文件的最后修改时间reverseTrue表明是倒序排列
items[:] self._get_increasing_order(new_items.values()) self._get_increasing_order(other_items.values())保证新加的用例永远在最前面
1.4. --cache-clear先清除所有缓存再执行用例
直接看源码
# _pytest/cacheprovider.pyclass Cache:... classmethoddef for_config(cls, config):cachedir cls.cache_dir_from_config(config)if config.getoption(cacheclear) and cachedir.exists():rm_rf(cachedir)cachedir.mkdir()return cls(cachedir, config)可以看到它会先把已有的缓存文件夹删除rm_rf(cachedir)再创建一个空的同名文件夹cachedir.mkdir()这样会导致上述的功能失效所以一般不使用这个命令
1.5. 如果上一轮没有失败的用例
现在我们清除缓存再执行test_pass.py模块它的用例都是能测试成功的
λ pytest --cache-clear -q -s src/chapter-12/test_pass.py
.
1 passed in 0.01s这时候我们再去看一下缓存目录
.pytest-cache
└───v└───cachenodeidsstepwise是不是少了什么对因为没有失败的用例所以不会生成lastfailed文件那么这个时候在使用--lf和--ff会发生什么呢我们来试试 注意 如果我们观察的足够仔细就会发现现在的缓存目录和之前相比不止少了lastfailed文件还少了CACHEDIR.TAG、.gitignore和README.md三个文件 这是一个bug我已经在pytest 5.3.1版本上提交了issue预计会在之后的版本修复如果你有兴趣深入了解一下它的成因和修复方案可以参考这个https://github.com/pytest-dev/pytest/issues/6290 luyaoNJ-LUYAO-T460 /d/Personal Files/Projects/pytest-chinese-doc (5.1.3)
λ pytest -q -s --lf src/chapter-12/test_pass.py
.
1 passed in 0.01sluyaoNJ-LUYAO-T460 /d/Personal Files/Projects/pytest-chinese-doc (5.1.3)
λ pytest -q -s --ff src/chapter-12/test_pass.py
.
1 passed in 0.02s可以看到它们没有实施任何影响为什么会这样我们去源码里找一下答案吧
# _pytest/cacheprovider.pyclass LFPlugin: Plugin which implements the --lf (run last-failing) option def __init__(self, config):...self.lastfailed config.cache.get(cache/lastfailed, {})...def pytest_collection_modifyitems(self, session, config, items):...if self.lastfailed:...else:self._report_status no previously failed tests, if self.config.getoption(last_failed_no_failures) none:self._report_status deselecting all items.config.hook.pytest_deselected(itemsitems)items[:] []else:self._report_status not deselecting items.可以看到当self.lastfailed判断失败时如果我们指定了last_failed_no_failures选项为nonepytest会忽略所有的用例items[:] []否则不做任何修改和没加--lf或--ff一样而判断self.lastfailed的依据是就是lastfailed文件
继续看看我们会学习到一个新的命令行选项
# _pytest/cacheprovider.pygroup.addoption(--lfnf,--last-failed-no-failures,actionstore,destlast_failed_no_failures,choices(all, none),defaultall,helpwhich tests to run with no previously (known) failures.,)来试试吧
λ pytest -q -s --ff --lfnf none src/chapter-12/test_pass.py1 deselected in 0.01sλ pytest -q -s --ff --lfnf all src/chapter-12/test_pass.py
.
1 passed in 0.01s注意 --lfnf的实参只支持choices(all, none) 2. config.cache对象
我们可以通过pytest的config对象去访问和设置缓存中的数据下面是一个简单的例子
# content of test_caching.pyimport pytest
import timedef expensive_computation():print(running expensive computation...)pytest.fixture
def mydata(request):val request.config.cache.get(example/value, None)if val is None:expensive_computation()val 42request.config.cache.set(example/value, val)return valdef test_function(mydata):assert mydata 23我们先执行一次这个测试用例
λ pytest -q src/chapter-12/test_caching.py
F [100%]FAILURES
______________________________ test_function ______________________________mydata 42def test_function(mydata):assert mydata 23
E assert 42 23src/chapter-12/test_caching.py:43: AssertionError
-------------------------- Captured stdout setup --------------------------
running expensive computation...
1 failed in 0.05s这个时候缓存中没有example/value将val的值写入缓存终端打印running expensive computation...
查看缓存其中新加了一个文件.pytest-cache/v/example/value
.pytest-cache/
├── .gitignore
├── CACHEDIR.TAG
├── README.md
└── v├── cache│ ├── lastfailed│ ├── nodeids│ └── stepwise└── example└── value3 directories, 7 files通过--cache-show选项查看发现其内容正是42
λ pytest src/chapter-12/ -q --cache-show example/value
cachedir: /Users/yaomeng/Private/Projects/pytest-chinese-doc/src/chapter-12/.pytest-cache
-------------------- cache values for example/value ---------------------
example/value contains:42no tests ran in 0.00s再次执行这个用例这个时候缓存中已经有我们需要的数据了终端就不会再打印running expensive computation...
λ pytest -q src/chapter-12/test_caching.py
F [100%]FAILURES
______________________________ test_function ______________________________mydata 42def test_function(mydata):assert mydata 23
E assert 42 23src/chapter-12/test_caching.py:43: AssertionError
1 failed in 0.04s3. Stepwise
试想一下现在有这么一个场景我们想要在遇到第一个失败的用例时退出执行并且下次还是从这个用例开始执行
以下面这个测试模块为例
# src/chapter-12/test_sample.pydef test_one():assert 1def test_two():assert 0def test_three():assert 1def test_four():assert 0def test_five():assert 1我们先执行一下测试pytest --cache-clear --sw src/chapter-12/test_sample.py
λ pytest --cache-clear --sw -q src/chapter-12/test_sample.py
.FFAILURES
_________________________________ test_two _________________________________def test_two():assert 0
E assert 0src/chapter-12/test_sample.py:28: AssertionError
!!!!!! Interrupted: Test failed, continuing from this test next run. !!!!!!!
1 failed, 1 passed in 0.13s使用--cache-clear清除之前的缓存使用--sw, --stepwise使其在第一个失败的用例处退出执行
现在我们的缓存文件中lastfailed记录了这次执行失败的用例即为test_two()nodeids记录了所有的测试用例特殊的是stepwise记录了最近一次失败的测试用例这里也是test_two()
接下来我们用--sw的方式再次执行pytest首先会读取stepwise中的值并将其作为第一个用例开始执行
λ pytest --sw -q src/chapter-12/test_sample.py
FFAILURES
_________________________________ test_two _________________________________def test_two():assert 0
E assert 0src/chapter-12/test_sample.py:28: AssertionError
!!!!!! Interrupted: Test failed, continuing from this test next run. !!!!!!!
1 failed, 1 deselected in 0.12s可以看到test_two()作为第一个用例开始执行在第一个失败处退出
其实pytest还提供了一个--stepwise-skip的命令行选项它会忽略第一个失败的用例在第二个失败处退出执行我们来试一下
λ pytest --sw --stepwise-skip -q src/chapter-12/test_sample.py
F.FFAILURES
_______________________________ test_two ________________________________def test_two():assert 0
E assert 0src\chapter-12\test_sample.py:28: AssertionError
_______________________________ test_four _______________________________def test_four():assert 0
E assert 0src\chapter-12\test_sample.py:36: AssertionError
!!!!! Interrupted: Test failed, continuing from this test next run. !!!!! 2 failed, 1 passed, 1 deselected in 0.16s这个时候在第二个失败的用例test_four()处退出执行同时stepwise文件的值也改成了test_sample.py::test_four 其实本章所有的内容都可以在源码的_pytest/cacheprovider.py文件中体现如果能结合源码学习会有事半功倍的效果