我想在文件共享测试数据和/或函数中有几个 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
复制一次模块,然后复制每个文档字符串的副本?
在任何情况下,将模块导入每个文档字符串似乎是有用的,如果尴尬的话。
我更愿意为此使用单独的命名空间,以避免意外践踏实际模块数据,这些数据将以可能未记录的方式导入或不会导入到后续测试中。
我突然想到(理论上)可以动态创建一个模块以包含这个命名空间。但是,到目前为止,我还没有从我不久前提出的问题中得到关于如何做到这一点的任何方向。任何信息都非常受欢迎!(作为对适当问题的回应)
在任何情况下,我都希望将更改直接传播到后续文档字符串的命名空间中。所以我最初的问题仍然存在,作为一个限定词。