关于ZAKER 融媒体解决方案 合作 加入

python- 如何为所有 doctest 自动更改为 pytest 临时 .

CocoaChina 11-11

我想在每个 doctest 的开头更改为 pytest 临时目录 , 我想知道是否有一种方法可以自动执行此操作 , 而无需以以下方式启动每个 doctest:

>>> tmp = getfixture ( 'tmpdir' ) >>> old = tmp.chdir ( )

最佳答案

一切都可行:

conftest.py:

import pytest@pytest.fixture ( autouse=True ) def _docdir ( request ) : # Trigger ONLY for the doctests. doctest_plugin = request.config.pluginmanager.getplugin ( "doctest" ) if isinstance ( request.node, doctest_plugin.DoctestItem ) : # Get the fixture dynamically by its name. tmpdir = request.getfuncargvalue ( 'tmpdir' ) # Chdir only for the duration of the test. with tmpdir.as_cwd ( ) : yield else: # For normal tests, we have to yield, since this is a yield-fixture. yield

test_me.py:

import os.path# Regular tests are NOT chdir'ed.def test_me ( ) : moddir = os.path.dirname ( __file__ ) assert os.getcwd ( ) == moddir

import_me.py:

import os, os.path# Doctests are chdir'ed.def some_func ( ) : """ >>> 2+3 5 >>> os.getcwd ( ) .startswith ( '/private/' ) True """ pass

希望这可以使您了解如何检测 doctest, 以及如何在测试期间临时 chdir.

此外 , 您还可以在设备中放置一个断点并调查 request.node.dtest 的内容 . 这样 , 您可以向文档字符串或文档测试行添加可选的注释 / 标记 , 并相应地执行以下操作:

( Pdb++ ) pp request.node.dtest.docstring" >>> 2+3 5 >>> os.getcwd ( ) .startswith ( '/private/' ) True " ( Pdb++ ) pp request.node.dtest.examples [ 0 ] .source'2+3' ( Pdb++ ) pp request.node.dtest.examples [ 0 ] .want'5' ( Pdb++ ) pp request.node.dtest.examples [ 1 ] .source"os.getcwd ( ) .startswith ( '/private/' ) " ( Pdb++ ) pp request.node.dtest.examples [ 1 ] .want'True' ( Pdb++ ) pp request.node.dtest.examples [ 1 ] .exc_msgNone

以上内容由"CocoaChina"上传发布 查看原文
相关标签 设备

觉得文章不错,微信扫描分享好友

扫码分享