PyCharm 中 Python heredoc 行的尾随空格已删除

Trailing spaces removed on Python heredoc lines in PyCharm

我在 PyCharm 社区 3.4.1 中使用 Python 2.7 和 unittest2。我需要将 CLI 命令的文本输出与自动化测试的字符串内容相匹配。

此命令的输出经常在行尾有尾随空格;如果我在用于存储预期文本的 heredoc 中的行尾添加空格,它们会神秘地在编辑器中被删除并且不会进入文件。为了解决这个问题,我不得不拆分我的 heredoc 并将其与空格重新组合;这非常丑陋,但这是我让它工作的唯一方法。

我试过谷歌搜索和搜索解释,但我找到了 none;我怀疑这可能是 PyCharm 的自动格式化变得混乱,并将其视为一行 Python 代码,在其中删除尾随空格是安全的。

这是我的代码;它在 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')

欢迎提出建议:

这并不是 PyCharm 中的真正错误;这是其 "Strip trailing spaces on save" 功能的一个限制,该功能对上下文不敏感,并且会去除所有行中的尾随空格。您可以在设置 | 下将其关闭编辑|一般。

或者,您可以对 heredoc 字符串中的尾随空格进行编码,方法是将它们替换为一些特殊标记(“%20”或类似的东西),然后在执行 assertMultilineEqual() 调用之前将它们替换回去。

另一种选择是在将 CLI 命令的输出与预期输出进行比较之前简单地去除尾随空格。