| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
import os |
| 23 |
import sys |
| 24 |
|
| 25 |
from hypothesis.strategies import composite, sampled_from, lists, \ |
| 26 |
integers, binary, randoms |
| 27 |
|
| 28 |
|
| 29 |
class _PathLike: |
| 30 |
|
| 31 |
def __init__(self, value): |
| 32 |
self._value = value |
| 33 |
|
| 34 |
def __fspath__(self): |
| 35 |
return self._value |
| 36 |
|
| 37 |
|
| 38 |
@composite |
| 39 |
def fspaths(draw, allow_pathlike=True): |
| 40 |
"""A hypothesis strategy which gives valid path values. |
| 41 |
|
| 42 |
Valid path values are everything which when passed to open() will not raise |
| 43 |
ValueError or TypeError (but might raise OSError due to file system or |
| 44 |
operating system restrictions). |
| 45 |
|
| 46 |
Args: |
| 47 |
allow_pathlike (bool): |
| 48 |
If the result can be a pathlike (see :class:`os.PathLike`) |
| 49 |
""" |
| 50 |
|
| 51 |
s = [] |
| 52 |
|
| 53 |
if os.name == "nt": |
| 54 |
|
| 55 |
hight_surrogate = integers( |
| 56 |
min_value=0xD800, max_value=0xDBFF).map(lambda i: chr(i)) |
| 57 |
low_surrogate = integers( |
| 58 |
min_value=0xDC00, max_value=0xDFFF).map(lambda i: chr(i)) |
| 59 |
uni_char = integers( |
| 60 |
min_value=1, max_value=sys.maxunicode).map(lambda i: chr(i)) |
| 61 |
any_char = sampled_from([ |
| 62 |
draw(uni_char), draw(hight_surrogate), draw(low_surrogate)]) |
| 63 |
any_text = lists(any_char).map(lambda l: "".join(l)) |
| 64 |
|
| 65 |
windows_path_text = any_text |
| 66 |
s.append(windows_path_text) |
| 67 |
|
| 68 |
def text_to_bytes(path): |
| 69 |
fs_enc = sys.getfilesystemencoding() |
| 70 |
try: |
| 71 |
return path.encode(fs_enc, "surrogatepass") |
| 72 |
except UnicodeEncodeError: |
| 73 |
return path.encode(fs_enc, "replace") |
| 74 |
|
| 75 |
windows_path_bytes = windows_path_text.map(text_to_bytes) |
| 76 |
s.append(windows_path_bytes) |
| 77 |
else: |
| 78 |
unix_path_bytes = binary().map(lambda b: b.replace(b"\x00", b" ")) |
| 79 |
s.append(unix_path_bytes) |
| 80 |
|
| 81 |
unix_path_text = unix_path_bytes.map( |
| 82 |
lambda b: b.decode( |
| 83 |
sys.getfilesystemencoding(), "surrogateescape")) |
| 84 |
|
| 85 |
r = draw(randoms(use_true_random=False)) |
| 86 |
|
| 87 |
def shuffle_text(t): |
| 88 |
l = list(t) |
| 89 |
r.shuffle(l) |
| 90 |
return "".join(l) |
| 91 |
|
| 92 |
s.append(unix_path_text.map(shuffle_text)) |
| 93 |
|
| 94 |
result = draw(sampled_from(list(map(draw, s)))) |
| 95 |
|
| 96 |
if allow_pathlike and hasattr(os, "fspath"): |
| 97 |
result = draw(sampled_from([result, _PathLike(result)])) |
| 98 |
|
| 99 |
return result |