@@ -808,6 +808,7 @@ def test_chr() -> None:
808808
809809[case testOrd]
810810from testutil import assertRaises
811+ from mypy_extensions import i64, i32, i16
811812
812813def test_ord() -> None:
813814 assert ord(' ') == 32
@@ -834,6 +835,77 @@ def test_ord() -> None:
834835 with assertRaises(TypeError):
835836 ord('')
836837
838+ def test_ord_str_index() -> None:
839+ # ASCII
840+ s1 = "hello"
841+ assert ord(s1[0 + int()]) == 104 # 'h'
842+ assert ord(s1[1 + int()]) == 101 # 'e'
843+ assert ord(s1[4 + int()]) == 111 # 'o'
844+ assert ord(s1[-1 + int()]) == 111 # 'o'
845+ assert ord(s1[-5 + int()]) == 104 # 'h'
846+
847+ # Latin-1 (8 bits)
848+ s2 = "café"
849+ assert ord(s2[0 + int()]) == 99 # 'c'
850+ assert ord(s2[3 + int()]) == 233 # 'é' (U+00E9)
851+ assert ord(s2[-1 + int()]) == 233
852+
853+ # 16-bit unicode
854+ s3 = "你好" # Chinese
855+ assert ord(s3[0 + int()]) == 20320 # '你' (U+4F60)
856+ assert ord(s3[1 + int()]) == 22909 # '好' (U+597D)
857+ assert ord(s3[-1 + int()]) == 22909
858+ assert ord(s3[-2 + int()]) == 20320
859+
860+ # 4-byte unicode
861+ s5 = "a😀b" # Emoji between ASCII chars
862+ assert ord(s5[0 + int()]) == 97 # 'a'
863+ assert ord(s5[1 + int()]) == 128512 # '😀' (U+1F600)
864+ assert ord(s5[2 + int()]) == 98 # 'b'
865+ assert ord(s5[-1 + int()]) == 98
866+ assert ord(s5[-2 + int()]) == 128512
867+ assert ord(s5[-3 + int()]) == 97
868+
869+ with assertRaises(IndexError, "index out of range"):
870+ ord(s1[5 + int()])
871+ with assertRaises(IndexError, "index out of range"):
872+ ord(s1[100 + int()])
873+ with assertRaises(IndexError, "index out of range"):
874+ ord(s1[-6 + int()])
875+ with assertRaises(IndexError, "index out of range"):
876+ ord(s1[-100 + int()])
877+
878+ s_empty = ""
879+ with assertRaises(IndexError, "index out of range"):
880+ ord(s_empty[0 + int()])
881+ with assertRaises(IndexError, "index out of range"):
882+ ord(s_empty[-1 + int()])
883+
884+ def test_ord_str_index_i64() -> None:
885+ s = "hello"
886+
887+ idx_i64: i64 = 2 + int()
888+ assert ord(s[idx_i64]) == 108 # 'l'
889+
890+ idx_i64_neg: i64 = -1 + int()
891+ assert ord(s[idx_i64_neg]) == 111 # 'o'
892+
893+ idx_overflow: i64 = 10 + int()
894+ with assertRaises(IndexError, "index out of range"):
895+ ord(s[idx_overflow])
896+
897+ idx_underflow: i64 = -10 + int()
898+ with assertRaises(IndexError, "index out of range"):
899+ ord(s[idx_underflow])
900+
901+ def test_ord_str_index_unicode_mix() -> None:
902+ # Mix of 1-byte, 2-byte, 3-byte, and 4-byte characters
903+ s = "a\u00e9\u4f60😀" # 'a', 'é', '你', '😀'
904+ assert ord(s[0 + int()]) == 97 # 1-byte
905+ assert ord(s[1 + int()]) == 233 # 2-byte
906+ assert ord(s[2 + int()]) == 20320 # 3-byte
907+ assert ord(s[3 + int()]) == 128512 # 4-byte
908+
837909[case testDecode]
838910from testutil import assertRaises
839911
0 commit comments