Doctests that contain string literals
Asked Answered
H

1

4

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).

Hoover answered 21/12, 2011 at 16:47 Comment(2)
Have you tried putting in the ... continuation prompts that the interactive shell uses?Hubie
I don't have python2.4 to test, but using three apostrophes ''' inside to avoid the \" bits and adding the "... " prefixes works for me.Paradox
H
15

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')
Hoover answered 21/12, 2011 at 17:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.