Beispiel #1
0
def test_normal_safe_formatter():
    from xoutil.string import SafeFormatter, safe_encode

    f = SafeFormatter(x=1, y=2)
    result = f.format(safe_encode('CWD: "{cwd}"; "x+d["x"]": {x+d["x"]}.'),
                      cwd=safe_encode('~/tmp/foóbar'), d=dict(x=1))
    assert 'CWD: "~/tmp/foóbar"; "x+d["x"]": 2.' == result
Beispiel #2
0
    def makedirs(name, mode=0o777, exist_ok=False):
        """makedirs(path [, mode=0o777][, exist_ok=False])

        Super-mkdir; create a leaf directory and all intermediate ones.
        Works like mkdir, except that any intermediate path segment (not
        just the rightmost) will be created if it does not exist. If the
        target directory with the same mode as we specified already exists,
        raises an OSError if exist_ok is False, otherwise no exception is
        raised.  This is recursive.

        """
        from errno import EEXIST
        from xoutil.string import safe_encode
        head, tail = os.path.split(name)
        if not tail:
            head, tail = os.path.split(head)
        if head and tail and not os.path.exists(head):
            try:
                makedirs(head, mode, exist_ok)
            except OSError as e:
                # be happy if someone already created the path
                if e.errno != EEXIST:
                    raise
            cdir = os.path.curdir
            if isinstance(tail, bytes):
                cdir = safe_encode(os.path.curdir, 'ASCII')
            if tail == cdir:      # xxx/newdir/. exists if xxx/newdir exists
                return
        try:
            os.mkdir(name, mode)
        except OSError as e:
            if not exist_ok or e.errno != EEXIST or not os.path.isdir(name):
                raise
Beispiel #3
0
 def __repr__(self):
     from xoutil.names import nameof
     name = getattr(self, 'name', None)
     if name:
         return str("<%s '%s'>" % (
             nameof(type(self), inner=True, full=True),
             safe_encode(name)))
     else:
         return super(Entity, self).__repr__()
Beispiel #4
0
def _further_escape(s):
    import re
    from xoutil.string import safe_encode
    ASCII = getattr(re, 'ASCII', 0)  # Py3k
    what = re.compile(br'[\x00-\x1F\x80-\xFF]', ASCII)
    res, pos = b'', 0
    for match in what.finditer(s):
        char, start, end = match.group(), match.start(), match.end()
        assert start + 1 == end
        res += s[pos:start]
        res += b'&#' + safe_encode(str(ord(char))) + b';'
        pos = end
    res += s[pos:]
    return res
Beispiel #5
0
    def escape(s, quote=True):
        """Replace special characters "&", "<" and ">" to HTML-safe sequences

        If the optional flag quote is true (the default), the quotation mark
        characters, both double quote (") and single quote (') characters are
        also translated.

        """
        from xoutil.eight import text_type
        from xoutil.string import safe_decode, safe_encode
        if not isinstance(s, text_type):
            arg = safe_decode(s)
        else:
            arg = s
        if quote:
            res = arg.translate(_escape_map_full)
        else:
            res = arg.translate(_escape_map)
        if not isinstance(res, type(s)):
            return safe_encode(res)
        return res
Beispiel #6
0
def test_safe_encode_dont_fail_uppon_invalid_encoding(s):
    from xoutil.string import safe_encode
    assert safe_encode(s, 'i-dont-exist') == safe_encode(s)