-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathtest_c.py
More file actions
4551 lines (4273 loc) · 159 KB
/
test_c.py
File metadata and controls
4551 lines (4273 loc) · 159 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import contextlib
import traceback
import unittest.mock
import pytest
import sys
import typing as t
is_musl = False
if sys.platform == 'linux':
try:
from packaging.tags import platform_tags
is_musl = any(t.startswith('musllinux') for t in platform_tags())
del platform_tags
except ImportError:
pass
def _setup_path():
import os, sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
_setup_path()
from _cffi_backend import *
from _cffi_backend import _get_types, _get_common_types
try:
from _cffi_backend import _testfunc
except ImportError:
def _testfunc(num):
pytest.skip("_testunc() not available")
from _cffi_backend import __version__
@contextlib.contextmanager
def _assert_unraisable(error_type: type[Exception] | None, message: str = '', traceback_tokens: list[str] | None = None):
"""Assert that a given sys.unraisablehook interaction occurred (or did not occur, if error_type is None) while this context was active"""
raised_errors: list[Exception] = []
raised_traceback: str = ''
# sys.unraisablehook is called more than once for chained exceptions; accumulate the errors and tracebacks for inspection
def _capture_unraisable_hook(ur_args):
nonlocal raised_traceback
raised_errors.append(ur_args.exc_value)
# NB: need to use the old etype/value/tb form until 3.10 is the minimum
raised_traceback += (ur_args.err_msg or '' + '\n') + ''.join(traceback.format_exception(None, ur_args.exc_value, ur_args.exc_traceback))
with pytest.MonkeyPatch.context() as mp:
mp.setattr(sys, 'unraisablehook', _capture_unraisable_hook)
yield
if error_type is None:
assert not raised_errors
assert not raised_traceback
return
assert any(type(raised_error) is error_type for raised_error in raised_errors)
assert any(message in str(raised_error) for raised_error in raised_errors)
for t in traceback_tokens or []:
assert t in raised_traceback
# ____________________________________________________________
import sys
assert __version__ == "1.17.1", ("This test_c.py file is for testing a version"
" of cffi that differs from the one that we"
" get from 'import _cffi_backend'")
if sys.version_info < (3,):
type_or_class = "type"
mandatory_b_prefix = ''
mandatory_u_prefix = 'u'
bytechr = chr
bitem2bchr = lambda x: x
class U(object):
def __add__(self, other):
return eval('u'+repr(other).replace(r'\\u', r'\u')
.replace(r'\\U', r'\U'))
u = U()
str2bytes = str
strict_compare = False
else:
type_or_class = "class"
long = int
unicode = str
unichr = chr
mandatory_b_prefix = 'b'
mandatory_u_prefix = ''
bytechr = lambda n: bytes([n])
bitem2bchr = bytechr
u = ""
str2bytes = lambda s: bytes(s, "ascii")
strict_compare = True
def size_of_int():
BInt = new_primitive_type("int")
return sizeof(BInt)
def size_of_long():
BLong = new_primitive_type("long")
return sizeof(BLong)
def size_of_ptr():
BInt = new_primitive_type("int")
BPtr = new_pointer_type(BInt)
return sizeof(BPtr)
def find_and_load_library(name, flags=RTLD_NOW):
import ctypes.util
if name is None:
path = None
else:
path = ctypes.util.find_library(name)
if path is None and sys.platform == 'darwin' and sys.version_info[:2] == (3, 8):
pytest.xfail("find_library usually broken on MacOS Python 3.8")
if path is None and name == 'c':
assert sys.platform == 'win32'
assert (sys.version_info >= (3,) or
'__pypy__' in sys.builtin_module_names)
pytest.skip("dlopen(None) cannot work on Windows "
"with PyPy or Python 3")
return load_library(path, flags)
def test_load_library():
x = find_and_load_library('c')
assert repr(x).startswith("<clibrary '")
x = find_and_load_library('c', RTLD_NOW | RTLD_GLOBAL)
assert repr(x).startswith("<clibrary '")
x = find_and_load_library('c', RTLD_LAZY)
assert repr(x).startswith("<clibrary '")
def test_all_rtld_symbols():
import sys
FFI_DEFAULT_ABI # these symbols must be defined
FFI_CDECL
RTLD_LAZY
RTLD_NOW
RTLD_GLOBAL
RTLD_LOCAL
if sys.platform.startswith("linux"):
RTLD_NODELETE
RTLD_NOLOAD
if not is_musl:
RTLD_DEEPBIND
def test_new_primitive_type():
pytest.raises(KeyError, new_primitive_type, "foo")
p = new_primitive_type("signed char")
assert repr(p) == "<ctype 'signed char'>"
def check_dir(p, expected):
got = [name for name in dir(p) if not name.startswith('_')]
assert got == sorted(expected)
def test_inspect_primitive_type():
p = new_primitive_type("signed char")
assert p.kind == "primitive"
assert p.cname == "signed char"
check_dir(p, ['cname', 'kind'])
def test_cast_to_signed_char():
p = new_primitive_type("signed char")
x = cast(p, -65 + 17*256)
assert repr(x) == "<cdata 'signed char' -65>"
assert repr(type(x)) == "<%s '_cffi_backend._CDataBase'>" % type_or_class
assert int(x) == -65
x = cast(p, -66 + (1<<199)*256)
assert repr(x) == "<cdata 'signed char' -66>"
assert int(x) == -66
assert (x == cast(p, -66)) is True
assert (x != cast(p, -66)) is False
q = new_primitive_type("short")
assert (x == cast(q, -66)) is True
assert (x != cast(q, -66)) is False
def test_sizeof_type():
pytest.raises(TypeError, sizeof, 42.5)
p = new_primitive_type("short")
assert sizeof(p) == 2
def test_integer_types():
for name in ['signed char', 'short', 'int', 'long', 'long long']:
p = new_primitive_type(name)
size = sizeof(p)
min = -(1 << (8*size-1))
max = (1 << (8*size-1)) - 1
assert int(cast(p, min)) == min
assert int(cast(p, max)) == max
assert int(cast(p, min - 1)) == max
assert int(cast(p, max + 1)) == min
pytest.raises(TypeError, cast, p, None)
assert long(cast(p, min - 1)) == max
assert int(cast(p, b'\x08')) == 8
assert int(cast(p, u+'\x08')) == 8
for name in ['char', 'short', 'int', 'long', 'long long']:
p = new_primitive_type('unsigned ' + name)
size = sizeof(p)
max = (1 << (8*size)) - 1
assert int(cast(p, 0)) == 0
assert int(cast(p, max)) == max
assert int(cast(p, -1)) == max
assert int(cast(p, max + 1)) == 0
assert long(cast(p, -1)) == max
assert int(cast(p, b'\xFE')) == 254
assert int(cast(p, u+'\xFE')) == 254
def test_no_float_on_int_types():
p = new_primitive_type('long')
pytest.raises(TypeError, float, cast(p, 42))
pytest.raises(TypeError, complex, cast(p, 42))
def test_float_types():
INF = 1E200 * 1E200
for name in ["float", "double"]:
p = new_primitive_type(name)
assert bool(cast(p, 0)) is False # since 1.7
assert bool(cast(p, -0.0)) is False # since 1.7
assert bool(cast(p, 1e-42)) is True
assert bool(cast(p, -1e-42)) is True
assert bool(cast(p, INF))
assert bool(cast(p, -INF))
assert bool(cast(p, float("nan")))
assert int(cast(p, -150)) == -150
assert int(cast(p, 61.91)) == 61
assert long(cast(p, 61.91)) == 61
assert type(int(cast(p, 61.91))) is int
assert type(int(cast(p, 1E22))) is long
assert type(long(cast(p, 61.91))) is long
assert type(long(cast(p, 1E22))) is long
pytest.raises(OverflowError, int, cast(p, INF))
pytest.raises(OverflowError, int, cast(p, -INF))
assert float(cast(p, 1.25)) == 1.25
assert float(cast(p, INF)) == INF
assert float(cast(p, -INF)) == -INF
if name == "float":
assert float(cast(p, 1.1)) != 1.1 # rounding error
assert float(cast(p, 1E200)) == INF # limited range
assert cast(p, -1.1) == cast(p, -1.1)
assert repr(float(cast(p, -0.0))) == '-0.0'
assert float(cast(p, b'\x09')) == 9.0
assert float(cast(p, u+'\x09')) == 9.0
assert float(cast(p, True)) == 1.0
pytest.raises(TypeError, cast, p, None)
def test_complex_types():
INF = 1E200 * 1E200
for name in ["float", "double"]:
p = new_primitive_type("_cffi_" + name + "_complex_t")
assert bool(cast(p, 0)) is False
assert bool(cast(p, INF))
assert bool(cast(p, -INF))
assert bool(cast(p, 0j)) is False
assert bool(cast(p, INF*1j))
assert bool(cast(p, -INF*1j))
# "can't convert complex to float", like CPython's "float(0j)"
pytest.raises(TypeError, int, cast(p, -150))
pytest.raises(TypeError, long, cast(p, -150))
pytest.raises(TypeError, float, cast(p, -150))
assert complex(cast(p, 1.25)) == 1.25
assert complex(cast(p, 1.25j)) == 1.25j
assert complex(cast(p, complex(0,INF))) == complex(0,INF)
assert complex(cast(p, -INF)) == -INF
if name == "float":
assert complex(cast(p, 1.1j)) != 1.1j # rounding error
assert complex(cast(p, 1E200+3j)) == INF+3j # limited range
assert complex(cast(p, complex(3,1E200))) == complex(3,INF) # limited range
assert cast(p, -1.1j) == cast(p, -1.1j)
assert repr(complex(cast(p, -0.0)).real) == '-0.0'
#assert repr(complex(cast(p, -0j))) == '-0j' # http://bugs.python.org/issue29602
assert complex(cast(p, b'\x09')) == 9.0 + 0j
assert complex(cast(p, u+'\x09')) == 9.0 + 0j
assert complex(cast(p, True)) == 1.0 + 0j
pytest.raises(TypeError, cast, p, None)
#
pytest.raises(TypeError, cast, new_primitive_type(name), 1+0j)
#
for basetype in ["char", "int", "uint64_t", "float",
"double", "long double"]:
baseobj = cast(new_primitive_type(basetype), 65)
pytest.raises(TypeError, complex, baseobj)
#
BArray = new_array_type(new_pointer_type(p), 10)
x = newp(BArray, None)
x[5] = 12.34 + 56.78j
assert type(x[5]) is complex
assert abs(x[5] - (12.34 + 56.78j)) < 1e-5
assert (x[5] == 12.34 + 56.78j) == (name == "double") # rounding error
#
class Foo:
def __complex__(self):
return 2 + 3j
assert complex(Foo()) == 2 + 3j
assert complex(cast(p, Foo())) == 2 + 3j
pytest.raises(TypeError, cast, new_primitive_type("int"), 1+0j)
def test_character_type():
p = new_primitive_type("char")
assert bool(cast(p, 'A')) is True
assert bool(cast(p, '\x00')) is False # since 1.7
assert cast(p, '\x00') == cast(p, -17*256)
assert int(cast(p, 'A')) == 65
assert long(cast(p, 'A')) == 65
assert type(int(cast(p, 'A'))) is int
assert type(long(cast(p, 'A'))) is long
assert str(cast(p, 'A')) == repr(cast(p, 'A'))
assert repr(cast(p, 'A')) == "<cdata 'char' %s'A'>" % mandatory_b_prefix
assert repr(cast(p, 255)) == r"<cdata 'char' %s'\xff'>" % mandatory_b_prefix
assert repr(cast(p, 0)) == r"<cdata 'char' %s'\x00'>" % mandatory_b_prefix
def test_pointer_type():
p = new_primitive_type("int")
assert repr(p) == "<ctype 'int'>"
p = new_pointer_type(p)
assert repr(p) == "<ctype 'int *'>"
p = new_pointer_type(p)
assert repr(p) == "<ctype 'int * *'>"
p = new_pointer_type(p)
assert repr(p) == "<ctype 'int * * *'>"
def test_inspect_pointer_type():
p1 = new_primitive_type("int")
p2 = new_pointer_type(p1)
assert p2.kind == "pointer"
assert p2.cname == "int *"
assert p2.item is p1
check_dir(p2, ['cname', 'kind', 'item'])
p3 = new_pointer_type(p2)
assert p3.item is p2
def test_pointer_to_int():
BInt = new_primitive_type("int")
pytest.raises(TypeError, newp, BInt)
pytest.raises(TypeError, newp, BInt, None)
BPtr = new_pointer_type(BInt)
p = newp(BPtr)
assert repr(p) == "<cdata 'int *' owning %d bytes>" % size_of_int()
p = newp(BPtr, None)
assert repr(p) == "<cdata 'int *' owning %d bytes>" % size_of_int()
p = newp(BPtr, 5000)
assert repr(p) == "<cdata 'int *' owning %d bytes>" % size_of_int()
q = cast(BPtr, p)
assert repr(q).startswith("<cdata 'int *' 0x")
assert p == q
assert hash(p) == hash(q)
e = pytest.raises(TypeError, newp, new_array_type(BPtr, None), None)
assert str(e.value) == (
"expected new array length or list/tuple/str, not NoneType")
def test_pointer_bool():
BInt = new_primitive_type("int")
BPtr = new_pointer_type(BInt)
p = cast(BPtr, 0)
assert bool(p) is False
p = cast(BPtr, 42)
assert bool(p) is True
def test_pointer_to_pointer():
BInt = new_primitive_type("int")
BPtr = new_pointer_type(BInt)
BPtrPtr = new_pointer_type(BPtr)
p = newp(BPtrPtr, None)
assert repr(p) == "<cdata 'int * *' owning %d bytes>" % size_of_ptr()
def test_reading_pointer_to_int():
BInt = new_primitive_type("int")
BPtr = new_pointer_type(BInt)
p = newp(BPtr, None)
assert p[0] == 0
p = newp(BPtr, 5000)
assert p[0] == 5000
with pytest.raises(IndexError):
p[1]
with pytest.raises(IndexError):
p[-1]
def test_reading_pointer_to_float():
BFloat = new_primitive_type("float")
pytest.raises(TypeError, newp, BFloat, None)
BPtr = new_pointer_type(BFloat)
p = newp(BPtr, None)
assert p[0] == 0.0 and type(p[0]) is float
p = newp(BPtr, 1.25)
assert p[0] == 1.25 and type(p[0]) is float
p = newp(BPtr, 1.1)
assert p[0] != 1.1 and abs(p[0] - 1.1) < 1E-5 # rounding errors
def test_cast_float_to_int():
for type in ["int", "unsigned int", "long", "unsigned long",
"long long", "unsigned long long"]:
p = new_primitive_type(type)
assert int(cast(p, 4.2)) == 4
pytest.raises(TypeError, newp, new_pointer_type(p), 4.2)
def test_newp_integer_types():
for name in ['signed char', 'short', 'int', 'long', 'long long']:
p = new_primitive_type(name)
pp = new_pointer_type(p)
size = sizeof(p)
min = -(1 << (8*size-1))
max = (1 << (8*size-1)) - 1
assert newp(pp, min)[0] == min
assert newp(pp, max)[0] == max
pytest.raises(OverflowError, newp, pp, min - 2 ** 32)
pytest.raises(OverflowError, newp, pp, min - 2 ** 64)
pytest.raises(OverflowError, newp, pp, max + 2 ** 32)
pytest.raises(OverflowError, newp, pp, max + 2 ** 64)
pytest.raises(OverflowError, newp, pp, min - 1)
pytest.raises(OverflowError, newp, pp, max + 1)
pytest.raises(OverflowError, newp, pp, min - 1 - 2 ** 32)
pytest.raises(OverflowError, newp, pp, min - 1 - 2 ** 64)
pytest.raises(OverflowError, newp, pp, max + 1)
pytest.raises(OverflowError, newp, pp, max + 1 + 2 ** 32)
pytest.raises(OverflowError, newp, pp, max + 1 + 2 ** 64)
pytest.raises(TypeError, newp, pp, 1.0)
for name in ['char', 'short', 'int', 'long', 'long long']:
p = new_primitive_type('unsigned ' + name)
pp = new_pointer_type(p)
size = sizeof(p)
max = (1 << (8*size)) - 1
assert newp(pp, 0)[0] == 0
assert newp(pp, max)[0] == max
pytest.raises(OverflowError, newp, pp, -1)
pytest.raises(OverflowError, newp, pp, max + 1)
def test_reading_pointer_to_char():
BChar = new_primitive_type("char")
pytest.raises(TypeError, newp, BChar, None)
BPtr = new_pointer_type(BChar)
p = newp(BPtr, None)
assert p[0] == b'\x00'
p = newp(BPtr, b'A')
assert p[0] == b'A'
pytest.raises(TypeError, newp, BPtr, 65)
pytest.raises(TypeError, newp, BPtr, b"foo")
pytest.raises(TypeError, newp, BPtr, u+"foo")
c = cast(BChar, b'A')
assert str(c) == repr(c)
assert int(c) == ord(b'A')
pytest.raises(TypeError, cast, BChar, b'foo')
pytest.raises(TypeError, cast, BChar, u+'foo')
e = pytest.raises(TypeError, newp, new_array_type(BPtr, None), 12.3)
assert str(e.value) == (
"expected new array length or list/tuple/str, not float")
def test_reading_pointer_to_pointer():
BVoidP = new_pointer_type(new_void_type())
BCharP = new_pointer_type(new_primitive_type("char"))
BInt = new_primitive_type("int")
BIntPtr = new_pointer_type(BInt)
BIntPtrPtr = new_pointer_type(BIntPtr)
q = newp(BIntPtr, 42)
assert q[0] == 42
p = newp(BIntPtrPtr, None)
assert p[0] is not None
assert p[0] == cast(BVoidP, 0)
assert p[0] == cast(BCharP, 0)
assert p[0] != None
assert repr(p[0]) == "<cdata 'int *' NULL>"
p[0] = q
assert p[0] != cast(BVoidP, 0)
assert p[0] != cast(BCharP, 0)
assert p[0][0] == 42
q[0] += 1
assert p[0][0] == 43
p = newp(BIntPtrPtr, q)
assert p[0][0] == 43
def test_load_standard_library():
if sys.platform == "win32":
pytest.raises(OSError, find_and_load_library, None)
return
x = find_and_load_library(None)
BVoidP = new_pointer_type(new_void_type())
assert x.load_function(BVoidP, 'strcpy')
pytest.raises(AttributeError, x.load_function,
BVoidP, 'xxx_this_function_does_not_exist')
# the next one is from 'libm', not 'libc', but we assume
# that it is already loaded too, so it should work
assert x.load_function(BVoidP, 'sqrt')
#
x.close_lib()
pytest.raises(ValueError, x.load_function, BVoidP, 'sqrt')
x.close_lib()
def test_no_len_on_nonarray():
p = new_primitive_type("int")
pytest.raises(TypeError, len, cast(p, 42))
def test_cmp_none():
p = new_primitive_type("int")
x = cast(p, 42)
assert (x == None) is False
assert (x != None) is True
assert (x == ["hello"]) is False
assert (x != ["hello"]) is True
y = cast(p, 0)
assert (y == None) is False
def test_invalid_indexing():
p = new_primitive_type("int")
x = cast(p, 42)
with pytest.raises(TypeError):
x[0]
def test_default_str():
BChar = new_primitive_type("char")
x = cast(BChar, 42)
assert str(x) == repr(x)
BInt = new_primitive_type("int")
x = cast(BInt, 42)
assert str(x) == repr(x)
BArray = new_array_type(new_pointer_type(BInt), 10)
x = newp(BArray, None)
assert str(x) == repr(x)
def test_default_unicode():
BInt = new_primitive_type("int")
x = cast(BInt, 42)
assert unicode(x) == unicode(repr(x))
BArray = new_array_type(new_pointer_type(BInt), 10)
x = newp(BArray, None)
assert unicode(x) == unicode(repr(x))
def test_cast_from_cdataint():
BInt = new_primitive_type("int")
x = cast(BInt, 0)
y = cast(new_pointer_type(BInt), x)
assert bool(y) is False
#
x = cast(BInt, 42)
y = cast(BInt, x)
assert int(y) == 42
y = cast(new_primitive_type("char"), x)
assert int(y) == 42
y = cast(new_primitive_type("float"), x)
assert float(y) == 42.0
#
z = cast(BInt, 42.5)
assert int(z) == 42
z = cast(BInt, y)
assert int(z) == 42
def test_void_type():
p = new_void_type()
assert p.kind == "void"
assert p.cname == "void"
check_dir(p, ['kind', 'cname'])
def test_array_type():
p = new_primitive_type("int")
assert repr(p) == "<ctype 'int'>"
#
pytest.raises(TypeError, new_array_type, new_pointer_type(p), "foo")
pytest.raises(ValueError, new_array_type, new_pointer_type(p), -42)
#
p1 = new_array_type(new_pointer_type(p), None)
assert repr(p1) == "<ctype 'int[]'>"
pytest.raises(ValueError, new_array_type, new_pointer_type(p1), 42)
#
p1 = new_array_type(new_pointer_type(p), 42)
p2 = new_array_type(new_pointer_type(p1), 25)
assert repr(p2) == "<ctype 'int[25][42]'>"
p2 = new_array_type(new_pointer_type(p1), None)
assert repr(p2) == "<ctype 'int[][42]'>"
#
pytest.raises(OverflowError,
new_array_type, new_pointer_type(p), sys.maxsize+1)
pytest.raises(OverflowError,
new_array_type, new_pointer_type(p), sys.maxsize // 3)
def test_inspect_array_type():
p = new_primitive_type("int")
p1 = new_array_type(new_pointer_type(p), None)
assert p1.kind == "array"
assert p1.cname == "int[]"
assert p1.item is p
assert p1.length is None
check_dir(p1, ['cname', 'kind', 'item', 'length'])
p1 = new_array_type(new_pointer_type(p), 42)
assert p1.kind == "array"
assert p1.cname == "int[42]"
assert p1.item is p
assert p1.length == 42
check_dir(p1, ['cname', 'kind', 'item', 'length'])
def test_array_instance():
LENGTH = 1423
p = new_primitive_type("int")
p1 = new_array_type(new_pointer_type(p), LENGTH)
a = newp(p1, None)
assert repr(a) == "<cdata 'int[%d]' owning %d bytes>" % (
LENGTH, LENGTH * size_of_int())
assert len(a) == LENGTH
for i in range(LENGTH):
assert a[i] == 0
with pytest.raises(IndexError):
a[LENGTH]
with pytest.raises(IndexError):
a[-1]
for i in range(LENGTH):
a[i] = i * i + 1
for i in range(LENGTH):
assert a[i] == i * i + 1
with pytest.raises(IndexError) as e:
a[LENGTH+100] = 500
assert ('(expected %d < %d)' % (LENGTH+100, LENGTH)) in str(e.value)
pytest.raises(TypeError, int, a)
def test_array_of_unknown_length_instance():
p = new_primitive_type("int")
p1 = new_array_type(new_pointer_type(p), None)
pytest.raises(TypeError, newp, p1, None)
pytest.raises(ValueError, newp, p1, -42)
a = newp(p1, 42)
assert len(a) == 42
for i in range(42):
a[i] -= i
for i in range(42):
assert a[i] == -i
with pytest.raises(IndexError):
a[42]
with pytest.raises(IndexError):
a[-1]
with pytest.raises(IndexError):
a[42] = 123
with pytest.raises(IndexError):
a[-1] = 456
def test_array_of_unknown_length_instance_with_initializer():
p = new_primitive_type("int")
p1 = new_array_type(new_pointer_type(p), None)
a = newp(p1, list(range(42)))
assert len(a) == 42
a = newp(p1, tuple(range(142)))
assert len(a) == 142
def test_array_initializer():
p = new_primitive_type("int")
p1 = new_array_type(new_pointer_type(p), None)
a = newp(p1, list(range(100, 142)))
for i in range(42):
assert a[i] == 100 + i
#
p2 = new_array_type(new_pointer_type(p), 43)
a = newp(p2, tuple(range(100, 142)))
for i in range(42):
assert a[i] == 100 + i
assert a[42] == 0 # extra uninitialized item
def test_array_add():
p = new_primitive_type("int")
p1 = new_array_type(new_pointer_type(p), 5) # int[5]
p2 = new_array_type(new_pointer_type(p1), 3) # int[3][5]
a = newp(p2, [list(range(n, n+5)) for n in [100, 200, 300]])
assert repr(a) == "<cdata 'int[3][5]' owning %d bytes>" % (
3*5*size_of_int(),)
assert repr(a + 0).startswith("<cdata 'int(*)[5]' 0x")
assert 0 + a == a + 0 != 1 + a == a + 1
assert repr(a[0]).startswith("<cdata 'int[5]' 0x")
assert repr((a + 0)[0]).startswith("<cdata 'int[5]' 0x")
assert repr(a[0] + 0).startswith("<cdata 'int *' 0x")
assert type(a[0][0]) is int
assert type((a[0] + 0)[0]) is int
def test_array_sub():
BInt = new_primitive_type("int")
BArray = new_array_type(new_pointer_type(BInt), 5) # int[5]
a = newp(BArray, None)
p = a + 1
assert p - a == 1
assert p - (a+0) == 1
assert a == (p - 1)
BPtr = new_pointer_type(new_primitive_type("short"))
q = newp(BPtr, None)
with pytest.raises(TypeError):
p - q
with pytest.raises(TypeError):
q - p
with pytest.raises(TypeError):
a - q
with pytest.raises(TypeError) as e:
q - a
assert str(e.value) == "cannot subtract cdata 'short *' and cdata 'int *'"
def test_ptr_sub_unaligned():
BInt = new_primitive_type("int")
BIntPtr = new_pointer_type(BInt)
a = cast(BIntPtr, 1240)
for bi in range(1430, 1438):
b = cast(BIntPtr, bi)
if ((bi - 1240) % size_of_int()) == 0:
assert b - a == (bi - 1240) // size_of_int()
assert a - b == (1240 - bi) // size_of_int()
else:
with pytest.raises(ValueError):
b - a
with pytest.raises(ValueError):
a - b
def test_cast_primitive_from_cdata():
p = new_primitive_type("int")
n = cast(p, cast(p, -42))
assert int(n) == -42
#
p = new_primitive_type("unsigned int")
n = cast(p, cast(p, 42))
assert int(n) == 42
#
p = new_primitive_type("long long")
n = cast(p, cast(p, -(1<<60)))
assert int(n) == -(1<<60)
#
p = new_primitive_type("unsigned long long")
n = cast(p, cast(p, 1<<63))
assert int(n) == 1<<63
#
p = new_primitive_type("float")
n = cast(p, cast(p, 42.5))
assert float(n) == 42.5
#
p = new_primitive_type("char")
n = cast(p, cast(p, "A"))
assert int(n) == ord("A")
def test_new_primitive_from_cdata():
p = new_primitive_type("int")
p1 = new_pointer_type(p)
n = newp(p1, cast(p, -42))
assert n[0] == -42
#
p = new_primitive_type("unsigned int")
p1 = new_pointer_type(p)
n = newp(p1, cast(p, 42))
assert n[0] == 42
#
p = new_primitive_type("float")
p1 = new_pointer_type(p)
n = newp(p1, cast(p, 42.5))
assert n[0] == 42.5
#
p = new_primitive_type("char")
p1 = new_pointer_type(p)
n = newp(p1, cast(p, "A"))
assert n[0] == b"A"
def test_cast_between_pointers():
BIntP = new_pointer_type(new_primitive_type("int"))
BIntA = new_array_type(BIntP, None)
a = newp(BIntA, [40, 41, 42, 43, 44])
BShortP = new_pointer_type(new_primitive_type("short"))
b = cast(BShortP, a)
c = cast(BIntP, b)
assert c[3] == 43
BLongLong = new_primitive_type("long long")
d = cast(BLongLong, c)
e = cast(BIntP, d)
assert e[3] == 43
f = cast(BIntP, int(d))
assert f[3] == 43
#
b = cast(BShortP, 0)
assert not b
c = cast(BIntP, b)
assert not c
assert int(cast(BLongLong, c)) == 0
def test_alignof():
BInt = new_primitive_type("int")
assert alignof(BInt) == sizeof(BInt)
BPtr = new_pointer_type(BInt)
assert alignof(BPtr) == sizeof(BPtr)
BArray = new_array_type(BPtr, None)
assert alignof(BArray) == alignof(BInt)
def test_new_struct_type():
BStruct = new_struct_type("foo")
assert repr(BStruct) == "<ctype 'foo'>"
BStruct = new_struct_type("struct foo")
assert repr(BStruct) == "<ctype 'struct foo'>"
BPtr = new_pointer_type(BStruct)
assert repr(BPtr) == "<ctype 'struct foo *'>"
pytest.raises(ValueError, sizeof, BStruct)
pytest.raises(ValueError, alignof, BStruct)
def test_new_union_type():
BUnion = new_union_type("union foo")
assert repr(BUnion) == "<ctype 'union foo'>"
BPtr = new_pointer_type(BUnion)
assert repr(BPtr) == "<ctype 'union foo *'>"
def test_complete_struct():
BLong = new_primitive_type("long")
BChar = new_primitive_type("char")
BShort = new_primitive_type("short")
BStruct = new_struct_type("struct foo")
assert BStruct.kind == "struct"
assert BStruct.cname == "struct foo"
assert BStruct.fields is None
check_dir(BStruct, ['cname', 'kind', 'fields'])
#
complete_struct_or_union(BStruct, [('a1', BLong, -1),
('a2', BChar, -1),
('a3', BShort, -1)])
d = BStruct.fields
assert len(d) == 3
assert d[0][0] == 'a1'
assert d[0][1].type is BLong
assert d[0][1].offset == 0
assert d[0][1].bitshift == -1
assert d[0][1].bitsize == -1
assert d[1][0] == 'a2'
assert d[1][1].type is BChar
assert d[1][1].offset == sizeof(BLong)
assert d[1][1].bitshift == -1
assert d[1][1].bitsize == -1
assert d[2][0] == 'a3'
assert d[2][1].type is BShort
assert d[2][1].offset == sizeof(BLong) + sizeof(BShort)
assert d[2][1].bitshift == -1
assert d[2][1].bitsize == -1
assert sizeof(BStruct) == 2 * sizeof(BLong)
assert alignof(BStruct) == alignof(BLong)
def test_complete_union():
BLong = new_primitive_type("long")
BChar = new_primitive_type("char")
BUnion = new_union_type("union foo")
assert BUnion.kind == "union"
assert BUnion.cname == "union foo"
assert BUnion.fields is None
complete_struct_or_union(BUnion, [('a1', BLong, -1),
('a2', BChar, -1)])
d = BUnion.fields
assert len(d) == 2
assert d[0][0] == 'a1'
assert d[0][1].type is BLong
assert d[0][1].offset == 0
assert d[1][0] == 'a2'
assert d[1][1].type is BChar
assert d[1][1].offset == 0
assert sizeof(BUnion) == sizeof(BLong)
assert alignof(BUnion) == alignof(BLong)
def test_struct_instance():
BInt = new_primitive_type("int")
BStruct = new_struct_type("struct foo")
BStructPtr = new_pointer_type(BStruct)
p = cast(BStructPtr, 42)
with pytest.raises(AttributeError) as e:
p.a1 # opaque
assert str(e.value) == ("cdata 'struct foo *' points to an opaque type: "
"cannot read fields")
with pytest.raises(AttributeError) as e:
p.a1 = 10 # opaque
assert str(e.value) == ("cdata 'struct foo *' points to an opaque type: "
"cannot write fields")
complete_struct_or_union(BStruct, [('a1', BInt, -1),
('a2', BInt, -1)])
p = newp(BStructPtr, None)
s = p[0]
assert s.a1 == 0
s.a2 = 123
assert s.a1 == 0
assert s.a2 == 123
with pytest.raises(OverflowError):
s.a1 = sys.maxsize+1
assert s.a1 == 0
with pytest.raises(AttributeError) as e:
p.foobar
assert str(e.value) == "cdata 'struct foo *' has no field 'foobar'"
with pytest.raises(AttributeError) as e:
p.foobar = 42
assert str(e.value) == "cdata 'struct foo *' has no field 'foobar'"
with pytest.raises(AttributeError) as e:
s.foobar
assert str(e.value) == "cdata 'struct foo' has no field 'foobar'"
with pytest.raises(AttributeError) as e:
s.foobar = 42
assert str(e.value) == "cdata 'struct foo' has no field 'foobar'"
j = cast(BInt, 42)
with pytest.raises(AttributeError) as e:
j.foobar
assert str(e.value) == "cdata 'int' has no attribute 'foobar'"
with pytest.raises(AttributeError) as e:
j.foobar = 42
assert str(e.value) == "cdata 'int' has no attribute 'foobar'"
j = cast(new_pointer_type(BInt), 42)
with pytest.raises(AttributeError) as e:
j.foobar
assert str(e.value) == "cdata 'int *' has no attribute 'foobar'"
with pytest.raises(AttributeError) as e:
j.foobar = 42
assert str(e.value) == "cdata 'int *' has no attribute 'foobar'"
pp = newp(new_pointer_type(BStructPtr), p)
with pytest.raises(AttributeError) as e:
pp.a1
assert str(e.value) == "cdata 'struct foo * *' has no attribute 'a1'"
with pytest.raises(AttributeError) as e:
pp.a1 = 42
assert str(e.value) == "cdata 'struct foo * *' has no attribute 'a1'"
def test_union_instance():
BInt = new_primitive_type("int")
BUInt = new_primitive_type("unsigned int")
BUnion = new_union_type("union bar")
complete_struct_or_union(BUnion, [('a1', BInt, -1), ('a2', BUInt, -1)])
p = newp(new_pointer_type(BUnion), [-42])
bigval = -42 + (1 << (8*size_of_int()))
assert p.a1 == -42
assert p.a2 == bigval
p = newp(new_pointer_type(BUnion), {'a2': bigval})
assert p.a1 == -42
assert p.a2 == bigval
pytest.raises(OverflowError, newp, new_pointer_type(BUnion),
{'a1': bigval})
p = newp(new_pointer_type(BUnion), [])
assert p.a1 == p.a2 == 0
def test_struct_pointer():
BInt = new_primitive_type("int")
BStruct = new_struct_type("struct foo")
BStructPtr = new_pointer_type(BStruct)
complete_struct_or_union(BStruct, [('a1', BInt, -1),
('a2', BInt, -1)])
p = newp(BStructPtr, None)
assert p.a1 == 0 # read/write via the pointer (C equivalent: '->')
p.a2 = 123
assert p.a1 == 0
assert p.a2 == 123
def test_struct_init_list():
BVoidP = new_pointer_type(new_void_type())
BInt = new_primitive_type("int")
BIntPtr = new_pointer_type(BInt)
BStruct = new_struct_type("struct foo")
BStructPtr = new_pointer_type(BStruct)
complete_struct_or_union(BStruct, [('a1', BInt, -1),
('a2', BInt, -1),
('a3', BInt, -1),
('p4', BIntPtr, -1)])
s = newp(BStructPtr, [123, 456])
assert s.a1 == 123
assert s.a2 == 456
assert s.a3 == 0
assert s.p4 == cast(BVoidP, 0)
assert s.p4 != 0
#
s = newp(BStructPtr, {'a2': 41122, 'a3': -123})
assert s.a1 == 0
assert s.a2 == 41122
assert s.a3 == -123
assert s.p4 == cast(BVoidP, 0)
#
pytest.raises(KeyError, newp, BStructPtr, {'foobar': 0})
#
p = newp(BIntPtr, 14141)
s = newp(BStructPtr, [12, 34, 56, p])
assert s.p4 == p
assert s.p4
#
s = newp(BStructPtr, [12, 34, 56, cast(BVoidP, 0)])
assert s.p4 == cast(BVoidP, 0)
assert not s.p4
#
pytest.raises(TypeError, newp, BStructPtr, [12, 34, 56, None])
def test_array_in_struct():
BInt = new_primitive_type("int")
BStruct = new_struct_type("struct foo")
BArrayInt5 = new_array_type(new_pointer_type(BInt), 5)
complete_struct_or_union(BStruct, [('a1', BArrayInt5, -1)])
s = newp(new_pointer_type(BStruct), [[20, 24, 27, 29, 30]])
assert s.a1[2] == 27
assert repr(s.a1).startswith("<cdata 'int[5]' 0x")
def test_offsetof():
def offsetof(BType, fieldname):
return typeoffsetof(BType, fieldname)[1]
BInt = new_primitive_type("int")
BStruct = new_struct_type("struct foo")
pytest.raises(TypeError, offsetof, BInt, "abc")
pytest.raises(TypeError, offsetof, BStruct, "abc")
complete_struct_or_union(BStruct, [('abc', BInt, -1), ('def', BInt, -1)])
assert offsetof(BStruct, 'abc') == 0
assert offsetof(BStruct, 'def') == size_of_int()
pytest.raises(KeyError, offsetof, BStruct, "ghi")
assert offsetof(new_pointer_type(BStruct), "def") == size_of_int()
def test_function_type():
BInt = new_primitive_type("int")
BFunc = new_function_type((BInt, BInt), BInt, False)
assert repr(BFunc) == "<ctype 'int(*)(int, int)'>"
BFunc2 = new_function_type((), BFunc, False)
assert repr(BFunc2) == "<ctype 'int(*(*)())(int, int)'>"
def test_inspect_function_type():