python - 如何自动更改为所有doctests的pytest临时目录

标签 python testing pytest doctest

我想在每个 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。


此外,您还可以打个断点,查看fixture中request.node.dtest的内容。这样,您可以向文档字符串或 doctest 行添加可选的注释/标记,并相应地进行操作:

(Pdb++) pp request.node.dtest.docstring
"\n    >>> 2+3\n    5\n    >>> os.getcwd().startswith('/private/')\n    True\n    "

(Pdb++) pp request.node.dtest.examples[0].source
'2+3\n'
(Pdb++) pp request.node.dtest.examples[0].want
'5\n'

(Pdb++) pp request.node.dtest.examples[1].source
"os.getcwd().startswith('/private/')\n"
(Pdb++) pp request.node.dtest.examples[1].want
'True\n'
(Pdb++) pp request.node.dtest.examples[1].exc_msg
None

关于python - 如何自动更改为所有doctests的pytest临时目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46962007/

相关文章:

python - 如何安装 py.test-2.3?

python - 发布 Jupyter Notebook html 笔记

javascript - 在 Firefox 中记录并稍后回放 DOM 更改?

python - pytest从不同的测试文件独立导入同一模块

Python如何用字典中的值替换一个列表中的值?

python - Shutil.move 是否保证删除或抛出?

java - 如何测试基于 jline 的控制台应用程序

ruby-on-rails - 没有特定差异值的 rails assert_difference

python - 这 3 个 pytest 装置的功能差异是什么?

python - Django force_login 没有登录 Django 客户端?