Trailing spaces removed on Python heredoc lines in PyCharm

孤者浪人 提交于 2020-01-03 13:58:44

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/28701782/trailing-spaces-removed-on-python-heredoc-lines-in-pycharm

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