Doctests that contain string literals

耗尽温柔 提交于 2019-12-21 02:47:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!