5
5
6
6
_testcapi = import_helper .import_module ('_testcapi' )
7
7
8
+ NULL = None
9
+
8
10
9
11
class CAPIFileTest (unittest .TestCase ):
10
12
def test_py_fopen (self ):
@@ -25,15 +27,22 @@ def test_py_fopen(self):
25
27
os_helper .TESTFN ,
26
28
os .fsencode (os_helper .TESTFN ),
27
29
]
28
- # TESTFN_UNDECODABLE cannot be used to create a file on macOS/WASI.
30
+ if os_helper .TESTFN_UNDECODABLE is not None :
31
+ filenames .append (os_helper .TESTFN_UNDECODABLE )
32
+ filenames .append (os .fsdecode (os_helper .TESTFN_UNDECODABLE ))
29
33
if os_helper .TESTFN_UNENCODABLE is not None :
30
34
filenames .append (os_helper .TESTFN_UNENCODABLE )
31
35
for filename in filenames :
32
36
with self .subTest (filename = filename ):
33
37
try :
34
38
with open (filename , "wb" ) as fp :
35
39
fp .write (source )
36
-
40
+ except OSError :
41
+ # TESTFN_UNDECODABLE cannot be used to create a file
42
+ # on macOS/WASI.
43
+ filename = None
44
+ continue
45
+ try :
37
46
data = _testcapi .py_fopen (filename , "rb" )
38
47
self .assertEqual (data , source [:256 ])
39
48
finally :
@@ -47,7 +56,14 @@ def test_py_fopen(self):
47
56
48
57
# non-ASCII mode failing with "Invalid argument"
49
58
with self .assertRaises (OSError ):
50
- _testcapi .py_fopen (__file__ , "\xe9 " )
59
+ _testcapi .py_fopen (__file__ , b"\xc2 \x80 " )
60
+ with self .assertRaises (OSError ):
61
+ # \x98 is invalid in cp1250, cp1251, cp1257
62
+ # \x9d is invalid in cp1252-cp1255, cp1258
63
+ _testcapi .py_fopen (__file__ , b"\xc2 \x98 \xc2 \x9d " )
64
+ # UnicodeDecodeError can come from the audit hook code
65
+ with self .assertRaises ((UnicodeDecodeError , OSError )):
66
+ _testcapi .py_fopen (__file__ , b"\x98 \x9d " )
51
67
52
68
# invalid filename type
53
69
for invalid_type in (123 , object ()):
@@ -60,7 +76,8 @@ def test_py_fopen(self):
60
76
# On Windows, the file mode is limited to 10 characters
61
77
_testcapi .py_fopen (__file__ , "rt+, ccs=UTF-8" )
62
78
63
- # CRASHES py_fopen(__file__, None)
79
+ # CRASHES _testcapi.py_fopen(NULL, 'rb')
80
+ # CRASHES _testcapi.py_fopen(__file__, NULL)
64
81
65
82
66
83
if __name__ == "__main__" :
0 commit comments