【问题标题】:How to put string on two lines in Python? [duplicate]如何在Python中将字符串放在两行? [复制]
【发布时间】:2014-12-20 18:13:12
【问题描述】:

我是 Python、PyCharm 和 Web API 测试领域的新手。

我正在尝试测试在 Web API 中出现错误时显示的错误消息。此错误消息有两个部分,并显示在两个单独的行上。

但不知何故,我为比较而生成的任何字符串定义总是显示在一行上。

这是我尝试过的事情之一 - 在两个部分之间创建了一个带有新行 \n 的字符串。

    wp_error = 'This page can\'t be saved.\n Some required information is missing.'

    # create new workspace and save it without filling up any information.
    self.test_mycode.click_and_wait(self.workspace_overview.new_workspace_button,
                                     self.new_workspace._save_button_locator)
    self.new_workspace.save_button.click()

    self.message.check_message('error', wp_error)

但这不起作用,我得到了:

在 check_message 中 Assert.equal(message.message_body.text, message_text)

self = <class 'unittestzero.Assert'>
first = "This page can't be saved.
Some required information is missing."
second = "This page can't be saved.\n Some required information is missing."
.....

>       assert first == second, msg
E       AssertionError: None

所以我的问题是如何定义字符串以适当地测试出现在两行上的错误消息? 谢谢。

【问题讨论】:

  • @user2864740,OP 的wp_error 行有什么问题?
  • @PadraicCunningham 好电话,我误读了症状。

标签: python string


【解决方案1】:

如果:

first = """This page can't be saved.
Some required information is missing."""
second = "This page can't be saved.\n Some required information is missing."
assert first == second

失败,那么问题可能是:

first  == "This page can't be saved.\nSome required information is missing."
second == "This page can't be saved.\n Some required information is missing."

即在换行符之后,第二个中有一个额外的空格。 (还要注意三引号,以允许字符串跨行而编译器不会抱怨,)

解决方案:您可以:

  1. 对测试数据要格外小心。

  2. 使用“垫片”来允许“大约等于”。例如:

    import re
    FOLD_WHITESPACE = re.compile(r'\s+')
    
    def oneline(s):
       return FOLD_WHITESPACE.sub(" ", s)
    
    assert oneline(first) == oneline(second)
    

    我并不是说这种特殊的转换是所有字符串比较的理想转换,但它是一种简单的转换,您无需过度关注空格(包括换行符)。

    类似的“几乎等于”或“转换后的等于”测试通常方便或需要测试字符串和浮点值。

    顺便说一句,如果您使用的是断言的对象调用版本,它可能会表达为:

    Assert.equal(oneline(message.message_body.text),
                 oneline(message_text))
    

【讨论】:

  • 我也在想同样的事情,但我很困惑为什么测试运行程序似乎会 print first(或至少解释换行符),并且另一方面显示repr()second?
  • @LukasGraf 好点。我不完全相信所提供的代码。我的意思是,你怎么得到self = &lt;class 'unittestzero.Assert'&gt;?作为一个等于== 好的,但是作为一个任务?那不是合法的Python。但是,我的测试运行器输出(pytest 和 fox)看起来非常不同。所以我忽略了这些怪癖。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 2016-04-13
相关资源
最近更新 更多