Debian Codegraph @

lib-python/3/test/test_clinic.py

raw symbols SCIP
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 import SHORT_TIMEOUT, requires_subprocess
9 from test.support.os_helper import TESTFN, unlink
10 from textwrap import dedent
11 from unittest import TestCase
12 import collections
13 import inspect
14 import os.path
15 import subprocess
16 import sys
17 import unittest
18
19 test_tools.skip_if_missing('clinic')
20 with test_tools.imports_under_tool('clinic'):
21 import clinic
22 from clinic import DSLParser
23
24
25 def restore_dict(converters, old_converters):
26 converters.clear()
27 converters.update(old_converters)
28
29
30 def save_restore_converters(testcase):
31 testcase.addCleanup(restore_dict, clinic.converters,
32 clinic.converters.copy())
33 testcase.addCleanup(restore_dict, clinic.legacy_converters,
34 clinic.legacy_converters.copy())
35 testcase.addCleanup(restore_dict, clinic.return_converters,
36 clinic.return_converters.copy())
37
38
39 class _ParserBase(TestCase):
40 maxDiff = None
41
42 def expect_parser_failure(self, parser, _input):
43 with support.captured_stdout() as stdout:
44 with self.assertRaises(SystemExit):
45 parser(_input)
46 return stdout.getvalue()
47
48 def parse_function_should_fail(self, _input):
49 return self.expect_parser_failure(self.parse_function, _input)
50
51
52 class FakeConverter:
53 def __init__(self, name, args):
54 self.name = name
55 self.args = args
56
57
58 class FakeConverterFactory:
59 def __init__(self, name):
60 self.name = name
61
62 def __call__(self, name, default, **kwargs):
63 return FakeConverter(self.name, kwargs)
64
65
66 class FakeConvertersDict:
67 def __init__(self):
68 self.used_converters = {}
69
70 def get(self, name, default):
71 return self.used_converters.setdefault(name, FakeConverterFactory(name))
72
73 c = clinic.Clinic(language='C', filename = "file")
74
75 class FakeClinic:
76 def __init__(self):
77 self.converters = FakeConvertersDict()
78 self.legacy_converters = FakeConvertersDict()
79 self.language = clinic.CLanguage(None)
80 self.filename = None
81 self.destination_buffers = {}
82 self.block_parser = clinic.BlockParser('', self.language)
83 self.modules = collections.OrderedDict()
84 self.classes = collections.OrderedDict()
85 clinic.clinic = self
86 self.name = "FakeClinic"
87 self.line_prefix = self.line_suffix = ''
88 self.destinations = {}
89 self.add_destination("block", "buffer")
90 self.add_destination("file", "buffer")
91 self.add_destination("suppress", "suppress")
92 d = self.destinations.get
93 self.field_destinations = collections.OrderedDict((
94 ('docstring_prototype', d('suppress')),
95 ('docstring_definition', d('block')),
96 ('methoddef_define', d('block')),
97 ('impl_prototype', d('block')),
98 ('parser_prototype', d('suppress')),
99 ('parser_definition', d('block')),
100 ('impl_definition', d('block')),
101 ))
102
103 def get_destination(self, name):
104 d = self.destinations.get(name)
105 if not d:
106 sys.exit("Destination does not exist: " + repr(name))
107 return d
108
109 def add_destination(self, name, type, *args):
110 if name in self.destinations:
111 sys.exit("Destination already exists: " + repr(name))
112 self.destinations[name] = clinic.Destination(name, type, self, *args)
113
114 def is_directive(self, name):
115 return name == "module"
116
117 def directive(self, name, args):
118 self.called_directives[name] = args
119
120 _module_and_class = clinic.Clinic._module_and_class
121
122
123 class ClinicWholeFileTest(_ParserBase):
124 def setUp(self):
125 save_restore_converters(self)
126 self.clinic = clinic.Clinic(clinic.CLanguage(None), filename="test.c")
127
128 def expect_failure(self, raw):
129 _input = dedent(raw).strip()
130 return self.expect_parser_failure(self.clinic.parse, _input)
131
132 def test_eol(self):
133 # regression test:
134 # clinic's block parser didn't recognize
135 # the "end line" for the block if it
136 # didn't end in "\n" (as in, the last)
137 # byte of the file was '/'.
138 # so it would spit out an end line for you.
139 # and since you really already had one,
140 # the last line of the block got corrupted.
141 raw = "/*[clinic]\nfoo\n[clinic]*/"
142 cooked = self.clinic.parse(raw).splitlines()
143 end_line = cooked[2].rstrip()
144 # this test is redundant, it's just here explicitly to catch
145 # the regression test so we don't forget what it looked like
146 self.assertNotEqual(end_line, "[clinic]*/[clinic]*/")
147 self.assertEqual(end_line, "[clinic]*/")
148
149 def test_mangled_marker_line(self):
150 raw = """
151 /*[clinic input]
152 [clinic start generated code]*/
153 /*[clinic end generated code: foo]*/
154 """
155 msg = (
156 'Error in file "test.c" on line 3:\n'
157 "Mangled Argument Clinic marker line: '/*[clinic end generated code: foo]*/'\n"
158 )
159 out = self.expect_failure(raw)
160 self.assertEqual(out, msg)
161
162 def test_checksum_mismatch(self):
163 raw = """
164 /*[clinic input]
165 [clinic start generated code]*/
166 /*[clinic end generated code: output=0123456789abcdef input=fedcba9876543210]*/
167 """
168 msg = (
169 'Error in file "test.c" on line 3:\n'
170 'Checksum mismatch!\n'
171 'Expected: 0123456789abcdef\n'
172 'Computed: da39a3ee5e6b4b0d\n'
173 )
174 out = self.expect_failure(raw)
175 self.assertIn(msg, out)
176
177 def test_garbage_after_stop_line(self):
178 raw = """
179 /*[clinic input]
180 [clinic start generated code]*/foobarfoobar!
181 """
182 msg = (
183 'Error in file "test.c" on line 2:\n'
184 "Garbage after stop line: 'foobarfoobar!'\n"
185 )
186 out = self.expect_failure(raw)
187 self.assertEqual(out, msg)
188
189 def test_whitespace_before_stop_line(self):
190 raw = """
191 /*[clinic input]
192 [clinic start generated code]*/
193 """
194 msg = (
195 'Error in file "test.c" on line 2:\n'
196 "Whitespace is not allowed before the stop line: ' [clinic start generated code]*/'\n"
197 )
198 out = self.expect_failure(raw)
199 self.assertEqual(out, msg)
200
201 def test_parse_with_body_prefix(self):
202 clang = clinic.CLanguage(None)
203 clang.body_prefix = "//"
204 clang.start_line = "//[{dsl_name} start]"
205 clang.stop_line = "//[{dsl_name} stop]"
206 cl = clinic.Clinic(clang, filename="test.c")
207 raw = dedent("""
208 //[clinic start]
209 //module test
210 //[clinic stop]
211 """).strip()
212 out = cl.parse(raw)
213 expected = dedent("""
214 //[clinic start]
215 //module test
216 //
217 //[clinic stop]
218 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=65fab8adff58cf08]*/
219 """).lstrip() # Note, lstrip() because of the newline
220 self.assertEqual(out, expected)
221
222 def test_cpp_monitor_fail_nested_block_comment(self):
223 raw = """
224 /* start
225 /* nested
226 */
227 */
228 """
229 msg = (
230 'Error in file "test.c" on line 2:\n'
231 'Nested block comment!\n'
232 )
233 out = self.expect_failure(raw)
234 self.assertEqual(out, msg)
235
236 def test_cpp_monitor_fail_invalid_format_noarg(self):
237 raw = """
238 #if
239 a()
240 #endif
241 """
242 msg = (
243 'Error in file "test.c" on line 1:\n'
244 'Invalid format for #if line: no argument!\n'
245 )
246 out = self.expect_failure(raw)
247 self.assertEqual(out, msg)
248
249 def test_cpp_monitor_fail_invalid_format_toomanyargs(self):
250 raw = """
251 #ifdef A B
252 a()
253 #endif
254 """
255 msg = (
256 'Error in file "test.c" on line 1:\n'
257 'Invalid format for #ifdef line: should be exactly one argument!\n'
258 )
259 out = self.expect_failure(raw)
260 self.assertEqual(out, msg)
261
262 def test_cpp_monitor_fail_no_matching_if(self):
263 raw = '#else'
264 msg = (
265 'Error in file "test.c" on line 1:\n'
266 '#else without matching #if / #ifdef / #ifndef!\n'
267 )
268 out = self.expect_failure(raw)
269 self.assertEqual(out, msg)
270
271 def test_directive_output_unknown_preset(self):
272 out = self.expect_failure("""
273 /*[clinic input]
274 output preset nosuchpreset
275 [clinic start generated code]*/
276 """)
277 msg = "Unknown preset 'nosuchpreset'"
278 self.assertIn(msg, out)
279
280 def test_directive_output_cant_pop(self):
281 out = self.expect_failure("""
282 /*[clinic input]
283 output pop
284 [clinic start generated code]*/
285 """)
286 msg = "Can't 'output pop', stack is empty"
287 self.assertIn(msg, out)
288
289 def test_directive_output_print(self):
290 raw = dedent("""
291 /*[clinic input]
292 output print 'I told you once.'
293 [clinic start generated code]*/
294 """)
295 out = self.clinic.parse(raw)
296 # The generated output will differ for every run, but we can check that
297 # it starts with the clinic block, we check that it contains all the
298 # expected fields, and we check that it contains the checksum line.
299 self.assertTrue(out.startswith(dedent("""
300 /*[clinic input]
301 output print 'I told you once.'
302 [clinic start generated code]*/
303 """)))
304 fields = {
305 "cpp_endif",
306 "cpp_if",
307 "docstring_definition",
308 "docstring_prototype",
309 "impl_definition",
310 "impl_prototype",
311 "methoddef_define",
312 "methoddef_ifndef",
313 "parser_definition",
314 "parser_prototype",
315 }
316 for field in fields:
317 with self.subTest(field=field):
318 self.assertIn(field, out)
319 last_line = out.rstrip().split("\n")[-1]
320 self.assertTrue(
321 last_line.startswith("/*[clinic end generated code: output=")
322 )
323
324 def test_unknown_destination_command(self):
325 out = self.expect_failure("""
326 /*[clinic input]
327 destination buffer nosuchcommand
328 [clinic start generated code]*/
329 """)
330 msg = "unknown destination command 'nosuchcommand'"
331 self.assertIn(msg, out)
332
333 def test_no_access_to_members_in_converter_init(self):
334 out = self.expect_failure("""
335 /*[python input]
336 class Custom_converter(CConverter):
337 converter = "some_c_function"
338 def converter_init(self):
339 self.function.noaccess
340 [python start generated code]*/
341 /*[clinic input]
342 module test
343 test.fn
344 a: Custom
345 [clinic start generated code]*/
346 """)
347 msg = (
348 "Stepped on a land mine, trying to access attribute 'noaccess':\n"
349 "Don't access members of self.function inside converter_init!"
350 )
351 self.assertIn(msg, out)
352
353
354 class ClinicGroupPermuterTest(TestCase):
355 def _test(self, l, m, r, output):
356 computed = clinic.permute_optional_groups(l, m, r)
357 self.assertEqual(output, computed)
358
359 def test_range(self):
360 self._test([['start']], ['stop'], [['step']],
361 (
362 ('stop',),
363 ('start', 'stop',),
364 ('start', 'stop', 'step',),
365 ))
366
367 def test_add_window(self):
368 self._test([['x', 'y']], ['ch'], [['attr']],
369 (
370 ('ch',),
371 ('ch', 'attr'),
372 ('x', 'y', 'ch',),
373 ('x', 'y', 'ch', 'attr'),
374 ))
375
376 def test_ludicrous(self):
377 self._test([['a1', 'a2', 'a3'], ['b1', 'b2']], ['c1'], [['d1', 'd2'], ['e1', 'e2', 'e3']],
378 (
379 ('c1',),
380 ('b1', 'b2', 'c1'),
381 ('b1', 'b2', 'c1', 'd1', 'd2'),
382 ('a1', 'a2', 'a3', 'b1', 'b2', 'c1'),
383 ('a1', 'a2', 'a3', 'b1', 'b2', 'c1', 'd1', 'd2'),
384 ('a1', 'a2', 'a3', 'b1', 'b2', 'c1', 'd1', 'd2', 'e1', 'e2', 'e3'),
385 ))
386
387 def test_right_only(self):
388 self._test([], [], [['a'],['b'],['c']],
389 (
390 (),
391 ('a',),
392 ('a', 'b'),
393 ('a', 'b', 'c')
394 ))
395
396 def test_have_left_options_but_required_is_empty(self):
397 def fn():
398 clinic.permute_optional_groups(['a'], [], [])
399 self.assertRaises(AssertionError, fn)
400
401
402 class ClinicLinearFormatTest(TestCase):
403 def _test(self, input, output, **kwargs):
404 computed = clinic.linear_format(input, **kwargs)
405 self.assertEqual(output, computed)
406
407 def test_empty_strings(self):
408 self._test('', '')
409
410 def test_solo_newline(self):
411 self._test('\n', '\n')
412
413 def test_no_substitution(self):
414 self._test("""
415 abc
416 """, """
417 abc
418 """)
419
420 def test_empty_substitution(self):
421 self._test("""
422 abc
423 {name}
424 def
425 """, """
426 abc
427 def
428 """, name='')
429
430 def test_single_line_substitution(self):
431 self._test("""
432 abc
433 {name}
434 def
435 """, """
436 abc
437 GARGLE
438 def
439 """, name='GARGLE')
440
441 def test_multiline_substitution(self):
442 self._test("""
443 abc
444 {name}
445 def
446 """, """
447 abc
448 bingle
449 bungle
450
451 def
452 """, name='bingle\nbungle\n')
453
454 class InertParser:
455 def __init__(self, clinic):
456 pass
457
458 def parse(self, block):
459 pass
460
461 class CopyParser:
462 def __init__(self, clinic):
463 pass
464
465 def parse(self, block):
466 block.output = block.input
467
468
469 class ClinicBlockParserTest(TestCase):
470 def _test(self, input, output):
471 language = clinic.CLanguage(None)
472
473 blocks = list(clinic.BlockParser(input, language))
474 writer = clinic.BlockPrinter(language)
475 for block in blocks:
476 writer.print_block(block)
477 output = writer.f.getvalue()
478 assert output == input, "output != input!\n\noutput " + repr(output) + "\n\n input " + repr(input)
479
480 def round_trip(self, input):
481 return self._test(input, input)
482
483 def test_round_trip_1(self):
484 self.round_trip("""
485 verbatim text here
486 lah dee dah
487 """)
488 def test_round_trip_2(self):
489 self.round_trip("""
490 verbatim text here
491 lah dee dah
492 /*[inert]
493 abc
494 [inert]*/
495 def
496 /*[inert checksum: 7b18d017f89f61cf17d47f92749ea6930a3f1deb]*/
497 xyz
498 """)
499
500 def _test_clinic(self, input, output):
501 language = clinic.CLanguage(None)
502 c = clinic.Clinic(language, filename="file")
503 c.parsers['inert'] = InertParser(c)
504 c.parsers['copy'] = CopyParser(c)
505 computed = c.parse(input)
506 self.assertEqual(output, computed)
507
508 def test_clinic_1(self):
509 self._test_clinic("""
510 verbatim text here
511 lah dee dah
512 /*[copy input]
513 def
514 [copy start generated code]*/
515 abc
516 /*[copy end generated code: output=03cfd743661f0797 input=7b18d017f89f61cf]*/
517 xyz
518 """, """
519 verbatim text here
520 lah dee dah
521 /*[copy input]
522 def
523 [copy start generated code]*/
524 def
525 /*[copy end generated code: output=7b18d017f89f61cf input=7b18d017f89f61cf]*/
526 xyz
527 """)
528
529
530 class ClinicParserTest(_ParserBase):
531 def checkDocstring(self, fn, expected):
532 self.assertTrue(hasattr(fn, "docstring"))
533 self.assertEqual(fn.docstring.strip(),
534 dedent(expected).strip())
535
536 def test_trivial(self):
537 parser = DSLParser(FakeClinic())
538 block = clinic.Block("""
539 module os
540 os.access
541 """)
542 parser.parse(block)
543 module, function = block.signatures
544 self.assertEqual("access", function.name)
545 self.assertEqual("os", module.name)
546
547 def test_ignore_line(self):
548 block = self.parse(dedent("""
549 #
550 module os
551 os.access
552 """))
553 module, function = block.signatures
554 self.assertEqual("access", function.name)
555 self.assertEqual("os", module.name)
556
557 def test_param(self):
558 function = self.parse_function("""
559 module os
560 os.access
561 path: int
562 """)
563 self.assertEqual("access", function.name)
564 self.assertEqual(2, len(function.parameters))
565 p = function.parameters['path']
566 self.assertEqual('path', p.name)
567 self.assertIsInstance(p.converter, clinic.int_converter)
568
569 def test_param_default(self):
570 function = self.parse_function("""
571 module os
572 os.access
573 follow_symlinks: bool = True
574 """)
575 p = function.parameters['follow_symlinks']
576 self.assertEqual(True, p.default)
577
578 def test_param_with_continuations(self):
579 function = self.parse_function(r"""
580 module os
581 os.access
582 follow_symlinks: \
583 bool \
584 = \
585 True
586 """)
587 p = function.parameters['follow_symlinks']
588 self.assertEqual(True, p.default)
589
590 def test_param_default_expression(self):
591 function = self.parse_function("""
592 module os
593 os.access
594 follow_symlinks: int(c_default='MAXSIZE') = sys.maxsize
595 """)
596 p = function.parameters['follow_symlinks']
597 self.assertEqual(sys.maxsize, p.default)
598 self.assertEqual("MAXSIZE", p.converter.c_default)
599
600 expected_msg = (
601 "Error on line 0:\n"
602 "When you specify a named constant ('sys.maxsize') as your default value,\n"
603 "you MUST specify a valid c_default.\n"
604 )
605 out = self.parse_function_should_fail("""
606 module os
607 os.access
608 follow_symlinks: int = sys.maxsize
609 """)
610 self.assertEqual(out, expected_msg)
611
612 def test_param_no_docstring(self):
613 function = self.parse_function("""
614 module os
615 os.access
616 follow_symlinks: bool = True
617 something_else: str = ''
618 """)
619 p = function.parameters['follow_symlinks']
620 self.assertEqual(3, len(function.parameters))
621 conv = function.parameters['something_else'].converter
622 self.assertIsInstance(conv, clinic.str_converter)
623
624 def test_param_default_parameters_out_of_order(self):
625 expected_msg = (
626 "Error on line 0:\n"
627 "Can't have a parameter without a default ('something_else')\n"
628 "after a parameter with a default!\n"
629 )
630 out = self.parse_function_should_fail("""
631 module os
632 os.access
633 follow_symlinks: bool = True
634 something_else: str""")
635 self.assertEqual(out, expected_msg)
636
637 def disabled_test_converter_arguments(self):
638 function = self.parse_function("""
639 module os
640 os.access
641 path: path_t(allow_fd=1)
642 """)
643 p = function.parameters['path']
644 self.assertEqual(1, p.converter.args['allow_fd'])
645
646 def test_function_docstring(self):
647 function = self.parse_function("""
648 module os
649 os.stat as os_stat_fn
650
651 path: str
652 Path to be examined
653
654 Perform a stat system call on the given path.
655 """)
656 self.checkDocstring(function, """
657 stat($module, /, path)
658 --
659
660 Perform a stat system call on the given path.
661
662 path
663 Path to be examined
664 """)
665
666 def test_explicit_parameters_in_docstring(self):
667 function = self.parse_function(dedent("""
668 module foo
669 foo.bar
670 x: int
671 Documentation for x.
672 y: int
673
674 This is the documentation for foo.
675
676 Okay, we're done here.
677 """))
678 self.checkDocstring(function, """
679 bar($module, /, x, y)
680 --
681
682 This is the documentation for foo.
683
684 x
685 Documentation for x.
686
687 Okay, we're done here.
688 """)
689
690 def test_parser_regression_special_character_in_parameter_column_of_docstring_first_line(self):
691 function = self.parse_function(dedent("""
692 module os
693 os.stat
694 path: str
695 This/used to break Clinic!
696 """))
697 self.checkDocstring(function, """
698 stat($module, /, path)
699 --
700
701 This/used to break Clinic!
702 """)
703
704 def test_c_name(self):
705 function = self.parse_function("""
706 module os
707 os.stat as os_stat_fn
708 """)
709 self.assertEqual("os_stat_fn", function.c_basename)
710
711 def test_return_converter(self):
712 function = self.parse_function("""
713 module os
714 os.stat -> int
715 """)
716 self.assertIsInstance(function.return_converter, clinic.int_return_converter)
717
718 def test_star(self):
719 function = self.parse_function("""
720 module os
721 os.access
722 *
723 follow_symlinks: bool = True
724 """)
725 p = function.parameters['follow_symlinks']
726 self.assertEqual(inspect.Parameter.KEYWORD_ONLY, p.kind)
727 self.assertEqual(0, p.group)
728
729 def test_group(self):
730 function = self.parse_function("""
731 module window
732 window.border
733 [
734 ls: int
735 ]
736 /
737 """)
738 p = function.parameters['ls']
739 self.assertEqual(1, p.group)
740
741 def test_left_group(self):
742 function = self.parse_function("""
743 module curses
744 curses.addch
745 [
746 y: int
747 Y-coordinate.
748 x: int
749 X-coordinate.
750 ]
751 ch: char
752 Character to add.
753 [
754 attr: long
755 Attributes for the character.
756 ]
757 /
758 """)
759 dataset = (
760 ('y', -1), ('x', -1),
761 ('ch', 0),
762 ('attr', 1),
763 )
764 for name, group in dataset:
765 with self.subTest(name=name, group=group):
766 p = function.parameters[name]
767 self.assertEqual(p.group, group)
768 self.assertEqual(p.kind, inspect.Parameter.POSITIONAL_ONLY)
769 self.checkDocstring(function, """
770 addch([y, x,] ch, [attr])
771
772
773 y
774 Y-coordinate.
775 x
776 X-coordinate.
777 ch
778 Character to add.
779 attr
780 Attributes for the character.
781 """)
782
783 def test_nested_groups(self):
784 function = self.parse_function("""
785 module curses
786 curses.imaginary
787 [
788 [
789 y1: int
790 Y-coordinate.
791 y2: int
792 Y-coordinate.
793 ]
794 x1: int
795 X-coordinate.
796 x2: int
797 X-coordinate.
798 ]
799 ch: char
800 Character to add.
801 [
802 attr1: long
803 Attributes for the character.
804 attr2: long
805 Attributes for the character.
806 attr3: long
807 Attributes for the character.
808 [
809 attr4: long
810 Attributes for the character.
811 attr5: long
812 Attributes for the character.
813 attr6: long
814 Attributes for the character.
815 ]
816 ]
817 /
818 """)
819 dataset = (
820 ('y1', -2), ('y2', -2),
821 ('x1', -1), ('x2', -1),
822 ('ch', 0),
823 ('attr1', 1), ('attr2', 1), ('attr3', 1),
824 ('attr4', 2), ('attr5', 2), ('attr6', 2),
825 )
826 for name, group in dataset:
827 with self.subTest(name=name, group=group):
828 p = function.parameters[name]
829 self.assertEqual(p.group, group)
830 self.assertEqual(p.kind, inspect.Parameter.POSITIONAL_ONLY)
831
832 self.checkDocstring(function, """
833 imaginary([[y1, y2,] x1, x2,] ch, [attr1, attr2, attr3, [attr4, attr5,
834 attr6]])
835
836
837 y1
838 Y-coordinate.
839 y2
840 Y-coordinate.
841 x1
842 X-coordinate.
843 x2
844 X-coordinate.
845 ch
846 Character to add.
847 attr1
848 Attributes for the character.
849 attr2
850 Attributes for the character.
851 attr3
852 Attributes for the character.
853 attr4
854 Attributes for the character.
855 attr5
856 Attributes for the character.
857 attr6
858 Attributes for the character.
859 """)
860
861 def parse_function_should_fail(self, s):
862 with support.captured_stdout() as stdout:
863 with self.assertRaises(SystemExit):
864 self.parse_function(s)
865 return stdout.getvalue()
866
867 def test_disallowed_grouping__two_top_groups_on_left(self):
868 expected_msg = (
869 'Error on line 0:\n'
870 'Function two_top_groups_on_left has an unsupported group '
871 'configuration. (Unexpected state 2.b)\n'
872 )
873 out = self.parse_function_should_fail("""
874 module foo
875 foo.two_top_groups_on_left
876 [
877 group1 : int
878 ]
879 [
880 group2 : int
881 ]
882 param: int
883 """)
884 self.assertEqual(out, expected_msg)
885
886 def test_disallowed_grouping__two_top_groups_on_right(self):
887 out = self.parse_function_should_fail("""
888 module foo
889 foo.two_top_groups_on_right
890 param: int
891 [
892 group1 : int
893 ]
894 [
895 group2 : int
896 ]
897 """)
898 msg = (
899 "Function two_top_groups_on_right has an unsupported group "
900 "configuration. (Unexpected state 6.b)"
901 )
902 self.assertIn(msg, out)
903
904 def test_disallowed_grouping__parameter_after_group_on_right(self):
905 out = self.parse_function_should_fail("""
906 module foo
907 foo.parameter_after_group_on_right
908 param: int
909 [
910 [
911 group1 : int
912 ]
913 group2 : int
914 ]
915 """)
916 msg = (
917 "Function parameter_after_group_on_right has an unsupported group "
918 "configuration. (Unexpected state 6.a)"
919 )
920 self.assertIn(msg, out)
921
922 def test_disallowed_grouping__group_after_parameter_on_left(self):
923 out = self.parse_function_should_fail("""
924 module foo
925 foo.group_after_parameter_on_left
926 [
927 group2 : int
928 [
929 group1 : int
930 ]
931 ]
932 param: int
933 """)
934 msg = (
935 "Function group_after_parameter_on_left has an unsupported group "
936 "configuration. (Unexpected state 2.b)"
937 )
938 self.assertIn(msg, out)
939
940 def test_disallowed_grouping__empty_group_on_left(self):
941 out = self.parse_function_should_fail("""
942 module foo
943 foo.empty_group
944 [
945 [
946 ]
947 group2 : int
948 ]
949 param: int
950 """)
951 msg = (
952 "Function empty_group has an empty group.\n"
953 "All groups must contain at least one parameter."
954 )
955 self.assertIn(msg, out)
956
957 def test_disallowed_grouping__empty_group_on_right(self):
958 out = self.parse_function_should_fail("""
959 module foo
960 foo.empty_group
961 param: int
962 [
963 [
964 ]
965 group2 : int
966 ]
967 """)
968 msg = (
969 "Function empty_group has an empty group.\n"
970 "All groups must contain at least one parameter."
971 )
972 self.assertIn(msg, out)
973
974 def test_disallowed_grouping__no_matching_bracket(self):
975 out = self.parse_function_should_fail("""
976 module foo
977 foo.empty_group
978 param: int
979 ]
980 group2: int
981 ]
982 """)
983 msg = "Function empty_group has a ] without a matching [."
984 self.assertIn(msg, out)
985
986 def test_no_parameters(self):
987 function = self.parse_function("""
988 module foo
989 foo.bar
990
991 Docstring
992
993 """)
994 self.assertEqual("bar($module, /)\n--\n\nDocstring", function.docstring)
995 self.assertEqual(1, len(function.parameters)) # self!
996
997 def test_init_with_no_parameters(self):
998 function = self.parse_function("""
999 module foo
1000 class foo.Bar "unused" "notneeded"
1001 foo.Bar.__init__
1002
1003 Docstring
1004
1005 """, signatures_in_block=3, function_index=2)
1006
1007 # self is not in the signature
1008 self.assertEqual("Bar()\n--\n\nDocstring", function.docstring)
1009 # but it *is* a parameter
1010 self.assertEqual(1, len(function.parameters))
1011
1012 def test_illegal_module_line(self):
1013 out = self.parse_function_should_fail("""
1014 module foo
1015 foo.bar => int
1016 /
1017 """)
1018 msg = "Illegal function name: foo.bar => int"
1019 self.assertIn(msg, out)
1020
1021 def test_illegal_c_basename(self):
1022 out = self.parse_function_should_fail("""
1023 module foo
1024 foo.bar as 935
1025 /
1026 """)
1027 msg = "Illegal C basename: 935"
1028 self.assertIn(msg, out)
1029
1030 def test_single_star(self):
1031 out = self.parse_function_should_fail("""
1032 module foo
1033 foo.bar
1034 *
1035 *
1036 """)
1037 self.assertIn("Function bar uses '*' more than once.", out)
1038
1039 def test_parameters_required_after_star(self):
1040 dataset = (
1041 "module foo\nfoo.bar\n *",
1042 "module foo\nfoo.bar\n *\nDocstring here.",
1043 "module foo\nfoo.bar\n this: int\n *",
1044 "module foo\nfoo.bar\n this: int\n *\nDocstring.",
1045 )
1046 msg = "Function bar specifies '*' without any parameters afterwards."
1047 for block in dataset:
1048 with self.subTest(block=block):
1049 out = self.parse_function_should_fail(block)
1050 self.assertIn(msg, out)
1051
1052 def test_single_slash(self):
1053 out = self.parse_function_should_fail("""
1054 module foo
1055 foo.bar
1056 /
1057 /
1058 """)
1059 msg = (
1060 "Function bar has an unsupported group configuration. "
1061 "(Unexpected state 0.d)"
1062 )
1063 self.assertIn(msg, out)
1064
1065 def test_double_slash(self):
1066 out = self.parse_function_should_fail("""
1067 module foo
1068 foo.bar
1069 a: int
1070 /
1071 b: int
1072 /
1073 """)
1074 msg = "Function bar uses '/' more than once."
1075 self.assertIn(msg, out)
1076
1077 def test_mix_star_and_slash(self):
1078 out = self.parse_function_should_fail("""
1079 module foo
1080 foo.bar
1081 x: int
1082 y: int
1083 *
1084 z: int
1085 /
1086 """)
1087 msg = (
1088 "Function bar mixes keyword-only and positional-only parameters, "
1089 "which is unsupported."
1090 )
1091 self.assertIn(msg, out)
1092
1093 def test_parameters_not_permitted_after_slash_for_now(self):
1094 out = self.parse_function_should_fail("""
1095 module foo
1096 foo.bar
1097 /
1098 x: int
1099 """)
1100 msg = (
1101 "Function bar has an unsupported group configuration. "
1102 "(Unexpected state 0.d)"
1103 )
1104 self.assertIn(msg, out)
1105
1106 def test_parameters_no_more_than_one_vararg(self):
1107 expected_msg = (
1108 "Error on line 0:\n"
1109 "Too many var args\n"
1110 )
1111 out = self.parse_function_should_fail("""
1112 module foo
1113 foo.bar
1114 *vararg1: object
1115 *vararg2: object
1116 """)
1117 self.assertEqual(out, expected_msg)
1118
1119 def test_function_not_at_column_0(self):
1120 function = self.parse_function("""
1121 module foo
1122 foo.bar
1123 x: int
1124 Nested docstring here, goeth.
1125 *
1126 y: str
1127 Not at column 0!
1128 """)
1129 self.checkDocstring(function, """
1130 bar($module, /, x, *, y)
1131 --
1132
1133 Not at column 0!
1134
1135 x
1136 Nested docstring here, goeth.
1137 """)
1138
1139 def test_indent_stack_no_tabs(self):
1140 out = self.parse_function_should_fail("""
1141 module foo
1142 foo.bar
1143 *vararg1: object
1144 \t*vararg2: object
1145 """)
1146 msg = "Tab characters are illegal in the Clinic DSL."
1147 self.assertIn(msg, out)
1148
1149 def test_indent_stack_illegal_outdent(self):
1150 out = self.parse_function_should_fail("""
1151 module foo
1152 foo.bar
1153 a: object
1154 b: object
1155 """)
1156 self.assertIn("Illegal outdent", out)
1157
1158 def test_directive(self):
1159 c = FakeClinic()
1160 parser = DSLParser(c)
1161 parser.flag = False
1162 parser.directives['setflag'] = lambda : setattr(parser, 'flag', True)
1163 block = clinic.Block("setflag")
1164 parser.parse(block)
1165 self.assertTrue(parser.flag)
1166
1167 def test_legacy_converters(self):
1168 block = self.parse('module os\nos.access\n path: "s"')
1169 module, function = block.signatures
1170 conv = (function.parameters['path']).converter
1171 self.assertIsInstance(conv, clinic.str_converter)
1172
1173 def test_legacy_converters_non_string_constant_annotation(self):
1174 expected_failure_message = (
1175 "Error on line 0:\n"
1176 "Annotations must be either a name, a function call, or a string.\n"
1177 )
1178 dataset = (
1179 'module os\nos.access\n path: 42',
1180 'module os\nos.access\n path: 42.42',
1181 'module os\nos.access\n path: 42j',
1182 'module os\nos.access\n path: b"42"',
1183 )
1184 for block in dataset:
1185 with self.subTest(block=block):
1186 out = self.parse_function_should_fail(block)
1187 self.assertEqual(out, expected_failure_message)
1188
1189 def test_other_bizarre_things_in_annotations_fail(self):
1190 expected_failure_message = (
1191 "Error on line 0:\n"
1192 "Annotations must be either a name, a function call, or a string.\n"
1193 )
1194 dataset = (
1195 'module os\nos.access\n path: {"some": "dictionary"}',
1196 'module os\nos.access\n path: ["list", "of", "strings"]',
1197 'module os\nos.access\n path: (x for x in range(42))',
1198 )
1199 for block in dataset:
1200 with self.subTest(block=block):
1201 out = self.parse_function_should_fail(block)
1202 self.assertEqual(out, expected_failure_message)
1203
1204 def test_self_param_placement(self):
1205 expected_error_msg = (
1206 "Error on line 0:\n"
1207 "A 'self' parameter, if specified, must be the very first thing "
1208 "in the parameter block.\n"
1209 )
1210 block = """
1211 module foo
1212 foo.func
1213 a: int
1214 self: self(type="PyObject *")
1215 """
1216 out = self.parse_function_should_fail(block)
1217 self.assertEqual(out, expected_error_msg)
1218
1219 def test_self_param_cannot_be_optional(self):
1220 expected_error_msg = (
1221 "Error on line 0:\n"
1222 "A 'self' parameter cannot be marked optional.\n"
1223 )
1224 block = """
1225 module foo
1226 foo.func
1227 self: self(type="PyObject *") = None
1228 """
1229 out = self.parse_function_should_fail(block)
1230 self.assertEqual(out, expected_error_msg)
1231
1232 def test_defining_class_param_placement(self):
1233 expected_error_msg = (
1234 "Error on line 0:\n"
1235 "A 'defining_class' parameter, if specified, must either be the "
1236 "first thing in the parameter block, or come just after 'self'.\n"
1237 )
1238 block = """
1239 module foo
1240 foo.func
1241 self: self(type="PyObject *")
1242 a: int
1243 cls: defining_class
1244 """
1245 out = self.parse_function_should_fail(block)
1246 self.assertEqual(out, expected_error_msg)
1247
1248 def test_defining_class_param_cannot_be_optional(self):
1249 expected_error_msg = (
1250 "Error on line 0:\n"
1251 "A 'defining_class' parameter cannot be marked optional.\n"
1252 )
1253 block = """
1254 module foo
1255 foo.func
1256 cls: defining_class(type="PyObject *") = None
1257 """
1258 out = self.parse_function_should_fail(block)
1259 self.assertEqual(out, expected_error_msg)
1260
1261 def test_slot_methods_cannot_access_defining_class(self):
1262 block = """
1263 module foo
1264 class Foo "" ""
1265 Foo.__init__
1266 cls: defining_class
1267 a: object
1268 """
1269 msg = "Slot methods cannot access their defining class."
1270 with self.assertRaisesRegex(ValueError, msg):
1271 self.parse_function(block)
1272
1273 def test_new_must_be_a_class_method(self):
1274 expected_error_msg = (
1275 "Error on line 0:\n"
1276 "__new__ must be a class method!\n"
1277 )
1278 out = self.parse_function_should_fail("""
1279 module foo
1280 class Foo "" ""
1281 Foo.__new__
1282 """)
1283 self.assertEqual(out, expected_error_msg)
1284
1285 def test_init_must_be_a_normal_method(self):
1286 expected_error_msg = (
1287 "Error on line 0:\n"
1288 "__init__ must be a normal method, not a class or static method!\n"
1289 )
1290 out = self.parse_function_should_fail("""
1291 module foo
1292 class Foo "" ""
1293 @classmethod
1294 Foo.__init__
1295 """)
1296 self.assertEqual(out, expected_error_msg)
1297
1298 def parse(self, text):
1299 c = FakeClinic()
1300 parser = DSLParser(c)
1301 block = clinic.Block(text)
1302 parser.parse(block)
1303 return block
1304
1305 def parse_function(self, text, signatures_in_block=2, function_index=1):
1306 block = self.parse(text)
1307 s = block.signatures
1308 self.assertEqual(len(s), signatures_in_block)
1309 assert isinstance(s[0], clinic.Module)
1310 assert isinstance(s[function_index], clinic.Function)
1311 return s[function_index]
1312
1313 def test_scaffolding(self):
1314 # test repr on special values
1315 self.assertEqual(repr(clinic.unspecified), '<Unspecified>')
1316 self.assertEqual(repr(clinic.NULL), '<Null>')
1317
1318 # test that fail fails
1319 expected = (
1320 'Error in file "clown.txt" on line 69:\n'
1321 'The igloos are melting!\n'
1322 )
1323 with support.captured_stdout() as stdout:
1324 with self.assertRaises(SystemExit):
1325 clinic.fail('The igloos are melting!',
1326 filename='clown.txt', line_number=69)
1327 actual = stdout.getvalue()
1328 self.assertEqual(actual, expected)
1329
1330
1331 class ClinicExternalTest(TestCase):
1332 maxDiff = None
1333 clinic_py = os.path.join(test_tools.toolsdir, "clinic", "clinic.py")
1334
1335 def setUp(self):
1336 save_restore_converters(self)
1337
1338 def _do_test(self, *args, expect_success=True):
1339 with subprocess.Popen(
1340 [sys.executable, "-Xutf8", self.clinic_py, *args],
1341 encoding="utf-8",
1342 bufsize=0,
1343 stdout=subprocess.PIPE,
1344 stderr=subprocess.PIPE,
1345 ) as proc:
1346 proc.wait()
1347 if expect_success and proc.returncode:
1348 self.fail("".join([*proc.stdout, *proc.stderr]))
1349 stdout = proc.stdout.read()
1350 stderr = proc.stderr.read()
1351 # Clinic never writes to stderr.
1352 self.assertEqual(stderr, "")
1353 return stdout
1354
1355 def expect_success(self, *args):
1356 return self._do_test(*args)
1357
1358 def expect_failure(self, *args):
1359 return self._do_test(*args, expect_success=False)
1360
1361 def test_external(self):
1362 CLINIC_TEST = 'clinic.test.c'
1363 source = support.findfile(CLINIC_TEST)
1364 with open(source, 'r', encoding='utf-8') as f:
1365 orig_contents = f.read()
1366
1367 # Run clinic CLI and verify that it does not complain.
1368 self.addCleanup(unlink, TESTFN)
1369 out = self.expect_success("-f", "-o", TESTFN, source)
1370 self.assertEqual(out, "")
1371
1372 with open(TESTFN, 'r', encoding='utf-8') as f:
1373 new_contents = f.read()
1374
1375 self.assertEqual(new_contents, orig_contents)
1376
1377 def test_no_change(self):
1378 # bpo-42398: Test that the destination file is left unchanged if the
1379 # content does not change. Moreover, check also that the file
1380 # modification time does not change in this case.
1381 code = dedent("""
1382 /*[clinic input]
1383 [clinic start generated code]*/
1384 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=da39a3ee5e6b4b0d]*/
1385 """)
1386 with os_helper.temp_dir() as tmp_dir:
1387 fn = os.path.join(tmp_dir, "test.c")
1388 with open(fn, "w", encoding="utf-8") as f:
1389 f.write(code)
1390 pre_mtime = os.stat(fn).st_mtime_ns
1391 self.expect_success(fn)
1392 post_mtime = os.stat(fn).st_mtime_ns
1393 # Don't change the file modification time
1394 # if the content does not change
1395 self.assertEqual(pre_mtime, post_mtime)
1396
1397 def test_cli_force(self):
1398 invalid_input = dedent("""
1399 /*[clinic input]
1400 output preset block
1401 module test
1402 test.fn
1403 a: int
1404 [clinic start generated code]*/
1405
1406 const char *hand_edited = "output block is overwritten";
1407 /*[clinic end generated code: output=bogus input=bogus]*/
1408 """)
1409 fail_msg = dedent("""
1410 Checksum mismatch!
1411 Expected: bogus
1412 Computed: 2ed19
1413 Suggested fix: remove all generated code including the end marker,
1414 or use the '-f' option.
1415 """)
1416 with os_helper.temp_dir() as tmp_dir:
1417 fn = os.path.join(tmp_dir, "test.c")
1418 with open(fn, "w", encoding="utf-8") as f:
1419 f.write(invalid_input)
1420 # First, run the CLI without -f and expect failure.
1421 # Note, we cannot check the entire fail msg, because the path to
1422 # the tmp file will change for every run.
1423 out = self.expect_failure(fn)
1424 self.assertTrue(out.endswith(fail_msg))
1425 # Then, force regeneration; success expected.
1426 out = self.expect_success("-f", fn)
1427 self.assertEqual(out, "")
1428 # Verify by checking the checksum.
1429 checksum = (
1430 "/*[clinic end generated code: "
1431 "output=6c2289b73f32bc19 input=9543a8d2da235301]*/\n"
1432 )
1433 with open(fn, 'r', encoding='utf-8') as f:
1434 generated = f.read()
1435 self.assertTrue(generated.endswith(checksum))
1436
1437 def test_cli_make(self):
1438 c_code = dedent("""
1439 /*[clinic input]
1440 [clinic start generated code]*/
1441 """)
1442 py_code = "pass"
1443 c_files = "file1.c", "file2.c"
1444 py_files = "file1.py", "file2.py"
1445
1446 def create_files(files, srcdir, code):
1447 for fn in files:
1448 path = os.path.join(srcdir, fn)
1449 with open(path, "w", encoding="utf-8") as f:
1450 f.write(code)
1451
1452 with os_helper.temp_dir() as tmp_dir:
1453 # add some folders, some C files and a Python file
1454 create_files(c_files, tmp_dir, c_code)
1455 create_files(py_files, tmp_dir, py_code)
1456
1457 # create C files in externals/ dir
1458 ext_path = os.path.join(tmp_dir, "externals")
1459 with os_helper.temp_dir(path=ext_path) as externals:
1460 create_files(c_files, externals, c_code)
1461
1462 # run clinic in verbose mode with --make on tmpdir
1463 out = self.expect_success("-v", "--make", "--srcdir", tmp_dir)
1464
1465 # expect verbose mode to only mention the C files in tmp_dir
1466 for filename in c_files:
1467 with self.subTest(filename=filename):
1468 path = os.path.join(tmp_dir, filename)
1469 self.assertIn(path, out)
1470 for filename in py_files:
1471 with self.subTest(filename=filename):
1472 path = os.path.join(tmp_dir, filename)
1473 self.assertNotIn(path, out)
1474 # don't expect C files from the externals dir
1475 for filename in c_files:
1476 with self.subTest(filename=filename):
1477 path = os.path.join(ext_path, filename)
1478 self.assertNotIn(path, out)
1479
1480 def test_cli_verbose(self):
1481 with os_helper.temp_dir() as tmp_dir:
1482 fn = os.path.join(tmp_dir, "test.c")
1483 with open(fn, "w", encoding="utf-8") as f:
1484 f.write("")
1485 out = self.expect_success("-v", fn)
1486 self.assertEqual(out.strip(), fn)
1487
1488 def test_cli_help(self):
1489 out = self.expect_success("-h")
1490 self.assertIn("usage: clinic.py", out)
1491
1492 def test_cli_converters(self):
1493 prelude = dedent("""
1494 Legacy converters:
1495 B C D L O S U Y Z Z#
1496 b c d f h i l p s s# s* u u# w* y y# y* z z# z*
1497
1498 Converters:
1499 """)
1500 expected_converters = (
1501 "bool",
1502 "byte",
1503 "char",
1504 "defining_class",
1505 "double",
1506 "fildes",
1507 "float",
1508 "int",
1509 "long",
1510 "long_long",
1511 "object",
1512 "Py_buffer",
1513 "Py_complex",
1514 "Py_ssize_t",
1515 "Py_UNICODE",
1516 "PyByteArrayObject",
1517 "PyBytesObject",
1518 "self",
1519 "short",
1520 "size_t",
1521 "slice_index",
1522 "str",
1523 "unicode",
1524 "unsigned_char",
1525 "unsigned_int",
1526 "unsigned_long",
1527 "unsigned_long_long",
1528 "unsigned_short",
1529 )
1530 finale = dedent("""
1531 Return converters:
1532 bool()
1533 double()
1534 float()
1535 init()
1536 int()
1537 long()
1538 NoneType()
1539 Py_ssize_t()
1540 size_t()
1541 unsigned_int()
1542 unsigned_long()
1543
1544 All converters also accept (c_default=None, py_default=None, annotation=None).
1545 All return converters also accept (py_default=None).
1546 """)
1547 out = self.expect_success("--converters")
1548 # We cannot simply compare the output, because the repr of the *accept*
1549 # param may change (it's a set, thus unordered). So, let's compare the
1550 # start and end of the expected output, and then assert that the
1551 # converters appear lined up in alphabetical order.
1552 self.assertTrue(out.startswith(prelude), out)
1553 self.assertTrue(out.endswith(finale), out)
1554
1555 out = out.removeprefix(prelude)
1556 out = out.removesuffix(finale)
1557 lines = out.split("\n")
1558 for converter, line in zip(expected_converters, lines):
1559 line = line.lstrip()
1560 with self.subTest(converter=converter):
1561 self.assertTrue(
1562 line.startswith(converter),
1563 f"expected converter {converter!r}, got {line!r}"
1564 )
1565
1566 def test_cli_fail_converters_and_filename(self):
1567 out = self.expect_failure("--converters", "test.c")
1568 msg = (
1569 "Usage error: can't specify --converters "
1570 "and a filename at the same time"
1571 )
1572 self.assertIn(msg, out)
1573
1574 def test_cli_fail_no_filename(self):
1575 out = self.expect_failure()
1576 self.assertIn("usage: clinic.py", out)
1577
1578 def test_cli_fail_output_and_multiple_files(self):
1579 out = self.expect_failure("-o", "out.c", "input.c", "moreinput.c")
1580 msg = "Usage error: can't use -o with multiple filenames"
1581 self.assertIn(msg, out)
1582
1583 def test_cli_fail_filename_or_output_and_make(self):
1584 for opts in ("-o", "out.c"), ("filename.c",):
1585 with self.subTest(opts=opts):
1586 out = self.expect_failure("--make", *opts)
1587 msg = "Usage error: can't use -o or filenames with --make"
1588 self.assertIn(msg, out)
1589
1590 def test_cli_fail_make_without_srcdir(self):
1591 out = self.expect_failure("--make", "--srcdir", "")
1592 msg = "Usage error: --srcdir must not be empty with --make"
1593 self.assertIn(msg, out)
1594
1595
1596 try:
1597 import _testclinic as ac_tester
1598 except ImportError:
1599 ac_tester = None
1600
1601 @unittest.skipIf(ac_tester is None, "_testclinic is missing")
1602 class ClinicFunctionalTest(unittest.TestCase):
1603 locals().update((name, getattr(ac_tester, name))
1604 for name in dir(ac_tester) if name.startswith('test_'))
1605
1606 def test_objects_converter(self):
1607 with self.assertRaises(TypeError):
1608 ac_tester.objects_converter()
1609 self.assertEqual(ac_tester.objects_converter(1, 2), (1, 2))
1610 self.assertEqual(ac_tester.objects_converter([], 'whatever class'), ([], 'whatever class'))
1611 self.assertEqual(ac_tester.objects_converter(1), (1, None))
1612
1613 def test_bytes_object_converter(self):
1614 with self.assertRaises(TypeError):
1615 ac_tester.bytes_object_converter(1)
1616 self.assertEqual(ac_tester.bytes_object_converter(b'BytesObject'), (b'BytesObject',))
1617
1618 def test_byte_array_object_converter(self):
1619 with self.assertRaises(TypeError):
1620 ac_tester.byte_array_object_converter(1)
1621 byte_arr = bytearray(b'ByteArrayObject')
1622 self.assertEqual(ac_tester.byte_array_object_converter(byte_arr), (byte_arr,))
1623
1624 def test_unicode_converter(self):
1625 with self.assertRaises(TypeError):
1626 ac_tester.unicode_converter(1)
1627 self.assertEqual(ac_tester.unicode_converter('unicode'), ('unicode',))
1628
1629 def test_bool_converter(self):
1630 with self.assertRaises(TypeError):
1631 ac_tester.bool_converter(False, False, 'not a int')
1632 self.assertEqual(ac_tester.bool_converter(), (True, True, True))
1633 self.assertEqual(ac_tester.bool_converter('', [], 5), (False, False, True))
1634 self.assertEqual(ac_tester.bool_converter(('not empty',), {1: 2}, 0), (True, True, False))
1635
1636 def test_char_converter(self):
1637 with self.assertRaises(TypeError):
1638 ac_tester.char_converter(1)
1639 with self.assertRaises(TypeError):
1640 ac_tester.char_converter(b'ab')
1641 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']
1642 expected = tuple(ord(c) for c in chars)
1643 self.assertEqual(ac_tester.char_converter(), expected)
1644 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']
1645 expected = tuple(ord(c) for c in chars)
1646 self.assertEqual(ac_tester.char_converter(*chars), expected)
1647
1648 def test_unsigned_char_converter(self):
1649 from _testcapi import UCHAR_MAX
1650 with self.assertRaises(OverflowError):
1651 ac_tester.unsigned_char_converter(-1)
1652 with self.assertRaises(OverflowError):
1653 ac_tester.unsigned_char_converter(UCHAR_MAX + 1)
1654 with self.assertRaises(OverflowError):
1655 ac_tester.unsigned_char_converter(0, UCHAR_MAX + 1)
1656 with self.assertRaises(TypeError):
1657 ac_tester.unsigned_char_converter([])
1658 self.assertEqual(ac_tester.unsigned_char_converter(), (12, 34, 56))
1659 self.assertEqual(ac_tester.unsigned_char_converter(0, 0, UCHAR_MAX + 1), (0, 0, 0))
1660 self.assertEqual(ac_tester.unsigned_char_converter(0, 0, (UCHAR_MAX + 1) * 3 + 123), (0, 0, 123))
1661
1662 def test_short_converter(self):
1663 from _testcapi import SHRT_MIN, SHRT_MAX
1664 with self.assertRaises(OverflowError):
1665 ac_tester.short_converter(SHRT_MIN - 1)
1666 with self.assertRaises(OverflowError):
1667 ac_tester.short_converter(SHRT_MAX + 1)
1668 with self.assertRaises(TypeError):
1669 ac_tester.short_converter([])
1670 self.assertEqual(ac_tester.short_converter(-1234), (-1234,))
1671 self.assertEqual(ac_tester.short_converter(4321), (4321,))
1672
1673 def test_unsigned_short_converter(self):
1674 from _testcapi import USHRT_MAX
1675 with self.assertRaises(ValueError):
1676 ac_tester.unsigned_short_converter(-1)
1677 with self.assertRaises(OverflowError):
1678 ac_tester.unsigned_short_converter(USHRT_MAX + 1)
1679 with self.assertRaises(OverflowError):
1680 ac_tester.unsigned_short_converter(0, USHRT_MAX + 1)
1681 with self.assertRaises(TypeError):
1682 ac_tester.unsigned_short_converter([])
1683 self.assertEqual(ac_tester.unsigned_short_converter(), (12, 34, 56))
1684 self.assertEqual(ac_tester.unsigned_short_converter(0, 0, USHRT_MAX + 1), (0, 0, 0))
1685 self.assertEqual(ac_tester.unsigned_short_converter(0, 0, (USHRT_MAX + 1) * 3 + 123), (0, 0, 123))
1686
1687 def test_int_converter(self):
1688 from _testcapi import INT_MIN, INT_MAX
1689 with self.assertRaises(OverflowError):
1690 ac_tester.int_converter(INT_MIN - 1)
1691 with self.assertRaises(OverflowError):
1692 ac_tester.int_converter(INT_MAX + 1)
1693 with self.assertRaises(TypeError):
1694 ac_tester.int_converter(1, 2, 3)
1695 with self.assertRaises(TypeError):
1696 ac_tester.int_converter([])
1697 self.assertEqual(ac_tester.int_converter(), (12, 34, 45))
1698 self.assertEqual(ac_tester.int_converter(1, 2, '3'), (1, 2, ord('3')))
1699
1700 def test_unsigned_int_converter(self):
1701 from _testcapi import UINT_MAX
1702 with self.assertRaises(ValueError):
1703 ac_tester.unsigned_int_converter(-1)
1704 with self.assertRaises(OverflowError):
1705 ac_tester.unsigned_int_converter(UINT_MAX + 1)
1706 with self.assertRaises(OverflowError):
1707 ac_tester.unsigned_int_converter(0, UINT_MAX + 1)
1708 with self.assertRaises(TypeError):
1709 ac_tester.unsigned_int_converter([])
1710 self.assertEqual(ac_tester.unsigned_int_converter(), (12, 34, 56))
1711 self.assertEqual(ac_tester.unsigned_int_converter(0, 0, UINT_MAX + 1), (0, 0, 0))
1712 self.assertEqual(ac_tester.unsigned_int_converter(0, 0, (UINT_MAX + 1) * 3 + 123), (0, 0, 123))
1713
1714 def test_long_converter(self):
1715 from _testcapi import LONG_MIN, LONG_MAX
1716 with self.assertRaises(OverflowError):
1717 ac_tester.long_converter(LONG_MIN - 1)
1718 with self.assertRaises(OverflowError):
1719 ac_tester.long_converter(LONG_MAX + 1)
1720 with self.assertRaises(TypeError):
1721 ac_tester.long_converter([])
1722 self.assertEqual(ac_tester.long_converter(), (12,))
1723 self.assertEqual(ac_tester.long_converter(-1234), (-1234,))
1724
1725 def test_unsigned_long_converter(self):
1726 from _testcapi import ULONG_MAX
1727 with self.assertRaises(ValueError):
1728 ac_tester.unsigned_long_converter(-1)
1729 with self.assertRaises(OverflowError):
1730 ac_tester.unsigned_long_converter(ULONG_MAX + 1)
1731 with self.assertRaises(OverflowError):
1732 ac_tester.unsigned_long_converter(0, ULONG_MAX + 1)
1733 with self.assertRaises(TypeError):
1734 ac_tester.unsigned_long_converter([])
1735 self.assertEqual(ac_tester.unsigned_long_converter(), (12, 34, 56))
1736 self.assertEqual(ac_tester.unsigned_long_converter(0, 0, ULONG_MAX + 1), (0, 0, 0))
1737 self.assertEqual(ac_tester.unsigned_long_converter(0, 0, (ULONG_MAX + 1) * 3 + 123), (0, 0, 123))
1738
1739 def test_long_long_converter(self):
1740 from _testcapi import LLONG_MIN, LLONG_MAX
1741 with self.assertRaises(OverflowError):
1742 ac_tester.long_long_converter(LLONG_MIN - 1)
1743 with self.assertRaises(OverflowError):
1744 ac_tester.long_long_converter(LLONG_MAX + 1)
1745 with self.assertRaises(TypeError):
1746 ac_tester.long_long_converter([])
1747 self.assertEqual(ac_tester.long_long_converter(), (12,))
1748 self.assertEqual(ac_tester.long_long_converter(-1234), (-1234,))
1749
1750 def test_unsigned_long_long_converter(self):
1751 from _testcapi import ULLONG_MAX
1752 with self.assertRaises(ValueError):
1753 ac_tester.unsigned_long_long_converter(-1)
1754 with self.assertRaises(OverflowError):
1755 ac_tester.unsigned_long_long_converter(ULLONG_MAX + 1)
1756 with self.assertRaises(OverflowError):
1757 ac_tester.unsigned_long_long_converter(0, ULLONG_MAX + 1)
1758 with self.assertRaises(TypeError):
1759 ac_tester.unsigned_long_long_converter([])
1760 self.assertEqual(ac_tester.unsigned_long_long_converter(), (12, 34, 56))
1761 self.assertEqual(ac_tester.unsigned_long_long_converter(0, 0, ULLONG_MAX + 1), (0, 0, 0))
1762 self.assertEqual(ac_tester.unsigned_long_long_converter(0, 0, (ULLONG_MAX + 1) * 3 + 123), (0, 0, 123))
1763
1764 def test_py_ssize_t_converter(self):
1765 from _testcapi import PY_SSIZE_T_MIN, PY_SSIZE_T_MAX
1766 with self.assertRaises(OverflowError):
1767 ac_tester.py_ssize_t_converter(PY_SSIZE_T_MIN - 1)
1768 with self.assertRaises(OverflowError):
1769 ac_tester.py_ssize_t_converter(PY_SSIZE_T_MAX + 1)
1770 with self.assertRaises(TypeError):
1771 ac_tester.py_ssize_t_converter([])
1772 self.assertEqual(ac_tester.py_ssize_t_converter(), (12, 34, 56))
1773 self.assertEqual(ac_tester.py_ssize_t_converter(1, 2, None), (1, 2, 56))
1774
1775 def test_slice_index_converter(self):
1776 from _testcapi import PY_SSIZE_T_MIN, PY_SSIZE_T_MAX
1777 with self.assertRaises(TypeError):
1778 ac_tester.slice_index_converter([])
1779 self.assertEqual(ac_tester.slice_index_converter(), (12, 34, 56))
1780 self.assertEqual(ac_tester.slice_index_converter(1, 2, None), (1, 2, 56))
1781 self.assertEqual(ac_tester.slice_index_converter(PY_SSIZE_T_MAX, PY_SSIZE_T_MAX + 1, PY_SSIZE_T_MAX + 1234),
1782 (PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX))
1783 self.assertEqual(ac_tester.slice_index_converter(PY_SSIZE_T_MIN, PY_SSIZE_T_MIN - 1, PY_SSIZE_T_MIN - 1234),
1784 (PY_SSIZE_T_MIN, PY_SSIZE_T_MIN, PY_SSIZE_T_MIN))
1785
1786 def test_size_t_converter(self):
1787 with self.assertRaises(ValueError):
1788 ac_tester.size_t_converter(-1)
1789 with self.assertRaises(TypeError):
1790 ac_tester.size_t_converter([])
1791 self.assertEqual(ac_tester.size_t_converter(), (12,))
1792
1793 def test_float_converter(self):
1794 with self.assertRaises(TypeError):
1795 ac_tester.float_converter([])
1796 self.assertEqual(ac_tester.float_converter(), (12.5,))
1797 self.assertEqual(ac_tester.float_converter(-0.5), (-0.5,))
1798
1799 def test_double_converter(self):
1800 with self.assertRaises(TypeError):
1801 ac_tester.double_converter([])
1802 self.assertEqual(ac_tester.double_converter(), (12.5,))
1803 self.assertEqual(ac_tester.double_converter(-0.5), (-0.5,))
1804
1805 def test_py_complex_converter(self):
1806 with self.assertRaises(TypeError):
1807 ac_tester.py_complex_converter([])
1808 self.assertEqual(ac_tester.py_complex_converter(complex(1, 2)), (complex(1, 2),))
1809 self.assertEqual(ac_tester.py_complex_converter(complex('-1-2j')), (complex('-1-2j'),))
1810 self.assertEqual(ac_tester.py_complex_converter(-0.5), (-0.5,))
1811 self.assertEqual(ac_tester.py_complex_converter(10), (10,))
1812
1813 def test_str_converter(self):
1814 with self.assertRaises(TypeError):
1815 ac_tester.str_converter(1)
1816 with self.assertRaises(TypeError):
1817 ac_tester.str_converter('a', 'b', 'c')
1818 with self.assertRaises(ValueError):
1819 ac_tester.str_converter('a', b'b\0b', 'c')
1820 self.assertEqual(ac_tester.str_converter('a', b'b', 'c'), ('a', 'b', 'c'))
1821 self.assertEqual(ac_tester.str_converter('a', b'b', b'c'), ('a', 'b', 'c'))
1822 self.assertEqual(ac_tester.str_converter('a', b'b', 'c\0c'), ('a', 'b', 'c\0c'))
1823
1824 def test_str_converter_encoding(self):
1825 with self.assertRaises(TypeError):
1826 ac_tester.str_converter_encoding(1)
1827 self.assertEqual(ac_tester.str_converter_encoding('a', 'b', 'c'), ('a', 'b', 'c'))
1828 with self.assertRaises(TypeError):
1829 ac_tester.str_converter_encoding('a', b'b\0b', 'c')
1830 self.assertEqual(ac_tester.str_converter_encoding('a', b'b', bytearray([ord('c')])), ('a', 'b', 'c'))
1831 self.assertEqual(ac_tester.str_converter_encoding('a', b'b', bytearray([ord('c'), 0, ord('c')])),
1832 ('a', 'b', 'c\x00c'))
1833 self.assertEqual(ac_tester.str_converter_encoding('a', b'b', b'c\x00c'), ('a', 'b', 'c\x00c'))
1834
1835 def test_py_buffer_converter(self):
1836 with self.assertRaises(TypeError):
1837 ac_tester.py_buffer_converter('a', 'b')
1838 self.assertEqual(ac_tester.py_buffer_converter('abc', bytearray([1, 2, 3])), (b'abc', b'\x01\x02\x03'))
1839
1840 def test_keywords(self):
1841 self.assertEqual(ac_tester.keywords(1, 2), (1, 2))
1842 self.assertEqual(ac_tester.keywords(1, b=2), (1, 2))
1843 self.assertEqual(ac_tester.keywords(a=1, b=2), (1, 2))
1844
1845 def test_keywords_kwonly(self):
1846 with self.assertRaises(TypeError):
1847 ac_tester.keywords_kwonly(1, 2)
1848 self.assertEqual(ac_tester.keywords_kwonly(1, b=2), (1, 2))
1849 self.assertEqual(ac_tester.keywords_kwonly(a=1, b=2), (1, 2))
1850
1851 def test_keywords_opt(self):
1852 self.assertEqual(ac_tester.keywords_opt(1), (1, None, None))
1853 self.assertEqual(ac_tester.keywords_opt(1, 2), (1, 2, None))
1854 self.assertEqual(ac_tester.keywords_opt(1, 2, 3), (1, 2, 3))
1855 self.assertEqual(ac_tester.keywords_opt(1, b=2), (1, 2, None))
1856 self.assertEqual(ac_tester.keywords_opt(1, 2, c=3), (1, 2, 3))
1857 self.assertEqual(ac_tester.keywords_opt(a=1, c=3), (1, None, 3))
1858 self.assertEqual(ac_tester.keywords_opt(a=1, b=2, c=3), (1, 2, 3))
1859
1860 def test_keywords_opt_kwonly(self):
1861 self.assertEqual(ac_tester.keywords_opt_kwonly(1), (1, None, None, None))
1862 self.assertEqual(ac_tester.keywords_opt_kwonly(1, 2), (1, 2, None, None))
1863 with self.assertRaises(TypeError):
1864 ac_tester.keywords_opt_kwonly(1, 2, 3)
1865 self.assertEqual(ac_tester.keywords_opt_kwonly(1, b=2), (1, 2, None, None))
1866 self.assertEqual(ac_tester.keywords_opt_kwonly(1, 2, c=3), (1, 2, 3, None))
1867 self.assertEqual(ac_tester.keywords_opt_kwonly(a=1, c=3), (1, None, 3, None))
1868 self.assertEqual(ac_tester.keywords_opt_kwonly(a=1, b=2, c=3, d=4), (1, 2, 3, 4))
1869
1870 def test_keywords_kwonly_opt(self):
1871 self.assertEqual(ac_tester.keywords_kwonly_opt(1), (1, None, None))
1872 with self.assertRaises(TypeError):
1873 ac_tester.keywords_kwonly_opt(1, 2)
1874 self.assertEqual(ac_tester.keywords_kwonly_opt(1, b=2), (1, 2, None))
1875 self.assertEqual(ac_tester.keywords_kwonly_opt(a=1, c=3), (1, None, 3))
1876 self.assertEqual(ac_tester.keywords_kwonly_opt(a=1, b=2, c=3), (1, 2, 3))
1877
1878 def test_posonly_keywords(self):
1879 with self.assertRaises(TypeError):
1880 ac_tester.posonly_keywords(1)
1881 with self.assertRaises(TypeError):
1882 ac_tester.posonly_keywords(a=1, b=2)
1883 self.assertEqual(ac_tester.posonly_keywords(1, 2), (1, 2))
1884 self.assertEqual(ac_tester.posonly_keywords(1, b=2), (1, 2))
1885
1886 def test_posonly_kwonly(self):
1887 with self.assertRaises(TypeError):
1888 ac_tester.posonly_kwonly(1)
1889 with self.assertRaises(TypeError):
1890 ac_tester.posonly_kwonly(1, 2)
1891 with self.assertRaises(TypeError):
1892 ac_tester.posonly_kwonly(a=1, b=2)
1893 self.assertEqual(ac_tester.posonly_kwonly(1, b=2), (1, 2))
1894
1895 def test_posonly_keywords_kwonly(self):
1896 with self.assertRaises(TypeError):
1897 ac_tester.posonly_keywords_kwonly(1)
1898 with self.assertRaises(TypeError):
1899 ac_tester.posonly_keywords_kwonly(1, 2, 3)
1900 with self.assertRaises(TypeError):
1901 ac_tester.posonly_keywords_kwonly(a=1, b=2, c=3)
1902 self.assertEqual(ac_tester.posonly_keywords_kwonly(1, 2, c=3), (1, 2, 3))
1903 self.assertEqual(ac_tester.posonly_keywords_kwonly(1, b=2, c=3), (1, 2, 3))
1904
1905 def test_posonly_keywords_opt(self):
1906 with self.assertRaises(TypeError):
1907 ac_tester.posonly_keywords_opt(1)
1908 self.assertEqual(ac_tester.posonly_keywords_opt(1, 2), (1, 2, None, None))
1909 self.assertEqual(ac_tester.posonly_keywords_opt(1, 2, 3), (1, 2, 3, None))
1910 self.assertEqual(ac_tester.posonly_keywords_opt(1, 2, 3, 4), (1, 2, 3, 4))
1911 self.assertEqual(ac_tester.posonly_keywords_opt(1, b=2), (1, 2, None, None))
1912 self.assertEqual(ac_tester.posonly_keywords_opt(1, 2, c=3), (1, 2, 3, None))
1913 with self.assertRaises(TypeError):
1914 ac_tester.posonly_keywords_opt(a=1, b=2, c=3, d=4)
1915 self.assertEqual(ac_tester.posonly_keywords_opt(1, b=2, c=3, d=4), (1, 2, 3, 4))
1916
1917 def test_posonly_opt_keywords_opt(self):
1918 self.assertEqual(ac_tester.posonly_opt_keywords_opt(1), (1, None, None, None))
1919 self.assertEqual(ac_tester.posonly_opt_keywords_opt(1, 2), (1, 2, None, None))
1920 self.assertEqual(ac_tester.posonly_opt_keywords_opt(1, 2, 3), (1, 2, 3, None))
1921 self.assertEqual(ac_tester.posonly_opt_keywords_opt(1, 2, 3, 4), (1, 2, 3, 4))
1922 with self.assertRaises(TypeError):
1923 ac_tester.posonly_opt_keywords_opt(1, b=2)
1924 self.assertEqual(ac_tester.posonly_opt_keywords_opt(1, 2, c=3), (1, 2, 3, None))
1925 self.assertEqual(ac_tester.posonly_opt_keywords_opt(1, 2, c=3, d=4), (1, 2, 3, 4))
1926 with self.assertRaises(TypeError):
1927 ac_tester.posonly_opt_keywords_opt(a=1, b=2, c=3, d=4)
1928
1929 def test_posonly_kwonly_opt(self):
1930 with self.assertRaises(TypeError):
1931 ac_tester.posonly_kwonly_opt(1)
1932 with self.assertRaises(TypeError):
1933 ac_tester.posonly_kwonly_opt(1, 2)
1934 self.assertEqual(ac_tester.posonly_kwonly_opt(1, b=2), (1, 2, None, None))
1935 self.assertEqual(ac_tester.posonly_kwonly_opt(1, b=2, c=3), (1, 2, 3, None))
1936 self.assertEqual(ac_tester.posonly_kwonly_opt(1, b=2, c=3, d=4), (1, 2, 3, 4))
1937 with self.assertRaises(TypeError):
1938 ac_tester.posonly_kwonly_opt(a=1, b=2, c=3, d=4)
1939
1940 def test_posonly_opt_kwonly_opt(self):
1941 self.assertEqual(ac_tester.posonly_opt_kwonly_opt(1), (1, None, None, None))
1942 self.assertEqual(ac_tester.posonly_opt_kwonly_opt(1, 2), (1, 2, None, None))
1943 with self.assertRaises(TypeError):
1944 ac_tester.posonly_opt_kwonly_opt(1, 2, 3)
1945 with self.assertRaises(TypeError):
1946 ac_tester.posonly_opt_kwonly_opt(1, b=2)
1947 self.assertEqual(ac_tester.posonly_opt_kwonly_opt(1, 2, c=3), (1, 2, 3, None))
1948 self.assertEqual(ac_tester.posonly_opt_kwonly_opt(1, 2, c=3, d=4), (1, 2, 3, 4))
1949
1950 def test_posonly_keywords_kwonly_opt(self):
1951 with self.assertRaises(TypeError):
1952 ac_tester.posonly_keywords_kwonly_opt(1)
1953 with self.assertRaises(TypeError):
1954 ac_tester.posonly_keywords_kwonly_opt(1, 2)
1955 with self.assertRaises(TypeError):
1956 ac_tester.posonly_keywords_kwonly_opt(1, b=2)
1957 with self.assertRaises(TypeError):
1958 ac_tester.posonly_keywords_kwonly_opt(1, 2, 3)
1959 with self.assertRaises(TypeError):
1960 ac_tester.posonly_keywords_kwonly_opt(a=1, b=2, c=3)
1961 self.assertEqual(ac_tester.posonly_keywords_kwonly_opt(1, 2, c=3), (1, 2, 3, None, None))
1962 self.assertEqual(ac_tester.posonly_keywords_kwonly_opt(1, b=2, c=3), (1, 2, 3, None, None))
1963 self.assertEqual(ac_tester.posonly_keywords_kwonly_opt(1, 2, c=3, d=4), (1, 2, 3, 4, None))
1964 self.assertEqual(ac_tester.posonly_keywords_kwonly_opt(1, 2, c=3, d=4, e=5), (1, 2, 3, 4, 5))
1965
1966 def test_posonly_keywords_opt_kwonly_opt(self):
1967 with self.assertRaises(TypeError):
1968 ac_tester.posonly_keywords_opt_kwonly_opt(1)
1969 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, 2), (1, 2, None, None, None))
1970 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, b=2), (1, 2, None, None, None))
1971 with self.assertRaises(TypeError):
1972 ac_tester.posonly_keywords_opt_kwonly_opt(1, 2, 3, 4)
1973 with self.assertRaises(TypeError):
1974 ac_tester.posonly_keywords_opt_kwonly_opt(a=1, b=2)
1975 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, 2, c=3), (1, 2, 3, None, None))
1976 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, b=2, c=3), (1, 2, 3, None, None))
1977 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, 2, 3, d=4), (1, 2, 3, 4, None))
1978 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, 2, c=3, d=4), (1, 2, 3, 4, None))
1979 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, 2, 3, d=4, e=5), (1, 2, 3, 4, 5))
1980 self.assertEqual(ac_tester.posonly_keywords_opt_kwonly_opt(1, 2, c=3, d=4, e=5), (1, 2, 3, 4, 5))
1981
1982 def test_posonly_opt_keywords_opt_kwonly_opt(self):
1983 self.assertEqual(ac_tester.posonly_opt_keywords_opt_kwonly_opt(1), (1, None, None, None))
1984 self.assertEqual(ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, 2), (1, 2, None, None))
1985 with self.assertRaises(TypeError):
1986 ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, b=2)
1987 self.assertEqual(ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, 2, 3), (1, 2, 3, None))
1988 self.assertEqual(ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, 2, c=3), (1, 2, 3, None))
1989 self.assertEqual(ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, 2, 3, d=4), (1, 2, 3, 4))
1990 self.assertEqual(ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, 2, c=3, d=4), (1, 2, 3, 4))
1991 with self.assertRaises(TypeError):
1992 ac_tester.posonly_opt_keywords_opt_kwonly_opt(1, 2, 3, 4)
1993
1994 def test_keyword_only_parameter(self):
1995 with self.assertRaises(TypeError):
1996 ac_tester.keyword_only_parameter()
1997 with self.assertRaises(TypeError):
1998 ac_tester.keyword_only_parameter(1)
1999 self.assertEqual(ac_tester.keyword_only_parameter(a=1), (1,))
2000
2001 def test_posonly_vararg(self):
2002 with self.assertRaises(TypeError):
2003 ac_tester.posonly_vararg()
2004 self.assertEqual(ac_tester.posonly_vararg(1, 2), (1, 2, ()))
2005 self.assertEqual(ac_tester.posonly_vararg(1, b=2), (1, 2, ()))
2006 self.assertEqual(ac_tester.posonly_vararg(1, 2, 3, 4), (1, 2, (3, 4)))
2007
2008 def test_vararg_and_posonly(self):
2009 with self.assertRaises(TypeError):
2010 ac_tester.vararg_and_posonly()
2011 with self.assertRaises(TypeError):
2012 ac_tester.vararg_and_posonly(1, b=2)
2013 self.assertEqual(ac_tester.vararg_and_posonly(1, 2, 3, 4), (1, (2, 3, 4)))
2014
2015 def test_vararg(self):
2016 with self.assertRaises(TypeError):
2017 ac_tester.vararg()
2018 with self.assertRaises(TypeError):
2019 ac_tester.vararg(1, b=2)
2020 self.assertEqual(ac_tester.vararg(1, 2, 3, 4), (1, (2, 3, 4)))
2021
2022 def test_vararg_with_default(self):
2023 with self.assertRaises(TypeError):
2024 ac_tester.vararg_with_default()
2025 self.assertEqual(ac_tester.vararg_with_default(1, b=False), (1, (), False))
2026 self.assertEqual(ac_tester.vararg_with_default(1, 2, 3, 4), (1, (2, 3, 4), False))
2027 self.assertEqual(ac_tester.vararg_with_default(1, 2, 3, 4, b=True), (1, (2, 3, 4), True))
2028
2029 def test_vararg_with_only_defaults(self):
2030 self.assertEqual(ac_tester.vararg_with_only_defaults(), ((), None))
2031 self.assertEqual(ac_tester.vararg_with_only_defaults(b=2), ((), 2))
2032 self.assertEqual(ac_tester.vararg_with_only_defaults(1, b=2), ((1, ), 2))
2033 self.assertEqual(ac_tester.vararg_with_only_defaults(1, 2, 3, 4), ((1, 2, 3, 4), None))
2034 self.assertEqual(ac_tester.vararg_with_only_defaults(1, 2, 3, 4, b=5), ((1, 2, 3, 4), 5))
2035
2036 def test_gh_32092_oob(self):
2037 ac_tester.gh_32092_oob(1, 2, 3, 4, kw1=5, kw2=6)
2038
2039 def test_gh_32092_kw_pass(self):
2040 ac_tester.gh_32092_kw_pass(1, 2, 3)
2041
2042 def test_gh_99233_refcount(self):
2043 arg = '*A unique string is not referenced by anywhere else.*'
2044 arg_refcount_origin = sys.getrefcount(arg)
2045 ac_tester.gh_99233_refcount(arg)
2046 arg_refcount_after = sys.getrefcount(arg)
2047 self.assertEqual(arg_refcount_origin, arg_refcount_after)
2048
2049 def test_gh_99240_double_free(self):
2050 expected_error = r'gh_99240_double_free\(\) argument 2 must be encoded string without null bytes, not str'
2051 with self.assertRaisesRegex(TypeError, expected_error):
2052 ac_tester.gh_99240_double_free('a', '\0b')
2053
2054 def test_meth_method_no_params(self):
2055 obj = ac_tester.TestClass()
2056 meth = obj.meth_method_no_params
2057 check = partial(self.assertRaisesRegex, TypeError, "no arguments")
2058 check(meth, 1)
2059 check(meth, a=1)
2060
2061 def test_meth_method_no_params_capi(self):
2062 from _testcapi import pyobject_vectorcall
2063 obj = ac_tester.TestClass()
2064 meth = obj.meth_method_no_params
2065 pyobject_vectorcall(meth, None, None)
2066 pyobject_vectorcall(meth, (), None)
2067 pyobject_vectorcall(meth, (), ())
2068 pyobject_vectorcall(meth, None, ())
2069
2070 check = partial(self.assertRaisesRegex, TypeError, "no arguments")
2071 check(pyobject_vectorcall, meth, (1,), None)
2072 check(pyobject_vectorcall, meth, (1,), ("a",))
2073
2074
2075 class PermutationTests(unittest.TestCase):
2076 """Test permutation support functions."""
2077
2078 def test_permute_left_option_groups(self):
2079 expected = (
2080 (),
2081 (3,),
2082 (2, 3),
2083 (1, 2, 3),
2084 )
2085 data = list(zip([1, 2, 3])) # Generate a list of 1-tuples.
2086 actual = tuple(clinic.permute_left_option_groups(data))
2087 self.assertEqual(actual, expected)
2088
2089 def test_permute_right_option_groups(self):
2090 expected = (
2091 (),
2092 (1,),
2093 (1, 2),
2094 (1, 2, 3),
2095 )
2096 data = list(zip([1, 2, 3])) # Generate a list of 1-tuples.
2097 actual = tuple(clinic.permute_right_option_groups(data))
2098 self.assertEqual(actual, expected)
2099
2100 def test_permute_optional_groups(self):
2101 empty = {
2102 "left": (), "required": (), "right": (),
2103 "expected": ((),),
2104 }
2105 noleft1 = {
2106 "left": (), "required": ("b",), "right": ("c",),
2107 "expected": (
2108 ("b",),
2109 ("b", "c"),
2110 ),
2111 }
2112 noleft2 = {
2113 "left": (), "required": ("b", "c",), "right": ("d",),
2114 "expected": (
2115 ("b", "c"),
2116 ("b", "c", "d"),
2117 ),
2118 }
2119 noleft3 = {
2120 "left": (), "required": ("b", "c",), "right": ("d", "e"),
2121 "expected": (
2122 ("b", "c"),
2123 ("b", "c", "d"),
2124 ("b", "c", "d", "e"),
2125 ),
2126 }
2127 noright1 = {
2128 "left": ("a",), "required": ("b",), "right": (),
2129 "expected": (
2130 ("b",),
2131 ("a", "b"),
2132 ),
2133 }
2134 noright2 = {
2135 "left": ("a",), "required": ("b", "c"), "right": (),
2136 "expected": (
2137 ("b", "c"),
2138 ("a", "b", "c"),
2139 ),
2140 }
2141 noright3 = {
2142 "left": ("a", "b"), "required": ("c",), "right": (),
2143 "expected": (
2144 ("c",),
2145 ("b", "c"),
2146 ("a", "b", "c"),
2147 ),
2148 }
2149 leftandright1 = {
2150 "left": ("a",), "required": ("b",), "right": ("c",),
2151 "expected": (
2152 ("b",),
2153 ("a", "b"), # Prefer left.
2154 ("a", "b", "c"),
2155 ),
2156 }
2157 leftandright2 = {
2158 "left": ("a", "b"), "required": ("c", "d"), "right": ("e", "f"),
2159 "expected": (
2160 ("c", "d"),
2161 ("b", "c", "d"), # Prefer left.
2162 ("a", "b", "c", "d"), # Prefer left.
2163 ("a", "b", "c", "d", "e"),
2164 ("a", "b", "c", "d", "e", "f"),
2165 ),
2166 }
2167 dataset = (
2168 empty,
2169 noleft1, noleft2, noleft3,
2170 noright1, noright2, noright3,
2171 leftandright1, leftandright2,
2172 )
2173 for params in dataset:
2174 with self.subTest(**params):
2175 left, required, right, expected = params.values()
2176 permutations = clinic.permute_optional_groups(left, required, right)
2177 actual = tuple(permutations)
2178 self.assertEqual(actual, expected)
2179
2180
2181 if __name__ == "__main__":
2182 unittest.main()