def test_safe_representation(): class TestObject(object): """A test object that has neither __str__ nor __repr__.""" def __str__(self): return NotImplementedError() def __repr__(self): return NotImplementedError() assert_eq("2", qcore.safe_str(2)) assert_eq("2....", qcore.safe_str("2.192842", max_length=5)) assert_is_substring("<n/a: str(...) raised", qcore.safe_str(TestObject())) assert_eq("'a'", qcore.safe_repr("a")) assert_eq("'...", qcore.safe_repr("2.192842", max_length=4)) assert_eq("<n/a: repr...", qcore.safe_repr(TestObject(), max_length=13))
def safe_text(obj): """Safely turns an object into a textual representation. Calls str(), then on Python 2 decodes the result. """ result = qcore.safe_str(obj) if isinstance(result, bytes): try: result = result.decode("utf-8") except Exception as e: result = "<n/a: .decode() raised %r>" % e return result
def str(source, truncate=True): return qcore.safe_str(source, options.DEBUG_STR_REPR_MAX_LENGTH if truncate else 0)