包含字符串文字的doctest [英] Doctests that contain string literals
问题描述
我有一个单元测试,我想为将XML作为字符串的函数编写.这是一个doctest,我希望XML与测试保持一致.由于XML是多行的,因此我在doctest中尝试了字符串文字,但没有成功.这是简化的测试代码:
I have a unit test that I'd like to write for a function that takes XML as a string. It's a doctest and I'd like the XML in-line with the tests. Since the XML is multi-line, I tried a string literal within the doctest, but no success. Here's simplified test code:
def test():
"""
>>> config = \"\"\"\
<?xml version="1.0"?>
<test>
<data>d1</data>
<data>d2</data>
</test>\"\"\"
"""
if __name__ == "__main__":
import doctest
doctest.testmod(name='test')
我得到的错误是
File "<doctest test.test[0]>", line 1
config = """ <?xml version="1.0"?>
^
SyntaxError: EOF while scanning triple-quoted string
我尝试了许多组合,但似乎无法使它正常工作.我得到的要么是此错误,要么是前后不一致的白领"错误.有什么建议?我正在使用python 2.4(不,没有升级的可能性).
I've tried many combinations and can't seem to get this to work. It's either this or a "inconsistent leading whitepsace" error that I get. Any suggestions? I'm using python 2.4 (and no, there's no possibility of upgrading).
推荐答案
此代码有效,例如使用Python 2.7.12和3.5.2:
This code works, e.g. with Python 2.7.12 and 3.5.2:
def test():
"""
>>> config = '''<?xml version="1.0"?>
... <test>
... <data>d1</data>
... <data>d2</data>
... </test>'''
>>> print(config)
<?xml version="1.0"?>
<test>
<data>d1</data>
<data>d2</data>
</test>
"""
if __name__ == "__main__":
import doctest
doctest.testmod(name='test')
这篇关于包含字符串文字的doctest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!