|  | 
| 1 | 1 | import os | 
| 2 | 2 | import unittest | 
| 3 |  | -from test.support import import_helper | 
|  | 3 | +from test import support | 
|  | 4 | +from test.support import import_helper, os_helper | 
| 4 | 5 | 
 | 
| 5 | 6 | _testcapi = import_helper.import_module('_testcapi') | 
| 6 | 7 | 
 | 
| 7 | 8 | 
 | 
| 8 | 9 | class CAPIFileTest(unittest.TestCase): | 
| 9 | 10 |     def test_py_fopen(self): | 
|  | 11 | +        # Test Py_fopen() and Py_fclose() | 
| 10 | 12 |         for filename in (__file__, os.fsencode(__file__)): | 
| 11 | 13 |             with self.subTest(filename=filename): | 
| 12 | 14 |                 content = _testcapi.py_fopen(filename, "rb") | 
| 13 | 15 |                 with open(filename, "rb") as fp: | 
| 14 | 16 |                     self.assertEqual(fp.read(256), content) | 
| 15 | 17 | 
 | 
|  | 18 | +        with open(__file__, "rb") as fp: | 
|  | 19 | +            content = fp.read() | 
|  | 20 | +        for filename in ( | 
|  | 21 | +            os_helper.TESTFN, | 
|  | 22 | +            os.fsencode(os_helper.TESTFN), | 
|  | 23 | +            os_helper.TESTFN_UNDECODABLE, | 
|  | 24 | +            os_helper.TESTFN_UNENCODABLE, | 
|  | 25 | +        ): | 
|  | 26 | +            with self.subTest(filename=filename): | 
|  | 27 | +                try: | 
|  | 28 | +                    with open(filename, "wb") as fp: | 
|  | 29 | +                        fp.write(content) | 
|  | 30 | + | 
|  | 31 | +                    content = _testcapi.py_fopen(filename, "rb") | 
|  | 32 | +                    with open(filename, "rb") as fp: | 
|  | 33 | +                        self.assertEqual(fp.read(256), content[:256]) | 
|  | 34 | +                finally: | 
|  | 35 | +                    os_helper.unlink(filename) | 
|  | 36 | + | 
|  | 37 | +        # embedded null character/byte in the filename | 
|  | 38 | +        with self.assertRaises(ValueError): | 
|  | 39 | +            _testcapi.py_fopen("a\x00b", "rb") | 
|  | 40 | +        with self.assertRaises(ValueError): | 
|  | 41 | +            _testcapi.py_fopen(b"a\x00b", "rb") | 
|  | 42 | + | 
| 16 | 43 |         for invalid_type in (123, object()): | 
| 17 | 44 |             with self.subTest(filename=invalid_type): | 
| 18 | 45 |                 with self.assertRaises(TypeError): | 
| 19 | 46 |                     _testcapi.py_fopen(invalid_type, "r") | 
| 20 | 47 | 
 | 
|  | 48 | +        if support.MS_WINDOWS: | 
|  | 49 | +            with self.assertRaises(OSError): | 
|  | 50 | +                # On Windows, the file mode is limited to 10 characters | 
|  | 51 | +                _testcapi.py_fopen(__file__, "rt+, ccs=UTF-8") | 
|  | 52 | + | 
| 21 | 53 | 
 | 
| 22 | 54 | if __name__ == "__main__": | 
| 23 | 55 |     unittest.main() | 
0 commit comments