Debian Codegraph @

Lib/test/test_clinic.py

raw
1 # Argument Clinic
2 # Copyright 2012-2013 by Larry Hastings.
3 # Licensed to the PSF under a contributor agreement.
4
5 from functools import partial
6 from test import support, test_tools
7 from test.support import os_helper
8 from test.support.os_helper import TESTFN, unlink, rmtree
9 from textwrap import dedent
10 from unittest import TestCase
11 import inspect
12 import os.path
13 import re
14 import sys
15 import unittest
16
17 test_tools.skip_if_missing('clinic')
18 with test_tools.imports_under_tool('clinic'):
19 import libclinic
20 from libclinic import ClinicError, unspecified, NULL, fail
21 from libclinic.converters import int_converter, str_converter, self_converter
22 from libclinic.function import (
23 Module, Class, Function, FunctionKind, Parameter,
24 permute_optional_groups, permute_right_option_groups,
25 permute_left_option_groups)
26 import clinic
27 from libclinic.clanguage import CLanguage
28 from libclinic.converter import converters, legacy_converters
29 from libclinic.return_converters import return_converters, int_return_converter
30 from libclinic.block_parser import Block, BlockParser
31 from libclinic.codegen import BlockPrinter, Destination
32 from libclinic.dsl_parser import DSLParser
33 from libclinic.cli import parse_file, Clinic
34
35
36 def _make_clinic(*, filename='clinic_tests', limited_capi=False):
37 clang = CLanguage(filename)
38 c = Clinic(clang, filename=filename, limited_capi=limited_capi)
39 c.block_parser = BlockParser('', clang)
40 return c
41
42
43 def _expect_failure(tc, parser, code, errmsg, *, filename=None, lineno=None,
44 strip=True):
45 """Helper for the parser tests.
46
47 tc: unittest.TestCase; passed self in the wrapper
48 parser: the clinic parser used for this test case
49 code: a str with input text (clinic code)
50 errmsg: the expected error message
51 filename: str, optional filename
52 lineno: int, optional line number
53 """
54 code = dedent(code)
55 if strip:
56 code = code.strip()
57 errmsg = re.escape(errmsg)
58 with tc.assertRaisesRegex(ClinicError, errmsg) as cm:
59 parser(code)
60 if filename is not None:
61 tc.assertEqual(cm.exception.filename, filename)
62 if lineno is not None:
63 tc.assertEqual(cm.exception.lineno, lineno)
64 return cm.exception
65
66
67 def restore_dict(converters, old_converters):
68 converters.clear()
69 converters.update(old_converters)
70
71
72 def save_restore_converters(testcase):
73 testcase.addCleanup(restore_dict, converters,
74 converters.copy())
75 testcase.addCleanup(restore_dict, legacy_converters,
76 legacy_converters.copy())
77 testcase.addCleanup(restore_dict, return_converters,
78 return_converters.copy())
79
80
81 class ClinicWholeFileTest(TestCase):
82 maxDiff = None
83
84 def expect_failure(self, raw, errmsg, *, filename=None, lineno=None):
85 _expect_failure(self, self.clinic.parse, raw, errmsg,
86 filename=filename, lineno=lineno)
87
88 def setUp(self):
89 save_restore_converters(self)
90 self.clinic = _make_clinic(filename="test.c")
91
92 def test_eol(self):
93 # regression test:
94 # clinic's block parser didn't recognize
95 # the "end line" for the block if it
96 # didn't end in "\n" (as in, the last)
97 # byte of the file was '/'.
98 # so it would spit out an end line for you.
99 # and since you really already had one,
100 # the last line of the block got corrupted.
101 raw = "/*[clinic]\nfoo\n[clinic]*/"
102 cooked = self.clinic.parse(raw).splitlines()
103 end_line = cooked[2].rstrip()
104 # this test is redundant, it's just here explicitly to catch
105 # the regression test so we don't forget what it looked like
106 self.assertNotEqual(end_line, "[clinic]*/[clinic]*/")
107 self.assertEqual(end_line, "[clinic]*/")
108
109 def test_mangled_marker_line(self):
110 raw = """
111 /*[clinic input]
112 [clinic start generated code]*/
113 /*[clinic end generated code: foo]*/
114 """
115 err = (
116 "Mangled Argument Clinic marker line: "
117 "'/*[clinic end generated code: foo]*/'"
118 )
119 self.expect_failure(raw, err, filename="test.c", lineno=3)
120
121 def test_checksum_mismatch(self):
122 raw = """
123 /*[clinic input]
124 [clinic start generated code]*/
125 /*[clinic end generated code: output=0123456789abcdef input=fedcba9876543210]*/
126 """
127 err = ("Checksum mismatch! "
128 "Expected '0123456789abcdef', computed 'da39a3ee5e6b4b0d'")
129 self.expect_failure(raw, err, filename="test.c", lineno=3)
130
131 def test_garbage_after_stop_line(self):
132 raw = """
133 /*[clinic input]
134 [clinic start generated code]*/foobarfoobar!
135 """
136 err = "Garbage after stop line: 'foobarfoobar!'"
137 self.expect_failure(raw, err, filename="test.c", lineno=2)
138
139 def test_whitespace_before_stop_line(self):
140 raw = """
141 /*[clinic input]
142 [clinic start generated code]*/
143 """
144 err = (
145 "Whitespace is not allowed before the stop line: "
146 "' [clinic start generated code]*/'"
147 )
148 self.expect_failure(raw, err, filename="test.c", lineno=2)
149
150 def test_parse_with_body_prefix(self):
151 clang = CLanguage(None)
152 clang.body_prefix = "//"
153 clang.start_line = "//[{dsl_name} start]"
154 clang.stop_line = "//[{dsl_name} stop]"
155 cl = Clinic(clang, filename="test.c", limited_capi=False)
156 raw = dedent("""
157 //[clinic start]
158 //module test
159 //[clinic stop]
160 """).strip()
161 out = cl.parse(raw)
162 expected = dedent("""
163 //[clinic start]
164 //module test
165 //
166 //[clinic stop]
167 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=65fab8adff58cf08]*/
168 """).lstrip() # Note, lstrip() because of the newline
169 self.assertEqual(out, expected)
170
171 def test_cpp_monitor_fail_nested_block_comment(self):
172 raw = """
173 /* start
174 /* nested
175 */
176 */
177 """
178 err = 'Nested block comment!'
179 self.expect_failure(raw, err, filename="test.c", lineno=2)
180
181 def test_cpp_monitor_fail_invalid_format_noarg(self):
182 raw = """
183 #if
184 a()
185 #endif
186 """
187 err = 'Invalid format for #if line: no argument!'
188 self.expect_failure(raw, err, filename="test.c", lineno=1)
189
190 def test_cpp_monitor_fail_invalid_format_toomanyargs(self):
191 raw = """
192 #ifdef A B
193 a()
194 #endif
195 """
196 err = 'Invalid format for #ifdef line: should be exactly one argument!'
197 self.expect_failure(raw, err, filename="test.c", lineno=1)
198
199 def test_cpp_monitor_fail_no_matching_if(self):
200 raw = '#else'
201 err = '#else without matching #if / #ifdef / #ifndef!'
202 self.expect_failure(raw, err, filename="test.c", lineno=1)
203
204 def test_directive_output_unknown_preset(self):
205 raw = """
206 /*[clinic input]
207 output preset nosuchpreset
208 [clinic start generated code]*/
209 """
210 err = "Unknown preset 'nosuchpreset'"
211 self.expect_failure(raw, err)
212
213 def test_directive_output_cant_pop(self):
214 raw = """
215 /*[clinic input]
216 output pop
217 [clinic start generated code]*/
218 """
219 err = "Can't 'output pop', stack is empty"
220 self.expect_failure(raw, err)
221
222 def test_directive_output_print(self):
223 raw = dedent("""
224 /*[clinic input]
225 output print 'I told you once.'
226 [clinic start generated code]*/
227 """)
228 out = self.clinic.parse(raw)
229 # The generated output will differ for every run, but we can check that
230 # it starts with the clinic block, we check that it contains all the
231 # expected fields, and we check that it contains the checksum line.
232 self.assertTrue(out.startswith(dedent("""
233 /*[clinic input]
234 output print 'I told you once.'
235 [clinic start generated code]*/
236 """)))
237 fields = {
238 "cpp_endif",
239 "cpp_if",
240 "docstring_definition",
241 "docstring_prototype",
242 "impl_definition",
243 "impl_prototype",
244 "methoddef_define",
245 "methoddef_ifndef",
246 "parser_definition",
247 "parser_prototype",
248 }
249 for field in fields:
250 with self.subTest(field=field):
251 self.assertIn(field, out)
252 last_line = out.rstrip().split("\n")[-1]
253 self.assertTrue(
254 last_line.startswith("/*[clinic end generated code: output=")
255 )
256
257 def test_directive_wrong_arg_number(self):
258 raw = dedent("""
259 /*[clinic input]
260 preserve foo bar baz eggs spam ham mushrooms
261 [clinic start generated code]*/
262 """)
263 err = "takes 1 positional argument but 8 were given"
264 self.expect_failure(raw, err)
265
266 def test_unknown_destination_command(self):
267 raw = """
268 /*[clinic input]
269 destination buffer nosuchcommand
270 [clinic start generated code]*/
271 """
272 err = "unknown destination command 'nosuchcommand'"
273 self.expect_failure(raw, err)
274
275 def test_no_access_to_members_in_converter_init(self):
276 raw = """
277 /*[python input]
278 class Custom_converter(CConverter):
279 converter = "some_c_function"
280 def converter_init(self):
281 self.function.noaccess
282 [python start generated code]*/
283 /*[clinic input]
284 module test
285 test.fn
286 a: Custom
287 [clinic start generated code]*/
288 """
289 err = (
290 "accessing self.function inside converter_init is disallowed!"
291 )
292 self.expect_failure(raw, err)
293
294 def test_clone_mismatch(self):
295 err = "'kind' of function and cloned function don't match!"
296 block = """
297 /*[clinic input]
298 module m
299 @classmethod
300 m.f1
301 a: object
302 [clinic start generated code]*/
303 /*[clinic input]
304 @staticmethod
305 m.f2 = m.f1
306 [clinic start generated code]*/
307 """
308 self.expect_failure(block, err, lineno=9)
309
310 def test_badly_formed_return_annotation(self):
311 err = "Badly formed annotation for 'm.f': 'Custom'"
312 block = """
313 /*[python input]
314 class Custom_return_converter(CReturnConverter):
315 def __init__(self):
316 raise ValueError("abc")
317 [python start generated code]*/
318 /*[clinic input]
319 module m
320 m.f -> Custom
321 [clinic start generated code]*/
322 """
323 self.expect_failure(block, err, lineno=8)
324
325 def test_star_after_vararg(self):
326 err = "'my_test_func' uses '*' more than once."
327 block = """
328 /*[clinic input]
329 my_test_func
330
331 pos_arg: object
332 *args: object
333 *
334 kw_arg: object
335 [clinic start generated code]*/
336 """
337 self.expect_failure(block, err, lineno=6)
338
339 def test_vararg_after_star(self):
340 err = "'my_test_func' uses '*' more than once."
341 block = """
342 /*[clinic input]
343 my_test_func
344
345 pos_arg: object
346 *
347 *args: object
348 kw_arg: object
349 [clinic start generated code]*/
350 """
351 self.expect_failure(block, err, lineno=6)
352
353 def test_module_already_got_one(self):
354 err = "Already defined module 'm'!"
355 block = """
356 /*[clinic input]
357 module m
358 module m
359 [clinic start generated code]*/
360 """
361 self.expect_failure(block, err, lineno=3)
362
363 def test_destination_already_got_one(self):
364 err = "Destination already exists: 'test'"
365 block = """
366 /*[clinic input]
367 destination test new buffer
368 destination test new buffer
369 [clinic start generated code]*/
370 """
371 self.expect_failure(block, err, lineno=3)
372
373 def test_destination_does_not_exist(self):
374 err = "Destination does not exist: '/dev/null'"
375 block = """
376 /*[clinic input]
377 output everything /dev/null
378 [clinic start generated code]*/
379 """
380 self.expect_failure(block, err, lineno=2)
381
382 def test_class_already_got_one(self):
383 err = "Already defined class 'C'!"
384 block = """
385 /*[clinic input]
386 class C "" ""
387 class C "" ""
388 [clinic start generated code]*/
389 """
390 self.expect_failure(block, err, lineno=3)
391
392 def test_cant_nest_module_inside_class(self):
393 err = "Can't nest a module inside a class!"
394 block = """
395 /*[clinic input]
396 class C "" ""
397 module C.m
398 [clinic start generated code]*/
399 """
400 self.expect_failure(block, err, lineno=3)
401
402 def test_dest_buffer_not_empty_at_eof(self):
403 expected_warning = ("Destination buffer 'buffer' not empty at "
404 "end of file, emptying.")
405 expected_generated = dedent("""
406 /*[clinic input]
407 output everything buffer
408 fn
409 a: object
410 /
411 [clinic start generated code]*/
412 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=1c4668687f5fd002]*/
413
414 /*[clinic input]
415 dump buffer
416 [clinic start generated code]*/
417
418 PyDoc_VAR(fn__doc__);
419
420 PyDoc_STRVAR(fn__doc__,
421 "fn($module, a, /)\\n"
422 "--\\n"
423 "\\n");
424
425 #define FN_METHODDEF \\
426 {"fn", (PyCFunction)fn, METH_O, fn__doc__},
427
428 static PyObject *
429 fn(PyObject *module, PyObject *a)
430 /*[clinic end generated code: output=be6798b148ab4e53 input=524ce2e021e4eba6]*/
431 """)
432 block = dedent("""
433 /*[clinic input]
434 output everything buffer
435 fn
436 a: object
437 /
438 [clinic start generated code]*/
439 """)
440 with support.captured_stdout() as stdout:
441 generated = self.clinic.parse(block)
442 self.assertIn(expected_warning, stdout.getvalue())
443 self.assertEqual(generated, expected_generated)
444
445 def test_dest_clear(self):
446 err = "Can't clear destination 'file': it's not of type 'buffer'"
447 block = """
448 /*[clinic input]
449 destination file clear
450 [clinic start generated code]*/
451 """
452 self.expect_failure(block, err, lineno=2)
453
454 def test_directive_set_misuse(self):
455 err = "unknown variable 'ets'"
456 block = """
457 /*[clinic input]
458 set ets tse
459 [clinic start generated code]*/
460 """
461 self.expect_failure(block, err, lineno=2)
462
463 def test_directive_set_prefix(self):
464 block = dedent("""
465 /*[clinic input]
466 set line_prefix '// '
467 output everything suppress
468 output docstring_prototype buffer
469 fn
470 a: object
471 /
472 [clinic start generated code]*/
473 /* We need to dump the buffer.
474 * If not, Argument Clinic will emit a warning */
475 /*[clinic input]
476 dump buffer
477 [clinic start generated code]*/
478 """)
479 generated = self.clinic.parse(block)
480 expected_docstring_prototype = "// PyDoc_VAR(fn__doc__);"
481 self.assertIn(expected_docstring_prototype, generated)
482
483 def test_directive_set_suffix(self):
484 block = dedent("""
485 /*[clinic input]
486 set line_suffix ' // test'
487 output everything suppress
488 output docstring_prototype buffer
489 fn
490 a: object
491 /
492 [clinic start generated code]*/
493 /* We need to dump the buffer.
494 * If not, Argument Clinic will emit a warning */
495 /*[clinic input]
496 dump buffer
497 [clinic start generated code]*/
498 """)
499 generated = self.clinic.parse(block)
500 expected_docstring_prototype = "PyDoc_VAR(fn__doc__); // test"
501 self.assertIn(expected_docstring_prototype, generated)
502
503 def test_directive_set_prefix_and_suffix(self):
504 block = dedent("""
505 /*[clinic input]
506 set line_prefix '{block comment start} '
507 set line_suffix ' {block comment end}'
508 output everything suppress
509 output docstring_prototype buffer
510 fn
511 a: object
512 /
513 [clinic start generated code]*/
514 /* We need to dump the buffer.
515 * If not, Argument Clinic will emit a warning */
516 /*[clinic input]
517 dump buffer
518 [clinic start generated code]*/
519 """)
520 generated = self.clinic.parse(block)
521 expected_docstring_prototype = "/* PyDoc_VAR(fn__doc__); */"
522 self.assertIn(expected_docstring_prototype, generated)
523
524 def test_directive_printout(self):
525 block = dedent("""
526 /*[clinic input]
527 output everything buffer
528 printout test
529 [clinic start generated code]*/
530 """)
531 expected = dedent("""
532 /*[clinic input]
533 output everything buffer
534 printout test
535 [clinic start generated code]*/
536 test
537 /*[clinic end generated code: output=4e1243bd22c66e76 input=898f1a32965d44ca]*/
538 """)
539 generated = self.clinic.parse(block)
540 self.assertEqual(generated, expected)
541
542 def test_directive_preserve_twice(self):
543 err = "Can't have 'preserve' twice in one block!"
544 block = """
545 /*[clinic input]
546 preserve
547 preserve
548 [clinic start generated code]*/
549 """
550 self.expect_failure(block, err, lineno=3)
551
552 def test_directive_preserve_input(self):
553 err = "'preserve' only works for blocks that don't produce any output!"
554 block = """
555 /*[clinic input]
556 preserve
557 fn
558 a: object
559 /
560 [clinic start generated code]*/
561 """
562 self.expect_failure(block, err, lineno=6)
563
564 def test_directive_preserve_output(self):
565 block = dedent("""
566 /*[clinic input]
567 output everything buffer
568 preserve
569 [clinic start generated code]*/
570 // Preserve this
571 /*[clinic end generated code: output=eaa49677ae4c1f7d input=559b5db18fddae6a]*/
572 /*[clinic input]
573 dump buffer
574 [clinic start generated code]*/
575 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=524ce2e021e4eba6]*/
576 """)
577 generated = self.clinic.parse(block)
578 self.assertEqual(generated, block)
579
580 def test_directive_output_invalid_command(self):
581 err = dedent("""
582 Invalid command or destination name 'cmd'. Must be one of:
583 - 'preset'
584 - 'push'
585 - 'pop'
586 - 'print'
587 - 'everything'
588 - 'cpp_if'
589 - 'docstring_prototype'
590 - 'docstring_definition'
591 - 'methoddef_define'
592 - 'impl_prototype'
593 - 'parser_prototype'
594 - 'parser_definition'
595 - 'cpp_endif'
596 - 'methoddef_ifndef'
597 - 'impl_definition'
598 """).strip()
599 block = """
600 /*[clinic input]
601 output cmd buffer
602 [clinic start generated code]*/
603 """
604 self.expect_failure(block, err, lineno=2)
605
606 def test_validate_cloned_init(self):
607 block = """
608 /*[clinic input]
609 class C "void *" ""
610 C.meth
611 a: int
612 [clinic start generated code]*/
613 /*[clinic input]
614 @classmethod
615 C.__init__ = C.meth
616 [clinic start generated code]*/
617 """
618 err = "'__init__' must be a normal method; got 'FunctionKind.CLASS_METHOD'!"
619 self.expect_failure(block, err, lineno=8)
620
621 def test_validate_cloned_new(self):
622 block = """
623 /*[clinic input]
624 class C "void *" ""
625 C.meth
626 a: int
627 [clinic start generated code]*/
628 /*[clinic input]
629 C.__new__ = C.meth
630 [clinic start generated code]*/
631 """
632 err = "'__new__' must be a class method"
633 self.expect_failure(block, err, lineno=7)
634
635 def test_no_c_basename_cloned(self):
636 block = """
637 /*[clinic input]
638 foo2
639 [clinic start generated code]*/
640 /*[clinic input]
641 foo as = foo2
642 [clinic start generated code]*/
643 """
644 err = "No C basename provided after 'as' keyword"
645 self.expect_failure(block, err, lineno=5)
646
647 def test_cloned_with_custom_c_basename(self):
648 raw = dedent("""
649 /*[clinic input]
650 # Make sure we don't create spurious clinic/ directories.
651 output everything suppress
652 foo2
653 [clinic start generated code]*/
654
655 /*[clinic input]
656 foo as foo1 = foo2
657 [clinic start generated code]*/
658 """)
659 self.clinic.parse(raw)
660 funcs = self.clinic.functions
661 self.assertEqual(len(funcs), 2)
662 self.assertEqual(funcs[1].name, "foo")
663 self.assertEqual(funcs[1].c_basename, "foo1")
664
665 def test_cloned_with_illegal_c_basename(self):
666 block = """
667 /*[clinic input]
668 class C "void *" ""
669 foo1
670 [clinic start generated code]*/
671
672 /*[clinic input]
673 foo2 as .illegal. = foo1
674 [clinic start generated code]*/
675 """
676 err = "Illegal C basename: '.illegal.'"
677 self.expect_failure(block, err, lineno=7)
678
679 def test_cloned_forced_text_signature(self):
680 block = dedent("""
681 /*[clinic input]
682 @text_signature "($module, a[, b])"
683 src
684 a: object
685 param a
686 b: object = NULL
687 /
688
689 docstring
690 [clinic start generated code]*/
691
692 /*[clinic input]
693 dst = src
694 [clinic start generated code]*/
695 """)
696 self.clinic.parse(block)
697 self.addCleanup(rmtree, "clinic")
698 funcs = self.clinic.functions
699 self.assertEqual(len(funcs), 2)
700
701 src_docstring_lines = funcs[0].docstring.split("\n")
702 dst_docstring_lines = funcs[1].docstring.split("\n")
703
704 # Signatures are copied.
705 self.assertEqual(src_docstring_lines[0], "src($module, a[, b])")
706 self.assertEqual(dst_docstring_lines[0], "dst($module, a[, b])")
707
708 # Param docstrings are copied.
709 self.assertIn(" param a", src_docstring_lines)
710 self.assertIn(" param a", dst_docstring_lines)
711
712 # Docstrings are not copied.
713 self.assertIn("docstring", src_docstring_lines)
714 self.assertNotIn("docstring", dst_docstring_lines)
715
716 def test_cloned_forced_text_signature_illegal(self):
717 block = """
718 /*[clinic input]
719 @text_signature "($module, a[, b])"
720 src
721 a: object
722 b: object = NULL
723 /
724 [clinic start generated code]*/
725
726 /*[clinic input]
727 @text_signature "($module, a_override[, b])"
728 dst = src
729 [clinic start generated code]*/
730 """
731 err = "Cannot use @text_signature when cloning a function"
732 self.expect_failure(block, err, lineno=11)
733
734 def test_ignore_preprocessor_in_comments(self):
735 for dsl in "clinic", "python":
736 raw = dedent(f"""\
737 /*[{dsl} input]
738 # CPP directives, valid or not, should be ignored in C comments.
739 #
740 [{dsl} start generated code]*/
741 """)
742 self.clinic.parse(raw)
743
744
745 class ParseFileUnitTest(TestCase):
746 def expect_parsing_failure(
747 self, *, filename, expected_error, verify=True, output=None
748 ):
749 errmsg = re.escape(dedent(expected_error).strip())
750 with self.assertRaisesRegex(ClinicError, errmsg):
751 parse_file(filename, limited_capi=False)
752
753 def test_parse_file_no_extension(self) -> None:
754 self.expect_parsing_failure(
755 filename="foo",
756 expected_error="Can't extract file type for file 'foo'"
757 )
758
759 def test_parse_file_strange_extension(self) -> None:
760 filenames_to_errors = {
761 "foo.rs": "Can't identify file type for file 'foo.rs'",
762 "foo.hs": "Can't identify file type for file 'foo.hs'",
763 "foo.js": "Can't identify file type for file 'foo.js'",
764 }
765 for filename, errmsg in filenames_to_errors.items():
766 with self.subTest(filename=filename):
767 self.expect_parsing_failure(filename=filename, expected_error=errmsg)
768
769
770 class ClinicGroupPermuterTest(TestCase):
771 def _test(self, l, m, r, output):
772 computed = permute_optional_groups(l, m, r)
773 self.assertEqual(output, computed)
774
775 def test_range(self):
776 self._test([['start']], ['stop'], [['step']],
777 (
778 ('stop',),
779 ('start', 'stop',),
780 ('start', 'stop', 'step',),
781 ))
782
783 def test_add_window(self):
784 self._test([['x', 'y']], ['ch'], [['attr']],
785 (
786 ('ch',),
787 ('ch', 'attr'),
788 ('x', 'y', 'ch',),
789 ('x', 'y', 'ch', 'attr'),
790 ))
791
792 def test_ludicrous(self):
793 self._test([['a1', 'a2', 'a3'], ['b1', 'b2']], ['c1'], [['d1', 'd2'], ['e1', 'e2', 'e3']],
794 (
795 ('c1',),
796 ('b1', 'b2', 'c1'),
797 ('b1', 'b2', 'c1', 'd1', 'd2'),
798 ('a1', 'a2', 'a3', 'b1', 'b2', 'c1'),
799 ('a1', 'a2', 'a3', 'b1', 'b2', 'c1', 'd1', 'd2'),
800 ('a1', 'a2', 'a3', 'b1', 'b2', 'c1', 'd1', 'd2', 'e1', 'e2', 'e3'),
801 ))
802
803 def test_right_only(self):
804 self._test([], [], [['a'],['b'],['c']],
805 (
806 (),
807 ('a',),
808 ('a', 'b'),
809 ('a', 'b', 'c')
810 ))
811
812 def test_have_left_options_but_required_is_empty(self):
813 def fn():
814 permute_optional_groups(['a'], [], [])
815 self.assertRaises(ValueError, fn)
816
817
818 class ClinicLinearFormatTest(TestCase):
819 def _test(self, input, output, **kwargs):
820 computed = libclinic.linear_format(input, **kwargs)
821 self.assertEqual(output, computed)
822
823 def test_empty_strings(self):
824 self._test('', '')
825
826 def test_solo_newline(self):
827 self._test('\n', '\n')
828
829 def test_no_substitution(self):
830 self._test("""
831 abc
832 """, """
833 abc
834 """)
835
836 def test_empty_substitution(self):
837 self._test("""
838 abc
839 {name}
840 def
841 """, """
842 abc
843 def
844 """, name='')
845
846 def test_single_line_substitution(self):
847 self._test("""
848 abc
849 {name}
850 def
851 """, """
852 abc
853 GARGLE
854 def
855 """, name='GARGLE')
856
857 def test_multiline_substitution(self):
858 self._test("""
859 abc
860 {name}
861 def
862 """, """
863 abc
864 bingle
865 bungle
866
867 def
868 """, name='bingle\nbungle\n')
869
870 def test_text_before_block_marker(self):
871 regex = re.escape("found before '{marker}'")
872 with self.assertRaisesRegex(ClinicError, regex):
873 libclinic.linear_format("no text before marker for you! {marker}",
874 marker="not allowed!")
875
876 def test_text_after_block_marker(self):
877 regex = re.escape("found after '{marker}'")
878 with self.assertRaisesRegex(ClinicError, regex):
879 libclinic.linear_format("{marker} no text after marker for you!",
880 marker="not allowed!")
881
882
883 class InertParser:
884 def __init__(self, clinic):
885 pass
886
887 def parse(self, block):
888 pass
889
890 class CopyParser:
891 def __init__(self, clinic):
892 pass
893
894 def parse(self, block):
895 block.output = block.input
896
897
898 class ClinicBlockParserTest(TestCase):
899 def _test(self, input, output):
900 language = CLanguage(None)
901
902 blocks = list(BlockParser(input, language))
903 writer = BlockPrinter(language)
904 for block in blocks:
905 writer.print_block(block)
906 output = writer.f.getvalue()
907 assert output == input, "output != input!\n\noutput " + repr(output) + "\n\n input " + repr(input)
908
909 def round_trip(self, input):
910 return self._test(input, input)
911
912 def test_round_trip_1(self):
913 self.round_trip("""
914 verbatim text here
915 lah dee dah
916 """)
917 def test_round_trip_2(self):
918 self.round_trip("""
919 verbatim text here
920 lah dee dah
921 /*[inert]
922 abc
923 [inert]*/
924 def
925 /*[inert checksum: 7b18d017f89f61cf17d47f92749ea6930a3f1deb]*/
926 xyz
927 """)
928
929 def _test_clinic(self, input, output):
930 language = CLanguage(None)
931 c = Clinic(language, filename="file", limited_capi=False)
932 c.parsers['inert'] = InertParser(c)
933 c.parsers['copy'] = CopyParser(c)
934 computed = c.parse(input)
935 self.assertEqual(output, computed)
936
937 def test_clinic_1(self):
938 self._test_clinic("""
939 verbatim text here
940 lah dee dah
941 /*[copy input]
942 def
943 [copy start generated code]*/
944 abc
945 /*[copy end generated code: output=03cfd743661f0797 input=7b18d017f89f61cf]*/
946 xyz
947 """, """
948 verbatim text here
949 lah dee dah
950 /*[copy input]
951 def
952 [copy start generated code]*/
953 def
954 /*[copy end generated code: output=7b18d017f89f61cf input=7b18d017f89f61cf]*/
955 xyz
956 """)
957
958
959 class ClinicParserTest(TestCase):
960
961 def parse(self, text):
962 c = _make_clinic()
963 parser = DSLParser(c)
964 block = Block(text)
965 parser.parse(block)
966 return block
967
968 def parse_function(self, text, signatures_in_block=2, function_index=1):
969 block = self.parse(text)
970 s = block.signatures
971 self.assertEqual(len(s), signatures_in_block)
972 assert isinstance(s[0], Module)
973 assert isinstance(s[function_index], Function)
974 return s[function_index]
975
976 def expect_failure(self, block, err, *,
977 filename=None, lineno=None, strip=True):
978 return _expect_failure(self, self.parse_function, block, err,
979 filename=filename, lineno=lineno, strip=strip)
980
981 def checkDocstring(self, fn, expected):
982 self.assertTrue(hasattr(fn, "docstring"))
983 self.assertEqual(dedent(expected).strip(),
984 fn.docstring.strip())
985
986 def test_trivial(self):
987 parser = DSLParser(_make_clinic())
988 block = Block("""
989 module os
990 os.access
991 """)
992 parser.parse(block)
993 module, function = block.signatures
994 self.assertEqual("access", function.name)
995 self.assertEqual("os", module.name)
996
997 def test_ignore_line(self):
998 block = self.parse(dedent("""
999 #
1000 module os
1001 os.access
1002 """))
1003 module, function = block.signatures
1004 self.assertEqual("access", function.name)
1005 self.assertEqual("os", module.name)
1006
1007 def test_param(self):
1008 function = self.parse_function("""
1009 module os
1010 os.access
1011 path: int
1012 """)
1013 self.assertEqual("access", function.name)
1014 self.assertEqual(2, len(function.parameters))
1015 p = function.parameters['path']
1016 self.assertEqual('path', p.name)
1017 self.assertIsInstance(p.converter, int_converter)
1018
1019 def test_param_default(self):
1020 function = self.parse_function("""
1021 module os
1022 os.access
1023 follow_symlinks: bool = True
1024 """)
1025 p = function.parameters['follow_symlinks']
1026 self.assertEqual(True, p.default)
1027
1028 def test_param_with_continuations(self):
1029 function = self.parse_function(r"""
1030 module os
1031 os.access
1032 follow_symlinks: \
1033 bool \
1034 = \
1035 True
1036 """)
1037 p = function.parameters['follow_symlinks']
1038 self.assertEqual(True, p.default)
1039
1040 def test_param_default_expr_named_constant(self):
1041 function = self.parse_function("""
1042 module os
1043 os.access
1044 follow_symlinks: int(c_default='MAXSIZE') = sys.maxsize
1045 """)
1046 p = function.parameters['follow_symlinks']
1047 self.assertEqual(sys.maxsize, p.default)
1048 self.assertEqual("MAXSIZE", p.converter.c_default)
1049
1050 err = (
1051 "When you specify a named constant ('sys.maxsize') as your default value, "
1052 "you MUST specify a valid c_default."
1053 )
1054 block = """
1055 module os
1056 os.access
1057 follow_symlinks: int = sys.maxsize
1058 """
1059 self.expect_failure(block, err, lineno=2)
1060
1061 def test_param_with_bizarre_default_fails_correctly(self):
1062 template = """
1063 module os
1064 os.access
1065 follow_symlinks: int = {default}
1066 """
1067 err = "Unsupported expression as default value"
1068 for bad_default_value in (
1069 "{1, 2, 3}",
1070 "3 if bool() else 4",
1071 "[x for x in range(42)]"
1072 ):
1073 with self.subTest(bad_default=bad_default_value):
1074 block = template.format(default=bad_default_value)
1075 self.expect_failure(block, err, lineno=2)
1076
1077 def test_unspecified_not_allowed_as_default_value(self):
1078 block = """
1079 module os
1080 os.access
1081 follow_symlinks: int(c_default='MAXSIZE') = unspecified
1082 """
1083 err = "'unspecified' is not a legal default value!"
1084 exc = self.expect_failure(block, err, lineno=2)
1085 self.assertNotIn('Malformed expression given as default value', str(exc))
1086
1087 def test_malformed_expression_as_default_value(self):
1088 block = """
1089 module os
1090 os.access
1091 follow_symlinks: int(c_default='MAXSIZE') = 1/0
1092 """
1093 err = "Malformed expression given as default value"
1094 self.expect_failure(block, err, lineno=2)
1095
1096 def test_param_default_expr_binop(self):
1097 err = (
1098 "When you specify an expression ('a + b') as your default value, "
1099 "you MUST specify a valid c_default."
1100 )
1101 block = """
1102 fn
1103 follow_symlinks: int = a + b
1104 """
1105 self.expect_failure(block, err, lineno=1)
1106
1107 def test_param_no_docstring(self):
1108 function = self.parse_function("""
1109 module os
1110 os.access
1111 follow_symlinks: bool = True
1112 something_else: str = ''
1113 """)
1114 self.assertEqual(3, len(function.parameters))
1115 conv = function.parameters['something_else'].converter
1116 self.assertIsInstance(conv, str_converter)
1117
1118 def test_param_default_parameters_out_of_order(self):
1119 err = (
1120 "Can't have a parameter without a default ('something_else') "
1121 "after a parameter with a default!"
1122 )
1123 block = """
1124 module os
1125 os.access
1126 follow_symlinks: bool = True
1127 something_else: str
1128 """
1129 self.expect_failure(block, err, lineno=3)
1130
1131 def disabled_test_converter_arguments(self):
1132 function = self.parse_function("""
1133 module os
1134 os.access
1135 path: path_t(allow_fd=1)
1136 """)
1137 p = function.parameters['path']
1138 self.assertEqual(1, p.converter.args['allow_fd'])
1139
1140 def test_function_docstring(self):
1141 function = self.parse_function("""
1142 module os
1143 os.stat as os_stat_fn
1144
1145 path: str
1146 Path to be examined
1147 Ensure that multiple lines are indented correctly.
1148
1149 Perform a stat system call on the given path.
1150
1151 Ensure that multiple lines are indented correctly.
1152 Ensure that multiple lines are indented correctly.
1153 """)
1154 self.checkDocstring(function, """
1155 stat($module, /, path)
1156 --
1157
1158 Perform a stat system call on the given path.
1159
1160 path
1161 Path to be examined
1162 Ensure that multiple lines are indented correctly.
1163
1164 Ensure that multiple lines are indented correctly.
1165 Ensure that multiple lines are indented correctly.
1166 """)
1167
1168 def test_docstring_trailing_whitespace(self):
1169 function = self.parse_function(
1170 "module t\n"
1171 "t.s\n"
1172 " a: object\n"
1173 " Param docstring with trailing whitespace \n"
1174 "Func docstring summary with trailing whitespace \n"
1175 " \n"
1176 "Func docstring body with trailing whitespace \n"
1177 )
1178 self.checkDocstring(function, """
1179 s($module, /, a)
1180 --
1181
1182 Func docstring summary with trailing whitespace
1183
1184 a
1185 Param docstring with trailing whitespace
1186
1187 Func docstring body with trailing whitespace
1188 """)
1189
1190 def test_explicit_parameters_in_docstring(self):
1191 function = self.parse_function(dedent("""
1192 module foo
1193 foo.bar
1194 x: int
1195 Documentation for x.
1196 y: int
1197
1198 This is the documentation for foo.
1199
1200 Okay, we're done here.
1201 """))
1202 self.checkDocstring(function, """
1203 bar($module, /, x, y)
1204 --
1205
1206 This is the documentation for foo.
1207
1208 x
1209 Documentation for x.
1210
1211 Okay, we're done here.
1212 """)
1213
1214 def test_docstring_with_comments(self):
1215 function = self.parse_function(dedent("""
1216 module foo
1217 foo.bar
1218 x: int
1219 # We're about to have
1220 # the documentation for x.
1221 Documentation for x.
1222 # We've just had
1223 # the documentation for x.
1224 y: int
1225
1226 # We're about to have
1227 # the documentation for foo.
1228 This is the documentation for foo.
1229 # We've just had
1230 # the documentation for foo.
1231
1232 Okay, we're done here.
1233 """))
1234 self.checkDocstring(function, """
1235 bar($module, /, x, y)
1236 --
1237
1238 This is the documentation for foo.
1239
1240 x
1241 Documentation for x.
1242
1243 Okay, we're done here.
1244 """)
1245
1246 def test_parser_regression_special_character_in_parameter_column_of_docstring_first_line(self):
1247 function = self.parse_function(dedent("""
1248 module os
1249 os.stat
1250 path: str
1251 This/used to break Clinic!
1252 """))
1253 self.checkDocstring(function, """
1254 stat($module, /, path)
1255 --
1256
1257 This/used to break Clinic!
1258 """)
1259
1260 def test_c_name(self):
1261 function = self.parse_function("""
1262 module os
1263 os.stat as os_stat_fn
1264 """)
1265 self.assertEqual("os_stat_fn", function.c_basename)
1266
1267 def test_base_invalid_syntax(self):
1268 block = """
1269 module os
1270 os.stat
1271 invalid syntax: int = 42
1272 """
1273 err = dedent(r"""
1274 Function 'stat' has an invalid parameter declaration:
1275 \s+'invalid syntax: int = 42'
1276 """).strip()
1277 with self.assertRaisesRegex(ClinicError, err):
1278 self.parse_function(block)
1279
1280 def test_param_default_invalid_syntax(self):
1281 block = """
1282 module os
1283 os.stat
1284 x: int = invalid syntax
1285 """
1286 err = r"Syntax error: 'x = invalid syntax\n'"
1287 self.expect_failure(block, err, lineno=2)
1288
1289 def test_cloning_nonexistent_function_correctly_fails(self):
1290 block = """
1291 cloned = fooooooooooooooooo
1292 This is trying to clone a nonexistent function!!
1293 """
1294 err = "Couldn't find existing function 'fooooooooooooooooo'!"
1295 with support.captured_stderr() as stderr:
1296 self.expect_failure(block, err, lineno=0)
1297 expected_debug_print = dedent("""\
1298 cls=None, module=<clinic.Clinic object>, existing='fooooooooooooooooo'
1299 (cls or module).functions=[]
1300 """)
1301 stderr = stderr.getvalue()
1302 self.assertIn(expected_debug_print, stderr)
1303
1304 def test_return_converter(self):
1305 function = self.parse_function("""
1306 module os
1307 os.stat -> int
1308 """)
1309 self.assertIsInstance(function.return_converter, int_return_converter)
1310
1311 def test_return_converter_invalid_syntax(self):
1312 block = """
1313 module os
1314 os.stat -> invalid syntax
1315 """
1316 err = "Badly formed annotation for 'os.stat': 'invalid syntax'"
1317 self.expect_failure(block, err)
1318
1319 def test_legacy_converter_disallowed_in_return_annotation(self):
1320 block = """
1321 module os
1322 os.stat -> "s"
1323 """
1324 err = "Legacy converter 's' not allowed as a return converter"
1325 self.expect_failure(block, err)
1326
1327 def test_unknown_return_converter(self):
1328 block = """
1329 module os
1330 os.stat -> fooooooooooooooooooooooo
1331 """
1332 err = "No available return converter called 'fooooooooooooooooooooooo'"
1333 self.expect_failure(block, err)
1334
1335 def test_star(self):
1336 function = self.parse_function("""
1337 module os
1338 os.access
1339 *
1340 follow_symlinks: bool = True
1341 """)
1342 p = function.parameters['follow_symlinks']
1343 self.assertEqual(inspect.Parameter.KEYWORD_ONLY, p.kind)
1344 self.assertEqual(0, p.group)
1345
1346 def test_group(self):
1347 function = self.parse_function("""
1348 module window
1349 window.border
1350 [
1351 ls: int
1352 ]
1353 /
1354 """)
1355 p = function.parameters['ls']
1356 self.assertEqual(1, p.group)
1357
1358 def test_left_group(self):
1359 function = self.parse_function("""
1360 module curses
1361 curses.addch
1362 [
1363 y: int
1364 Y-coordinate.
1365 x: int
1366 X-coordinate.
1367 ]
1368 ch: char
1369 Character to add.
1370 [
1371 attr: long
1372 Attributes for the character.
1373 ]
1374 /
1375 """)
1376 dataset = (
1377 ('y', -1), ('x', -1),
1378 ('ch', 0),
1379 ('attr', 1),
1380 )
1381 for name, group in dataset:
1382 with self.subTest(name=name, group=group):
1383 p = function.parameters[name]
1384 self.assertEqual(p.group, group)
1385 self.assertEqual(p.kind, inspect.Parameter.POSITIONAL_ONLY)
1386 self.checkDocstring(function, """
1387 addch([y, x,] ch, [attr])
1388
1389
1390 y
1391 Y-coordinate.
1392 x
1393 X-coordinate.
1394 ch
1395 Character to add.
1396 attr
1397 Attributes for the character.
1398 """)
1399
1400 def test_nested_groups(self):
1401 function = self.parse_function("""
1402 module curses
1403 curses.imaginary
1404 [
1405 [
1406 y1: int
1407 Y-coordinate.
1408 y2: int
1409 Y-coordinate.
1410 ]
1411 x1: int
1412 X-coordinate.
1413 x2: int
1414 X-coordinate.
1415 ]
1416 ch: char
1417 Character to add.
1418 [
1419 attr1: long
1420 Attributes for the character.
1421 attr2: long
1422 Attributes for the character.
1423 attr3: long
1424 Attributes for the character.
1425 [
1426 attr4: long
1427 Attributes for the character.
1428 attr5: long
1429 Attributes for the character.
1430 attr6: long
1431 Attributes for the character.
1432 ]
1433 ]
1434 /
1435 """)
1436 dataset = (
1437 ('y1', -2), ('y2', -2),
1438 ('x1', -1), ('x2', -1),
1439 ('ch', 0),
1440 ('attr1', 1), ('attr2', 1), ('attr3', 1),
1441 ('attr4', 2), ('attr5', 2), ('attr6', 2),
1442 )
1443 for name, group in dataset:
1444 with self.subTest(name=name, group=group):
1445 p = function.parameters[name]
1446 self.assertEqual(p.group, group)
1447 self.assertEqual(p.kind, inspect.Parameter.POSITIONAL_ONLY)
1448
1449 self.checkDocstring(function, """
1450 imaginary([[y1, y2,] x1, x2,] ch, [attr1, attr2, attr3, [attr4, attr5,
1451 attr6]])
1452
1453
1454 y1
1455 Y-coordinate.
1456 y2
1457 Y-coordinate.
1458 x1
1459 X-coordinate.
1460 x2
1461 X-coordinate.
1462 ch
1463 Character to add.
1464 attr1
1465 Attributes for the character.
1466 attr2
1467 Attributes for the character.
1468 attr3
1469 Attributes for the character.
1470 attr4
1471 Attributes for the character.
1472 attr5
1473 Attributes for the character.
1474 attr6
1475 Attributes for the character.
1476 """)
1477
1478 def test_disallowed_grouping__two_top_groups_on_left(self):
1479 err = (
1480 "Function 'two_top_groups_on_left' has an unsupported group "
1481 "configuration. (Unexpected state 2.b)"
1482 )
1483 block = """
1484 module foo
1485 foo.two_top_groups_on_left
1486 [
1487 group1 : int
1488 ]
1489 [
1490 group2 : int
1491 ]
1492 param: int
1493 """
1494 self.expect_failure(block, err, lineno=5)
1495
1496 def test_disallowed_grouping__two_top_groups_on_right(self):
1497 block = """
1498 module foo
1499 foo.two_top_groups_on_right
1500 param: int
1501 [
1502 group1 : int
1503 ]
1504 [
1505 group2 : int
1506 ]
1507 """
1508 err = (
1509 "Function 'two_top_groups_on_right' has an unsupported group "
1510 "configuration. (Unexpected state 6.b)"
1511 )
1512 self.expect_failure(block, err)
1513
1514 def test_disallowed_grouping__parameter_after_group_on_right(self):
1515 block = """
1516 module foo
1517 foo.parameter_after_group_on_right
1518 param: int
1519 [
1520 [
1521 group1 : int
1522 ]
1523 group2 : int
1524 ]
1525 """
1526 err = (
1527 "Function parameter_after_group_on_right has an unsupported group "
1528 "configuration. (Unexpected state 6.a)"
1529 )
1530 self.expect_failure(block, err)
1531
1532 def test_disallowed_grouping__group_after_parameter_on_left(self):
1533 block = """
1534 module foo
1535 foo.group_after_parameter_on_left
1536 [
1537 group2 : int
1538 [
1539 group1 : int
1540 ]
1541 ]
1542 param: int
1543 """
1544 err = (
1545 "Function 'group_after_parameter_on_left' has an unsupported group "
1546 "configuration. (Unexpected state 2.b)"
1547 )
1548 self.expect_failure(block, err)
1549
1550 def test_disallowed_grouping__empty_group_on_left(self):
1551 block = """
1552 module foo
1553 foo.empty_group
1554 [
1555 [
1556 ]
1557 group2 : int
1558 ]
1559 param: int
1560 """
1561 err = (
1562 "Function 'empty_group' has an empty group. "
1563 "All groups must contain at least one parameter."
1564 )
1565 self.expect_failure(block, err)
1566
1567 def test_disallowed_grouping__empty_group_on_right(self):
1568 block = """
1569 module foo
1570 foo.empty_group
1571 param: int
1572 [
1573 [
1574 ]
1575 group2 : int
1576 ]
1577 """
1578 err = (
1579 "Function 'empty_group' has an empty group. "
1580 "All groups must contain at least one parameter."
1581 )
1582 self.expect_failure(block, err)
1583
1584 def test_disallowed_grouping__no_matching_bracket(self):
1585 block = """
1586 module foo
1587 foo.empty_group
1588 param: int
1589 ]
1590 group2: int
1591 ]
1592 """
1593 err = "Function 'empty_group' has a ']' without a matching '['"
1594 self.expect_failure(block, err)
1595
1596 def test_disallowed_grouping__must_be_position_only(self):
1597 dataset = ("""
1598 with_kwds
1599 [
1600 *
1601 a: object
1602 ]
1603 """, """
1604 with_kwds
1605 [
1606 a: object
1607 ]
1608 """)
1609 err = (
1610 "You cannot use optional groups ('[' and ']') unless all "
1611 "parameters are positional-only ('/')"
1612 )
1613 for block in dataset:
1614 with self.subTest(block=block):
1615 self.expect_failure(block, err)
1616
1617 def test_no_parameters(self):
1618 function = self.parse_function("""
1619 module foo
1620 foo.bar
1621
1622 Docstring
1623
1624 """)
1625 self.assertEqual("bar($module, /)\n--\n\nDocstring", function.docstring)
1626 self.assertEqual(1, len(function.parameters)) # self!
1627
1628 def test_init_with_no_parameters(self):
1629 function = self.parse_function("""
1630 module foo
1631 class foo.Bar "unused" "notneeded"
1632 foo.Bar.__init__
1633
1634 Docstring
1635
1636 """, signatures_in_block=3, function_index=2)
1637
1638 # self is not in the signature
1639 self.assertEqual("Bar()\n--\n\nDocstring", function.docstring)
1640 # but it *is* a parameter
1641 self.assertEqual(1, len(function.parameters))
1642
1643 def test_illegal_module_line(self):
1644 block = """
1645 module foo
1646 foo.bar => int
1647 /
1648 """
1649 err = "Illegal function name: 'foo.bar => int'"
1650 self.expect_failure(block, err)
1651
1652 def test_illegal_c_basename(self):
1653 block = """
1654 module foo
1655 foo.bar as 935
1656 /
1657 """
1658 err = "Illegal C basename: '935'"
1659 self.expect_failure(block, err)
1660
1661 def test_no_c_basename(self):
1662 block = "foo as "
1663 err = "No C basename provided after 'as' keyword"
1664 self.expect_failure(block, err, strip=False)
1665
1666 def test_single_star(self):
1667 block = """
1668 module foo
1669 foo.bar
1670 *
1671 *
1672 """
1673 err = "Function 'bar' uses '*' more than once."
1674 self.expect_failure(block, err)
1675
1676 def test_parameters_required_after_star(self):
1677 dataset = (
1678 "module foo\nfoo.bar\n *",
1679 "module foo\nfoo.bar\n *\nDocstring here.",
1680 "module foo\nfoo.bar\n this: int\n *",
1681 "module foo\nfoo.bar\n this: int\n *\nDocstring.",
1682 )
1683 err = "Function 'bar' specifies '*' without following parameters."
1684 for block in dataset:
1685 with self.subTest(block=block):
1686 self.expect_failure(block, err)
1687
1688 def test_fulldisplayname_class(self):
1689 dataset = (
1690 ("T", """
1691 class T "void *" ""
1692 T.__init__
1693 """),
1694 ("m.T", """
1695 module m
1696 class m.T "void *" ""
1697 @classmethod
1698 m.T.__new__
1699 """),
1700 ("m.T.C", """
1701 module m
1702 class m.T "void *" ""
1703 class m.T.C "void *" ""
1704 m.T.C.__init__
1705 """),
1706 )
1707 for name, code in dataset:
1708 with self.subTest(name=name, code=code):
1709 block = self.parse(code)
1710 func = block.signatures[-1]
1711 self.assertEqual(func.fulldisplayname, name)
1712
1713 def test_fulldisplayname_meth(self):
1714 dataset = (
1715 ("func", "func"),
1716 ("m.func", """
1717 module m
1718 m.func
1719 """),
1720 ("T.meth", """
1721 class T "void *" ""
1722 T.meth
1723 """),
1724 ("m.T.meth", """
1725 module m
1726 class m.T "void *" ""
1727 m.T.meth
1728 """),
1729 ("m.T.C.meth", """
1730 module m
1731 class m.T "void *" ""
1732 class m.T.C "void *" ""
1733 m.T.C.meth
1734 """),
1735 )
1736 for name, code in dataset:
1737 with self.subTest(name=name, code=code):
1738 block = self.parse(code)
1739 func = block.signatures[-1]
1740 self.assertEqual(func.fulldisplayname, name)
1741
1742 def test_depr_star_invalid_format_1(self):
1743 block = """
1744 module foo
1745 foo.bar
1746 this: int
1747 * [from 3]
1748 Docstring.
1749 """
1750 err = (
1751 "Function 'bar': expected format '[from major.minor]' "
1752 "where 'major' and 'minor' are integers; got '3'"
1753 )
1754 self.expect_failure(block, err, lineno=3)
1755
1756 def test_depr_star_invalid_format_2(self):
1757 block = """
1758 module foo
1759 foo.bar
1760 this: int
1761 * [from a.b]
1762 Docstring.
1763 """
1764 err = (
1765 "Function 'bar': expected format '[from major.minor]' "
1766 "where 'major' and 'minor' are integers; got 'a.b'"
1767 )
1768 self.expect_failure(block, err, lineno=3)
1769
1770 def test_depr_star_invalid_format_3(self):
1771 block = """
1772 module foo
1773 foo.bar
1774 this: int
1775 * [from 1.2.3]
1776 Docstring.
1777 """
1778 err = (
1779 "Function 'bar': expected format '[from major.minor]' "
1780 "where 'major' and 'minor' are integers; got '1.2.3'"
1781 )
1782 self.expect_failure(block, err, lineno=3)
1783
1784 def test_parameters_required_after_depr_star(self):
1785 block = """
1786 module foo
1787 foo.bar
1788 this: int
1789 * [from 3.14]
1790 Docstring.
1791 """
1792 err = (
1793 "Function 'bar' specifies '* [from ...]' without "
1794 "following parameters."
1795 )
1796 self.expect_failure(block, err, lineno=4)
1797
1798 def test_parameters_required_after_depr_star2(self):
1799 block = """
1800 module foo
1801 foo.bar
1802 a: int
1803 * [from 3.14]
1804 *
1805 b: int
1806 Docstring.
1807 """
1808 err = (
1809 "Function 'bar' specifies '* [from ...]' without "
1810 "following parameters."
1811 )
1812 self.expect_failure(block, err, lineno=4)
1813
1814 def test_parameters_required_after_depr_star3(self):
1815 block = """
1816 module foo
1817 foo.bar
1818 a: int
1819 * [from 3.14]
1820 *args: object
1821 b: int
1822 Docstring.
1823 """
1824 err = (
1825 "Function 'bar' specifies '* [from ...]' without "
1826 "following parameters."
1827 )
1828 self.expect_failure(block, err, lineno=4)
1829
1830 def test_depr_star_must_come_before_star(self):
1831 block = """
1832 module foo
1833 foo.bar
1834 a: int
1835 *
1836 * [from 3.14]
1837 b: int
1838 Docstring.
1839 """
1840 err = "Function 'bar': '* [from ...]' must precede '*'"
1841 self.expect_failure(block, err, lineno=4)
1842
1843 def test_depr_star_must_come_before_vararg(self):
1844 block = """
1845 module foo
1846 foo.bar
1847 a: int
1848 *args: object
1849 * [from 3.14]
1850 b: int
1851 Docstring.
1852 """
1853 err = "Function 'bar': '* [from ...]' must precede '*'"
1854 self.expect_failure(block, err, lineno=4)
1855
1856 def test_depr_star_duplicate(self):
1857 block = """
1858 module foo
1859 foo.bar
1860 a: int
1861 * [from 3.14]
1862 b: int
1863 * [from 3.14]
1864 c: int
1865 Docstring.
1866 """
1867 err = "Function 'bar' uses '* [from 3.14]' more than once."
1868 self.expect_failure(block, err, lineno=5)
1869
1870 def test_depr_star_duplicate2(self):
1871 block = """
1872 module foo
1873 foo.bar
1874 a: int
1875 * [from 3.14]
1876 b: int
1877 * [from 3.15]
1878 c: int
1879 Docstring.
1880 """
1881 err = "Function 'bar': '* [from 3.15]' must precede '* [from 3.14]'"
1882 self.expect_failure(block, err, lineno=5)
1883
1884 def test_depr_slash_duplicate(self):
1885 block = """
1886 module foo
1887 foo.bar
1888 a: int
1889 / [from 3.14]
1890 b: int
1891 / [from 3.14]
1892 c: int
1893 Docstring.
1894 """
1895 err = "Function 'bar' uses '/ [from 3.14]' more than once."
1896 self.expect_failure(block, err, lineno=5)
1897
1898 def test_depr_slash_duplicate2(self):
1899 block = """
1900 module foo
1901 foo.bar
1902 a: int
1903 / [from 3.15]
1904 b: int
1905 / [from 3.14]
1906 c: int
1907 Docstring.
1908 """
1909 err = "Function 'bar': '/ [from 3.14]' must precede '/ [from 3.15]'"
1910 self.expect_failure(block, err, lineno=5)
1911
1912 def test_single_slash(self):
1913 block = """
1914 module foo
1915 foo.bar
1916 /
1917 /
1918 """
1919 err = (
1920 "Function 'bar' has an unsupported group configuration. "
1921 "(Unexpected state 0.d)"
1922 )
1923 self.expect_failure(block, err)
1924
1925 def test_parameters_required_before_depr_slash(self):
1926 block = """
1927 module foo
1928 foo.bar
1929 / [from 3.14]
1930 Docstring.
1931 """
1932 err = (
1933 "Function 'bar' specifies '/ [from ...]' without "
1934 "preceding parameters."
1935 )
1936 self.expect_failure(block, err, lineno=2)
1937
1938 def test_parameters_required_before_depr_slash2(self):
1939 block = """
1940 module foo
1941 foo.bar
1942 a: int
1943 /
1944 / [from 3.14]
1945 Docstring.
1946 """
1947 err = (
1948 "Function 'bar' specifies '/ [from ...]' without "
1949 "preceding parameters."
1950 )
1951 self.expect_failure(block, err, lineno=4)
1952
1953 def test_double_slash(self):
1954 block = """
1955 module foo
1956 foo.bar
1957 a: int
1958 /
1959 b: int
1960 /
1961 """
1962 err = "Function 'bar' uses '/' more than once."
1963 self.expect_failure(block, err)
1964
1965 def test_slash_after_star(self):
1966 block = """
1967 module foo
1968 foo.bar
1969 x: int
1970 y: int
1971 *
1972 z: int
1973 /
1974 """
1975 err = "Function 'bar': '/' must precede '*'"
1976 self.expect_failure(block, err)
1977
1978 def test_slash_after_vararg(self):
1979 block = """
1980 module foo
1981 foo.bar
1982 x: int
1983 y: int
1984 *args: object
1985 z: int
1986 /
1987 """
1988 err = "Function 'bar': '/' must precede '*'"
1989 self.expect_failure(block, err)
1990
1991 def test_depr_star_must_come_after_slash(self):
1992 block = """
1993 module foo
1994 foo.bar
1995 a: int
1996 * [from 3.14]
1997 /
1998 b: int
1999 Docstring.
2000 """
2001 err = "Function 'bar': '/' must precede '* [from ...]'"
2002 self.expect_failure(block, err, lineno=4)
2003
2004 def test_depr_star_must_come_after_depr_slash(self):
2005 block = """
2006 module foo
2007 foo.bar
2008 a: int
2009 * [from 3.14]
2010 / [from 3.14]
2011 b: int
2012 Docstring.
2013 """
2014 err = "Function 'bar': '/ [from ...]' must precede '* [from ...]'"
2015 self.expect_failure(block, err, lineno=4)
2016
2017 def test_star_must_come_after_depr_slash(self):
2018 block = """
2019 module foo
2020 foo.bar
2021 a: int
2022 *
2023 / [from 3.14]
2024 b: int
2025 Docstring.
2026 """
2027 err = "Function 'bar': '/ [from ...]' must precede '*'"
2028 self.expect_failure(block, err, lineno=4)
2029
2030 def test_vararg_must_come_after_depr_slash(self):
2031 block = """
2032 module foo
2033 foo.bar
2034 a: int
2035 *args: object
2036 / [from 3.14]
2037 b: int
2038 Docstring.
2039 """
2040 err = "Function 'bar': '/ [from ...]' must precede '*'"
2041 self.expect_failure(block, err, lineno=4)
2042
2043 def test_depr_slash_must_come_after_slash(self):
2044 block = """
2045 module foo
2046 foo.bar
2047 a: int
2048 / [from 3.14]
2049 /
2050 b: int
2051 Docstring.
2052 """
2053 err = "Function 'bar': '/' must precede '/ [from ...]'"
2054 self.expect_failure(block, err, lineno=4)
2055
2056 def test_parameters_not_permitted_after_slash_for_now(self):
2057 block = """
2058 module foo
2059 foo.bar
2060 /
2061 x: int
2062 """
2063 err = (
2064 "Function 'bar' has an unsupported group configuration. "
2065 "(Unexpected state 0.d)"
2066 )
2067 self.expect_failure(block, err)
2068
2069 def test_parameters_no_more_than_one_vararg(self):
2070 err = "Function 'bar' uses '*' more than once."
2071 block = """
2072 module foo
2073 foo.bar
2074 *vararg1: object
2075 *vararg2: object
2076 """
2077 self.expect_failure(block, err, lineno=3)
2078
2079 def test_function_not_at_column_0(self):
2080 function = self.parse_function("""
2081 module foo
2082 foo.bar
2083 x: int
2084 Nested docstring here, goeth.
2085 *
2086 y: str
2087 Not at column 0!
2088 """)
2089 self.checkDocstring(function, """
2090 bar($module, /, x, *, y)
2091 --
2092
2093 Not at column 0!
2094
2095 x
2096 Nested docstring here, goeth.
2097 """)
2098
2099 def test_docstring_only_summary(self):
2100 function = self.parse_function("""
2101 module m
2102 m.f
2103 summary
2104 """)
2105 self.checkDocstring(function, """
2106 f($module, /)
2107 --
2108
2109 summary
2110 """)
2111
2112 def test_docstring_empty_lines(self):
2113 function = self.parse_function("""
2114 module m
2115 m.f
2116
2117
2118 """)
2119 self.checkDocstring(function, """
2120 f($module, /)
2121 --
2122 """)
2123
2124 def test_docstring_explicit_params_placement(self):
2125 function = self.parse_function("""
2126 module m
2127 m.f
2128 a: int
2129 Param docstring for 'a' will be included
2130 b: int
2131 c: int
2132 Param docstring for 'c' will be included
2133 This is the summary line.
2134
2135 We'll now place the params section here:
2136 {parameters}
2137 And now for something completely different!
2138 (Note the added newline)
2139 """)
2140 self.checkDocstring(function, """
2141 f($module, /, a, b, c)
2142 --
2143
2144 This is the summary line.
2145
2146 We'll now place the params section here:
2147 a
2148 Param docstring for 'a' will be included
2149 c
2150 Param docstring for 'c' will be included
2151
2152 And now for something completely different!
2153 (Note the added newline)
2154 """)
2155
2156 def test_indent_stack_no_tabs(self):
2157 block = """
2158 module foo
2159 foo.bar
2160 *vararg1: object
2161 \t*vararg2: object
2162 """
2163 err = ("Tab characters are illegal in the Clinic DSL: "
2164 r"'\t*vararg2: object'")
2165 self.expect_failure(block, err)
2166
2167 def test_indent_stack_illegal_outdent(self):
2168 block = """
2169 module foo
2170 foo.bar
2171 a: object
2172 b: object
2173 """
2174 err = "Illegal outdent"
2175 self.expect_failure(block, err)
2176
2177 def test_directive(self):
2178 parser = DSLParser(_make_clinic())
2179 parser.flag = False
2180 parser.directives['setflag'] = lambda : setattr(parser, 'flag', True)
2181 block = Block("setflag")
2182 parser.parse(block)
2183 self.assertTrue(parser.flag)
2184
2185 def test_legacy_converters(self):
2186 block = self.parse('module os\nos.access\n path: "s"')
2187 module, function = block.signatures
2188 conv = (function.parameters['path']).converter
2189 self.assertIsInstance(conv, str_converter)
2190
2191 def test_legacy_converters_non_string_constant_annotation(self):
2192 err = "Annotations must be either a name, a function call, or a string"
2193 dataset = (
2194 'module os\nos.access\n path: 42',
2195 'module os\nos.access\n path: 42.42',
2196 'module os\nos.access\n path: 42j',
2197 'module os\nos.access\n path: b"42"',
2198 )
2199 for block in dataset:
2200 with self.subTest(block=block):
2201 self.expect_failure(block, err, lineno=2)
2202
2203 def test_other_bizarre_things_in_annotations_fail(self):
2204 err = "Annotations must be either a name, a function call, or a string"
2205 dataset = (
2206 'module os\nos.access\n path: {"some": "dictionary"}',
2207 'module os\nos.access\n path: ["list", "of", "strings"]',
2208 'module os\nos.access\n path: (x for x in range(42))',
2209 )
2210 for block in dataset:
2211 with self.subTest(block=block):
2212 self.expect_failure(block, err, lineno=2)
2213
2214 def test_kwarg_splats_disallowed_in_function_call_annotations(self):
2215 err = "Cannot use a kwarg splat in a function-call annotation"
2216 dataset = (
2217 'module fo\nfo.barbaz\n o: bool(**{None: "bang!"})',
2218 'module fo\nfo.barbaz -> bool(**{None: "bang!"})',
2219 'module fo\nfo.barbaz -> bool(**{"bang": 42})',
2220 'module fo\nfo.barbaz\n o: bool(**{"bang": None})',
2221 )
2222 for block in dataset:
2223 with self.subTest(block=block):
2224 self.expect_failure(block, err)
2225
2226 def test_self_param_placement(self):
2227 err = (
2228 "A 'self' parameter, if specified, must be the very first thing "
2229 "in the parameter block."
2230 )
2231 block = """
2232 module foo
2233 foo.func
2234 a: int
2235 self: self(type="PyObject *")
2236 """
2237 self.expect_failure(block, err, lineno=3)
2238
2239 def test_self_param_cannot_be_optional(self):
2240 err = "A 'self' parameter cannot be marked optional."
2241 block = """
2242 module foo
2243 foo.func
2244 self: self(type="PyObject *") = None
2245 """
2246 self.expect_failure(block, err, lineno=2)
2247
2248 def test_defining_class_param_placement(self):
2249 err = (
2250 "A 'defining_class' parameter, if specified, must either be the "
2251 "first thing in the parameter block, or come just after 'self'."
2252 )
2253 block = """
2254 module foo
2255 foo.func
2256 self: self(type="PyObject *")
2257 a: int
2258 cls: defining_class
2259 """
2260 self.expect_failure(block, err, lineno=4)
2261
2262 def test_defining_class_param_cannot_be_optional(self):
2263 err = "A 'defining_class' parameter cannot be marked optional."
2264 block = """
2265 module foo
2266 foo.func
2267 cls: defining_class(type="PyObject *") = None
2268 """
2269 self.expect_failure(block, err, lineno=2)
2270
2271 def test_slot_methods_cannot_access_defining_class(self):
2272 block = """
2273 module foo
2274 class Foo "" ""
2275 Foo.__init__
2276 cls: defining_class
2277 a: object
2278 """
2279 err = "Slot methods cannot access their defining class."
2280 with self.assertRaisesRegex(ValueError, err):
2281 self.parse_function(block)
2282
2283 def test_new_must_be_a_class_method(self):
2284 err = "'__new__' must be a class method!"
2285 block = """
2286 module foo
2287 class Foo "" ""
2288 Foo.__new__
2289 """
2290 self.expect_failure(block, err, lineno=2)
2291
2292 def test_init_must_be_a_normal_method(self):
2293 err_template = "'__init__' must be a normal method; got 'FunctionKind.{}'!"
2294 annotations = {
2295 "@classmethod": "CLASS_METHOD",
2296 "@staticmethod": "STATIC_METHOD",
2297 "@getter": "GETTER",
2298 }
2299 for annotation, invalid_kind in annotations.items():
2300 with self.subTest(annotation=annotation, invalid_kind=invalid_kind):
2301 block = f"""
2302 module foo
2303 class Foo "" ""
2304 {annotation}
2305 Foo.__init__
2306 """
2307 expected_error = err_template.format(invalid_kind)
2308 self.expect_failure(block, expected_error, lineno=3)
2309
2310 def test_init_cannot_define_a_return_type(self):
2311 block = """
2312 class Foo "" ""
2313 Foo.__init__ -> long
2314 """
2315 expected_error = "__init__ methods cannot define a return type"
2316 self.expect_failure(block, expected_error, lineno=1)
2317
2318 def test_invalid_getset(self):
2319 annotations = ["@getter", "@setter"]
2320 for annotation in annotations:
2321 with self.subTest(annotation=annotation):
2322 block = f"""
2323 module foo
2324 class Foo "" ""
2325 {annotation}
2326 Foo.property -> int
2327 """
2328 expected_error = f"{annotation} method cannot define a return type"
2329 self.expect_failure(block, expected_error, lineno=3)
2330
2331 block = f"""
2332 module foo
2333 class Foo "" ""
2334 {annotation}
2335 Foo.property
2336 obj: int
2337 /
2338 """
2339 expected_error = f"{annotation} methods cannot define parameters"
2340 self.expect_failure(block, expected_error)
2341
2342 def test_setter_docstring(self):
2343 block = """
2344 module foo
2345 class Foo "" ""
2346 @setter
2347 Foo.property
2348
2349 foo
2350
2351 bar
2352 [clinic start generated code]*/
2353 """
2354 expected_error = "docstrings are only supported for @getter, not @setter"
2355 self.expect_failure(block, expected_error)
2356
2357 def test_duplicate_getset(self):
2358 annotations = ["@getter", "@setter"]
2359 for annotation in annotations:
2360 with self.subTest(annotation=annotation):
2361 block = f"""
2362 module foo
2363 class Foo "" ""
2364 {annotation}
2365 {annotation}
2366 Foo.property -> int
2367 """
2368 expected_error = f"Cannot apply {annotation} twice to the same function!"
2369 self.expect_failure(block, expected_error, lineno=3)
2370
2371 def test_getter_and_setter_disallowed_on_same_function(self):
2372 dup_annotations = [("@getter", "@setter"), ("@setter", "@getter")]
2373 for dup in dup_annotations:
2374 with self.subTest(dup=dup):
2375 block = f"""
2376 module foo
2377 class Foo "" ""
2378 {dup[0]}
2379 {dup[1]}
2380 Foo.property -> int
2381 """
2382 expected_error = "Cannot apply both @getter and @setter to the same function!"
2383 self.expect_failure(block, expected_error, lineno=3)
2384
2385 def test_getset_no_class(self):
2386 for annotation in "@getter", "@setter":
2387 with self.subTest(annotation=annotation):
2388 block = f"""
2389 module m
2390 {annotation}
2391 m.func
2392 """
2393 expected_error = "@getter and @setter must be methods"
2394 self.expect_failure(block, expected_error, lineno=2)
2395
2396 def test_duplicate_coexist(self):
2397 err = "Called @coexist twice"
2398 block = """
2399 module m
2400 @coexist
2401 @coexist
2402 m.fn
2403 """
2404 self.expect_failure(block, err, lineno=2)
2405
2406 def test_unused_param(self):
2407 block = self.parse("""
2408 module foo
2409 foo.func
2410 fn: object
2411 k: float
2412 i: float(unused=True)
2413 /
2414 *
2415 flag: bool(unused=True) = False
2416 """)
2417 sig = block.signatures[1] # Function index == 1
2418 params = sig.parameters
2419 conv = lambda fn: params[fn].converter
2420 dataset = (
2421 {"name": "fn", "unused": False},
2422 {"name": "k", "unused": False},
2423 {"name": "i", "unused": True},
2424 {"name": "flag", "unused": True},
2425 )
2426 for param in dataset:
2427 name, unused = param.values()
2428 with self.subTest(name=name, unused=unused):
2429 p = conv(name)
2430 # Verify that the unused flag is parsed correctly.
2431 self.assertEqual(unused, p.unused)
2432
2433 # Now, check that we'll produce correct code.
2434 decl = p.simple_declaration(in_parser=False)
2435 if unused:
2436 self.assertIn("Py_UNUSED", decl)
2437 else:
2438 self.assertNotIn("Py_UNUSED", decl)
2439
2440 # Make sure the Py_UNUSED macro is not used in the parser body.
2441 parser_decl = p.simple_declaration(in_parser=True)
2442 self.assertNotIn("Py_UNUSED", parser_decl)
2443
2444 def test_scaffolding(self):
2445 # test repr on special values
2446 self.assertEqual(repr(unspecified), '<Unspecified>')
2447 self.assertEqual(repr(NULL), '<Null>')
2448
2449 # test that fail fails
2450 with support.captured_stdout() as stdout:
2451 errmsg = 'The igloos are melting'
2452 with self.assertRaisesRegex(ClinicError, errmsg) as cm:
2453 fail(errmsg, filename='clown.txt', line_number=69)
2454 exc = cm.exception
2455 self.assertEqual(exc.filename, 'clown.txt')
2456 self.assertEqual(exc.lineno, 69)
2457 self.assertEqual(stdout.getvalue(), "")
2458
2459 def test_non_ascii_character_in_docstring(self):
2460 block = """
2461 module test
2462 test.fn
2463 a: int
2464 á param docstring
2465 docstring fü bár baß
2466 """
2467 with support.captured_stdout() as stdout:
2468 self.parse(block)
2469 # The line numbers are off; this is a known limitation.
2470 expected = dedent("""\
2471 Warning:
2472 Non-ascii characters are not allowed in docstrings: 'á'
2473
2474 Warning:
2475 Non-ascii characters are not allowed in docstrings: 'ü', 'á', 'ß'
2476
2477 """)
2478 self.assertEqual(stdout.getvalue(), expected)
2479
2480 def test_illegal_c_identifier(self):
2481 err = "Illegal C identifier: 17a"
2482 block = """
2483 module test
2484 test.fn
2485 a as 17a: int
2486 """
2487 self.expect_failure(block, err, lineno=2)
2488
2489 def test_cannot_convert_special_method(self):
2490 err = "'__len__' is a special method and cannot be converted"
2491 block = """
2492 class T "" ""
2493 T.__len__
2494 """
2495 self.expect_failure(block, err, lineno=1)
2496
2497 def test_cannot_specify_pydefault_without_default(self):
2498 err = "You can't specify py_default without specifying a default value!"
2499 block = """
2500 fn
2501 a: object(py_default='NULL')
2502 """
2503 self.expect_failure(block, err, lineno=1)
2504
2505 def test_vararg_cannot_take_default_value(self):
2506 err = "Vararg can't take a default value!"
2507 block = """
2508 fn
2509 *args: object = None
2510 """
2511 self.expect_failure(block, err, lineno=1)
2512
2513 def test_default_is_not_of_correct_type(self):
2514 err = ("int_converter: default value 2.5 for field 'a' "
2515 "is not of type 'int'")
2516 block = """
2517 fn
2518 a: int = 2.5
2519 """
2520 self.expect_failure(block, err, lineno=1)
2521
2522 def test_invalid_legacy_converter(self):
2523 err = "'fhi' is not a valid legacy converter"
2524 block = """
2525 fn
2526 a: 'fhi'
2527 """
2528 self.expect_failure(block, err, lineno=1)
2529
2530 def test_parent_class_or_module_does_not_exist(self):
2531 err = "Parent class or module 'baz' does not exist"
2532 block = """
2533 module m
2534 baz.func
2535 """
2536 self.expect_failure(block, err, lineno=1)
2537
2538 def test_duplicate_param_name(self):
2539 err = "You can't have two parameters named 'a'"
2540 block = """
2541 module m
2542 m.func
2543 a: int
2544 a: float
2545 """
2546 self.expect_failure(block, err, lineno=3)
2547
2548 def test_param_requires_custom_c_name(self):
2549 err = "Parameter 'module' requires a custom C name"
2550 block = """
2551 module m
2552 m.func
2553 module: int
2554 """
2555 self.expect_failure(block, err, lineno=2)
2556
2557 def test_state_func_docstring_assert_no_group(self):
2558 err = "Function 'func' has a ']' without a matching '['"
2559 block = """
2560 module m
2561 m.func
2562 ]
2563 docstring
2564 """
2565 self.expect_failure(block, err, lineno=2)
2566
2567 def test_state_func_docstring_no_summary(self):
2568 err = "Docstring for 'm.func' does not have a summary line!"
2569 block = """
2570 module m
2571 m.func
2572 docstring1
2573 docstring2
2574 """
2575 self.expect_failure(block, err, lineno=3)
2576
2577 def test_state_func_docstring_only_one_param_template(self):
2578 err = "You may not specify {parameters} more than once in a docstring!"
2579 block = """
2580 module m
2581 m.func
2582 docstring summary
2583
2584 these are the params:
2585 {parameters}
2586 these are the params again:
2587 {parameters}
2588 """
2589 self.expect_failure(block, err, lineno=7)
2590
2591 def test_kind_defining_class(self):
2592 function = self.parse_function("""
2593 module m
2594 class m.C "PyObject *" ""
2595 m.C.meth
2596 cls: defining_class
2597 """, signatures_in_block=3, function_index=2)
2598 p = function.parameters['cls']
2599 self.assertEqual(p.kind, inspect.Parameter.POSITIONAL_ONLY)
2600
2601 def test_disallow_defining_class_at_module_level(self):
2602 err = "A 'defining_class' parameter cannot be defined at module level."
2603 block = """
2604 module m
2605 m.func
2606 cls: defining_class
2607 """
2608 self.expect_failure(block, err, lineno=2)
2609
2610
2611 class ClinicExternalTest(TestCase):
2612 maxDiff = None
2613
2614 def setUp(self):
2615 save_restore_converters(self)
2616
2617 def run_clinic(self, *args):
2618 with (
2619 support.captured_stdout() as out,
2620 support.captured_stderr() as err,
2621 self.assertRaises(SystemExit) as cm
2622 ):
2623 clinic.main(args)
2624 return out.getvalue(), err.getvalue(), cm.exception.code
2625
2626 def expect_success(self, *args):
2627 out, err, code = self.run_clinic(*args)
2628 if code != 0:
2629 self.fail("\n".join([f"Unexpected failure: {args=}", out, err]))
2630 self.assertEqual(err, "")
2631 return out
2632
2633 def expect_failure(self, *args):
2634 out, err, code = self.run_clinic(*args)
2635 self.assertNotEqual(code, 0, f"Unexpected success: {args=}")
2636 return out, err
2637
2638 def test_external(self):
2639 CLINIC_TEST = 'clinic.test.c'
2640 source = support.findfile(CLINIC_TEST)
2641 with open(source, encoding='utf-8') as f:
2642 orig_contents = f.read()
2643
2644 # Run clinic CLI and verify that it does not complain.
2645 self.addCleanup(unlink, TESTFN)
2646 out = self.expect_success("-f", "-o", TESTFN, source)
2647 self.assertEqual(out, "")
2648
2649 with open(TESTFN, encoding='utf-8') as f:
2650 new_contents = f.read()
2651
2652 self.assertEqual(new_contents, orig_contents)
2653
2654 def test_no_change(self):
2655 # bpo-42398: Test that the destination file is left unchanged if the
2656 # content does not change. Moreover, check also that the file
2657 # modification time does not change in this case.
2658 code = dedent("""
2659 /*[clinic input]
2660 [clinic start generated code]*/
2661 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=da39a3ee5e6b4b0d]*/
2662 """)
2663 with os_helper.temp_dir() as tmp_dir:
2664 fn = os.path.join(tmp_dir, "test.c")
2665 with open(fn, "w", encoding="utf-8") as f:
2666 f.write(code)
2667 pre_mtime = os.stat(fn).st_mtime_ns
2668 self.expect_success(fn)
2669 post_mtime = os.stat(fn).st_mtime_ns
2670 # Don't change the file modification time
2671 # if the content does not change
2672 self.assertEqual(pre_mtime, post_mtime)
2673
2674 def test_cli_force(self):
2675 invalid_input = dedent("""
2676 /*[clinic input]
2677 output preset block
2678 module test
2679 test.fn
2680 a: int
2681 [clinic start generated code]*/
2682
2683 const char *hand_edited = "output block is overwritten";
2684 /*[clinic end generated code: output=bogus input=bogus]*/
2685 """)
2686 fail_msg = (
2687 "Checksum mismatch! Expected 'bogus', computed '2ed19'. "
2688 "Suggested fix: remove all generated code including the end marker, "
2689 "or use the '-f' option.\n"
2690 )
2691 with os_helper.temp_dir() as tmp_dir:
2692 fn = os.path.join(tmp_dir, "test.c")
2693 with open(fn, "w", encoding="utf-8") as f:
2694 f.write(invalid_input)
2695 # First, run the CLI without -f and expect failure.
2696 # Note, we cannot check the entire fail msg, because the path to
2697 # the tmp file will change for every run.
2698 _, err = self.expect_failure(fn)
2699 self.assertTrue(err.endswith(fail_msg),
2700 f"{err!r} does not end with {fail_msg!r}")
2701 # Then, force regeneration; success expected.
2702 out = self.expect_success("-f", fn)
2703 self.assertEqual(out, "")
2704 # Verify by checking the checksum.
2705 checksum = (
2706 "/*[clinic end generated code: "
2707 "output=0acbef4794cb933e input=9543a8d2da235301]*/\n"
2708 )
2709 with open(fn, encoding='utf-8') as f:
2710 generated = f.read()
2711 self.assertTrue(generated.endswith(checksum),
2712 (generated, checksum))
2713
2714 def test_cli_make(self):
2715 c_code = dedent("""
2716 /*[clinic input]
2717 [clinic start generated code]*/
2718 """)
2719 py_code = "pass"
2720 c_files = "file1.c", "file2.c"
2721 py_files = "file1.py", "file2.py"
2722
2723 def create_files(files, srcdir, code):
2724 for fn in files:
2725 path = os.path.join(srcdir, fn)
2726 with open(path, "w", encoding="utf-8") as f:
2727 f.write(code)
2728
2729 with os_helper.temp_dir() as tmp_dir:
2730 # add some folders, some C files and a Python file
2731 create_files(c_files, tmp_dir, c_code)
2732 create_files(py_files, tmp_dir, py_code)
2733
2734 # create C files in externals/ dir
2735 ext_path = os.path.join(tmp_dir, "externals")
2736 with os_helper.temp_dir(path=ext_path) as externals:
2737 create_files(c_files, externals, c_code)
2738
2739 # run clinic in verbose mode with --make on tmpdir
2740 out = self.expect_success("-v", "--make", "--srcdir", tmp_dir)
2741
2742 # expect verbose mode to only mention the C files in tmp_dir
2743 for filename in c_files:
2744 with self.subTest(filename=filename):
2745 path = os.path.join(tmp_dir, filename)
2746 self.assertIn(path, out)
2747 for filename in py_files:
2748 with self.subTest(filename=filename):
2749 path = os.path.join(tmp_dir, filename)
2750 self.assertNotIn(path, out)
2751 # don't expect C files from the externals dir
2752 for filename in c_files:
2753 with self.subTest(filename=filename):
2754 path = os.path.join(ext_path, filename)
2755 self.assertNotIn(path, out)
2756
2757 def test_cli_make_exclude(self):
2758 code = dedent("""
2759 /*[clinic input]
2760 [clinic start generated code]*/
2761 """)
2762 with os_helper.temp_dir(quiet=False) as tmp_dir:
2763 # add some folders, some C files and a Python file
2764 for fn in "file1.c", "file2.c", "file3.c", "file4.c":
2765 path = os.path.join(tmp_dir, fn)
2766 with open(path, "w", encoding="utf-8") as f:
2767 f.write(code)
2768
2769 # Run clinic in verbose mode with --make on tmpdir.
2770 # Exclude file2.c and file3.c.
2771 out = self.expect_success(
2772 "-v", "--make", "--srcdir", tmp_dir,
2773 "--exclude", os.path.join(tmp_dir, "file2.c"),
2774 # The added ./ should be normalised away.
2775 "--exclude", os.path.join(tmp_dir, "./file3.c"),
2776 # Relative paths should also work.
2777 "--exclude", "file4.c"
2778 )
2779
2780 # expect verbose mode to only mention the C files in tmp_dir
2781 self.assertIn("file1.c", out)
2782 self.assertNotIn("file2.c", out)
2783 self.assertNotIn("file3.c", out)
2784 self.assertNotIn("file4.c", out)
2785
2786 def test_cli_verbose(self):
2787 with os_helper.temp_dir() as tmp_dir:
2788 fn = os.path.join(tmp_dir, "test.c")
2789 with open(fn, "w", encoding="utf-8") as f:
2790 f.write("")
2791 out = self.expect_success("-v", fn)
2792 self.assertEqual(out.strip(), fn)
2793
2794 def test_cli_help(self):
2795 out = self.expect_success("-h")
2796 self.assertIn("usage: clinic.py", out)
2797
2798 def test_cli_converters(self):
2799 prelude = dedent("""
2800 Legacy converters:
2801 B C D L O S U Y Z Z#
2802 b c d f h i l p s s# s* u u# w* y y# y* z z# z*
2803
2804 Converters:
2805 """)
2806 expected_converters = (
2807 "bool",
2808 "byte",
2809 "char",
2810 "defining_class",
2811 "double",
2812 "fildes",
2813 "float",
2814 "int",
2815 "long",
2816 "long_long",
2817 "object",
2818 "Py_buffer",
2819 "Py_complex",
2820 "Py_ssize_t",
2821 "Py_UNICODE",
2822 "PyByteArrayObject",
2823 "PyBytesObject",
2824 "self",
2825 "short",
2826 "size_t",
2827 "slice_index",
2828 "str",
2829 "unicode",
2830 "unicode_fs_decoded",
2831 "unicode_fs_encoded",
2832 "unsigned_char",
2833 "unsigned_int",
2834 "unsigned_long",
2835 "unsigned_long_long",
2836 "unsigned_short",
2837 )
2838 finale = dedent("""
2839 Return converters:
2840 bool()
2841 double()
2842 float()
2843 int()
2844 long()
2845 object()
2846 Py_ssize_t()
2847 size_t()
2848 unsigned_int()
2849 unsigned_long()
2850
2851 All converters also accept (c_default=None, py_default=None, annotation=None).
2852 All return converters also accept (py_default=None).
2853 """)
2854 out = self.expect_success("--converters")
2855 # We cannot simply compare the output, because the repr of the *accept*
2856 # param may change (it's a set, thus unordered). So, let's compare the
2857 # start and end of the expected output, and then assert that the
2858 # converters appear lined up in alphabetical order.
2859 self.assertTrue(out.startswith(prelude), out)
2860 self.assertTrue(out.endswith(finale), out)
2861
2862 out = out.removeprefix(prelude)
2863 out = out.removesuffix(finale)
2864 lines = out.split("\n")
2865 for converter, line in zip(expected_converters, lines):
2866 line = line.lstrip()
2867 with self.subTest(converter=converter):
2868 self.assertTrue(
2869 line.startswith(converter),
2870 f"expected converter {converter!r}, got {line!r}"
2871 )
2872
2873 def test_cli_fail_converters_and_filename(self):
2874 _, err = self.expect_failure("--converters", "test.c")
2875 msg = "can't specify --converters and a filename at the same time"
2876 self.assertIn(msg, err)
2877
2878 def test_cli_fail_no_filename(self):
2879 _, err = self.expect_failure()
2880 self.assertIn("no input files", err)
2881
2882 def test_cli_fail_output_and_multiple_files(self):
2883 _, err = self.expect_failure("-o", "out.c", "input.c", "moreinput.c")
2884 msg = "error: can't use -o with multiple filenames"
2885 self.assertIn(msg, err)
2886
2887 def test_cli_fail_filename_or_output_and_make(self):
2888 msg = "can't use -o or filenames with --make"
2889 for opts in ("-o", "out.c"), ("filename.c",):
2890 with self.subTest(opts=opts):
2891 _, err = self.expect_failure("--make", *opts)
2892 self.assertIn(msg, err)
2893
2894 def test_cli_fail_make_without_srcdir(self):
2895 _, err = self.expect_failure("--make", "--srcdir", "")
2896 msg = "error: --srcdir must not be empty with --make"
2897 self.assertIn(msg, err)
2898
2899 def test_file_dest(self):
2900 block = dedent("""
2901 /*[clinic input]
2902 destination test new file {path}.h
2903 output everything test
2904 func
2905 a: object
2906 /
2907 [clinic start generated code]*/
2908 """)
2909 expected_checksum_line = (
2910 "/*[clinic end generated code: "
2911 "output=da39a3ee5e6b4b0d input=b602ab8e173ac3bd]*/\n"
2912 )
2913 expected_output = dedent("""\
2914 /*[clinic input]
2915 preserve
2916 [clinic start generated code]*/
2917
2918 PyDoc_VAR(func__doc__);
2919
2920 PyDoc_STRVAR(func__doc__,
2921 "func($module, a, /)\\n"
2922 "--\\n"
2923 "\\n");
2924
2925 #define FUNC_METHODDEF \\
2926 {"func", (PyCFunction)func, METH_O, func__doc__},
2927
2928 static PyObject *
2929 func(PyObject *module, PyObject *a)
2930 /*[clinic end generated code: output=3dde2d13002165b9 input=a9049054013a1b77]*/
2931 """)
2932 with os_helper.temp_dir() as tmp_dir:
2933 in_fn = os.path.join(tmp_dir, "test.c")
2934 out_fn = os.path.join(tmp_dir, "test.c.h")
2935 with open(in_fn, "w", encoding="utf-8") as f:
2936 f.write(block)
2937 with open(out_fn, "w", encoding="utf-8") as f:
2938 f.write("") # Write an empty output file!
2939 # Clinic should complain about the empty output file.
2940 _, err = self.expect_failure(in_fn)
2941 expected_err = (f"Modified destination file {out_fn!r}; "
2942 "not overwriting!")
2943 self.assertIn(expected_err, err)
2944 # Run clinic again, this time with the -f option.
2945 _ = self.expect_success("-f", in_fn)
2946 # Read back the generated output.
2947 with open(in_fn, encoding="utf-8") as f:
2948 data = f.read()
2949 expected_block = f"{block}{expected_checksum_line}"
2950 self.assertEqual(data, expected_block)
2951 with open(out_fn, encoding="utf-8") as f:
2952 data = f.read()
2953 self.assertEqual(data, expected_output)
2954
2955 try:
2956 import _testclinic as ac_tester
2957 except ImportError:
2958 ac_tester = None
2959
2960 @unittest.skipIf(ac_tester is None, "_testclinic is missing")
2961 class ClinicFunctionalTest(unittest.TestCase):
2962 locals().update((name, getattr(ac_tester, name))
2963 for name in dir(ac_tester) if name.startswith('test_'))
2964
2965 def check_depr(self, regex, fn, /, *args, **kwds):
2966 with self.assertWarnsRegex(DeprecationWarning, regex) as cm:
2967 # Record the line number, so we're sure we've got the correct stack
2968 # level on the deprecation warning.
2969 _, lineno = fn(*args, **kwds), sys._getframe().f_lineno
2970 self.assertEqual(cm.filename, __file__)
2971 self.assertEqual(cm.lineno, lineno)
2972
2973 def check_depr_star(self, pnames, fn, /, *args, name=None, **kwds):
2974 if name is None:
2975 name = fn.__qualname__
2976 if isinstance(fn, type):
2977 name = f'{fn.__module__}.{name}'
2978 regex = (
2979 fr"Passing( more than)?( [0-9]+)? positional argument(s)? to "
2980 fr"{re.escape(name)}\(\) is deprecated. Parameters? {pnames} will "
2981 fr"become( a)? keyword-only parameters? in Python 3\.14"
2982 )
2983 self.check_depr(regex, fn, *args, **kwds)
2984
2985 def check_depr_kwd(self, pnames, fn, *args, name=None, **kwds):
2986 if name is None:
2987 name = fn.__qualname__
2988 if isinstance(fn, type):
2989 name = f'{fn.__module__}.{name}'
2990 pl = 's' if ' ' in pnames else ''
2991 regex = (
2992 fr"Passing keyword argument{pl} {pnames} to "
2993 fr"{re.escape(name)}\(\) is deprecated. Parameter{pl} {pnames} "
2994 fr"will become positional-only in Python 3\.14."
2995 )
2996 self.check_depr(regex, fn, *args, **kwds)
2997
2998 def test_objects_converter(self):
2999 with self.assertRaises(TypeError):
3000 ac_tester.objects_converter()
3001 self.assertEqual(ac_tester.objects_converter(1, 2), (1, 2))
3002 self.assertEqual(ac_tester.objects_converter([], 'whatever class'), ([], 'whatever class'))
3003 self.assertEqual(ac_tester.objects_converter(1), (1, None))
3004
3005 def test_bytes_object_converter(self):
3006 with self.assertRaises(TypeError):
3007 ac_tester.bytes_object_converter(1)
3008 self.assertEqual(ac_tester.bytes_object_converter(b'BytesObject'), (b'BytesObject',))
3009
3010 def test_byte_array_object_converter(self):
3011 with self.assertRaises(TypeError):
3012 ac_tester.byte_array_object_converter(1)
3013 byte_arr = bytearray(b'ByteArrayObject')
3014 self.assertEqual(ac_tester.byte_array_object_converter(byte_arr), (byte_arr,))
3015
3016 def test_unicode_converter(self):
3017 with self.assertRaises(TypeError):
3018 ac_tester.unicode_converter(1)
3019 self.assertEqual(ac_tester.unicode_converter('unicode'), ('unicode',))
3020
3021 def test_bool_converter(self):
3022 with self.assertRaises(TypeError):
3023 ac_tester.bool_converter(False, False, 'not a int')
3024 self.assertEqual(ac_tester.bool_converter(), (True, True, True))
3025 self.assertEqual(ac_tester.bool_converter('', [], 5), (False, False, True))
3026 self.assertEqual(ac_tester.bool_converter(('not empty',), {1: 2}, 0), (True, True, False))
3027
3028 def test_bool_converter_c_default(self):
3029 self.assertEqual(ac_tester.bool_converter_c_default(), (1, 0, -2, -3))
3030 self.assertEqual(ac_tester.bool_converter_c_default(False, True, False, True),
3031 (0, 1, 0, 1))
3032
3033 def test_char_converter(self):
3034 with self.assertRaises(TypeError):
3035 ac_tester.char_converter(1)
3036 with self.assertRaises(TypeError):
3037 ac_tester.char_converter(b'ab')
3038 chars = [b'A', b'\a', b'\b', b'\t', b'\n', b'\v', b'\f', b'\r', b'"', b"'", b'?', b'\\', b'\000', b'\377']
3039 expected = tuple(ord(c) for c in chars)
3040 self.assertEqual(ac_tester.char_converter(), expected)
3041 chars = [b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'0', b'a', b'b', b'c', b'd']
3042 expected = tuple(ord(c) for c in chars)
3043 self.assertEqual(ac_tester.char_converter(*chars), expected)
3044
3045 def test_unsigned_char_converter(self):
3046 from _testcapi import UCHAR_MAX
3047 with self.assertRaises(OverflowError):
3048 ac_tester.unsigned_char_converter(-1)
3049 with self.assertRaises(OverflowError):
3050 ac_tester.unsigned_char_converter(UCHAR_MAX + 1)
3051 with self.assertRaises(OverflowError):
3052 ac_tester.unsigned_char_converter(0, UCHAR_MAX + 1)
3053 with self.assertRaises(TypeError):
3054 ac_tester.unsigned_char_converter([])
3055 self.assertEqual(ac_tester.unsigned_char_converter(), (12, 34, 56))
3056 self.assertEqual(ac_tester.unsigned_char_converter(0, 0, UCHAR_MAX + 1), (0, 0, 0))
3057 self.assertEqual(ac_tester.unsigned_char_converter(0, 0, (UCHAR_MAX + 1) * 3 + 123), (0, 0, 123))
3058
3059 def test_short_converter(self):
3060 from _testcapi import SHRT_MIN, SHRT_MAX
3061 with self.assertRaises(OverflowError):
3062 ac_tester.short_converter(SHRT_MIN - 1)
3063 with self.assertRaises(OverflowError):
3064 ac_tester.short_converter(SHRT_MAX + 1)
3065 with self.assertRaises(TypeError):
3066 ac_tester.short_converter([])
3067 self.assertEqual(ac_tester.short_converter(-1234), (-1234,))
3068 self.assertEqual(ac_tester.short_converter(4321), (4321,))
3069
3070 def test_unsigned_short_converter(self):
3071 from _testcapi import USHRT_MAX
3072 with self.assertRaises(ValueError):
3073 ac_tester.unsigned_short_converter(-1)
3074 with self.assertRaises(OverflowError):
3075 ac_tester.unsigned_short_converter(USHRT_MAX + 1)
3076 with self.assertRaises(OverflowError):
3077 ac_tester.unsigned_short_converter(0, USHRT_MAX + 1)
3078 with self.assertRaises(TypeError):
3079 ac_tester.unsigned_short_converter([])
3080 self.assertEqual(ac_tester.unsigned_short_converter(), (12, 34, 56))
3081 self.assertEqual(ac_tester.unsigned_short_converter(0, 0, USHRT_MAX + 1), (0, 0, 0))
3082 self.assertEqual(ac_tester.unsigned_short_converter(0, 0, (USHRT_MAX + 1) * 3 + 123), (0, 0, 123))
3083
3084 def test_int_converter(self):
3085 from _testcapi import INT_MIN, INT_MAX
3086 with self.assertRaises(OverflowError):
3087 ac_tester.int_converter(INT_MIN - 1)
3088 with self.assertRaises(OverflowError):
3089 ac_tester.int_converter(INT_MAX + 1)
3090 with self.assertRaises(TypeError):
3091 ac_tester.int_converter(1, 2, 3)
3092 with self.assertRaises(TypeError):
3093 ac_tester.int_converter([])
3094 self.assertEqual(ac_tester.int_converter(), (12, 34, 45))
3095 self.assertEqual(ac_tester.int_converter(1, 2, '3'), (1, 2, ord('3')))
3096
3097 def test_unsigned_int_converter(self):
3098 from _testcapi import UINT_MAX
3099 with self.assertRaises(ValueError):
3100 ac_tester.unsigned_int_converter(-1)
3101 with self.assertRaises(OverflowError):
3102 ac_tester.unsigned_int_converter(UINT_MAX + 1)
3103 with self.assertRaises(OverflowError):
3104 ac_tester.unsigned_int_converter(0, UINT_MAX + 1)
3105 with self.assertRaises(TypeError):
3106 ac_tester.unsigned_int_converter([])
3107 self.assertEqual(ac_tester.unsigned_int_converter(), (12, 34, 56))
3108 self.assertEqual(ac_tester.unsigned_int_converter(0, 0, UINT_MAX + 1), (0, 0, 0))
3109 self.assertEqual(ac_tester.unsigned_int_converter(0, 0, (UINT_MAX + 1) * 3 + 123), (0, 0, 123))
3110
3111 def test_long_converter(self):
3112 from _testcapi import LONG_MIN, LONG_MAX
3113 with self.assertRaises(OverflowError):
3114 ac_tester.long_converter(LONG_MIN - 1)
3115 with self.assertRaises(OverflowError):
3116 ac_tester.long_converter(LONG_MAX + 1)
3117 with self.assertRaises(TypeError):
3118 ac_tester.long_converter([])
3119 self.assertEqual(ac_tester.long_converter(), (12,))
3120 self.assertEqual(ac_tester.long_converter(-1234), (-1234,))
3121
3122 def test_unsigned_long_converter(self):
3123 from _testcapi import ULONG_MAX
3124 with self.assertRaises(ValueError):
3125 ac_tester.unsigned_long_converter(-1)
3126 with self.assertRaises(OverflowError):
3127 ac_tester.unsigned_long_converter(ULONG_MAX + 1)
3128 with self.assertRaises(OverflowError):
3129 ac_tester.unsigned_long_converter(0, ULONG_MAX + 1)
3130 with self.assertRaises(TypeError):
3131 ac_tester.unsigned_long_converter([])
3132 self.assertEqual(ac_tester.unsigned_long_converter(), (12, 34, 56))
3133 self.assertEqual(ac_tester.unsigned_long_converter(0, 0, ULONG_MAX + 1), (0, 0, 0))
3134 self.assertEqual(ac_tester.unsigned_long_converter(0, 0, (ULONG_MAX + 1) * 3 + 123), (0, 0, 123))
3135
3136 def test_long_long_converter(self):
3137 from _testcapi import LLONG_MIN, LLONG_MAX
3138 with self.assertRaises(OverflowError):
3139 ac_tester.long_long_converter(LLONG_MIN - 1)
3140 with self.assertRaises(OverflowError):
3141 ac_tester.long_long_converter(LLONG_MAX + 1)
3142 with self.assertRaises(TypeError):
3143 ac_tester.long_long_converter([])
3144 self.assertEqual(ac_tester.long_long_converter(), (12,))
3145 self.assertEqual(ac_tester.long_long_converter(-1234), (-1234,))
3146
3147 def test_unsigned_long_long_converter(self):
3148 from _testcapi import ULLONG_MAX
3149 with self.assertRaises(ValueError):
3150 ac_tester.unsigned_long_long_converter(-1)
3151 with self.assertRaises(OverflowError):
3152 ac_tester.unsigned_long_long_converter(ULLONG_MAX + 1)
3153 with self.assertRaises(OverflowError):
3154 ac_tester.unsigned_long_long_converter(0, ULLONG_MAX + 1)
3155 with self.assertRaises(TypeError):
3156 ac_tester.unsigned_long_long_converter([])
3157 self.assertEqual(ac_tester.unsigned_long_long_converter(), (12, 34, 56))
3158 self.assertEqual(ac_tester.unsigned_long_long_converter(0, 0, ULLONG_MAX + 1), (0, 0, 0))
3159 self.assertEqual(ac_tester.unsigned_long_long_converter(0, 0, (ULLONG_MAX + 1) * 3 + 123), (0, 0, 123))
3160
3161 def test_py_ssize_t_converter(self):
3162 from _testcapi import PY_SSIZE_T_MIN, PY_SSIZE_T_MAX
3163 with self.assertRaises(OverflowError):
3164 ac_tester.py_ssize_t_converter(PY_SSIZE_T_MIN - 1)
3165 with self.assertRaises(OverflowError):
3166 ac_tester.py_ssize_t_converter(PY_SSIZE_T_MAX + 1)
3167 with self.assertRaises(TypeError):
3168 ac_tester.py_ssize_t_converter([])
3169 self.assertEqual(ac_tester.py_ssize_t_converter(), (12, 34, 56))
3170 self.assertEqual(ac_tester.py_ssize_t_converter(1, 2, None), (1, 2, 56))
3171
3172 def test_slice_index_converter(self):
3173 from _testcapi import PY_SSIZE_T_MIN, PY_SSIZE_T_MAX
3174 with self.assertRaises(TypeError):
3175 ac_tester.slice_index_converter([])
3176 self.assertEqual(ac_tester.slice_index_converter(), (12, 34, 56))
3177 self.assertEqual(ac_tester.slice_index_converter(1, 2, None), (1, 2, 56))
3178 self.assertEqual(ac_tester.slice_index_converter(PY_SSIZE_T_MAX, PY_SSIZE_T_MAX + 1, PY_SSIZE_T_MAX + 1234),
3179 (PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX))
3180 self.assertEqual(ac_tester.slice_index_converter(PY_SSIZE_T_MIN, PY_SSIZE_T_MIN - 1, PY_SSIZE_T_MIN - 1234),
3181 (PY_SSIZE_T_MIN, PY_SSIZE_T_MIN, PY_SSIZE_T_MIN))
3182
3183 def test_size_t_converter(self):
3184 with self.assertRaises(ValueError):
3185 ac_tester.size_t_converter(-1)
3186 with self.assertRaises(TypeError):
3187 ac_tester.size_t_converter([])
3188 self.assertEqual(ac_tester.size_t_converter(), (12,))
3189
3190 def test_float_converter(self):
3191 with self.assertRaises(TypeError):
3192 ac_tester.float_converter([])
3193 self.assertEqual(ac_tester.float_converter(), (12.5,))
3194 self.assertEqual(ac_tester.float_converter(-0.5), (-0.5,))
3195
3196 def test_double_converter(self):
3197 with self.assertRaises(TypeError):
3198 ac_tester.double_converter([])
3199 self.assertEqual(ac_tester.double_converter(), (12.5,))
3200 self.assertEqual(ac_tester.double_converter(-0.5), (-0.5,))
3201
3202 def test_py_complex_converter(self):
3203 with self.assertRaises(TypeError):
3204 ac_tester.py_complex_converter([])
3205 self.assertEqual(ac_tester.py_complex_converter(complex(1, 2)), (complex(1, 2),))
3206 self.assertEqual(ac_tester.py_complex_converter(complex('-1-2j')), (complex('-1-2j'),))
3207 self.assertEqual(ac_tester.py_complex_converter(-0.5), (-0.5,))
3208 self.assertEqual(ac_tester.py_complex_converter(10), (10,))
3209
3210 def test_str_converter(self):
3211 with self.assertRaises(TypeError):
3212 ac_tester.str_converter(1)
3213 with self.assertRaises(TypeError):
3214 ac_tester.str_converter('a', 'b', 'c')
3215 with self.assertRaises(ValueError):
3216 ac_tester.str_converter('a', b'b\0b', 'c')
3217 self.assertEqual(ac_tester.str_converter('a', b'b', 'c'), ('a', 'b', 'c'))
3218 self.assertEqual(ac_tester.str_converter('a', b'b', b'c'), ('a', 'b', 'c'))
3219 self.assertEqual(ac_tester.str_converter('a', b'b', 'c\0c'), ('a', 'b', 'c\0c'))
3220
3221 def test_str_converter_encoding(self):
3222 with self.assertRaises(TypeError):
3223 ac_tester.str_converter_encoding(1)
3224 self.assertEqual(ac_tester.str_converter_encoding('a', 'b', 'c'), ('a', 'b', 'c'))
3225 with self.assertRaises(TypeError):
3226 ac_tester.str_converter_encoding('a', b'b\0b', 'c')
3227 self.assertEqual(ac_tester.str_converter_encoding('a', b'b', bytearray([ord('c')])), ('a', 'b', 'c'))
3228 self.assertEqual(ac_tester.str_converter_encoding('a', b'b', bytearray([ord('c'), 0, ord('c')])),
3229 ('a', 'b', 'c\x00c'))
3230 self.assertEqual(ac_tester.str_converter_encoding('a', b'b', b'c\x00c'), ('a', 'b', 'c\x00c'))
3231
3232 def test_py_buffer_converter(self):
3233 with self.assertRaises(TypeError):
3234 ac_tester.py_buffer_converter('a', 'b')
3235 self.assertEqual(ac_tester.py_buffer_converter('abc', bytearray([1, 2, 3])), (b'abc', b'\x01\x02\x03'))
3236
3237 def test_keywords(self):
3238 self.assertEqual(ac_tester.keywords(1, 2), (1, 2))
3239 self.assertEqual(ac_tester.keywords(1, b=2), (1, 2))
3240 self.assertEqual(ac_tester.keywords(a=1, b=2), (1, 2))
3241
3242 def test_keywords_kwonly(self):
3243 with self.assertRaises(TypeError):
3244 ac_tester.keywords_kwonly(1, 2)
3245 self.assertEqual(ac_tester.keywords_kwonly(1, b=2), (1, 2))
3246 self.assertEqual(ac_tester.keywords_kwonly(a=1, b=2), (1, 2))
3247
3248 def test_keywords_opt(self):
3249 self.assertEqual(ac_tester.keywords_opt(1), (1, None, None))
3250 self.assertEqual(ac_tester.keywords_opt(1, 2), (1, 2, None))
3251 self.assertEqual(ac_tester.keywords_opt(1, 2, 3), (1, 2, 3))
3252 self.assertEqual(ac_tester.keywords_opt(1, b=2), (1, 2, None))
3253 self.assertEqual(ac_tester.keywords_opt(1, 2, c=3), (1, 2, 3))
3254 self.assertEqual(ac_tester.keywords_opt(a=1, c=3), (1, None, 3))
3255 self.assertEqual(ac_tester.keywords_opt(a=1, b=2, c=3), (1, 2, 3))
3256
3257 def test_keywords_opt_kwonly(self):
3258 self.assertEqual(ac_tester.keywords_opt_kwonly(1), (1, None, None, None))
3259 self.assertEqual(ac_tester.keywords_opt_kwonly(1, 2), (1, 2, None, None))
3260 with self.assertRaises(TypeError):
3261 ac_tester.keywords_opt_kwonly(1, 2, 3)
3262 self.assertEqual(ac_tester.keywords_opt_kwonly(1, b=2), (1, 2, None, None))
3263 self.assertEqual(ac_tester.keywords_opt_kwonly(1, 2, c=3), (1, 2, 3, None))
3264 self.assertEqual(ac_tester.keywords_opt_kwonly(a=1, c=3), (1, None, 3, None))
3265 self.assertEqual(ac_tester.keywords_opt_kwonly(a=1, b=2, c=3, d=4), (1, 2, 3, 4))
3266
3267 def test_keywords_kwonly_opt(self):
3268 self.assertEqual(ac_tester.keywords_kwonly_opt(1), (1, None, None))
3269 with self.assertRaises(TypeError):
3270 ac_tester.keywords_kwonly_opt(1, 2)
3271 self.assertEqual(ac_tester.keywords_kwonly_opt(1, b=2), (1, 2, None))
3272 self.assertEqual(ac_tester.keywords_kwonly_opt(a=1, c=3), (1, None, 3))
3273 self.assertEqual(ac_tester.keywords_kwonly_opt(a=1, b=2, c=3), (1, 2, 3))
3274
3275 def test_posonly_keywords(self):
3276 with self.assertRaises(TypeError):
3277 ac_tester.posonly_keywords(1)
3278 with self.assertRaises(TypeError):
3279 ac_tester.posonly_keywords(a=1, b=2)
3280 self.assertEqual(ac_tester.posonly_keywords(1, 2), (1, 2))
3281 self.assertEqual(ac_tester.posonly_keywords(1, b=2), (1, 2))
3282
3283 def test_posonly_kwonly(self):
3284 with self.assertRaises(TypeError):
3285 ac_tester.posonly_kwonly(1)
3286 with self.assertRaises(TypeError):
3287 ac_tester.posonly_kwonly(1, 2)
3288 with self.assertRaises(TypeError):
3289 ac_tester.posonly_kwonly(a=1, b=2)
3290 self.assertEqual(ac_tester.posonly_kwonly(1, b=2), (1, 2))
3291
3292 def test_posonly_keywords_kwonly(self):
3293 with self.assertRaises(TypeError):
3294 ac_tester.posonly_keywords_kwonly(1)
3295 with self.assertRaises(TypeError):
3296 ac_tester.posonly_keywords_kwonly(1, 2, 3)
3297 with self.assertRaises(TypeError):
3298 ac_tester.posonly_keywords_kwonly(a=1, b=2, c=3)
3299 self.assertEqual(ac_tester.posonly_keywords_kwonly(1, 2, c=3), (1, 2, 3))
3300 self.assertEqual(ac_tester.posonly_keywords_kwonly(1, b=2, c=3), (1, 2, 3))
3301
3302 def test_posonly_keywords_opt(self):
3303 with self.assertRaises(TypeError):
3304 ac_tester.posonly_keywords_opt(1)
3305 self.assertEqual(ac_tester.posonly_keywords_opt(1, 2), (1, 2, None, None))
3306 self.assertEqual(ac_tester.posonly_keywords_opt(1, 2, 3), (1, 2, 3, None))
3307 self.assertEqual(ac_tester.posonly_keywords_opt(1, 2, 3, 4), (1, 2, 3, 4))
3308 self.assertEqual(ac_tester.posonly_keywords_opt(1, b=2), (1, 2, None, None))
3309 self.assertEqual(ac_tester.posonly_keywords_opt(1, 2, c=3), (1, 2, 3, None))
3310 with self.assertRaises(TypeError):
3311 ac_tester.posonly_keywords_opt(a=1, b=2, c=3, d=4)
3312 self.assertEqual(ac_tester.posonly_keywords_opt(1, b=2, c=3, d=4), (1, 2, 3, 4))
3313
3314 def test_posonly_opt_keywords_opt(self):
3315 self.assertEqual(ac_tester.posonly_opt_keywords_opt(1), (1, None, None, None))
3316 self.assertEqual(ac_tester.posonly_opt_keywords_opt(1, 2), (1, 2, None, None))
3317 self.assertEqual(ac_tester.posonly_opt_keywords_opt(1, 2, 3), (1, 2, 3, None))
3318 self.assertEqual(ac_tester.posonly_opt_keywords_opt(1, 2, 3, 4), (1, 2, 3, 4))
3319 with self.assertRaises(TypeError):
3320 ac_tester.posonly_opt_keywords_opt(1, b=2)
3321 self.assertEqual(ac_tester.posonly_opt_keywords_opt(1, 2, c=3), (1, 2, 3, None))
3322 self.assertEqual(ac_tester.posonly_opt_keywords_opt(1, 2, c=3, d=4), (1, 2, 3, 4))
3323 with self.assertRaises(TypeError):
3324 ac_tester.posonly_opt_keywords_opt(a=1, b=2, c=3, d=4)
3325
3326 def test_posonly_kwonly_opt(self):
3327 with self.assertRaises(TypeError):
3328 ac_tester.posonly_kwonly_opt(1)
3329 with self.assertRaises(TypeError):
3330 ac_tester.posonly_kwonly_opt(1, 2)
3331 self.assertEqual(ac_tester.posonly_kwonly_opt(1, b=2), (1, 2, None, None))
3332 self.assertEqual(ac_tester.posonly_kwonly_opt(1, b=2, c=3), (1, 2, 3, None))
3333 self.assertEqual(ac_tester.posonly_kwonly_opt(1, b=2, c=3, d=4), (1, 2, 3, 4))
3334 with self.assertRaises(TypeError):
3335 ac_tester.posonly_kwonly_opt(a=1, b=2, c=3, d=4)
3336
3337 def test_posonly_opt_kwonly_opt(self):
3338 self.assertEqual(ac_tester.posonly_opt_kwonly_opt(1), (1, None, None, None))
3339 self.assertEqual(ac_tester.posonly_opt_kwonly_opt(1, 2), (1, 2, None, None))
3340 with self.assertRaises(TypeError):
3341 ac_tester.posonly_opt_kwonly_opt(1, 2, 3)
3342 with self.assertRaises(TypeError):
3343 ac_tester.posonly_opt_kwonly_opt(1, b=2)
3344 self.assertEqual(ac_tester.posonly_opt_kwonly_opt(1, 2, c=3), (1, 2, 3, None))
3345 self.assertEqual(ac_tester.posonly_opt_kwonly_opt(1, 2, c=3, d=4), (1, 2, 3, 4))
3346
3347 def test_posonly_keywords_kwonly_opt(self):
3348 with self.assertRaises(TypeError):
3349 ac_tester.posonly_keywords_kwonly_opt(1)
3350 with self.assertRaises(TypeError):
3351 ac_tester.posonly_keywords_kwonly_opt(1, 2)
3352 with self.assertRaises(TypeError):
3353 ac_tester.posonly_keywords_kwonly_opt(1, b=2)
3354 with self.assertRaises(TypeError):
3355 ac_tester.posonly_keywords_kwonly_opt(1, 2, 3)
3356 with self.assertRaises(TypeError):
3357 ac_tester.posonly_keywords_kwonly_opt(a=1, b=2, c=3)
3358 self.assertEqual(ac_tester.posonly_keywords_kwonly_opt(1, 2, c=3), (1, 2, 3, None, None))
3359 self.assertEqual(ac_tester.posonly_keywords_kwonly_opt(1, b=2, c=3), (1, 2, 3, None, None))
3360 self.assertEqual(ac_tester.posonly_keywords_kwonly_opt(1, 2, c=3, d=4), (1, 2, 3, 4, None))
3361 self.assertEqual(ac_tester.posonly_keywords_kwonly_opt(1, 2, c=3, d=4, e=5), (1, 2, 3, 4, 5))
3362
3363 def test_posonly_keywords_opt_kwonly_opt(self):
3364 with self.assertRaises(TypeError):
3365 ac_tester.posonly_keywords_opt_kwonly_opt(1)
3366 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, 2), (1, 2, None, None, None))
3367 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, b=2), (1, 2, None, None, None))
3368 with self.assertRaises(TypeError):
3369 ac_tester.posonly_keywords_opt_kwonly_opt(1, 2, 3, 4)
3370 with self.assertRaises(TypeError):
3371 ac_tester.posonly_keywords_opt_kwonly_opt(a=1, b=2)
3372 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, 2, c=3), (1, 2, 3, None, None))
3373 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, b=2, c=3), (1, 2, 3, None, None))
3374 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, 2, 3, d=4), (1, 2, 3, 4, None))
3375 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, 2, c=3, d=4), (1, 2, 3, 4, None))
3376 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, 2, 3, d=4, e=5), (1, 2, 3, 4, 5))
3377 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, 2, c=3, d=4, e=5), (1, 2, 3, 4, 5))
3378
3379 def test_posonly_opt_keywords_opt_kwonly_opt(self):
3380 self.assertEqual(ac_tester.posonly_opt_keywords_opt_kwonly_opt(1), (1, None, None, None))
3381 self.assertEqual(ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, 2), (1, 2, None, None))
3382 with self.assertRaises(TypeError):
3383 ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, b=2)
3384 self.assertEqual(ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, 2, 3), (1, 2, 3, None))
3385 self.assertEqual(ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, 2, c=3), (1, 2, 3, None))
3386 self.assertEqual(ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, 2, 3, d=4), (1, 2, 3, 4))
3387 self.assertEqual(ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, 2, c=3, d=4), (1, 2, 3, 4))
3388 with self.assertRaises(TypeError):
3389 ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, 2, 3, 4)
3390
3391 def test_keyword_only_parameter(self):
3392 with self.assertRaises(TypeError):
3393 ac_tester.keyword_only_parameter()
3394 with self.assertRaises(TypeError):
3395 ac_tester.keyword_only_parameter(1)
3396 self.assertEqual(ac_tester.keyword_only_parameter(a=1), (1,))
3397
3398 def test_posonly_vararg(self):
3399 with self.assertRaises(TypeError):
3400 ac_tester.posonly_vararg()
3401 self.assertEqual(ac_tester.posonly_vararg(1, 2), (1, 2, ()))
3402 self.assertEqual(ac_tester.posonly_vararg(1, b=2), (1, 2, ()))
3403 self.assertEqual(ac_tester.posonly_vararg(1, 2, 3, 4), (1, 2, (3, 4)))
3404 with self.assertRaises(TypeError):
3405 ac_tester.posonly_vararg(b=4)
3406 with self.assertRaises(TypeError):
3407 ac_tester.posonly_vararg(1, 2, 3, b=4)
3408
3409 def test_vararg(self):
3410 with self.assertRaises(TypeError):
3411 ac_tester.vararg()
3412 with self.assertRaises(TypeError):
3413 ac_tester.vararg(1, b=2)
3414 self.assertEqual(ac_tester.vararg(1, 2, 3, 4), (1, (2, 3, 4)))
3415
3416 def test_vararg_with_default(self):
3417 fn = ac_tester.vararg_with_default
3418 self.assertRaises(TypeError, fn)
3419 self.assertRaises(TypeError, fn, 1, a=2)
3420 self.assertEqual(fn(1, b=2), (1, (), True))
3421 self.assertEqual(fn(1, 2, 3, 4), (1, (2, 3, 4), False))
3422 self.assertEqual(fn(1, 2, 3, 4, b=5), (1, (2, 3, 4), True))
3423 self.assertEqual(fn(a=1), (1, (), False))
3424 self.assertEqual(fn(a=1, b=2), (1, (), True))
3425
3426 def test_vararg_with_default2(self):
3427 fn = ac_tester.vararg_with_default2
3428 self.assertRaises(TypeError, fn)
3429 self.assertRaises(TypeError, fn, 1, a=2)
3430 self.assertEqual(fn(1, b=2), (1, (), 2, None))
3431 self.assertEqual(fn(1, b=2, c=3), (1, (), 2, 3))
3432 self.assertEqual(fn(1, 2, 3), (1, (2, 3), None, None))
3433 self.assertEqual(fn(1, 2, 3, b=4), (1, (2, 3), 4, None))
3434 self.assertEqual(fn(1, 2, 3, b=4, c=5), (1, (2, 3), 4, 5))
3435 self.assertEqual(fn(a=1), (1, (), None, None))
3436 self.assertEqual(fn(a=1, b=2), (1, (), 2, None))
3437 self.assertEqual(fn(a=1, b=2, c=3), (1, (), 2, 3))
3438
3439 def test_vararg_with_only_defaults(self):
3440 self.assertEqual(ac_tester.vararg_with_only_defaults(), ((), None))
3441 self.assertEqual(ac_tester.vararg_with_only_defaults(b=2), ((), 2))
3442 self.assertEqual(ac_tester.vararg_with_only_defaults(1, b=2), ((1, ), 2))
3443 self.assertEqual(ac_tester.vararg_with_only_defaults(1, 2, 3, 4), ((1, 2, 3, 4), None))
3444 self.assertEqual(ac_tester.vararg_with_only_defaults(1, 2, 3, 4, b=5), ((1, 2, 3, 4), 5))
3445
3446 def test_vararg_kwonly_req_opt(self):
3447 fn = ac_tester.vararg_kwonly_req_opt
3448 self.assertRaises(TypeError, fn)
3449 self.assertEqual(fn(a=1), ((), 1, None, None))
3450 self.assertEqual(fn(a=1, b=2), ((), 1, 2, None))
3451 self.assertEqual(fn(a=1, b=2, c=3), ((), 1, 2, 3))
3452 self.assertRaises(TypeError, fn, 1)
3453 self.assertEqual(fn(1, a=2), ((1,), 2, None, None))
3454 self.assertEqual(fn(1, a=2, b=3), ((1,), 2, 3, None))
3455 self.assertEqual(fn(1, a=2, b=3, c=4), ((1,), 2, 3, 4))
3456
3457 def test_gh_32092_oob(self):
3458 ac_tester.gh_32092_oob(1, 2, 3, 4, kw1=5, kw2=6)
3459
3460 def test_gh_32092_kw_pass(self):
3461 ac_tester.gh_32092_kw_pass(1, 2, 3)
3462
3463 def test_gh_99233_refcount(self):
3464 arg = '*A unique string is not referenced by anywhere else.*'
3465 arg_refcount_origin = sys.getrefcount(arg)
3466 ac_tester.gh_99233_refcount(arg)
3467 arg_refcount_after = sys.getrefcount(arg)
3468 self.assertEqual(arg_refcount_origin, arg_refcount_after)
3469
3470 def test_gh_99240_double_free(self):
3471 err = re.escape(
3472 "gh_99240_double_free() argument 2 must be encoded string "
3473 "without null bytes, not str"
3474 )
3475 with self.assertRaisesRegex(TypeError, err):
3476 ac_tester.gh_99240_double_free('a', '\0b')
3477
3478 def test_null_or_tuple_for_varargs(self):
3479 # All of these should not crash:
3480 valid_args_for_test = [
3481 (('a',), {},
3482 ('a', (), False)),
3483 (('a', 1, 2, 3), {'covariant': True},
3484 ('a', (1, 2, 3), True)),
3485 ((), {'name': 'a'},
3486 ('a', (), False)),
3487 ((), {'name': 'a', 'covariant': True},
3488 ('a', (), True)),
3489 ((), {'covariant': True, 'name': 'a'},
3490 ('a', (), True)),
3491 ]
3492 for args, kwargs, expected in valid_args_for_test:
3493 with self.subTest(args=args, kwargs=kwargs):
3494 self.assertEqual(
3495 ac_tester.null_or_tuple_for_varargs(*args, **kwargs),
3496 expected,
3497 )
3498
3499 def test_null_or_tuple_for_varargs_error(self):
3500 with self.assertRaises(TypeError):
3501 ac_tester.null_or_tuple_for_varargs(covariant=True)
3502 with self.assertRaises(TypeError):
3503 ac_tester.null_or_tuple_for_varargs(1, name='a')
3504 with self.assertRaises(TypeError):
3505 ac_tester.null_or_tuple_for_varargs(1, 2, 3, name='a', covariant=True)
3506 with self.assertRaises(TypeError):
3507 ac_tester.null_or_tuple_for_varargs(1, 2, 3, covariant=True, name='a')
3508
3509 def test_cloned_func_exception_message(self):
3510 incorrect_arg = -1 # f1() and f2() accept a single str
3511 with self.assertRaisesRegex(TypeError, "clone_f1"):
3512 ac_tester.clone_f1(incorrect_arg)
3513 with self.assertRaisesRegex(TypeError, "clone_f2"):
3514 ac_tester.clone_f2(incorrect_arg)
3515
3516 def test_cloned_func_with_converter_exception_message(self):
3517 for name in "clone_with_conv_f1", "clone_with_conv_f2":
3518 with self.subTest(name=name):
3519 func = getattr(ac_tester, name)
3520 self.assertEqual(func(), name)
3521
3522 def test_get_defining_class(self):
3523 obj = ac_tester.TestClass()
3524 meth = obj.get_defining_class
3525 self.assertIs(obj.get_defining_class(), ac_tester.TestClass)
3526
3527 # 'defining_class' argument is a positional only argument
3528 with self.assertRaises(TypeError):
3529 obj.get_defining_class_arg(cls=ac_tester.TestClass)
3530
3531 check = partial(self.assertRaisesRegex, TypeError, "no arguments")
3532 check(meth, 1)
3533 check(meth, a=1)
3534
3535 def test_get_defining_class_capi(self):
3536 from _testcapi import pyobject_vectorcall
3537 obj = ac_tester.TestClass()
3538 meth = obj.get_defining_class
3539 pyobject_vectorcall(meth, None, None)
3540 pyobject_vectorcall(meth, (), None)
3541 pyobject_vectorcall(meth, (), ())
3542 pyobject_vectorcall(meth, None, ())
3543 self.assertIs(pyobject_vectorcall(meth, (), ()), ac_tester.TestClass)
3544
3545 check = partial(self.assertRaisesRegex, TypeError, "no arguments")
3546 check(pyobject_vectorcall, meth, (1,), None)
3547 check(pyobject_vectorcall, meth, (1,), ("a",))
3548
3549 def test_get_defining_class_arg(self):
3550 obj = ac_tester.TestClass()
3551 self.assertEqual(obj.get_defining_class_arg("arg"),
3552 (ac_tester.TestClass, "arg"))
3553 self.assertEqual(obj.get_defining_class_arg(arg=123),
3554 (ac_tester.TestClass, 123))
3555
3556 # 'defining_class' argument is a positional only argument
3557 with self.assertRaises(TypeError):
3558 obj.get_defining_class_arg(cls=ac_tester.TestClass, arg="arg")
3559
3560 # wrong number of arguments
3561 with self.assertRaises(TypeError):
3562 obj.get_defining_class_arg()
3563 with self.assertRaises(TypeError):
3564 obj.get_defining_class_arg("arg1", "arg2")
3565
3566 def test_depr_star_new(self):
3567 cls = ac_tester.DeprStarNew
3568 cls()
3569 cls(a=None)
3570 self.check_depr_star("'a'", cls, None)
3571
3572 def test_depr_star_new_cloned(self):
3573 fn = ac_tester.DeprStarNew().cloned
3574 fn()
3575 fn(a=None)
3576 self.check_depr_star("'a'", fn, None, name='_testclinic.DeprStarNew.cloned')
3577
3578 def test_depr_star_init(self):
3579 cls = ac_tester.DeprStarInit
3580 cls()
3581 cls(a=None)
3582 self.check_depr_star("'a'", cls, None)
3583
3584 def test_depr_star_init_cloned(self):
3585 fn = ac_tester.DeprStarInit().cloned
3586 fn()
3587 fn(a=None)
3588 self.check_depr_star("'a'", fn, None, name='_testclinic.DeprStarInit.cloned')
3589
3590 def test_depr_star_init_noinline(self):
3591 cls = ac_tester.DeprStarInitNoInline
3592 self.assertRaises(TypeError, cls, "a")
3593 cls(a="a", b="b")
3594 cls(a="a", b="b", c="c")
3595 cls("a", b="b")
3596 cls("a", b="b", c="c")
3597 check = partial(self.check_depr_star, "'b' and 'c'", cls)
3598 check("a", "b")
3599 check("a", "b", "c")
3600 check("a", "b", c="c")
3601 self.assertRaises(TypeError, cls, "a", "b", "c", "d")
3602
3603 def test_depr_kwd_new(self):
3604 cls = ac_tester.DeprKwdNew
3605 cls()
3606 cls(None)
3607 self.check_depr_kwd("'a'", cls, a=None)
3608
3609 def test_depr_kwd_init(self):
3610 cls = ac_tester.DeprKwdInit
3611 cls()
3612 cls(None)
3613 self.check_depr_kwd("'a'", cls, a=None)
3614
3615 def test_depr_kwd_init_noinline(self):
3616 cls = ac_tester.DeprKwdInitNoInline
3617 cls = ac_tester.depr_star_noinline
3618 self.assertRaises(TypeError, cls, "a")
3619 cls(a="a", b="b")
3620 cls(a="a", b="b", c="c")
3621 cls("a", b="b")
3622 cls("a", b="b", c="c")
3623 check = partial(self.check_depr_star, "'b' and 'c'", cls)
3624 check("a", "b")
3625 check("a", "b", "c")
3626 check("a", "b", c="c")
3627 self.assertRaises(TypeError, cls, "a", "b", "c", "d")
3628
3629 def test_depr_star_pos0_len1(self):
3630 fn = ac_tester.depr_star_pos0_len1
3631 fn(a=None)
3632 self.check_depr_star("'a'", fn, "a")
3633
3634 def test_depr_star_pos0_len2(self):
3635 fn = ac_tester.depr_star_pos0_len2
3636 fn(a=0, b=0)
3637 check = partial(self.check_depr_star, "'a' and 'b'", fn)
3638 check("a", b=0)
3639 check("a", "b")
3640
3641 def test_depr_star_pos0_len3_with_kwd(self):
3642 fn = ac_tester.depr_star_pos0_len3_with_kwd
3643 fn(a=0, b=0, c=0, d=0)
3644 check = partial(self.check_depr_star, "'a', 'b' and 'c'", fn)
3645 check("a", b=0, c=0, d=0)
3646 check("a", "b", c=0, d=0)
3647 check("a", "b", "c", d=0)
3648
3649 def test_depr_star_pos1_len1_opt(self):
3650 fn = ac_tester.depr_star_pos1_len1_opt
3651 fn(a=0, b=0)
3652 fn("a", b=0)
3653 fn(a=0) # b is optional
3654 check = partial(self.check_depr_star, "'b'", fn)
3655 check("a", "b")
3656
3657 def test_depr_star_pos1_len1(self):
3658 fn = ac_tester.depr_star_pos1_len1
3659 fn(a=0, b=0)
3660 fn("a", b=0)
3661 check = partial(self.check_depr_star, "'b'", fn)
3662 check("a", "b")
3663
3664 def test_depr_star_pos1_len2_with_kwd(self):
3665 fn = ac_tester.depr_star_pos1_len2_with_kwd
3666 fn(a=0, b=0, c=0, d=0),
3667 fn("a", b=0, c=0, d=0),
3668 check = partial(self.check_depr_star, "'b' and 'c'", fn)
3669 check("a", "b", c=0, d=0),
3670 check("a", "b", "c", d=0),
3671
3672 def test_depr_star_pos2_len1(self):
3673 fn = ac_tester.depr_star_pos2_len1
3674 fn(a=0, b=0, c=0)
3675 fn("a", b=0, c=0)
3676 fn("a", "b", c=0)
3677 check = partial(self.check_depr_star, "'c'", fn)
3678 check("a", "b", "c")
3679
3680 def test_depr_star_pos2_len2(self):
3681 fn = ac_tester.depr_star_pos2_len2
3682 fn(a=0, b=0, c=0, d=0)
3683 fn("a", b=0, c=0, d=0)
3684 fn("a", "b", c=0, d=0)
3685 check = partial(self.check_depr_star, "'c' and 'd'", fn)
3686 check("a", "b", "c", d=0)
3687 check("a", "b", "c", "d")
3688
3689 def test_depr_star_pos2_len2_with_kwd(self):
3690 fn = ac_tester.depr_star_pos2_len2_with_kwd
3691 fn(a=0, b=0, c=0, d=0, e=0)
3692 fn("a", b=0, c=0, d=0, e=0)
3693 fn("a", "b", c=0, d=0, e=0)
3694 check = partial(self.check_depr_star, "'c' and 'd'", fn)
3695 check("a", "b", "c", d=0, e=0)
3696 check("a", "b", "c", "d", e=0)
3697
3698 def test_depr_star_noinline(self):
3699 fn = ac_tester.depr_star_noinline
3700 self.assertRaises(TypeError, fn, "a")
3701 fn(a="a", b="b")
3702 fn(a="a", b="b", c="c")
3703 fn("a", b="b")
3704 fn("a", b="b", c="c")
3705 check = partial(self.check_depr_star, "'b' and 'c'", fn)
3706 check("a", "b")
3707 check("a", "b", "c")
3708 check("a", "b", c="c")
3709 self.assertRaises(TypeError, fn, "a", "b", "c", "d")
3710
3711 def test_depr_star_multi(self):
3712 fn = ac_tester.depr_star_multi
3713 self.assertRaises(TypeError, fn, "a")
3714 fn("a", b="b", c="c", d="d", e="e", f="f", g="g", h="h")
3715 errmsg = (
3716 "Passing more than 1 positional argument to depr_star_multi() is deprecated. "
3717 "Parameter 'b' will become a keyword-only parameter in Python 3.16. "
3718 "Parameters 'c' and 'd' will become keyword-only parameters in Python 3.15. "
3719 "Parameters 'e', 'f' and 'g' will become keyword-only parameters in Python 3.14.")
3720 check = partial(self.check_depr, re.escape(errmsg), fn)
3721 check("a", "b", c="c", d="d", e="e", f="f", g="g", h="h")
3722 check("a", "b", "c", d="d", e="e", f="f", g="g", h="h")
3723 check("a", "b", "c", "d", e="e", f="f", g="g", h="h")
3724 check("a", "b", "c", "d", "e", f="f", g="g", h="h")
3725 check("a", "b", "c", "d", "e", "f", g="g", h="h")
3726 check("a", "b", "c", "d", "e", "f", "g", h="h")
3727 self.assertRaises(TypeError, fn, "a", "b", "c", "d", "e", "f", "g", "h")
3728
3729 def test_depr_kwd_required_1(self):
3730 fn = ac_tester.depr_kwd_required_1
3731 fn("a", "b")
3732 self.assertRaises(TypeError, fn, "a")
3733 self.assertRaises(TypeError, fn, "a", "b", "c")
3734 check = partial(self.check_depr_kwd, "'b'", fn)
3735 check("a", b="b")
3736 self.assertRaises(TypeError, fn, a="a", b="b")
3737
3738 def test_depr_kwd_required_2(self):
3739 fn = ac_tester.depr_kwd_required_2
3740 fn("a", "b", "c")
3741 self.assertRaises(TypeError, fn, "a", "b")
3742 self.assertRaises(TypeError, fn, "a", "b", "c", "d")
3743 check = partial(self.check_depr_kwd, "'b' and 'c'", fn)
3744 check("a", "b", c="c")
3745 check("a", b="b", c="c")
3746 self.assertRaises(TypeError, fn, a="a", b="b", c="c")
3747
3748 def test_depr_kwd_optional_1(self):
3749 fn = ac_tester.depr_kwd_optional_1
3750 fn("a")
3751 fn("a", "b")
3752 self.assertRaises(TypeError, fn)
3753 self.assertRaises(TypeError, fn, "a", "b", "c")
3754 check = partial(self.check_depr_kwd, "'b'", fn)
3755 check("a", b="b")
3756 self.assertRaises(TypeError, fn, a="a", b="b")
3757
3758 def test_depr_kwd_optional_2(self):
3759 fn = ac_tester.depr_kwd_optional_2
3760 fn("a")
3761 fn("a", "b")
3762 fn("a", "b", "c")
3763 self.assertRaises(TypeError, fn)
3764 self.assertRaises(TypeError, fn, "a", "b", "c", "d")
3765 check = partial(self.check_depr_kwd, "'b' and 'c'", fn)
3766 check("a", b="b")
3767 check("a", c="c")
3768 check("a", b="b", c="c")
3769 check("a", c="c", b="b")
3770 check("a", "b", c="c")
3771 self.assertRaises(TypeError, fn, a="a", b="b", c="c")
3772
3773 def test_depr_kwd_optional_3(self):
3774 fn = ac_tester.depr_kwd_optional_3
3775 fn()
3776 fn("a")
3777 fn("a", "b")
3778 fn("a", "b", "c")
3779 self.assertRaises(TypeError, fn, "a", "b", "c", "d")
3780 check = partial(self.check_depr_kwd, "'a', 'b' and 'c'", fn)
3781 check("a", "b", c="c")
3782 check("a", b="b")
3783 check(a="a")
3784
3785 def test_depr_kwd_required_optional(self):
3786 fn = ac_tester.depr_kwd_required_optional
3787 fn("a", "b")
3788 fn("a", "b", "c")
3789 self.assertRaises(TypeError, fn)
3790 self.assertRaises(TypeError, fn, "a")
3791 self.assertRaises(TypeError, fn, "a", "b", "c", "d")
3792 check = partial(self.check_depr_kwd, "'b' and 'c'", fn)
3793 check("a", b="b")
3794 check("a", b="b", c="c")
3795 check("a", c="c", b="b")
3796 check("a", "b", c="c")
3797 self.assertRaises(TypeError, fn, "a", c="c")
3798 self.assertRaises(TypeError, fn, a="a", b="b", c="c")
3799
3800 def test_depr_kwd_noinline(self):
3801 fn = ac_tester.depr_kwd_noinline
3802 fn("a", "b")
3803 fn("a", "b", "c")
3804 self.assertRaises(TypeError, fn, "a")
3805 check = partial(self.check_depr_kwd, "'b' and 'c'", fn)
3806 check("a", b="b")
3807 check("a", b="b", c="c")
3808 check("a", c="c", b="b")
3809 check("a", "b", c="c")
3810 self.assertRaises(TypeError, fn, "a", c="c")
3811 self.assertRaises(TypeError, fn, a="a", b="b", c="c")
3812
3813 def test_depr_kwd_multi(self):
3814 fn = ac_tester.depr_kwd_multi
3815 fn("a", "b", "c", "d", "e", "f", "g", h="h")
3816 errmsg = (
3817 "Passing keyword arguments 'b', 'c', 'd', 'e', 'f' and 'g' to depr_kwd_multi() is deprecated. "
3818 "Parameter 'b' will become positional-only in Python 3.14. "
3819 "Parameters 'c' and 'd' will become positional-only in Python 3.15. "
3820 "Parameters 'e', 'f' and 'g' will become positional-only in Python 3.16.")
3821 check = partial(self.check_depr, re.escape(errmsg), fn)
3822 check("a", "b", "c", "d", "e", "f", g="g", h="h")
3823 check("a", "b", "c", "d", "e", f="f", g="g", h="h")
3824 check("a", "b", "c", "d", e="e", f="f", g="g", h="h")
3825 check("a", "b", "c", d="d", e="e", f="f", g="g", h="h")
3826 check("a", "b", c="c", d="d", e="e", f="f", g="g", h="h")
3827 check("a", b="b", c="c", d="d", e="e", f="f", g="g", h="h")
3828 self.assertRaises(TypeError, fn, a="a", b="b", c="c", d="d", e="e", f="f", g="g", h="h")
3829
3830 def test_depr_multi(self):
3831 fn = ac_tester.depr_multi
3832 self.assertRaises(TypeError, fn, "a", "b", "c", "d", "e", "f", "g")
3833 errmsg = (
3834 "Passing more than 4 positional arguments to depr_multi() is deprecated. "
3835 "Parameter 'e' will become a keyword-only parameter in Python 3.15. "
3836 "Parameter 'f' will become a keyword-only parameter in Python 3.14.")
3837 check = partial(self.check_depr, re.escape(errmsg), fn)
3838 check("a", "b", "c", "d", "e", "f", g="g")
3839 check("a", "b", "c", "d", "e", f="f", g="g")
3840 fn("a", "b", "c", "d", e="e", f="f", g="g")
3841 fn("a", "b", "c", d="d", e="e", f="f", g="g")
3842 errmsg = (
3843 "Passing keyword arguments 'b' and 'c' to depr_multi() is deprecated. "
3844 "Parameter 'b' will become positional-only in Python 3.14. "
3845 "Parameter 'c' will become positional-only in Python 3.15.")
3846 check = partial(self.check_depr, re.escape(errmsg), fn)
3847 check("a", "b", c="c", d="d", e="e", f="f", g="g")
3848 check("a", b="b", c="c", d="d", e="e", f="f", g="g")
3849 self.assertRaises(TypeError, fn, a="a", b="b", c="c", d="d", e="e", f="f", g="g")
3850
3851
3852 class LimitedCAPIOutputTests(unittest.TestCase):
3853
3854 def setUp(self):
3855 self.clinic = _make_clinic(limited_capi=True)
3856
3857 @staticmethod
3858 def wrap_clinic_input(block):
3859 return dedent(f"""
3860 /*[clinic input]
3861 output everything buffer
3862 {block}
3863 [clinic start generated code]*/
3864 /*[clinic input]
3865 dump buffer
3866 [clinic start generated code]*/
3867 """)
3868
3869 def test_limited_capi_float(self):
3870 block = self.wrap_clinic_input("""
3871 func
3872 f: float
3873 /
3874 """)
3875 generated = self.clinic.parse(block)
3876 self.assertNotIn("PyFloat_AS_DOUBLE", generated)
3877 self.assertIn("float f;", generated)
3878 self.assertIn("f = (float) PyFloat_AsDouble", generated)
3879
3880 def test_limited_capi_double(self):
3881 block = self.wrap_clinic_input("""
3882 func
3883 f: double
3884 /
3885 """)
3886 generated = self.clinic.parse(block)
3887 self.assertNotIn("PyFloat_AS_DOUBLE", generated)
3888 self.assertIn("double f;", generated)
3889 self.assertIn("f = PyFloat_AsDouble", generated)
3890
3891
3892 try:
3893 import _testclinic_limited
3894 except ImportError:
3895 _testclinic_limited = None
3896
3897 @unittest.skipIf(_testclinic_limited is None, "_testclinic_limited is missing")
3898 class LimitedCAPIFunctionalTest(unittest.TestCase):
3899 locals().update((name, getattr(_testclinic_limited, name))
3900 for name in dir(_testclinic_limited) if name.startswith('test_'))
3901
3902 def test_my_int_func(self):
3903 with self.assertRaises(TypeError):
3904 _testclinic_limited.my_int_func()
3905 self.assertEqual(_testclinic_limited.my_int_func(3), 3)
3906 with self.assertRaises(TypeError):
3907 _testclinic_limited.my_int_func(1.0)
3908 with self.assertRaises(TypeError):
3909 _testclinic_limited.my_int_func("xyz")
3910
3911 def test_my_int_sum(self):
3912 with self.assertRaises(TypeError):
3913 _testclinic_limited.my_int_sum()
3914 with self.assertRaises(TypeError):
3915 _testclinic_limited.my_int_sum(1)
3916 self.assertEqual(_testclinic_limited.my_int_sum(1, 2), 3)
3917 with self.assertRaises(TypeError):
3918 _testclinic_limited.my_int_sum(1.0, 2)
3919 with self.assertRaises(TypeError):
3920 _testclinic_limited.my_int_sum(1, "str")
3921
3922 def test_my_double_sum(self):
3923 for func in (
3924 _testclinic_limited.my_float_sum,
3925 _testclinic_limited.my_double_sum,
3926 ):
3927 with self.subTest(func=func.__name__):
3928 self.assertEqual(func(1.0, 2.5), 3.5)
3929 with self.assertRaises(TypeError):
3930 func()
3931 with self.assertRaises(TypeError):
3932 func(1)
3933 with self.assertRaises(TypeError):
3934 func(1., "2")
3935
3936 def test_get_file_descriptor(self):
3937 # test 'file descriptor' converter: call PyObject_AsFileDescriptor()
3938 get_fd = _testclinic_limited.get_file_descriptor
3939
3940 class MyInt(int):
3941 pass
3942
3943 class MyFile:
3944 def __init__(self, fd):
3945 self._fd = fd
3946 def fileno(self):
3947 return self._fd
3948
3949 for fd in (0, 1, 2, 5, 123_456):
3950 self.assertEqual(get_fd(fd), fd)
3951
3952 myint = MyInt(fd)
3953 self.assertEqual(get_fd(myint), fd)
3954
3955 myfile = MyFile(fd)
3956 self.assertEqual(get_fd(myfile), fd)
3957
3958 with self.assertRaises(OverflowError):
3959 get_fd(2**256)
3960 with self.assertWarnsRegex(RuntimeWarning,
3961 "bool is used as a file descriptor"):
3962 get_fd(True)
3963 with self.assertRaises(TypeError):
3964 get_fd(1.0)
3965 with self.assertRaises(TypeError):
3966 get_fd("abc")
3967 with self.assertRaises(TypeError):
3968 get_fd(None)
3969
3970
3971 class PermutationTests(unittest.TestCase):
3972 """Test permutation support functions."""
3973
3974 def test_permute_left_option_groups(self):
3975 expected = (
3976 (),
3977 (3,),
3978 (2, 3),
3979 (1, 2, 3),
3980 )
3981 data = list(zip([1, 2, 3])) # Generate a list of 1-tuples.
3982 actual = tuple(permute_left_option_groups(data))
3983 self.assertEqual(actual, expected)
3984
3985 def test_permute_right_option_groups(self):
3986 expected = (
3987 (),
3988 (1,),
3989 (1, 2),
3990 (1, 2, 3),
3991 )
3992 data = list(zip([1, 2, 3])) # Generate a list of 1-tuples.
3993 actual = tuple(permute_right_option_groups(data))
3994 self.assertEqual(actual, expected)
3995
3996 def test_permute_optional_groups(self):
3997 empty = {
3998 "left": (), "required": (), "right": (),
3999 "expected": ((),),
4000 }
4001 noleft1 = {
4002 "left": (), "required": ("b",), "right": ("c",),
4003 "expected": (
4004 ("b",),
4005 ("b", "c"),
4006 ),
4007 }
4008 noleft2 = {
4009 "left": (), "required": ("b", "c",), "right": ("d",),
4010 "expected": (
4011 ("b", "c"),
4012 ("b", "c", "d"),
4013 ),
4014 }
4015 noleft3 = {
4016 "left": (), "required": ("b", "c",), "right": ("d", "e"),
4017 "expected": (
4018 ("b", "c"),
4019 ("b", "c", "d"),
4020 ("b", "c", "d", "e"),
4021 ),
4022 }
4023 noright1 = {
4024 "left": ("a",), "required": ("b",), "right": (),
4025 "expected": (
4026 ("b",),
4027 ("a", "b"),
4028 ),
4029 }
4030 noright2 = {
4031 "left": ("a",), "required": ("b", "c"), "right": (),
4032 "expected": (
4033 ("b", "c"),
4034 ("a", "b", "c"),
4035 ),
4036 }
4037 noright3 = {
4038 "left": ("a", "b"), "required": ("c",), "right": (),
4039 "expected": (
4040 ("c",),
4041 ("b", "c"),
4042 ("a", "b", "c"),
4043 ),
4044 }
4045 leftandright1 = {
4046 "left": ("a",), "required": ("b",), "right": ("c",),
4047 "expected": (
4048 ("b",),
4049 ("a", "b"), # Prefer left.
4050 ("a", "b", "c"),
4051 ),
4052 }
4053 leftandright2 = {
4054 "left": ("a", "b"), "required": ("c", "d"), "right": ("e", "f"),
4055 "expected": (
4056 ("c", "d"),
4057 ("b", "c", "d"), # Prefer left.
4058 ("a", "b", "c", "d"), # Prefer left.
4059 ("a", "b", "c", "d", "e"),
4060 ("a", "b", "c", "d", "e", "f"),
4061 ),
4062 }
4063 dataset = (
4064 empty,
4065 noleft1, noleft2, noleft3,
4066 noright1, noright2, noright3,
4067 leftandright1, leftandright2,
4068 )
4069 for params in dataset:
4070 with self.subTest(**params):
4071 left, required, right, expected = params.values()
4072 permutations = permute_optional_groups(left, required, right)
4073 actual = tuple(permutations)
4074 self.assertEqual(actual, expected)
4075
4076
4077 class FormatHelperTests(unittest.TestCase):
4078
4079 def test_strip_leading_and_trailing_blank_lines(self):
4080 dataset = (
4081 # Input lines, expected output.
4082 ("a\nb", "a\nb"),
4083 ("a\nb\n", "a\nb"),
4084 ("a\nb ", "a\nb"),
4085 ("\na\nb\n\n", "a\nb"),
4086 ("\n\na\nb\n\n", "a\nb"),
4087 ("\n\na\n\nb\n\n", "a\n\nb"),
4088 # Note, leading whitespace is preserved:
4089 (" a\nb", " a\nb"),
4090 (" a\nb ", " a\nb"),
4091 (" \n \n a\nb \n \n ", " a\nb"),
4092 )
4093 for lines, expected in dataset:
4094 with self.subTest(lines=lines, expected=expected):
4095 out = libclinic.normalize_snippet(lines)
4096 self.assertEqual(out, expected)
4097
4098 def test_normalize_snippet(self):
4099 snippet = """
4100 one
4101 two
4102 three
4103 """
4104
4105 # Expected outputs:
4106 zero_indent = (
4107 "one\n"
4108 "two\n"
4109 "three"
4110 )
4111 four_indent = (
4112 " one\n"
4113 " two\n"
4114 " three"
4115 )
4116 eight_indent = (
4117 " one\n"
4118 " two\n"
4119 " three"
4120 )
4121 expected_outputs = {0: zero_indent, 4: four_indent, 8: eight_indent}
4122 for indent, expected in expected_outputs.items():
4123 with self.subTest(indent=indent):
4124 actual = libclinic.normalize_snippet(snippet, indent=indent)
4125 self.assertEqual(actual, expected)
4126
4127 def test_escaped_docstring(self):
4128 dataset = (
4129 # input, expected
4130 (r"abc", r'"abc"'),
4131 (r"\abc", r'"\\abc"'),
4132 (r"\a\bc", r'"\\a\\bc"'),
4133 (r"\a\\bc", r'"\\a\\\\bc"'),
4134 (r'"abc"', r'"\"abc\""'),
4135 (r"'a'", r'"\'a\'"'),
4136 )
4137 for line, expected in dataset:
4138 with self.subTest(line=line, expected=expected):
4139 out = libclinic.docstring_for_c_string(line)
4140 self.assertEqual(out, expected)
4141
4142 def test_format_escape(self):
4143 line = "{}, {a}"
4144 expected = "{{}}, {{a}}"
4145 out = libclinic.format_escape(line)
4146 self.assertEqual(out, expected)
4147
4148 def test_indent_all_lines(self):
4149 # Blank lines are expected to be unchanged.
4150 self.assertEqual(libclinic.indent_all_lines("", prefix="bar"), "")
4151
4152 lines = (
4153 "one\n"
4154 "two" # The missing newline is deliberate.
4155 )
4156 expected = (
4157 "barone\n"
4158 "bartwo"
4159 )
4160 out = libclinic.indent_all_lines(lines, prefix="bar")
4161 self.assertEqual(out, expected)
4162
4163 # If last line is empty, expect it to be unchanged.
4164 lines = (
4165 "\n"
4166 "one\n"
4167 "two\n"
4168 ""
4169 )
4170 expected = (
4171 "bar\n"
4172 "barone\n"
4173 "bartwo\n"
4174 ""
4175 )
4176 out = libclinic.indent_all_lines(lines, prefix="bar")
4177 self.assertEqual(out, expected)
4178
4179 def test_suffix_all_lines(self):
4180 # Blank lines are expected to be unchanged.
4181 self.assertEqual(libclinic.suffix_all_lines("", suffix="foo"), "")
4182
4183 lines = (
4184 "one\n"
4185 "two" # The missing newline is deliberate.
4186 )
4187 expected = (
4188 "onefoo\n"
4189 "twofoo"
4190 )
4191 out = libclinic.suffix_all_lines(lines, suffix="foo")
4192 self.assertEqual(out, expected)
4193
4194 # If last line is empty, expect it to be unchanged.
4195 lines = (
4196 "\n"
4197 "one\n"
4198 "two\n"
4199 ""
4200 )
4201 expected = (
4202 "foo\n"
4203 "onefoo\n"
4204 "twofoo\n"
4205 ""
4206 )
4207 out = libclinic.suffix_all_lines(lines, suffix="foo")
4208 self.assertEqual(out, expected)
4209
4210
4211 class ClinicReprTests(unittest.TestCase):
4212 def test_Block_repr(self):
4213 block = Block("foo")
4214 expected_repr = "<clinic.Block 'text' input='foo' output=None>"
4215 self.assertEqual(repr(block), expected_repr)
4216
4217 block2 = Block("bar", "baz", [], "eggs", "spam")
4218 expected_repr_2 = "<clinic.Block 'baz' input='bar' output='eggs'>"
4219 self.assertEqual(repr(block2), expected_repr_2)
4220
4221 block3 = Block(
4222 input="longboi_" * 100,
4223 dsl_name="wow_so_long",
4224 signatures=[],
4225 output="very_long_" * 100,
4226 indent=""
4227 )
4228 expected_repr_3 = (
4229 "<clinic.Block 'wow_so_long' input='longboi_longboi_longboi_l...' output='very_long_very_long_very_...'>"
4230 )
4231 self.assertEqual(repr(block3), expected_repr_3)
4232
4233 def test_Destination_repr(self):
4234 c = _make_clinic()
4235
4236 destination = Destination(
4237 "foo", type="file", clinic=c, args=("eggs",)
4238 )
4239 self.assertEqual(
4240 repr(destination), "<clinic.Destination 'foo' type='file' file='eggs'>"
4241 )
4242
4243 destination2 = Destination("bar", type="buffer", clinic=c)
4244 self.assertEqual(repr(destination2), "<clinic.Destination 'bar' type='buffer'>")
4245
4246 def test_Module_repr(self):
4247 module = Module("foo", _make_clinic())
4248 self.assertRegex(repr(module), r"<clinic.Module 'foo' at \d+>")
4249
4250 def test_Class_repr(self):
4251 cls = Class("foo", _make_clinic(), None, 'some_typedef', 'some_type_object')
4252 self.assertRegex(repr(cls), r"<clinic.Class 'foo' at \d+>")
4253
4254 def test_FunctionKind_repr(self):
4255 self.assertEqual(
4256 repr(FunctionKind.CLASS_METHOD), "<clinic.FunctionKind.CLASS_METHOD>"
4257 )
4258
4259 def test_Function_and_Parameter_reprs(self):
4260 function = Function(
4261 name='foo',
4262 module=_make_clinic(),
4263 cls=None,
4264 c_basename=None,
4265 full_name='foofoo',
4266 return_converter=int_return_converter(),
4267 kind=FunctionKind.METHOD_INIT,
4268 coexist=False
4269 )
4270 self.assertEqual(repr(function), "<clinic.Function 'foo'>")
4271
4272 converter = self_converter('bar', 'bar', function)
4273 parameter = Parameter(
4274 "bar",
4275 kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
4276 function=function,
4277 converter=converter
4278 )
4279 self.assertEqual(repr(parameter), "<clinic.Parameter 'bar'>")
4280
4281 def test_Monitor_repr(self):
4282 monitor = libclinic.cpp.Monitor("test.c")
4283 self.assertRegex(repr(monitor), r"<clinic.Monitor \d+ line=0 condition=''>")
4284
4285 monitor.line_number = 42
4286 monitor.stack.append(("token1", "condition1"))
4287 self.assertRegex(
4288 repr(monitor), r"<clinic.Monitor \d+ line=42 condition='condition1'>"
4289 )
4290
4291 monitor.stack.append(("token2", "condition2"))
4292 self.assertRegex(
4293 repr(monitor),
4294 r"<clinic.Monitor \d+ line=42 condition='condition1 && condition2'>"
4295 )
4296
4297
4298 if __name__ == "__main__":
4299 unittest.main()