Robot Framework
unic.py
Go to the documentation of this file.
1 # Copyright 2008-2015 Nokia Networks
2 # Copyright 2016- Robot Framework Foundation
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 import sys
17 from pprint import PrettyPrinter
18 from unicodedata import normalize
19 
20 
21 def safe_str(item):
22  return normalize('NFC', _safe_str(item))
23 
24 
25 def _safe_str(item):
26  if isinstance(item, str):
27  return item
28  if isinstance(item, (bytes, bytearray)):
29  try:
30  return item.decode('ASCII')
31  except UnicodeError:
32  return ''.join(chr(b) if b < 128 else '\\x%x' % b for b in item)
33  try:
34  return str(item)
35  except:
36  return _unrepresentable_object(item)
37 
38 
39 def prepr(item, width=80):
40  return safe_str(PrettyRepr(width=width).pformat(item))
41 
42 
43 class PrettyRepr(PrettyPrinter):
44 
45  def format(self, object, context, maxlevels, level):
46  try:
47  return PrettyPrinter.format(self, object, context, maxlevels, level)
48  except:
49  return _unrepresentable_object(object), True, False
50 
51  # Don't split strings: https://stackoverflow.com/questions/31485402
52  def _format(self, object, *args, **kwargs):
53  if isinstance(object, (str, bytes, bytearray)):
54  width = self._width_width
55  self._width_width = sys.maxsize
56  try:
57  super()._format(object, *args, **kwargs)
58  finally:
59  self._width_width = width
60  else:
61  super()._format(object, *args, **kwargs)
62 
63 
65  from .error import get_error_message
66  return "<Unrepresentable object %s. Error: %s>" \
67  % (item.__class__.__name__, get_error_message())
def _format(self, object, *args, **kwargs)
Definition: unic.py:52
def format(self, object, context, maxlevels, level)
Definition: unic.py:45
def get_error_message()
Returns error message of the last occurred exception.
Definition: error.py:34
def normalize(string, ignore=(), caseless=True, spaceless=True)
Normalizes given string according to given spec.
Definition: normalizing.py:27
def prepr(item, width=80)
Definition: unic.py:39
def _safe_str(item)
Definition: unic.py:25
def safe_str(item)
Definition: unic.py:21
def _unrepresentable_object(item)
Definition: unic.py:64