MCPcopy Index your code
hub / github.com/python/cpython / test_custom_struct_new_and_init

Method test_custom_struct_new_and_init

Lib/test/test_struct.py:918–959  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

916 self.assertEqual(my_struct.pack(12345), b'\x30\x39')
917
918 def test_custom_struct_new_and_init(self):
919 # New way, no warnings:
920 class MyStruct(struct.Struct):
921 def __new__(cls, newargs, initargs):
922 return super().__new__(cls, *newargs)
923 def __init__(self, newargs, initargs):
924 if initargs is not None:
925 super().__init__(*initargs)
926
927 my_struct = MyStruct(('>h',), ('>h',))
928 self.assertEqual(my_struct.format, '>h')
929 self.assertEqual(my_struct.pack(12345), b'\x30\x39')
930 with self.assertRaises(TypeError):
931 MyStruct((), ())
932 with self.assertRaises(TypeError):
933 MyStruct(('>h',), ())
934 with self.assertRaises(TypeError):
935 MyStruct((), ('>h',))
936 with self.assertRaises(TypeError):
937 MyStruct((42,), ('>h',))
938 with self.assertWarns(FutureWarning):
939 with self.assertRaises(TypeError):
940 MyStruct(('>h',), (42,))
941 with self.assertRaises(struct.error):
942 MyStruct(('$',), ('>h',))
943 with self.assertWarns(FutureWarning):
944 with self.assertRaises(struct.error):
945 MyStruct(('>h',), ('$',))
946 with self.assertRaises(ValueError):
947 MyStruct(('\udc00',), ('>h',))
948 with self.assertRaises(ValueError):
949 MyStruct((b'\xa4',), ('>h',))
950 with self.assertWarns(FutureWarning):
951 with self.assertRaises(ValueError):
952 MyStruct(('>h',), ('\udc00',))
953 with self.assertWarns(FutureWarning):
954 with self.assertRaises(ValueError):
955 MyStruct(('>h',), (b'\xa4',))
956 with self.assertWarns(FutureWarning):
957 my_struct = MyStruct(('>h',), ('<h',))
958 self.assertEqual(my_struct.format, '<h')
959 self.assertEqual(my_struct.pack(12345), b'\x39\x30')
960
961 def test_no_custom_struct_new_or_init(self):
962 class MyStruct(struct.Struct):

Callers

nothing calls this directly

Calls 5

MyStructClass · 0.85
assertWarnsMethod · 0.80
assertEqualMethod · 0.45
packMethod · 0.45
assertRaisesMethod · 0.45

Tested by

no test coverage detected