python doctest 可以忽略某些输出行吗?

问题描述 投票:0回答:7

我想写一个这样的文档测试:

"""
>>> print a.string()
          foo : a
          bar : b
         date : <I don't care about the date output>
          baz : c
"""

有什么办法可以做到这一点吗?我认为切换到单元测试更有意义,但我很好奇是否可以指定不应该与 doctest 中的测试匹配的输出范围。

谢谢!

python doctest
7个回答
50
投票

使用

doctest.ELLIPSIS
,您可以使用
...
表示“匹配此处的任何字符串”。您可以使用 doctest 指令设置
doctest
选项,使其仅对一个测试用例有效:在线文档中的一个示例是:

>>> print range(20) # doctest:+ELLIPSIS
[0, 1, ..., 18, 19]

如果您希望 doctest 选项始终处于活动状态,您可以将其作为

optionflags=
参数传递给您使用的任何 doctest 函数,例如
doctest.testfile
。 (您可以使用
|
运算符对它们进行位或操作来传递多个选项标志)。


20
投票

回答有关“我们如何忽略整行”的问题:是的,事实上“...”看起来也像一个延续,使得很难忽略整个输出。如果您只想完全跳过该示例,则可以使用“#doctest: +SKIP”,但如果您依赖其副作用,则这将不起作用。如果您真的需要这样做,我想您可以对 doctest 模块本身进行猴子修补,尽管我不会特别推荐它:

>>> import doctest
>>> doctest.ELLIPSIS_MARKER = '-etc-'
>>> print 12 # doctest: +ELLIPSIS
-etc-

(此测试通过。)

或者您可以暂时抑制标准输出和/或标准错误:

>>> # Suppress stdout
>>> import sys
>>> class DevNull:
...     def noop(*args, **kwargs): pass
...     close = write = flush = writelines = noop
>>> sys.stdout = DevNull()
>>> # Run a test and ignore output (but we need its side effects)
>>> print 12 # NOTE: stdout is suppressed!
>>> # Restore stdout
>>> sys.stdout = sys.__stdout__

(这个测试也通过了。)


15
投票

我发现将不需要的返回值简单地分配给变量更容易:

>>> _ = do_something()
>>> check_something()
True

12
投票

忽略整行有点棘手。这里:

"""
>>> do_your_thing() #doctest:+ELLIPSIS
...
"""

三个点将被解释为续行,并导致语法错误。

如果你想忽略整行,你需要类似的东西:

"""
>>> sys.stdout.write('skip from here '); do_your_thing() #doctest:+ELLIPSIS
skip from here ...
"""

7
投票

您可以在函数之前和之后编写元组(受 Mark Horvath 的回答启发):

def foo():
    """
    >>> ();foo();() # doctest: +ELLIPSIS
    (...)
    """
    print "Hello world"
    return "Hello world"

0
投票

我可以在 Python 文档测试中的行首添加省略号吗? 解释如何创建使用附加字符串作为省略号的自定义输出检查器。这将允许您编写以下内容,同时在其他地方仍然使用“...”。

def foo():
  """
  >>> foo() # doctest: +ELLIPSIS
  [...] world
  """
  print "hello world"

0
投票

对于 Python3,我发现更容易检查是否显示了所需的输出,更容易用示例进行解释:

def some_function():
    '''
    blah blah blah explaining function
    example:
    >>>something_you_want in some_function()
    True
    '''

超级容易实施,对初学者友好。

© www.soinside.com 2019 - 2024. All rights reserved.