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