gh-94808:Improve coverage of PyObject_Print (GH-98749)

This commit is contained in:
MonadChains 2024-04-01 13:52:25 +01:00 committed by GitHub
parent 348cf6e007
commit 90c3c68a65
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 197 additions and 2 deletions

View file

@ -1,8 +1,10 @@
import enum
import unittest
from test.support import import_helper
from test.support import os_helper
_testlimitedcapi = import_helper.import_module('_testlimitedcapi')
_testcapi = import_helper.import_module('_testcapi')
class Constant(enum.IntEnum):
@ -20,7 +22,7 @@ class Constant(enum.IntEnum):
INVALID_CONSTANT = Py_CONSTANT_EMPTY_TUPLE + 1
class CAPITest(unittest.TestCase):
class GetConstantTest(unittest.TestCase):
def check_get_constant(self, get_constant):
self.assertIs(get_constant(Constant.Py_CONSTANT_NONE), None)
self.assertIs(get_constant(Constant.Py_CONSTANT_FALSE), False)
@ -50,5 +52,56 @@ def test_get_constant_borrowed(self):
self.check_get_constant(_testlimitedcapi.get_constant_borrowed)
class PrintTest(unittest.TestCase):
def testPyObjectPrintObject(self):
class PrintableObject:
def __repr__(self):
return "spam spam spam"
def __str__(self):
return "egg egg egg"
obj = PrintableObject()
output_filename = os_helper.TESTFN
self.addCleanup(os_helper.unlink, output_filename)
# Test repr printing
_testcapi.call_pyobject_print(obj, output_filename, False)
with open(output_filename, 'r') as output_file:
self.assertEqual(output_file.read(), repr(obj))
# Test str printing
_testcapi.call_pyobject_print(obj, output_filename, True)
with open(output_filename, 'r') as output_file:
self.assertEqual(output_file.read(), str(obj))
def testPyObjectPrintNULL(self):
output_filename = os_helper.TESTFN
self.addCleanup(os_helper.unlink, output_filename)
# Test repr printing
_testcapi.pyobject_print_null(output_filename)
with open(output_filename, 'r') as output_file:
self.assertEqual(output_file.read(), '<nil>')
def testPyObjectPrintNoRefObject(self):
output_filename = os_helper.TESTFN
self.addCleanup(os_helper.unlink, output_filename)
# Test repr printing
correct_output = _testcapi.pyobject_print_noref_object(output_filename)
with open(output_filename, 'r') as output_file:
self.assertEqual(output_file.read(), correct_output)
def testPyObjectPrintOSError(self):
output_filename = os_helper.TESTFN
self.addCleanup(os_helper.unlink, output_filename)
open(output_filename, "w+").close()
with self.assertRaises(OSError):
_testcapi.pyobject_print_os_error(output_filename)
if __name__ == "__main__":
unittest.main()

View file

@ -788,5 +788,6 @@ def __init__(self, obj):
Type(i)
self.assertEqual(calls, 100)
if __name__ == '__main__':
unittest.main()