@@ -426,7 +426,11 @@ def test_long_asvoidptr(self):
426426
427427 def test_long_asnativebytes (self ):
428428 import math
429- from _testcapi import pylong_asnativebytes as asnativebytes , SIZE_MAX
429+ from _testcapi import (
430+ pylong_asnativebytes as asnativebytes ,
431+ INT_MAX ,
432+ SIZE_MAX ,
433+ )
430434
431435 # Abbreviate sizeof(Py_ssize_t) to SZ because we use it a lot
432436 SZ = int (math .ceil (math .log (SIZE_MAX + 1 ) / math .log (2 )) / 8 )
@@ -453,6 +457,9 @@ def test_long_asnativebytes(self):
453457 buffer = bytearray (1 )
454458 self .assertEqual (expect , asnativebytes (v , buffer , 0 , - 1 ),
455459 "PyLong_AsNativeBytes(v, NULL, 0, -1)" )
460+ # Also check via the __index__ path
461+ self .assertEqual (expect , asnativebytes (Index (v ), buffer , 0 , - 1 ),
462+ "PyLong_AsNativeBytes(Index(v), NULL, 0, -1)" )
456463
457464 # We request as many bytes as `expect_be` contains, and always check
458465 # the result (both big and little endian). We check the return value
@@ -514,6 +521,19 @@ def test_long_asnativebytes(self):
514521 f"PyLong_AsNativeBytes(v, buffer, { n } , <little>)" )
515522 self .assertEqual (expect_le , buffer [:n ], "<little>" )
516523
524+ # Check a few error conditions. These are validated in code, but are
525+ # unspecified in docs, so if we make changes to the implementation, it's
526+ # fine to just update these tests rather than preserve the behaviour.
527+ with self .assertRaises (SystemError ):
528+ asnativebytes (1 , buffer , 0 , 2 )
529+ with self .assertRaises (TypeError ):
530+ asnativebytes ('not a number' , buffer , 0 , - 1 )
531+ with self .assertRaises (SystemError ):
532+ # n_bytes is taken as size_t and clamped to 'int'. With the sign
533+ # change, we should always be able to pass INT_MAX+1 and see this
534+ # failure.
535+ asnativebytes (1 , buffer , INT_MAX + 1 , - 1 )
536+
517537 def test_long_fromnativebytes (self ):
518538 import math
519539 from _testcapi import (
@@ -546,5 +566,14 @@ def test_long_fromnativebytes(self):
546566 self .assertEqual (expect_u , fromnativebytes (v_le , n , 1 , 0 ),
547567 f"PyLong_FromUnsignedNativeBytes(buffer, { n } , <little>)" )
548568
569+ # Check native endian when the result would be the same either
570+ # way and we can test it.
571+ if v_be == v_le :
572+ self .assertEqual (expect_s , fromnativebytes (v_be , n , - 1 , 1 ),
573+ f"PyLong_FromNativeBytes(buffer, { n } , <native>)" )
574+ self .assertEqual (expect_u , fromnativebytes (v_be , n , - 1 , 0 ),
575+ f"PyLong_FromUnsignedNativeBytes(buffer, { n } , <native>)" )
576+
577+
549578if __name__ == "__main__" :
550579 unittest .main ()
0 commit comments