2012-03-14 5 views
6

nullで動作する関数でdoctestを実行しようとしています。しかし、doctestのはヌルを好きにいないようです...docutilsでnullsを使用する方法

def do_something_with_hex(c): 
    """ 
    >>> do_something_with_hex('\x00') 
    '\x00' 
    """ 
return repr(c) 

import doctest 
doctest.testmod() 

私はこのようなテストケースでNULLを許可するために何ができる

Failed example: 
    do_something_with_hex(' ') 
Exception raised: 
    Traceback (most recent call last): 
     File "C:\Python27\lib\doctest.py", line 1254, in __run 
     compileflags, 1) in test.globs 
    TypeError: compile() expected string without null bytes 
********************************************************************** 

これらのエラーを見ていますか?

答えて

7

あなたはバックスラッシュのすべてをエスケープ、あるいはraw string literalにあなたのドキュメンテーション文字列を変更することができます:

def do_something_with_hex(c): 
    r""" 
    >>> do_something_with_hex('\x00') 
    '\x00' 
    """ 
    return repr(c) 

r接頭辞ではバックスラッシュの次の文字が含まれる文字列に文字列は変更されずに、すべてのバックスラッシュは文字列に残ります。

+0

ありがとうございました。治療をします! –

3

利用\\xの代わり\x\xを書くと、Pythonインタプリタはこれをヌルバイトとして解釈し、ヌルバイト自体がdocstringに挿入されます。例えば,:

>>> def func(x): 
...  """\x00""" 
... 
>>> print func.__doc__  # this will print a null byte 

>>> def func(x): 
...  """\\x00""" 
... 
>>> print func.__doc__ 
\x00 
関連する問題