MCPcopy Create free account
hub / github.com/python/cpython / test_pyobject_asfiledescriptor

Method test_pyobject_asfiledescriptor

Lib/test/test_capi/test_file.py:131–171  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

129 writeobject("abc", NULL, 0)
130
131 def test_pyobject_asfiledescriptor(self):
132 # Test PyObject_AsFileDescriptor(obj):
133 # - Return obj if obj is an integer.
134 # - Return obj.fileno() otherwise.
135 # File descriptor must be >= 0.
136 asfd = _testlimitedcapi.pyobject_asfiledescriptor
137
138 self.assertEqual(asfd(123), 123)
139 self.assertEqual(asfd(0), 0)
140
141 with open(__file__, "rb") as fp:
142 self.assertEqual(asfd(fp), fp.fileno())
143
144 # bool emits RuntimeWarning
145 msg = r"bool is used as a file descriptor"
146 with warnings_helper.check_warnings((msg, RuntimeWarning)):
147 self.assertEqual(asfd(True), 1)
148
149 class FakeFile:
150 def __init__(self, fd):
151 self.fd = fd
152 def fileno(self):
153 return self.fd
154
155 # file descriptor must be positive
156 with self.assertRaises(ValueError):
157 asfd(-1)
158 with self.assertRaises(ValueError):
159 asfd(FakeFile(-1))
160
161 # fileno() result must be an integer
162 with self.assertRaises(TypeError):
163 asfd(FakeFile("text"))
164
165 # unsupported types
166 for obj in ("string", ["list"], object()):
167 with self.subTest(obj=obj):
168 with self.assertRaises(TypeError):
169 asfd(obj)
170
171 # CRASHES asfd(NULL)
172
173 def test_pyfile_newstdprinter(self):
174 # Test PyFile_NewStdPrinter()

Callers

nothing calls this directly

Calls 6

FakeFileClass · 0.70
openFunction · 0.50
assertEqualMethod · 0.45
filenoMethod · 0.45
assertRaisesMethod · 0.45
subTestMethod · 0.45

Tested by

no test coverage detected