Skip to content

Should Be Equal (As Strings): Support formatting values in error messages with repr and ascii #2815

Closed

Description

@pekkaklarck

As explained in #2806, invisible characters like the null byte can make error messages confusing. Seeing something like example != example isn't very informative, and it would be better to use repr() to get something like 'example' != 'example\x00'. As discussed in that issue, it isn't particularly easy to detect when the rendered representation is same although strings themselves are different. This is especially complicated with strings having different Unicode normal form when using Python 3.

Instead of trying to detect when string representation of different strings are same, it is better to add separate argument repr=False that can be used to enable using repr(). In Python 3 this should use ascii(), though, to show differences between different Unicode forms. I propose to use repr as the argument name regardless of that, because we already use it with the Log keyword (#1584).

Activity

  1. pekkaklarck commented on Apr 24, 2018

    @pekkaklarck
    MemberAuthor

    The repr=False argument should be added at least to Should Be Equal and Should Be Equal As Strings keywords. Possibly also to others. If someone is interested to implement this, we can get this into RF 3.1 targeted for June.

  2. changed the title [-]`Should Be Equal` and possibly others: Support show `repr` of compared values[/-] [+]`Should Be Equal` and possibly others: Support showing `repr` of compared values[/+] on Apr 25, 2018
  3. indrakumarm commented on Jul 10, 2018

    @indrakumarm

    @pekkaklarck
    I am thinking of taking this up.

    My thought is that instead of handling repr=False all through call of should_be_equal

    should_be_equal()---> _should_be_equal() --> assert_equal() --> _report_inequality_failure()->_get_default_message
    

    How about directly handling this in (_report_inequality_failure) , as in all in equal scenario it will be clear why the stings are inequal. this will by default print the message(with repr/ascii). Please do let me know your thoughts.

    Diff:
     git diff robot/utils/asserts.py
    diff --git a/src/robot/utils/asserts.py b/src/robot/utils/asserts.py
    index 2094f11..4f9cb98 100644
    --- a/src/robot/utils/asserts.py
    +++ b/src/robot/utils/asserts.py
    @@ -96,7 +96,7 @@ Example output::
    
     from .robottypes import type_name
     from .unic import unic
    -
    +import sys
    
     def fail(msg=None):
         """Fail test immediately with the given message."""
    @@ -221,6 +221,12 @@ def _report_failure(msg):
    
    
     def _report_inequality_failure(obj1, obj2, msg, values, delim, extra=None):
    +    if sys.version_info[0] == 2:
    +       obj1 = repr(obj1)
    +       obj2 = repr(obj2)
    +    else:
    +       obj1 = ascii(obj1)
    +       obj2 = ascii(obj2)
         if not msg:
             msg = _get_default_message(obj1, obj2, delim)
         elif values:
  4. Tattoo commented on Jul 10, 2018

    @Tattoo
    Member

    @indrakumarm Please edit your comment to take Markdown into account. Currently it is very unreadable.

  5. pekkaklarck commented on Jul 10, 2018

    @pekkaklarck
    MemberAuthor

    First of all, it would be great if you @indrakumarm could implement this!

    Always using repr would have some benefits, but those who use non-ASCII letters would be annoyed. We Finns could still understand what's going on when the message would say 'hyv\xe4' != 'paha', but I'd assume, for example, Russians would highly prefer спасибо over '\u0441\u043f\u0430\u0441\u0438\u0431\u043e'. This kind of change would also be backwards incompatible, without a way to get the old behavior back. Adding new repr=False argument would keep the change fully backwards compatible but getting the repr would be easy.

  6. indrakumarm commented on Jul 11, 2018

    @indrakumarm

    Ok got it.
    Will Make changes to should_be_equal and should_be_equal_as_strings and share the diff

  7. indrakumarm commented on Jul 12, 2018

    @indrakumarm

    As suggested , made changes to should_be_equal and should_be_equal_as_string. Please fgo through the diff below and let me know how to proceed further to make changes in.

    diff --git a/src/robot/libraries/BuiltIn.py b/src/robot/libraries/BuiltIn.py
    index eeb1b66..08a1bc4 100644
    --- a/src/robot/libraries/BuiltIn.py
    +++ b/src/robot/libraries/BuiltIn.py
    @@ -17,6 +17,7 @@ import difflib
     import re
     import time
     import token
    +import sys
     from tokenize import generate_tokens, untokenize
    
     from robot.api import logger
    @@ -598,7 +599,7 @@ class _Verify(_BuiltInBase):
                 raise AssertionError(msg or "'%s' should be true." % condition)
    
         def should_be_equal(self, first, second, msg=None, values=True,
    -                        ignore_case=False):
    +                        ignore_case=False, repr=False):
             """Fails if the given objects are unequal.
    
             Optional ``msg`` and ``values`` arguments specify how to construct
    @@ -628,6 +629,8 @@ class _Verify(_BuiltInBase):
             if is_truthy(ignore_case) and is_string(first) and is_string(second):
                 first = first.lower()
                 second = second.lower()
    +        if is_truthy(repr):
    +           (first, second) =  self._call_repr(first, second)
             self._should_be_equal(first, second, msg, values)
    
         def _should_be_equal(self, first, second, msg, values):
    @@ -657,6 +660,15 @@ class _Verify(_BuiltInBase):
         def _include_values(self, values):
             return is_truthy(values) and str(values).upper() != 'NO VALUES'
    
    +    def _call_repr(self, first, second):
    +        if sys.version_info[0] == 2:
    +            first = repr(first)
    +            second = repr(second)
    +        else:
    +            first = ascii(first)
    +            second = ascii(second)
    +        return (first, second)
    +
         def should_not_be_equal(self, first, second, msg=None, values=True,
                                 ignore_case=False):
             """Fails if the given objects are equal.
    @@ -789,7 +801,7 @@ class _Verify(_BuiltInBase):
             self._should_not_be_equal(first, second, msg, values)
    
         def should_be_equal_as_strings(self, first, second, msg=None, values=True,
    -                                   ignore_case=False):
    +                                   ignore_case=False, repr=False):
             """Fails if objects are unequal after converting them to strings.
    
             See `Should Be Equal` for an explanation on how to override the default
    @@ -808,6 +820,8 @@ class _Verify(_BuiltInBase):
             if is_truthy(ignore_case):
                 first = first.lower()
                 second = second.lower()
    +        if is_truthy(repr):
    +           (first, second) =  self._call_repr(first, second)
             self._should_be_equal(first, second, msg, values)

    Tested changes as below:

    *** Test Cases ***
    TC1 - Negative case test equal without repr
    ${mystr}= Set Variable venkat\x00
    Log ${mystr}
    #Should Be Equal As Strings venkat ${mystr}
    Should Be Equal venkat ${mystr}

    TC2 - Negative case test equal with repr
    ${mystr}= Set Variable venkat\x00
    Log ${mystr}
    Should Be Equal venkat ${mystr} repr=True

    TC3 - Positive case equal
    ${mystr}= Set Variable venkat
    Log ${mystr}
    Should Be Equal venkat ${mystr}

    TC4 - positive case equal strings
    ${mystr}= Set Variable raj kumar
    should be equal as strings raj kumar ${mystr}

    TC5 - negative case equal strings without repr
    ${mystr}= Set Variable ab\u0308
    should be equal as strings ä ${mystr}

    TC5 - negative case equal strings with repr
    ${mystr}= Set Variable ba\u0308
    should be equal as strings ä ${mystr} repr=True

    result:

    TC1 - Negative case test equal without repr                           | FAIL |
    venkat != venkat
    ------------------------------------------------------------------------------
    TC2 - Negative case test equal with repr                              | FAIL |
    'venkat' != 'venkat\x00'
    
  8. pekkaklarck commented on Aug 8, 2018

    @pekkaklarck
    MemberAuthor

    Sorry @indrakumarm for not replying earlier due to holidays. Commenting now:

    1. Conversion using repr/ascii should be done only when constructing the error message, not before comparing the values. Otherwise when comparing objects, you'd compare their string representation and not objects themselves. This basically means that repr=False should be added all the way to the utils.asserts.assert_(not_)equal.

    2. No need to do type checking using sys.version_info[0] when we have PY2 and PY3 constants in robot.utils.

    3. Could convert this to a pull request so that it's easier to review the changes?

  9. added this to the v3.1.2 milestone on Mar 28, 2019
  10. pekkaklarck commented on Mar 28, 2019

    @pekkaklarck
    MemberAuthor

    Would be great to have this in RF 3.1.2 or latest in RF 3.2 to ease spotting differences between strings containing different spaces. See #3121 for related discussion.

  11. pekkaklarck commented on Apr 17, 2019

    @pekkaklarck
    MemberAuthor

    This would have helped also with debugging problems with different line endings (\n vs \r\n) related to #3097. Nobody has provided a pull request but I can implement this myself. Implementation isn't exactly trivial because some of the keywords have special features like multiline string comparison and repr=True should be handled there as well.

  12. removed
    good first issue
    help wanted
    on Apr 17, 2019
  13. changed the title [-]`Should Be Equal` and possibly others: Support showing `repr` of compared values[/-] [+]`Should Be Equal (As Strings)`: Support formatting values in error messages with `repr` and `ascii`[/+] on May 3, 2019
  14. pekkaklarck commented on May 3, 2019

    @pekkaklarck
    MemberAuthor

    This and related #3164 turned out to be more complicated than I envisioned. Hard parts were:

    1. Deciding how to enable this functionality. The final decision was to add new argument formatter=str that can be then used also like formatter=repr and formatter=ascii.

    2. Trying to customize Python's PrettyPrinter to allow using ascii(). In the end this turned out to be impossible to accomplish reliably and PrettyPrinter is only used with formatter=repr. When using formatter=ascii, the ascii() built-in is used directly on Python 3 and on Python 2 the standard repr() is used instead.

  15. nixuewei commented on Jun 27, 2020

    @nixuewei

    seems like should contain should be supported.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions