问题
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')
The error I get is
File "<doctest test.test[0]>", line 1
config = """ <?xml version="1.0"?>
^
SyntaxError: EOF while scanning triple-quoted string
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).
回答1:
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')
来源:https://stackoverflow.com/questions/8593315/doctests-that-contain-string-literals