Doctests that contain string literals

2020-06-05 01:21发布

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条回答
Melony?
2楼-- · 2020-06-05 01:55

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')
查看更多
登录 后发表回答