How to put string on two lines in Python?
Question: I am brand new to the world of Python, PyCharm, and Web API testing.

I am trying to test error message that gets displayed when an error is made in
Web API. This error message has two parts and are displayed on two separate
lines.

But somehow any string definition I generate for comparison is always
displayed on one line.

This is one of the things I tried - created a string with new line \n between
two parts.

    
    
        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)
    

But this didn't work and I got:

in 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
    

So my question is how do I define the string to appropriately test the error
message that appears on two lines? Thank you.


Answer: If:

    
    
    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
    

fails, then the problem is probably that:

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

I.e. there is an extra space in the second one, after the newline. (Note also
the triple quotes, to allow a string to span lines without the compiler
complaining,)

Solutions: You can either:

  1. Be extremely careful with your test data. 

  2. Use a "shim" to allow "approximately equals". For example:
    
        import re
    FOLD_WHITESPACE = re.compile(r'\s+')
    
    def oneline(s):
       return FOLD_WHITESPACE.sub(" ", s)
    
    assert oneline(first) == oneline(second)
    

I am not arguing that this particular transformation is the ideal one for all
string comparisons, but it's a simple one that gets at your need to not be
excessively concerned with whitespaces (including line breaks).

Similar "almost equals" or "transformed equals" tests are often convenient or
required for testing both string and floating point values.

Btw, if you're using the object call version of assert, it might be couched
as:

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

