Can python doctest ignore some output lines?

后端 未结 6 1612
灰色年华
灰色年华 2020-12-09 15:16

I\'d like to write a doctest like this:

\"\"\"
>>> print a.string()
          foo : a
          bar : b
         date : 

        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 15:25

    Responding to questions about "how can we ignore the whole line": yes, the fact that "..." also looks like a continuation like makes it hard to ignore the entire output. You can use "#doctest: +SKIP" if you just want to skip the example entirely, but that won't work if you are relying on its side-effects. If you really need to do this, I suppose you could monkey-patch the doctest module itself, though I wouldn't particularly recommend it:

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

    (this test passes.)

    Or you could temporarily suppress stdout and/or stderr:

    >>> # 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__
    

    (this test also passes.)

提交回复
热议问题