forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_clinic.py
3126 lines (2779 loc) · 107 KB
/
test_clinic.py
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
# Argument Clinic
# Copyright 2012-2013 by Larry Hastings.
# Licensed to the PSF under a contributor agreement.
from test import support, test_tools
from test.support import os_helper
from test.support.os_helper import TESTFN, unlink
from textwrap import dedent
from unittest import TestCase
import collections
import contextlib
import inspect
import os.path
import re
import sys
import unittest
test_tools.skip_if_missing('clinic')
with test_tools.imports_under_tool('clinic'):
import clinic
from clinic import DSLParser
def _expect_failure(tc, parser, code, errmsg, *, filename=None, lineno=None):
"""Helper for the parser tests.
tc: unittest.TestCase; passed self in the wrapper
parser: the clinic parser used for this test case
code: a str with input text (clinic code)
errmsg: the expected error message
filename: str, optional filename
lineno: int, optional line number
"""
code = dedent(code).strip()
errmsg = re.escape(errmsg)
with tc.assertRaisesRegex(clinic.ClinicError, errmsg) as cm:
parser(code)
if filename is not None:
tc.assertEqual(cm.exception.filename, filename)
if lineno is not None:
tc.assertEqual(cm.exception.lineno, lineno)
class FakeConverter:
def __init__(self, name, args):
self.name = name
self.args = args
class FakeConverterFactory:
def __init__(self, name):
self.name = name
def __call__(self, name, default, **kwargs):
return FakeConverter(self.name, kwargs)
class FakeConvertersDict:
def __init__(self):
self.used_converters = {}
def get(self, name, default):
return self.used_converters.setdefault(name, FakeConverterFactory(name))
c = clinic.Clinic(language='C', filename = "file")
class FakeClinic:
def __init__(self):
self.converters = FakeConvertersDict()
self.legacy_converters = FakeConvertersDict()
self.language = clinic.CLanguage(None)
self.filename = "clinic_tests"
self.destination_buffers = {}
self.block_parser = clinic.BlockParser('', self.language)
self.modules = collections.OrderedDict()
self.classes = collections.OrderedDict()
clinic.clinic = self
self.name = "FakeClinic"
self.line_prefix = self.line_suffix = ''
self.destinations = {}
self.add_destination("block", "buffer")
self.add_destination("file", "buffer")
self.add_destination("suppress", "suppress")
d = self.destinations.get
self.field_destinations = collections.OrderedDict((
('docstring_prototype', d('suppress')),
('docstring_definition', d('block')),
('methoddef_define', d('block')),
('impl_prototype', d('block')),
('parser_prototype', d('suppress')),
('parser_definition', d('block')),
('impl_definition', d('block')),
))
self.functions = []
def get_destination(self, name):
d = self.destinations.get(name)
if not d:
sys.exit("Destination does not exist: " + repr(name))
return d
def add_destination(self, name, type, *args):
if name in self.destinations:
sys.exit("Destination already exists: " + repr(name))
self.destinations[name] = clinic.Destination(name, type, self, *args)
def is_directive(self, name):
return name == "module"
def directive(self, name, args):
self.called_directives[name] = args
_module_and_class = clinic.Clinic._module_and_class
def __repr__(self):
return "<FakeClinic object>"
class ClinicWholeFileTest(TestCase):
maxDiff = None
def expect_failure(self, raw, errmsg, *, filename=None, lineno=None):
_expect_failure(self, self.clinic.parse, raw, errmsg,
filename=filename, lineno=lineno)
def setUp(self):
self.clinic = clinic.Clinic(clinic.CLanguage(None), filename="test.c")
def test_eol(self):
# regression test:
# clinic's block parser didn't recognize
# the "end line" for the block if it
# didn't end in "\n" (as in, the last)
# byte of the file was '/'.
# so it would spit out an end line for you.
# and since you really already had one,
# the last line of the block got corrupted.
raw = "/*[clinic]\nfoo\n[clinic]*/"
cooked = self.clinic.parse(raw).splitlines()
end_line = cooked[2].rstrip()
# this test is redundant, it's just here explicitly to catch
# the regression test so we don't forget what it looked like
self.assertNotEqual(end_line, "[clinic]*/[clinic]*/")
self.assertEqual(end_line, "[clinic]*/")
def test_mangled_marker_line(self):
raw = """
/*[clinic input]
[clinic start generated code]*/
/*[clinic end generated code: foo]*/
"""
err = (
"Mangled Argument Clinic marker line: "
"'/*[clinic end generated code: foo]*/'"
)
self.expect_failure(raw, err, filename="test.c", lineno=3)
def test_checksum_mismatch(self):
raw = """
/*[clinic input]
[clinic start generated code]*/
/*[clinic end generated code: output=0123456789abcdef input=fedcba9876543210]*/
"""
err = ("Checksum mismatch! "
"Expected '0123456789abcdef', computed 'da39a3ee5e6b4b0d'")
self.expect_failure(raw, err, filename="test.c", lineno=3)
def test_garbage_after_stop_line(self):
raw = """
/*[clinic input]
[clinic start generated code]*/foobarfoobar!
"""
err = "Garbage after stop line: 'foobarfoobar!'"
self.expect_failure(raw, err, filename="test.c", lineno=2)
def test_whitespace_before_stop_line(self):
raw = """
/*[clinic input]
[clinic start generated code]*/
"""
err = (
"Whitespace is not allowed before the stop line: "
"' [clinic start generated code]*/'"
)
self.expect_failure(raw, err, filename="test.c", lineno=2)
def test_parse_with_body_prefix(self):
clang = clinic.CLanguage(None)
clang.body_prefix = "//"
clang.start_line = "//[{dsl_name} start]"
clang.stop_line = "//[{dsl_name} stop]"
cl = clinic.Clinic(clang, filename="test.c")
raw = dedent("""
//[clinic start]
//module test
//[clinic stop]
""").strip()
out = cl.parse(raw)
expected = dedent("""
//[clinic start]
//module test
//
//[clinic stop]
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=65fab8adff58cf08]*/
""").lstrip() # Note, lstrip() because of the newline
self.assertEqual(out, expected)
def test_cpp_monitor_fail_nested_block_comment(self):
raw = """
/* start
/* nested
*/
*/
"""
err = 'Nested block comment!'
self.expect_failure(raw, err, filename="test.c", lineno=2)
def test_cpp_monitor_fail_invalid_format_noarg(self):
raw = """
#if
a()
#endif
"""
err = 'Invalid format for #if line: no argument!'
self.expect_failure(raw, err, filename="test.c", lineno=1)
def test_cpp_monitor_fail_invalid_format_toomanyargs(self):
raw = """
#ifdef A B
a()
#endif
"""
err = 'Invalid format for #ifdef line: should be exactly one argument!'
self.expect_failure(raw, err, filename="test.c", lineno=1)
def test_cpp_monitor_fail_no_matching_if(self):
raw = '#else'
err = '#else without matching #if / #ifdef / #ifndef!'
self.expect_failure(raw, err, filename="test.c", lineno=1)
def test_directive_output_unknown_preset(self):
raw = """
/*[clinic input]
output preset nosuchpreset
[clinic start generated code]*/
"""
err = "Unknown preset 'nosuchpreset'"
self.expect_failure(raw, err)
def test_directive_output_cant_pop(self):
raw = """
/*[clinic input]
output pop
[clinic start generated code]*/
"""
err = "Can't 'output pop', stack is empty"
self.expect_failure(raw, err)
def test_directive_output_print(self):
raw = dedent("""
/*[clinic input]
output print 'I told you once.'
[clinic start generated code]*/
""")
out = self.clinic.parse(raw)
# The generated output will differ for every run, but we can check that
# it starts with the clinic block, we check that it contains all the
# expected fields, and we check that it contains the checksum line.
self.assertTrue(out.startswith(dedent("""
/*[clinic input]
output print 'I told you once.'
[clinic start generated code]*/
""")))
fields = {
"cpp_endif",
"cpp_if",
"docstring_definition",
"docstring_prototype",
"impl_definition",
"impl_prototype",
"methoddef_define",
"methoddef_ifndef",
"parser_definition",
"parser_prototype",
}
for field in fields:
with self.subTest(field=field):
self.assertIn(field, out)
last_line = out.rstrip().split("\n")[-1]
self.assertTrue(
last_line.startswith("/*[clinic end generated code: output=")
)
def test_unknown_destination_command(self):
raw = """
/*[clinic input]
destination buffer nosuchcommand
[clinic start generated code]*/
"""
err = "unknown destination command 'nosuchcommand'"
self.expect_failure(raw, err)
def test_no_access_to_members_in_converter_init(self):
raw = """
/*[python input]
class Custom_converter(CConverter):
converter = "some_c_function"
def converter_init(self):
self.function.noaccess
[python start generated code]*/
/*[clinic input]
module test
test.fn
a: Custom
[clinic start generated code]*/
"""
err = (
"accessing self.function inside converter_init is disallowed!"
)
self.expect_failure(raw, err)
@staticmethod
@contextlib.contextmanager
def _clinic_version(new_version):
"""Helper for test_version_*() tests"""
_saved = clinic.version
clinic.version = new_version
try:
yield
finally:
clinic.version = _saved
def test_version_directive(self):
dataset = (
# (clinic version, required version)
('3', '2'), # required version < clinic version
('3.1', '3.0'), # required version < clinic version
('1.2b0', '1.2a7'), # required version < clinic version
('5', '5'), # required version == clinic version
('6.1', '6.1'), # required version == clinic version
('1.2b3', '1.2b3'), # required version == clinic version
)
for clinic_version, required_version in dataset:
with self.subTest(clinic_version=clinic_version,
required_version=required_version):
with self._clinic_version(clinic_version):
block = dedent(f"""
/*[clinic input]
version {required_version}
[clinic start generated code]*/
""")
self.clinic.parse(block)
def test_version_directive_insufficient_version(self):
with self._clinic_version('4'):
err = (
"Insufficient Clinic version!\n"
" Version: 4\n"
" Required: 5"
)
block = """
/*[clinic input]
version 5
[clinic start generated code]*/
"""
self.expect_failure(block, err)
def test_version_directive_illegal_char(self):
err = "Illegal character 'v' in version string 'v5'"
block = """
/*[clinic input]
version v5
[clinic start generated code]*/
"""
self.expect_failure(block, err)
def test_version_directive_unsupported_string(self):
err = "Unsupported version string: '.-'"
block = """
/*[clinic input]
version .-
[clinic start generated code]*/
"""
self.expect_failure(block, err)
def test_clone_mismatch(self):
err = "'kind' of function and cloned function don't match!"
block = """
/*[clinic input]
module m
@classmethod
m.f1
a: object
[clinic start generated code]*/
/*[clinic input]
@staticmethod
m.f2 = m.f1
[clinic start generated code]*/
"""
self.expect_failure(block, err, lineno=9)
def test_badly_formed_return_annotation(self):
err = "Badly formed annotation for 'm.f': 'Custom'"
block = """
/*[python input]
class Custom_return_converter(CReturnConverter):
def __init__(self):
raise ValueError("abc")
[python start generated code]*/
/*[clinic input]
module m
m.f -> Custom
[clinic start generated code]*/
"""
self.expect_failure(block, err, lineno=8)
def test_module_already_got_one(self):
err = "Already defined module 'm'!"
block = """
/*[clinic input]
module m
module m
[clinic start generated code]*/
"""
self.expect_failure(block, err, lineno=3)
def test_destination_already_got_one(self):
err = "Destination already exists: 'test'"
block = """
/*[clinic input]
destination test new buffer
destination test new buffer
[clinic start generated code]*/
"""
self.expect_failure(block, err, lineno=3)
def test_destination_does_not_exist(self):
err = "Destination does not exist: '/dev/null'"
block = """
/*[clinic input]
output everything /dev/null
[clinic start generated code]*/
"""
self.expect_failure(block, err, lineno=2)
def test_class_already_got_one(self):
err = "Already defined class 'C'!"
block = """
/*[clinic input]
class C "" ""
class C "" ""
[clinic start generated code]*/
"""
self.expect_failure(block, err, lineno=3)
def test_cant_nest_module_inside_class(self):
err = "Can't nest a module inside a class!"
block = """
/*[clinic input]
class C "" ""
module C.m
[clinic start generated code]*/
"""
self.expect_failure(block, err, lineno=3)
def test_dest_buffer_not_empty_at_eof(self):
expected_warning = ("Destination buffer 'buffer' not empty at "
"end of file, emptying.")
expected_generated = dedent("""
/*[clinic input]
output everything buffer
fn
a: object
/
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=1c4668687f5fd002]*/
/*[clinic input]
dump buffer
[clinic start generated code]*/
PyDoc_VAR(fn__doc__);
PyDoc_STRVAR(fn__doc__,
"fn($module, a, /)\\n"
"--\\n"
"\\n");
#define FN_METHODDEF \\
{"fn", (PyCFunction)fn, METH_O, fn__doc__},
static PyObject *
fn(PyObject *module, PyObject *a)
/*[clinic end generated code: output=be6798b148ab4e53 input=524ce2e021e4eba6]*/
""")
block = dedent("""
/*[clinic input]
output everything buffer
fn
a: object
/
[clinic start generated code]*/
""")
with support.captured_stdout() as stdout:
generated = self.clinic.parse(block)
self.assertIn(expected_warning, stdout.getvalue())
self.assertEqual(generated, expected_generated)
def test_dest_clear(self):
err = "Can't clear destination 'file': it's not of type 'buffer'"
block = """
/*[clinic input]
destination file clear
[clinic start generated code]*/
"""
self.expect_failure(block, err, lineno=2)
def test_directive_set_misuse(self):
err = "unknown variable 'ets'"
block = """
/*[clinic input]
set ets tse
[clinic start generated code]*/
"""
self.expect_failure(block, err, lineno=2)
def test_directive_set_prefix(self):
block = dedent("""
/*[clinic input]
set line_prefix '// '
output everything suppress
output docstring_prototype buffer
fn
a: object
/
[clinic start generated code]*/
/* We need to dump the buffer.
* If not, Argument Clinic will emit a warning */
/*[clinic input]
dump buffer
[clinic start generated code]*/
""")
generated = self.clinic.parse(block)
expected_docstring_prototype = "// PyDoc_VAR(fn__doc__);"
self.assertIn(expected_docstring_prototype, generated)
def test_directive_set_suffix(self):
block = dedent("""
/*[clinic input]
set line_suffix ' // test'
output everything suppress
output docstring_prototype buffer
fn
a: object
/
[clinic start generated code]*/
/* We need to dump the buffer.
* If not, Argument Clinic will emit a warning */
/*[clinic input]
dump buffer
[clinic start generated code]*/
""")
generated = self.clinic.parse(block)
expected_docstring_prototype = "PyDoc_VAR(fn__doc__); // test"
self.assertIn(expected_docstring_prototype, generated)
def test_directive_set_prefix_and_suffix(self):
block = dedent("""
/*[clinic input]
set line_prefix '{block comment start} '
set line_suffix ' {block comment end}'
output everything suppress
output docstring_prototype buffer
fn
a: object
/
[clinic start generated code]*/
/* We need to dump the buffer.
* If not, Argument Clinic will emit a warning */
/*[clinic input]
dump buffer
[clinic start generated code]*/
""")
generated = self.clinic.parse(block)
expected_docstring_prototype = "/* PyDoc_VAR(fn__doc__); */"
self.assertIn(expected_docstring_prototype, generated)
def test_directive_printout(self):
block = dedent("""
/*[clinic input]
output everything buffer
printout test
[clinic start generated code]*/
""")
expected = dedent("""
/*[clinic input]
output everything buffer
printout test
[clinic start generated code]*/
test
/*[clinic end generated code: output=4e1243bd22c66e76 input=898f1a32965d44ca]*/
""")
generated = self.clinic.parse(block)
self.assertEqual(generated, expected)
def test_directive_preserve_twice(self):
err = "Can't have 'preserve' twice in one block!"
block = """
/*[clinic input]
preserve
preserve
[clinic start generated code]*/
"""
self.expect_failure(block, err, lineno=3)
def test_directive_preserve_input(self):
err = "'preserve' only works for blocks that don't produce any output!"
block = """
/*[clinic input]
preserve
fn
a: object
/
[clinic start generated code]*/
"""
self.expect_failure(block, err, lineno=6)
def test_directive_preserve_output(self):
err = "'preserve' only works for blocks that don't produce any output!"
block = dedent("""
/*[clinic input]
output everything buffer
preserve
[clinic start generated code]*/
// Preserve this
/*[clinic end generated code: output=eaa49677ae4c1f7d input=559b5db18fddae6a]*/
/*[clinic input]
dump buffer
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=524ce2e021e4eba6]*/
""")
generated = self.clinic.parse(block)
self.assertEqual(generated, block)
def test_directive_output_invalid_command(self):
err = dedent("""
Invalid command or destination name 'cmd'. Must be one of:
- 'preset'
- 'push'
- 'pop'
- 'print'
- 'everything'
- 'cpp_if'
- 'docstring_prototype'
- 'docstring_definition'
- 'methoddef_define'
- 'impl_prototype'
- 'parser_prototype'
- 'parser_definition'
- 'cpp_endif'
- 'methoddef_ifndef'
- 'impl_definition'
""").strip()
block = """
/*[clinic input]
output cmd buffer
[clinic start generated code]*/
"""
self.expect_failure(block, err, lineno=2)
class ClinicGroupPermuterTest(TestCase):
def _test(self, l, m, r, output):
computed = clinic.permute_optional_groups(l, m, r)
self.assertEqual(output, computed)
def test_range(self):
self._test([['start']], ['stop'], [['step']],
(
('stop',),
('start', 'stop',),
('start', 'stop', 'step',),
))
def test_add_window(self):
self._test([['x', 'y']], ['ch'], [['attr']],
(
('ch',),
('ch', 'attr'),
('x', 'y', 'ch',),
('x', 'y', 'ch', 'attr'),
))
def test_ludicrous(self):
self._test([['a1', 'a2', 'a3'], ['b1', 'b2']], ['c1'], [['d1', 'd2'], ['e1', 'e2', 'e3']],
(
('c1',),
('b1', 'b2', 'c1'),
('b1', 'b2', 'c1', 'd1', 'd2'),
('a1', 'a2', 'a3', 'b1', 'b2', 'c1'),
('a1', 'a2', 'a3', 'b1', 'b2', 'c1', 'd1', 'd2'),
('a1', 'a2', 'a3', 'b1', 'b2', 'c1', 'd1', 'd2', 'e1', 'e2', 'e3'),
))
def test_right_only(self):
self._test([], [], [['a'],['b'],['c']],
(
(),
('a',),
('a', 'b'),
('a', 'b', 'c')
))
def test_have_left_options_but_required_is_empty(self):
def fn():
clinic.permute_optional_groups(['a'], [], [])
self.assertRaises(ValueError, fn)
class ClinicLinearFormatTest(TestCase):
def _test(self, input, output, **kwargs):
computed = clinic.linear_format(input, **kwargs)
self.assertEqual(output, computed)
def test_empty_strings(self):
self._test('', '')
def test_solo_newline(self):
self._test('\n', '\n')
def test_no_substitution(self):
self._test("""
abc
""", """
abc
""")
def test_empty_substitution(self):
self._test("""
abc
{name}
def
""", """
abc
def
""", name='')
def test_single_line_substitution(self):
self._test("""
abc
{name}
def
""", """
abc
GARGLE
def
""", name='GARGLE')
def test_multiline_substitution(self):
self._test("""
abc
{name}
def
""", """
abc
bingle
bungle
def
""", name='bingle\nbungle\n')
class InertParser:
def __init__(self, clinic):
pass
def parse(self, block):
pass
class CopyParser:
def __init__(self, clinic):
pass
def parse(self, block):
block.output = block.input
class ClinicBlockParserTest(TestCase):
def _test(self, input, output):
language = clinic.CLanguage(None)
blocks = list(clinic.BlockParser(input, language))
writer = clinic.BlockPrinter(language)
for block in blocks:
writer.print_block(block)
output = writer.f.getvalue()
assert output == input, "output != input!\n\noutput " + repr(output) + "\n\n input " + repr(input)
def round_trip(self, input):
return self._test(input, input)
def test_round_trip_1(self):
self.round_trip("""
verbatim text here
lah dee dah
""")
def test_round_trip_2(self):
self.round_trip("""
verbatim text here
lah dee dah
/*[inert]
abc
[inert]*/
def
/*[inert checksum: 7b18d017f89f61cf17d47f92749ea6930a3f1deb]*/
xyz
""")
def _test_clinic(self, input, output):
language = clinic.CLanguage(None)
c = clinic.Clinic(language, filename="file")
c.parsers['inert'] = InertParser(c)
c.parsers['copy'] = CopyParser(c)
computed = c.parse(input)
self.assertEqual(output, computed)
def test_clinic_1(self):
self._test_clinic("""
verbatim text here
lah dee dah
/*[copy input]
def
[copy start generated code]*/
abc
/*[copy end generated code: output=03cfd743661f0797 input=7b18d017f89f61cf]*/
xyz
""", """
verbatim text here
lah dee dah
/*[copy input]
def
[copy start generated code]*/
def
/*[copy end generated code: output=7b18d017f89f61cf input=7b18d017f89f61cf]*/
xyz
""")
class ClinicParserTest(TestCase):
def parse(self, text):
c = FakeClinic()
parser = DSLParser(c)
block = clinic.Block(text)
parser.parse(block)
return block
def parse_function(self, text, signatures_in_block=2, function_index=1):
block = self.parse(text)
s = block.signatures
self.assertEqual(len(s), signatures_in_block)
assert isinstance(s[0], clinic.Module)
assert isinstance(s[function_index], clinic.Function)
return s[function_index]
def expect_failure(self, block, err, *, filename=None, lineno=None):
_expect_failure(self, self.parse_function, block, err,
filename=filename, lineno=lineno)
def checkDocstring(self, fn, expected):
self.assertTrue(hasattr(fn, "docstring"))
self.assertEqual(fn.docstring.strip(),
dedent(expected).strip())
def test_trivial(self):
parser = DSLParser(FakeClinic())
block = clinic.Block("""
module os
os.access
""")
parser.parse(block)
module, function = block.signatures
self.assertEqual("access", function.name)
self.assertEqual("os", module.name)
def test_ignore_line(self):
block = self.parse(dedent("""
#
module os
os.access
"""))
module, function = block.signatures
self.assertEqual("access", function.name)
self.assertEqual("os", module.name)
def test_param(self):
function = self.parse_function("""
module os
os.access
path: int
""")
self.assertEqual("access", function.name)
self.assertEqual(2, len(function.parameters))
p = function.parameters['path']
self.assertEqual('path', p.name)
self.assertIsInstance(p.converter, clinic.int_converter)
def test_param_default(self):
function = self.parse_function("""
module os
os.access
follow_symlinks: bool = True
""")
p = function.parameters['follow_symlinks']
self.assertEqual(True, p.default)
def test_param_with_continuations(self):
function = self.parse_function(r"""
module os
os.access
follow_symlinks: \
bool \
= \
True
""")
p = function.parameters['follow_symlinks']
self.assertEqual(True, p.default)
def test_param_default_expr_named_constant(self):
function = self.parse_function("""
module os
os.access
follow_symlinks: int(c_default='MAXSIZE') = sys.maxsize
""")
p = function.parameters['follow_symlinks']
self.assertEqual(sys.maxsize, p.default)
self.assertEqual("MAXSIZE", p.converter.c_default)
err = (
"When you specify a named constant ('sys.maxsize') as your default value, "
"you MUST specify a valid c_default."
)
block = """
module os
os.access
follow_symlinks: int = sys.maxsize
"""
self.expect_failure(block, err, lineno=2)
def test_param_default_expr_binop(self):
err = (
"When you specify an expression ('a + b') as your default value, "
"you MUST specify a valid c_default."
)
block = """
fn
follow_symlinks: int = a + b
"""
self.expect_failure(block, err, lineno=1)
def test_param_no_docstring(self):
function = self.parse_function("""
module os
os.access
follow_symlinks: bool = True
something_else: str = ''
""")
p = function.parameters['follow_symlinks']
self.assertEqual(3, len(function.parameters))
conv = function.parameters['something_else'].converter
self.assertIsInstance(conv, clinic.str_converter)
def test_param_default_parameters_out_of_order(self):
err = (
"Can't have a parameter without a default ('something_else') "
"after a parameter with a default!"
)
block = """
module os
os.access
follow_symlinks: bool = True
something_else: str
"""
self.expect_failure(block, err, lineno=3)
def disabled_test_converter_arguments(self):
function = self.parse_function("""
module os
os.access
path: path_t(allow_fd=1)
""")
p = function.parameters['path']
self.assertEqual(1, p.converter.args['allow_fd'])
def test_function_docstring(self):
function = self.parse_function("""
module os
os.stat as os_stat_fn
path: str
Path to be examined