1# -*- coding: utf-8 -*-
2# Copyright 2017 Christoph Reiter
3#
4# Permission is hereby granted, free of charge, to any person obtaining
5# a copy of this software and associated documentation files (the
6# "Software"), to deal in the Software without restriction, including
7# without limitation the rights to use, copy, modify, merge, publish,
8# distribute, sublicense, and/or sell copies of the Software, and to
9# permit persons to whom the Software is furnished to do so, subject to
10# the following conditions:
11#
12# The above copyright notice and this permission notice shall be included
13# in all copies or substantial portions of the Software.
14#
15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
23import os
24import sys
25
26from hypothesis.strategies import composite, sampled_from, lists, \
27    integers, binary, randoms
28
29
30class _PathLike(object):
31
32    def __init__(self, value):
33        self._value = value
34
35    def __fspath__(self):
36        return self._value
37
38
39@composite
40def fspaths(draw, allow_pathlike=True):
41    """A hypothesis strategy which gives valid path values.
42
43    Valid path values are everything which when passed to open() will not raise
44    ValueError or TypeError (but might raise OSError due to file system or
45    operating system restrictions).
46
47    Args:
48        allow_pathlike (bool):
49            If the result can be a pathlike (see :class:`os.PathLike`)
50    """
51
52    s = []
53
54    if os.name == "nt":
55        if sys.version_info[0] == 3:
56            unichr_ = chr
57        else:
58            unichr_ = unichr
59
60        hight_surrogate = integers(
61            min_value=0xD800, max_value=0xDBFF).map(lambda i: unichr_(i))
62        low_surrogate = integers(
63            min_value=0xDC00, max_value=0xDFFF).map(lambda i: unichr_(i))
64        uni_char = integers(
65            min_value=1, max_value=sys.maxunicode).map(lambda i: unichr_(i))
66        any_char = sampled_from([
67            draw(uni_char), draw(hight_surrogate), draw(low_surrogate)])
68        any_text = lists(any_char).map(lambda l: u"".join(l))
69
70        windows_path_text = any_text
71        s.append(windows_path_text)
72
73        def text_to_bytes(path):
74            fs_enc = sys.getfilesystemencoding()
75            try:
76                return path.encode(fs_enc, "surrogatepass")
77            except UnicodeEncodeError:
78                return path.encode(fs_enc, "replace")
79
80        windows_path_bytes = windows_path_text.map(text_to_bytes)
81        s.append(windows_path_bytes)
82    else:
83        unix_path_bytes = binary().map(lambda b: b.replace(b"\x00", b" "))
84        s.append(unix_path_bytes)
85
86        if sys.version_info[0] == 3:
87            unix_path_text = unix_path_bytes.map(
88                lambda b: b.decode(
89                    sys.getfilesystemencoding(), "surrogateescape"))
90        else:
91            unix_path_text = unix_path_bytes.map(
92                lambda b: b.decode(
93                    sys.getfilesystemencoding(), "ignore"))
94
95        r = draw(randoms())
96
97        def shuffle_text(t):
98            l = list(t)
99            r.shuffle(l)
100            return u"".join(l)
101
102        s.append(unix_path_text.map(shuffle_text))
103
104    result = draw(sampled_from(list(map(draw, s))))
105
106    if allow_pathlike and hasattr(os, "fspath"):
107        result = draw(sampled_from([result, _PathLike(result)]))
108
109    return result
110