Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trailing spaces removed on Python heredoc lines in PyCharm

I'm using Python 2.7 with unittest2 within PyCharm community 3.4.1. I need to match the textual output of a CLI command with the contents of a string for an automated test.

The output of this command frequently has trailing spaces at the end of lines; if I add spaces to the ends of the lines in the heredoc that I'm using to store the expected text, they mysteriously get removed in the editor and don't make it to the file. To work around this I have had to split my heredoc and recombine it with spaces; this is very ugly, but it is the only way I can get it to work.

I've tried googling and searching for explanations, but I found none; I suspect it might be PyCharm's autoformatting getting confused and treating this like a line of Python code where it would be safe to remove trailing spaces.

Here is my code; it is in a unittest2 class:

def test_help_command(self):
    textgot = run_the_help_command()
    partone = """
blah blaah blah blah blah
This line has a space at the end in the help output"""
    parttwo = """
foo foo foo foo foo
This line also ends with a trailing space in the help output"""
    partthree = """
baz baz baz 
"""
    # Recombine parts with spaces
    helptext = partone + " " + parttwo + " " + partthree
    self.assertMultiLineEqual(helptext, textgot, 'Help text')

Suggestions welcomed for:

  • How do I fix this, so I can use a single heredoc string instead of splitting? I've got more complex examples to test which feature big blocks of text that would make this approach extremely annoying
  • Other better ways to store the strings than heredocs
  • Ways to prove this is or isn't a PyCharm bug
like image 337
Amias Avatar asked Feb 24 '15 17:02

Amias


1 Answers

This isn't really a bug in PyCharm; it's a limitation of its "Strip trailing spaces on save" feature, which is not context-sensitive and strips trailing spaces in all lines. You can turn it off under Settings | Editor | General.

Alternatively, you can encode the trailing spaces in your heredoc strings by replacing them with some special marker ("%20" or something like this), and replacing them back before performing the assertMultilineEqual() call.

Another option is to simply strip the trailing spaces from the output of your CLI command before comparing it with the expected output.

like image 157
yole Avatar answered Nov 15 '22 04:11

yole