2

我想在文件共享测试数据和/或函数中有几个 doctests。有没有办法在不将它们定位在外部文件或被测试文件的代码中的情况下做到这一点?

更新

"""This is the docstring for the module ``fish``.

I've discovered that I can access the module under test
  from within the doctest, and make changes to it, eg


>>> import fish
>>> fish.data = {1: 'red', 2: 'blue'}
"""

def jef():
    """
    Modifications made to the module will persist across subsequent tests:

    >>> import fish
    >>> fish.data[1]
    'red'
    """
    pass

def seuss():
    """
    Although the doctest documentation claims that
      "each time doctest finds a docstring to test,
       it uses a shallow copy of M‘s globals",
      modifications made to the module by a doctest
      are not imported into the context of subsequent docstrings:

    >>> data
    Traceback (most recent call last):
      ...
    NameError: name 'data' is not defined
    """
    pass

所以我猜想doctest复制一次模块,然后复制每个文档字符串的副本?

在任何情况下,将模块导入每个文档字符串似乎是有用的,如果尴尬的话。

我更愿意为此使用单独的命名空间,以避免意外践踏实际模块数据,这些数据将以可能未记录的方式导入或不会导入到后续测试中。

我突然想到(理论上)可以动态创建一个模块以包含这个命名空间。但是,到目前为止,我还没有从我不久前提出的问题中得到关于如何做到这一点的任何方向。任何信息都非常受欢迎!(作为对适当问题的回应)

在任何情况下,我都希望将更改直接传播到后续文档字符串的命名空间中。所以我最初的问题仍然存在,作为一个限定词。

4

2 回答 2

2

这就是导致人们远离 doctest 的原因:随着测试变得越来越复杂,您需要真正的编程工具来设计测试,就像设计产品代码一样。

我认为除了在产品代码中定义它们然后在 doctests 中使用它们之外,没有办法在 doctests 中包含共享数据或函数。

您将需要使用真实代码来定义一些测试基础设施。如果你喜欢 doctests,你可以使用你的 doctests 中的基础设施。

于 2010-07-20T03:12:22.353 回答
0

可能的,尽管可能没有大声宣传。

要获得具有所有使用共享执行上下文的测试的识字模块(即单个测试可以共享和重用它们的结果),必须查看文档的相关部分,其中说:

...每次doctest找到要测试的文档字符串时,它都会使用 's 全局变量的浅表 副本M因此运行测试不会更改模块的真实全局变量,因此一个测试M不会留下意外允许另一个测试的碎屑测试工作。

...

您可以通过传递给或代替来强制使用自己的dict作为执行上下文。globs=your_dicttestmod()testfile()

鉴于此,我设法doctest模块进行逆向工程,除了使用副本(即dict'copy()方法)外,它还clear()在每次测试后清除全局字典(使用 )。

因此,可以使用以下内容修补自己的全局字典:

class Context(dict):
    def clear(self):
        pass
    def copy(self):
        return self 

然后将其用作:

import doctest
from importlib import import_module

module = import_module('some.module')
doctest.testmod(module,
                # Make a copy of globals so tests in this
                # module don't affect the tests in another
                glob=Context(module.__dict__.copy()))
于 2016-02-06T14:53:16.603 回答