Best Python code snippet using slash
test_diff_parser.py
Source:test_diff_parser.py
...99 assert m.end_pos == (3, 1)100 m = differ.parse('a ', parsers=1)101 assert m.end_pos == (1, 2)102def test_if_simple(differ):103 src = dedent('''\104 if 1:105 a = 3106 ''')107 else_ = "else:\n a = ''\n"108 differ.initialize(src + 'a')109 differ.parse(src + else_ + "a", copies=0, parsers=1)110 differ.parse(else_, parsers=2, expect_error_leaves=True)111 differ.parse(src + else_, parsers=1)112def test_func_with_for_and_comment(differ):113 # The first newline is important, leave it. It should not trigger another114 # parser split.115 src = dedent("""\116 def func():117 pass118 for a in [1]:119 # COMMENT120 a""")121 differ.initialize(src)122 differ.parse('a\n' + src, copies=1, parsers=3)123def test_one_statement_func(differ):124 src = dedent("""\125 first126 def func(): a127 """)128 differ.initialize(src + 'second')129 differ.parse(src + 'def second():\n a', parsers=1, copies=1)130def test_for_on_one_line(differ):131 src = dedent("""\132 foo = 1133 for x in foo: pass134 def hi():135 pass136 """)137 differ.initialize(src)138 src = dedent("""\139 def hi():140 for x in foo: pass141 pass142 pass143 """)144 differ.parse(src, parsers=2)145 src = dedent("""\146 def hi():147 for x in foo: pass148 pass149 def nested():150 pass151 """)152 # The second parser is for parsing the `def nested()` which is an `equal`153 # operation in the SequenceMatcher.154 differ.parse(src, parsers=1, copies=1)155def test_open_parentheses(differ):156 func = 'def func():\n a\n'157 code = 'isinstance(\n\n' + func158 new_code = 'isinstance(\n' + func159 differ.initialize(code)160 differ.parse(new_code, parsers=1, expect_error_leaves=True)161 new_code = 'a = 1\n' + new_code162 differ.parse(new_code, parsers=2, expect_error_leaves=True)163 func += 'def other_func():\n pass\n'164 differ.initialize('isinstance(\n' + func)165 # Cannot copy all, because the prefix of the function is once a newline and166 # once not.167 differ.parse('isinstance()\n' + func, parsers=2, copies=1)168def test_open_parentheses_at_end(differ):169 code = "a['"170 differ.initialize(code)171 differ.parse(code, parsers=1, expect_error_leaves=True)172def test_backslash(differ):173 src = dedent(r"""174 a = 1\175 if 1 else 2176 def x():177 pass178 """)179 differ.initialize(src)180 src = dedent(r"""181 def x():182 a = 1\183 if 1 else 2184 def y():185 pass186 """)187 differ.parse(src, parsers=1)188 src = dedent(r"""189 def first():190 if foo \191 and bar \192 or baz:193 pass194 def second():195 pass196 """)197 differ.parse(src, parsers=2)198def test_full_copy(differ):199 code = 'def foo(bar, baz):\n pass\n bar'200 differ.initialize(code)201 differ.parse(code, copies=1)202def test_wrong_whitespace(differ):203 code = '''204 hello205 '''206 differ.initialize(code)207 differ.parse(code + 'bar\n ', parsers=2, expect_error_leaves=True)208 code += """abc(\npass\n """209 differ.parse(code, parsers=2, expect_error_leaves=True)210def test_issues_with_error_leaves(differ):211 code = dedent('''212 def ints():213 str..214 str215 ''')216 code2 = dedent('''217 def ints():218 str.219 str220 ''')221 differ.initialize(code)222 differ.parse(code2, parsers=1, expect_error_leaves=True)223def test_unfinished_nodes(differ):224 code = dedent('''225 class a():226 def __init__(self, a):227 self.a = a228 def p(self):229 a(1)230 ''')231 code2 = dedent('''232 class a():233 def __init__(self, a):234 self.a = a235 def p(self):236 self237 a(1)238 ''')239 differ.initialize(code)240 differ.parse(code2, parsers=2, copies=2)241def test_nested_if_and_scopes(differ):242 code = dedent('''243 class a():244 if 1:245 def b():246 2247 ''')248 code2 = code + ' else:\n 3'249 differ.initialize(code)250 differ.parse(code2, parsers=1, copies=0)251def test_word_before_def(differ):252 code1 = 'blub def x():\n'253 code2 = code1 + ' s'254 differ.initialize(code1)255 differ.parse(code2, parsers=1, copies=0, expect_error_leaves=True)256def test_classes_with_error_leaves(differ):257 code1 = dedent('''258 class X():259 def x(self):260 blablabla261 assert 3262 self.263 class Y():264 pass265 ''')266 code2 = dedent('''267 class X():268 def x(self):269 blablabla270 assert 3271 str(272 class Y():273 pass274 ''')275 differ.initialize(code1)276 differ.parse(code2, parsers=2, copies=1, expect_error_leaves=True)277def test_totally_wrong_whitespace(differ):278 code1 = '''279 class X():280 raise n281 class Y():282 pass283 '''284 code2 = '''285 class X():286 raise n287 str(288 class Y():289 pass290 '''291 differ.initialize(code1)292 differ.parse(code2, parsers=2, copies=0, expect_error_leaves=True)293def test_node_insertion(differ):294 code1 = dedent('''295 class X():296 def y(self):297 a = 1298 b = 2299 c = 3300 d = 4301 ''')302 code2 = dedent('''303 class X():304 def y(self):305 a = 1306 b = 2307 str308 c = 3309 d = 4310 ''')311 differ.initialize(code1)312 differ.parse(code2, parsers=1, copies=2)313def test_whitespace_at_end(differ):314 code = dedent('str\n\n')315 differ.initialize(code)316 differ.parse(code + '\n', parsers=1, copies=1)317def test_endless_while_loop(differ):318 """319 This was a bug in Jedi #878.320 """321 code = '#dead'322 differ.initialize(code)323 module = differ.parse(code, parsers=1)324 assert module.end_pos == (1, 5)325 code = '#dead\n'326 differ.initialize(code)327 module = differ.parse(code + '\n', parsers=1)328 assert module.end_pos == (3, 0)329def test_in_class_movements(differ):330 code1 = dedent("""\331 class PlaybookExecutor:332 p333 b334 def run(self):335 1336 try:337 x338 except:339 pass340 """)341 code2 = dedent("""\342 class PlaybookExecutor:343 b344 def run(self):345 1346 try:347 x348 except:349 pass350 """)351 differ.initialize(code1)352 differ.parse(code2, parsers=1)353def test_in_parentheses_newlines(differ):354 code1 = dedent("""355 x = str(356 True)357 a = 1358 def foo():359 pass360 b = 2""")361 code2 = dedent("""362 x = str(True)363 a = 1364 def foo():365 pass366 b = 2""")367 differ.initialize(code1)368 differ.parse(code2, parsers=1, copies=1)369def test_indentation_issue(differ):370 code1 = dedent("""371 import module372 """)373 code2 = dedent("""374 class L1:375 class L2:376 class L3:377 def f(): pass378 def f(): pass379 def f(): pass380 def f(): pass381 """)382 differ.initialize(code1)383 differ.parse(code2, parsers=2)384def test_endmarker_newline(differ):385 code1 = dedent('''\386 docu = None387 # some comment388 result = codet389 incomplete_dctassign = {390 "module"391 if "a":392 x = 3 # asdf393 ''')394 code2 = code1.replace('codet', 'coded')395 differ.initialize(code1)396 differ.parse(code2, parsers=2, copies=1, expect_error_leaves=True)397def test_newlines_at_end(differ):398 differ.initialize('a\n\n')399 differ.parse('a\n', copies=1)400def test_end_newline_with_decorator(differ):401 code = dedent('''\402 @staticmethod403 def spam():404 import json405 json.l''')406 differ.initialize(code)407 module = differ.parse(code + '\n', copies=1, parsers=1)408 decorated, endmarker = module.children409 assert decorated.type == 'decorated'410 decorator, func = decorated.children411 suite = func.children[-1]412 assert suite.type == 'suite'413 newline, first_stmt, second_stmt = suite.children414 assert first_stmt.get_code() == ' import json\n'415 assert second_stmt.get_code() == ' json.l\n'416def test_invalid_to_valid_nodes(differ):417 code1 = dedent('''\418 def a():419 foo = 3420 def b():421 la = 3422 else:423 la424 return425 foo426 base427 ''')428 code2 = dedent('''\429 def a():430 foo = 3431 def b():432 la = 3433 if foo:434 latte = 3435 else:436 la437 return438 foo439 base440 ''')441 differ.initialize(code1)442 differ.parse(code2, parsers=1, copies=3)443def test_if_removal_and_reappearence(differ):444 code1 = dedent('''\445 la = 3446 if foo:447 latte = 3448 else:449 la450 pass451 ''')452 code2 = dedent('''\453 la = 3454 latte = 3455 else:456 la457 pass458 ''')459 code3 = dedent('''\460 la = 3461 if foo:462 latte = 3463 else:464 la465 ''')466 differ.initialize(code1)467 differ.parse(code2, parsers=3, copies=2, expect_error_leaves=True)468 differ.parse(code1, parsers=1, copies=1)469 differ.parse(code3, parsers=1, copies=1)470def test_add_error_indentation(differ):471 code = 'if x:\n 1\n'472 differ.initialize(code)473 differ.parse(code + ' 2\n', parsers=1, copies=0, expect_error_leaves=True)474def test_differing_docstrings(differ):475 code1 = dedent('''\476 def foobar(x, y):477 1478 return x479 def bazbiz():480 foobar()481 lala482 ''')483 code2 = dedent('''\484 def foobar(x, y):485 2486 return x + y487 def bazbiz():488 z = foobar()489 lala490 ''')491 differ.initialize(code1)492 differ.parse(code2, parsers=2, copies=1)493 differ.parse(code1, parsers=2, copies=1)494def test_one_call_in_function_change(differ):495 code1 = dedent('''\496 def f(self):497 mro = [self]498 for a in something:499 yield a500 def g(self):501 return C(502 a=str,503 b=self,504 )505 ''')506 code2 = dedent('''\507 def f(self):508 mro = [self]509 def g(self):510 return C(511 a=str,512 t513 b=self,514 )515 ''')516 differ.initialize(code1)517 differ.parse(code2, parsers=2, copies=1, expect_error_leaves=True)518 differ.parse(code1, parsers=2, copies=1)519def test_function_deletion(differ):520 code1 = dedent('''\521 class C(list):522 def f(self):523 def iterate():524 for x in b:525 break526 return list(iterate())527 ''')528 code2 = dedent('''\529 class C():530 def f(self):531 for x in b:532 break533 return list(iterate())534 ''')535 differ.initialize(code1)536 differ.parse(code2, parsers=1, copies=0, expect_error_leaves=True)537 differ.parse(code1, parsers=1, copies=0)538def test_docstring_removal(differ):539 code1 = dedent('''\540 class E(Exception):541 """542 1543 2544 3545 """546 class S(object):547 @property548 def f(self):549 return cmd550 def __repr__(self):551 return cmd2552 ''')553 code2 = dedent('''\554 class E(Exception):555 """556 1557 3558 """559 class S(object):560 @property561 def f(self):562 return cmd563 return cmd2564 ''')565 differ.initialize(code1)566 differ.parse(code2, parsers=1, copies=2)567 differ.parse(code1, parsers=3, copies=1)568def test_paren_in_strange_position(differ):569 code1 = dedent('''\570 class C:571 """ ha """572 def __init__(self, message):573 self.message = message574 ''')575 code2 = dedent('''\576 class C:577 """ ha """578 )579 def __init__(self, message):580 self.message = message581 ''')582 differ.initialize(code1)583 differ.parse(code2, parsers=1, copies=2, expect_error_leaves=True)584 differ.parse(code1, parsers=0, copies=2)585def insert_line_into_code(code, index, line):586 lines = split_lines(code, keepends=True)587 lines.insert(index, line)588 return ''.join(lines)589def test_paren_before_docstring(differ):590 code1 = dedent('''\591 # comment592 """593 The594 """595 from parso import tree596 from parso import python597 ''')598 code2 = insert_line_into_code(code1, 1, ' ' * 16 + 'raise InternalParseError(\n')599 differ.initialize(code1)600 differ.parse(code2, parsers=1, copies=1, expect_error_leaves=True)601 differ.parse(code1, parsers=2, copies=1)602def test_parentheses_before_method(differ):603 code1 = dedent('''\604 class A:605 def a(self):606 pass607 class B:608 def b(self):609 if 1:610 pass611 ''')612 code2 = dedent('''\613 class A:614 def a(self):615 pass616 Exception.__init__(self, "x" %617 def b(self):618 if 1:619 pass620 ''')621 differ.initialize(code1)622 differ.parse(code2, parsers=2, copies=1, expect_error_leaves=True)623 differ.parse(code1, parsers=2, copies=1)624def test_indentation_issues(differ):625 code1 = dedent('''\626 class C:627 def f():628 1629 if 2:630 return 3631 def g():632 to_be_removed633 pass634 ''')635 code2 = dedent('''\636 class C:637 def f():638 1639 ``something``, very ``weird``).640 if 2:641 return 3642 def g():643 to_be_removed644 pass645 ''')646 code3 = dedent('''\647 class C:648 def f():649 1650 if 2:651 return 3652 def g():653 pass654 ''')655 differ.initialize(code1)656 differ.parse(code2, parsers=3, copies=1, expect_error_leaves=True)657 differ.parse(code1, copies=1, parsers=2)658 differ.parse(code3, parsers=2, copies=1)659 differ.parse(code1, parsers=2, copies=1)660def test_error_dedent_issues(differ):661 code1 = dedent('''\662 while True:663 try:664 1665 except KeyError:666 if 2:667 3668 except IndexError:669 4670 5671 ''')672 code2 = dedent('''\673 while True:674 try:675 except KeyError:676 1677 except KeyError:678 if 2:679 3680 except IndexError:681 4682 something_inserted683 5684 ''')685 differ.initialize(code1)686 differ.parse(code2, parsers=3, copies=0, expect_error_leaves=True)687 differ.parse(code1, parsers=1, copies=0)688def test_random_text_insertion(differ):689 code1 = dedent('''\690class C:691 def f():692 return node693 def g():694 try:695 1696 except KeyError:697 2698 ''')699 code2 = dedent('''\700class C:701 def f():702 return node703Some'random text: yeah704 for push in plan.dfa_pushes:705 def g():706 try:707 1708 except KeyError:709 2710 ''')711 differ.initialize(code1)712 differ.parse(code2, parsers=2, copies=1, expect_error_leaves=True)713 differ.parse(code1, parsers=2, copies=1)714def test_many_nested_ifs(differ):715 code1 = dedent('''\716 class C:717 def f(self):718 def iterate():719 if 1:720 yield t721 else:722 yield723 return724 def g():725 3726 ''')727 code2 = dedent('''\728 def f(self):729 def iterate():730 if 1:731 yield t732 hahahaha733 if 2:734 else:735 yield736 return737 def g():738 3739 ''')740 differ.initialize(code1)741 differ.parse(code2, parsers=2, copies=1, expect_error_leaves=True)742 differ.parse(code1, parsers=1, copies=1)743@pytest.mark.parametrize('prefix', ['', 'async '])744def test_with_and_funcdef_in_call(differ, prefix):745 code1 = prefix + dedent('''\746 with x:747 la = C(748 a=1,749 b=2,750 c=3,751 )752 ''')753 code2 = insert_line_into_code(code1, 3, 'def y(self, args):\n')754 differ.initialize(code1)755 differ.parse(code2, parsers=1, expect_error_leaves=True)756 differ.parse(code1, parsers=1)757def test_wrong_backslash(differ):758 code1 = dedent('''\759 def y():760 1761 for x in y:762 continue763 ''')764 code2 = insert_line_into_code(code1, 3, '\\.whl$\n')765 differ.initialize(code1)766 differ.parse(code2, parsers=3, copies=1, expect_error_leaves=True)767 differ.parse(code1, parsers=1, copies=1)768def test_random_unicode_characters(differ):769 """770 Those issues were all found with the fuzzer.771 """772 differ.initialize('')773 differ.parse('\x1dÄBÏÉËÅÊ˳˻ȣſéÃ\x90ÌÈòwÊ\x1dÄBÏÉËÅÊ˳˻ȣſéÃ', parsers=1,774 expect_error_leaves=True)775 differ.parse('\r\r', parsers=1)776 differ.parse("ËÄ\x05Ã\r rúƣ@\x8a\x15r()\n", parsers=1, expect_error_leaves=True)777 differ.parse('a\ntaÇ\rGÄÅns__\n\nb', parsers=1)778 s = ' if not (self, "_fi\x02\x0e\x08\n\nle"):'779 differ.parse(s, parsers=1, expect_error_leaves=True)780 differ.parse('')781 differ.parse(s + '\n', parsers=1, expect_error_leaves=True)782 differ.parse(' result = (\r\f\x17\t\x11res)', parsers=1, expect_error_leaves=True)783 differ.parse('')784 differ.parse(' a( # xx\ndef', parsers=1, expect_error_leaves=True)785def test_dedent_end_positions(differ):786 code1 = dedent('''\787 if 1:788 if b:789 2790 c = {791 5}792 ''')793 code2 = dedent('''\794 if 1:795 if âà´áྡྷá¹b:796 2797 'l': ''}798 c = {799 5}800 ''')801 differ.initialize(code1)802 differ.parse(code2, parsers=1, expect_error_leaves=True)803 differ.parse(code1, parsers=1)804def test_special_no_newline_ending(differ):805 code1 = dedent('''\806 1807 ''')808 code2 = dedent('''\809 1810 is ''')811 differ.initialize(code1)812 differ.parse(code2, copies=1, parsers=1, expect_error_leaves=True)813 differ.parse(code1, copies=1, parsers=0)814def test_random_character_insertion(differ):815 code1 = dedent('''\816 def create(self):817 1818 if self.path is not None:819 return820 # 3821 # 4822 ''')823 code2 = dedent('''\824 def create(self):825 1826 if 2:827 x return828 # 3829 # 4830 ''')831 differ.initialize(code1)832 differ.parse(code2, copies=1, parsers=1, expect_error_leaves=True)833 differ.parse(code1, copies=1, parsers=1)834def test_import_opening_bracket(differ):835 code1 = dedent('''\836 1837 2838 from bubu import (X,839 ''')840 code2 = dedent('''\841 11842 2843 from bubu import (X,844 ''')845 differ.initialize(code1)846 differ.parse(code2, copies=1, parsers=2, expect_error_leaves=True)847 differ.parse(code1, copies=1, parsers=2, expect_error_leaves=True)848def test_opening_bracket_at_end(differ):849 code1 = dedent('''\850 class C:851 1852 [853 ''')854 code2 = dedent('''\855 3856 class C:857 1858 [859 ''')860 differ.initialize(code1)861 differ.parse(code2, copies=1, parsers=2, expect_error_leaves=True)862 differ.parse(code1, copies=1, parsers=1, expect_error_leaves=True)863def test_all_sorts_of_indentation(differ):864 code1 = dedent('''\865 class C:866 1867 def f():868 'same'869 if foo:870 a = b871 end872 ''')873 code2 = dedent('''\874 class C:875 1876 def f(yield await %|(877 'same'878 \x02\x06\x0f\x1c\x11879 if foo:880 a = b881 end882 ''')883 differ.initialize(code1)884 differ.parse(code2, copies=1, parsers=1, expect_error_leaves=True)885 differ.parse(code1, copies=1, parsers=1, expect_error_leaves=True)886 code3 = dedent('''\887 if 1:888 a889 b890 c891 d892 \x00893 ''')894 differ.parse(code3, parsers=1, expect_error_leaves=True)895 differ.parse('')896def test_dont_copy_dedents_in_beginning(differ):897 code1 = dedent('''\898 a899 4900 ''')901 code2 = dedent('''\902 1903 2904 3905 4906 ''')907 differ.initialize(code1)908 differ.parse(code2, copies=1, parsers=1, expect_error_leaves=True)909 differ.parse(code1, parsers=1, copies=1)910def test_dont_copy_error_leaves(differ):911 code1 = dedent('''\912 def f(n):913 x914 if 2:915 3916 ''')917 code2 = dedent('''\918 def f(n):919 def if 1:920 indent921 x922 if 2:923 3924 ''')925 differ.initialize(code1)926 differ.parse(code2, parsers=1, expect_error_leaves=True)927 differ.parse(code1, parsers=1)928def test_error_dedent_in_between(differ):929 code1 = dedent('''\930 class C:931 def f():932 a933 if something:934 x935 z936 ''')937 code2 = dedent('''\938 class C:939 def f():940 a941 dedent942 if other_thing:943 b944 if something:945 x946 z947 ''')948 differ.initialize(code1)949 differ.parse(code2, copies=1, parsers=2, expect_error_leaves=True)950 differ.parse(code1, copies=1, parsers=2)951def test_some_other_indentation_issues(differ):952 code1 = dedent('''\953 class C:954 x955 def f():956 ""957 copied958 a959 ''')960 code2 = dedent('''\961 try:962 de963 a964 b965 c966 d967 def f():968 ""969 copied970 a971 ''')972 differ.initialize(code1)973 differ.parse(code2, copies=0, parsers=1, expect_error_leaves=True)974 differ.parse(code1, copies=1, parsers=1)975def test_open_bracket_case1(differ):976 code1 = dedent('''\977 class C:978 1979 2 # ha980 ''')981 code2 = insert_line_into_code(code1, 2, ' [str\n')982 code3 = insert_line_into_code(code2, 4, ' str\n')983 differ.initialize(code1)984 differ.parse(code2, copies=1, parsers=1, expect_error_leaves=True)985 differ.parse(code3, copies=1, parsers=1, expect_error_leaves=True)986 differ.parse(code1, copies=1, parsers=1)987def test_open_bracket_case2(differ):988 code1 = dedent('''\989 class C:990 def f(self):991 (992 b993 c994 def g(self):995 d996 ''')997 code2 = dedent('''\998 class C:999 def f(self):1000 (1001 b1002 c1003 self.1004 def g(self):1005 d1006 ''')1007 differ.initialize(code1)1008 differ.parse(code2, copies=0, parsers=1, expect_error_leaves=True)1009 differ.parse(code1, copies=0, parsers=1, expect_error_leaves=True)1010def test_some_weird_removals(differ):1011 code1 = dedent('''\1012 class C:1013 11014 ''')1015 code2 = dedent('''\1016 class C:1017 11018 @property1019 A1020 return1021 # x1022 omega1023 ''')1024 code3 = dedent('''\1025 class C:1026 11027 ;1028 omega1029 ''')1030 differ.initialize(code1)1031 differ.parse(code2, copies=1, parsers=1, expect_error_leaves=True)1032 differ.parse(code3, copies=1, parsers=3, expect_error_leaves=True)1033 differ.parse(code1, copies=1)1034def test_async_copy(differ):1035 code1 = dedent('''\1036 async def main():1037 x = 31038 print(1039 ''')1040 code2 = dedent('''\1041 async def main():1042 x = 31043 print()1044 ''')1045 differ.initialize(code1)1046 differ.parse(code2, copies=1, parsers=1)1047 differ.parse(code1, copies=1, parsers=1, expect_error_leaves=True)1048def test_parent_on_decorator(differ):1049 code1 = dedent('''\1050 class AClass:1051 @decorator()1052 def b_test(self):1053 print("Hello")1054 print("world")1055 def a_test(self):1056 pass''')1057 code2 = dedent('''\1058 class AClass:1059 @decorator()1060 def b_test(self):1061 print("Hello")1062 print("world")1063 def a_test(self):1064 pass''')1065 differ.initialize(code1)1066 module_node = differ.parse(code2, parsers=1)1067 cls = module_node.children[0]1068 cls_suite = cls.children[-1]1069 assert len(cls_suite.children) == 31070def test_wrong_indent_in_def(differ):1071 code1 = dedent('''\1072 def x():1073 a1074 b1075 ''')1076 code2 = dedent('''\1077 def x():1078 //1079 b1080 c1081 ''')1082 differ.initialize(code1)1083 differ.parse(code2, parsers=1, expect_error_leaves=True)1084 differ.parse(code1, parsers=1)1085def test_backslash_issue(differ):1086 code1 = dedent('''1087 pre = (1088 '')1089 after = 'instead'1090 ''')1091 code2 = dedent('''1092 pre = (1093 '')1094 \\if 1095 ''') # noqa1096 differ.initialize(code1)1097 differ.parse(code2, parsers=1, copies=1, expect_error_leaves=True)1098 differ.parse(code1, parsers=1, copies=1)1099def test_paren_with_indentation(differ):1100 code1 = dedent('''1101 class C:1102 def f(self, fullname, path=None):1103 x1104 def load_module(self, fullname):1105 a1106 for prefix in self.search_path:1107 try:1108 b1109 except ImportError:1110 c1111 else:1112 raise1113 def x():1114 pass1115 ''')1116 code2 = dedent('''1117 class C:1118 def f(self, fullname, path=None):1119 x1120 (1121 a1122 for prefix in self.search_path:1123 try:1124 b1125 except ImportError:1126 c1127 else:1128 raise1129 ''')1130 differ.initialize(code1)1131 differ.parse(code2, parsers=1, copies=1, expect_error_leaves=True)1132 differ.parse(code1, parsers=3, copies=1)1133def test_error_dedent_in_function(differ):1134 code1 = dedent('''\1135 def x():1136 a1137 b1138 c1139 d1140 ''')1141 code2 = dedent('''\1142 def x():1143 a1144 b1145 c1146 d1147 e1148 ''')1149 differ.initialize(code1)1150 differ.parse(code2, parsers=2, copies=1, expect_error_leaves=True)1151def test_with_formfeed(differ):1152 code1 = dedent('''\1153 @bla1154 async def foo():1155 11156 yield from []1157 return1158 return ''1159 ''')1160 code2 = dedent('''\1161 @bla1162 async def foo():1163 11164 \x0cimport 1165 return1166 return ''1167 ''') # noqa1168 differ.initialize(code1)1169 differ.parse(code2, parsers=ANY, copies=ANY, expect_error_leaves=True)1170def test_repeating_invalid_indent(differ):1171 code1 = dedent('''\1172 def foo():1173 return1174 @bla1175 a1176 def foo():1177 a1178 b1179 c1180 ''')1181 code2 = dedent('''\1182 def foo():1183 return1184 @bla1185 a1186 b1187 c1188 ''')1189 differ.initialize(code1)1190 differ.parse(code2, parsers=2, copies=1, expect_error_leaves=True)1191def test_another_random_indent(differ):1192 code1 = dedent('''\1193 def foo():1194 a1195 b1196 c1197 return1198 def foo():1199 d1200 ''')1201 code2 = dedent('''\1202 def foo():1203 a1204 c1205 return1206 def foo():1207 d1208 ''')1209 differ.initialize(code1)1210 differ.parse(code2, parsers=1, copies=3)1211def test_invalid_function(differ):1212 code1 = dedent('''\1213 a1214 def foo():1215 def foo():1216 b1217 ''')1218 code2 = dedent('''\1219 a1220 def foo():1221 def foo():1222 b1223 ''')1224 differ.initialize(code1)1225 differ.parse(code2, parsers=1, copies=1, expect_error_leaves=True)1226def test_async_func2(differ):1227 code1 = dedent('''\1228 async def foo():1229 return ''1230 @bla1231 async def foo():1232 x1233 ''')1234 code2 = dedent('''\1235 async def foo():1236 return ''1237 {1238 @bla1239 async def foo():1240 x1241 y1242 ''')1243 differ.initialize(code1)1244 differ.parse(code2, parsers=ANY, copies=ANY, expect_error_leaves=True)1245def test_weird_ending(differ):1246 code1 = dedent('''\1247 def foo():1248 a1249 return1250 ''')1251 code2 = dedent('''\1252 def foo():1253 a1254 nonlocal xF"""1255 y"""''')1256 differ.initialize(code1)1257 differ.parse(code2, parsers=1, copies=1, expect_error_leaves=True)1258def test_nested_class(differ):1259 code1 = dedent('''\1260def c():1261 a = 31262 class X:1263 b1264 ''')1265 code2 = dedent('''\1266def c():1267 a = 31268 class X:1269 elif1270 ''')1271 differ.initialize(code1)1272 differ.parse(code2, parsers=1, copies=1, expect_error_leaves=True)1273def test_class_with_paren_breaker(differ):1274 code1 = dedent('''\1275class Grammar:1276 x1277 def parse():1278 y1279 parser(1280 )1281 z1282 ''')1283 code2 = dedent('''\1284class Grammar:1285 x1286 def parse():1287 y1288 parser(1289 finally ;1290 )1291 z1292 ''')1293 differ.initialize(code1)1294 differ.parse(code2, parsers=3, copies=1, expect_error_leaves=True)1295def test_byte_order_mark(differ):1296 code2 = dedent('''\1297 x1298 \ufeff1299 else :1300 ''')1301 differ.initialize('\n')1302 differ.parse(code2, parsers=2, expect_error_leaves=True)1303 code3 = dedent('''\1304 \ufeff1305 if:1306 x1307 ''')1308 differ.initialize('\n')1309 differ.parse(code3, parsers=2, expect_error_leaves=True)1310def test_byte_order_mark2(differ):1311 code = '\ufeff# foo'1312 differ.initialize(code)1313 differ.parse(code + 'x', parsers=ANY)1314def test_byte_order_mark3(differ):1315 code1 = "\ufeff#\ny\n"1316 code2 = 'x\n\ufeff#\n\ufeff#\ny\n'1317 differ.initialize(code1)1318 differ.parse(code2, expect_error_leaves=True, parsers=ANY, copies=ANY)1319 differ.parse(code1, parsers=1)1320def test_backslash_insertion(differ):1321 code1 = dedent('''1322 def f():1323 x1324 def g():1325 base = "" \\1326 ""1327 return1328 ''')1329 code2 = dedent('''1330 def f():1331 x1332 def g():1333 base = "" \\1334 def h():1335 ""1336 return1337 ''')1338 differ.initialize(code1)1339 differ.parse(code2, parsers=2, copies=1, expect_error_leaves=True)1340 differ.parse(code1, parsers=2, copies=1)1341def test_fstring_with_error_leaf(differ):1342 code1 = dedent("""\1343 def f():1344 x1345 def g():1346 y1347 """)1348 code2 = dedent("""\1349 def f():1350 x1351 F'''1352 def g():1353 y1354 {a1355 \x011356 """)1357 differ.initialize(code1)1358 differ.parse(code2, parsers=1, copies=1, expect_error_leaves=True)1359def test_yet_another_backslash(differ):1360 code1 = dedent('''\1361 def f():1362 x1363 def g():1364 y1365 base = "" \\1366 "" % to1367 return1368 ''')1369 code2 = dedent('''\1370 def f():1371 x1372 def g():1373 y1374 base = "" \\1375 \x0f1376 return1377 ''')1378 differ.initialize(code1)1379 differ.parse(code2, parsers=ANY, copies=ANY, expect_error_leaves=True)1380 differ.parse(code1, parsers=ANY, copies=ANY)1381def test_backslash_before_def(differ):1382 code1 = dedent('''\1383 def f():1384 x1385 def g():1386 y1387 z1388 ''')1389 code2 = dedent('''\1390 def f():1391 x1392 >\\1393 def g():1394 y1395 x1396 z1397 ''')1398 differ.initialize(code1)1399 differ.parse(code2, parsers=3, copies=1, expect_error_leaves=True)1400def test_backslash_with_imports(differ):1401 code1 = dedent('''\1402 from x import y, \\1403 ''')1404 code2 = dedent('''\1405 from x import y, \\1406 z1407 ''')1408 differ.initialize(code1)1409 differ.parse(code2, parsers=1)1410 differ.parse(code1, parsers=1)1411def test_one_line_function_error_recovery(differ):1412 code1 = dedent('''\1413 class X:1414 x1415 def y(): word """1416 # a1417 # b1418 c(self)1419 ''')1420 code2 = dedent('''\1421 class X:1422 x1423 def y(): word """1424 # a1425 # b1426 c(\x01+self)1427 ''')1428 differ.initialize(code1)1429 differ.parse(code2, parsers=1, copies=1, expect_error_leaves=True)1430def test_one_line_property_error_recovery(differ):1431 code1 = dedent('''\1432 class X:1433 x1434 @property1435 def encoding(self): True -1436 return 11437 ''')1438 code2 = dedent('''\1439 class X:1440 x1441 @property1442 def encoding(self): True -1443 return 11444 ''')1445 differ.initialize(code1)...
test_translator.py
Source:test_translator.py
...7 OpenCLConverter, py2c8)9def test_simple_assignment_expression():10 # Given11 src = dedent('''12 b = (2*a + 1)*(-a/1.5)%213 ''')14 # When15 code = py2c(src)16 # Then17 expect = dedent('''18 double a;19 double b;20 b = ((((2 * a) + 1) * ((- a) / 1.5)) % 2);21 ''')22 assert code == expect.strip()23def test_multiple_assignment_expressions():24 # Given25 src = dedent('''26 a = 21.527 b = (2*a + 1)*(a/1.5)%228 ''')29 # When30 code = py2c(src)31 # Then32 expect = dedent('''33 double a;34 double b;35 a = 21.5;36 b = ((((2 * a) + 1) * (a / 1.5)) % 2);37 ''')38 assert code == expect.strip()39def test_if_block():40 # Given41 src = dedent('''42 a = 21.543 if a > 20:44 b = a - 145 elif a < 20:46 b = a + 147 else:48 b = a49 ''')50 # When51 code = py2c(src)52 # Then53 expect = dedent('''54 double a;55 double b;56 a = 21.5;57 if ((a > 20)) {58 b = (a - 1);59 }60 else {61 if ((a < 20)) {62 b = (a + 1);63 }64 else {65 b = a;66 }67 }68 ''')69 assert code.strip() == expect.strip()70def test_conditionals():71 # Given72 src = dedent('''73 if (x > 10 and x < 20) or not (x >= 10 and x <= 20):74 y75 ''')76 # When77 code = py2c(src)78 # Then79 expect = dedent('''80 double x;81 double y;82 if ((((x > 10) && (x < 20)) || (! ((x >= 10) && (x <= 20))))) {83 y;84 }85 ''')86 assert code.strip() == expect.strip()87 # Given88 src = dedent('''89 if x != 10 and x is 100 or (x == 20 and x is not 1):90 pass91 ''')92 # When93 code = py2c(src)94 # Then95 expect = dedent('''96 double x;97 if ((((x != 10) && (x == 100)) || ((x == 20) && (x != 1)))) {98 ;99 }100 ''')101 assert code.strip() == expect.strip()102 # Given103 src = dedent('''104 if x != 10 and x is 100 or (x == 20 and x is not 1):105 pass106 ''')107 # When108 code = py2c(src)109 # Then110 expect = dedent('''111 double x;112 if ((((x != 10) && (x == 100)) || ((x == 20) && (x != 1)))) {113 ;114 }115 ''')116 assert code.strip() == expect.strip()117def test_multiple_boolops():118 # Given119 src = dedent('''120 if x % 2 == 0 or x % 2 == 1 or x > 0:121 pass122 ''')123 # When124 code = py2c(src)125 # Then126 expect = dedent('''127 double x;128 if ((((x % 2) == 0) || ((x % 2) == 1) || (x > 0))) {129 ;130 }131 ''')132 assert code.strip() == expect.strip()133def test_power():134 # Given135 src = dedent('''136 1.5*x**2137 ''')138 # When139 code = py2c(src)140 # Then141 expect = dedent('''142 double x;143 (1.5 * pow(x, 2));144 ''')145 assert code.strip() == expect.strip()146def test_only_two_operands_supported_for_comparisons():147 # Given148 src = dedent('''149 if 10 < x < 20:150 pass151 ''')152 # When153 with pytest.raises(NotImplementedError):154 py2c(src)155def test_calling_function():156 # Given157 src = dedent('''158 sin(23.2 + 1)159 ''')160 # When161 code = py2c(src)162 # Then163 expect = dedent('''164 sin((23.2 + 1));165 ''')166 assert code == expect.strip()167def test_calling_printf_with_string():168 # Given169 src = dedent(r'''170 printf('%s %d %f\n', 'hello', 1, 2.0)171 ''')172 # When173 code = py2c(src)174 # Then175 expect = dedent('''176 printf("%s %d %f\n", "hello", 1, 2.0);177 ''')178 assert code == expect.strip()179def test_subscript():180 # Given181 src = dedent('''182 x[1]183 ''')184 # When185 code = py2c(src)186 # Then187 expect = dedent('''188 double x;189 x[1];190 ''')191 assert code == expect.strip()192def test_known_math_constants():193 # Given194 src = dedent('''195 x = M_E + M_LOG2E + M_LOG10E + M_LN2 + M_LN10196 x += M_PI + M_PI_2 + M_PI_4 + M_1_PI * M_2_PI197 x += M_2_SQRTPI * M_SQRT2 * M_SQRT1_2 * pi198 x = INFINITY199 x = NAN200 x = HUGE_VALF201 ''')202 # When203 code = py2c(src)204 # Then205 expect = dedent('''206 double x;207 x = ((((M_E + M_LOG2E) + M_LOG10E) + M_LN2) + M_LN10);208 x += (((M_PI + M_PI_2) + M_PI_4) + (M_1_PI * M_2_PI));209 x += (((M_2_SQRTPI * M_SQRT2) * M_SQRT1_2) * pi);210 x = INFINITY;211 x = NAN;212 x = HUGE_VALF;213 ''')214 assert code == expect.strip()215def test_simple_function_with_return():216 # Given217 src = dedent('''218 def f(x=0.0):219 'docstring'220 y = x + 1221 return y222 ''')223 # When224 code = py2c(src)225 # Then226 expect = dedent('''227 double f(double x)228 {229 double y;230 y = (x + 1);231 return y;232 }233 ''')234 assert code.strip() == expect.strip()235def test_simple_function_without_return():236 # Given237 src = dedent('''238 def f(y=0.0, x=0.0):239 z = y + x240 y = z241 ''')242 # When243 code = py2c(src)244 # Then245 expect = dedent('''246 void f(double y, double x)247 {248 double z;249 z = (y + x);250 y = z;251 }252 ''')253 assert code.strip() == expect.strip()254def test_function_argument_types():255 # Given256 src = dedent('''257 def f(s_idx, s_p, d_idx, d_p, J=0, t=0.0, l=[0,0], xx=(0, 0)):258 pass259 ''')260 # When261 code = py2c(src)262 # Then263 expect = dedent('''264void f(long s_idx, double* s_p, long d_idx, double* d_p, long J, double t,265 double* l, double* xx)266{267 ;268}269 ''')270 assert code.strip() == expect.strip()271def test_known_types_in_funcargs():272 # Given273 src = dedent('''274 def f(x, xx, cond=True):275 pass276 ''')277 # When278 known_types = {'xx': KnownType('foo*'), 'x': KnownType('float32')}279 code = py2c(src, known_types=known_types)280 # Then281 expect = dedent('''282 void f(float32 x, foo* xx, int cond)283 {284 ;285 }286 ''')287 assert code.strip() == expect.strip()288def test_raises_error_when_unknown_args_are_given():289 # Given290 src = dedent('''291 def f(x):292 pass293 ''')294 # When/Then295 with pytest.raises(CodeGenerationError):296 py2c(src)297 # Given298 # Unsupported default arg.299 src = dedent('''300 def f(x=''):301 pass302 ''')303 # When/Then304 with pytest.raises(CodeGenerationError):305 py2c(src)306 # Given307 # Unsupported default arg list.308 src = dedent('''309 def f(x=(1, '')):310 pass311 ''')312 # When/Then313 with pytest.raises(CodeGenerationError):314 py2c(src)315def test_user_supplied_detect_type():316 # Given317 src = dedent('''318 def f(x, xx=[1,2,3], cond=True):319 pass320 ''')321 # When322 def dt(name, value):323 return 'double'324 code = py2c(src, detect_type=dt)325 # Then326 expect = dedent('''327 void f(double x, double xx, double cond)328 {329 ;330 }331 ''')332 assert code.strip() == expect.strip()333def test_while():334 # Given335 src = dedent('''336 while x < 21:337 do(x)338 do1(x)339 ''')340 # When341 code = py2c(src)342 # Then343 expect = dedent('''344 double x;345 while ((x < 21)) {346 do(x);347 do1(x);348 }349 ''')350 assert code.strip() == expect.strip()351def test_bool_true_false_and_none():352 # Given353 src = dedent('''354 while True:355 pass356 if False:357 pass358 if x is None or x is not None:359 pass360 ''')361 # When362 code = py2c(src)363 # Then364 expect = dedent('''365 double x;366 while (1) {367 ;368 }369 if (0) {370 ;371 }372 if (((x == NULL) || (x != NULL))) {373 ;374 }375 ''')376 assert code.strip() == expect.strip()377def test_for():378 # Given379 src = dedent('''380 for i in range(5):381 do(i)382 ''')383 # When384 code = py2c(src)385 # Then386 expect = dedent('''387 for (long i=0; i<5; i+=1) {388 do(i);389 }390 ''')391 assert code.strip() == expect.strip()392 # Given393 src = dedent('''394 for i in range(2, 5):395 pass396 ''')397 # When398 code = py2c(src)399 # Then400 expect = dedent('''401 for (long i=2; i<5; i+=1) {402 ;403 }404 ''')405 assert code.strip() == expect.strip()406 # Given407 src = dedent('''408 for i in range(2, 10, 2):409 pass410 ''')411 # When412 code = py2c(src)413 # Then414 expect = dedent('''415 for (long i=2; i<10; i+=2) {416 ;417 }418 ''')419 assert code.strip() == expect.strip()420def test_two_fors():421 # Given422 src = dedent('''423 for i in range(5):424 do(i)425 for i in range(5):426 pass427 ''')428 # When429 code = py2c(src)430 # Then431 expect = dedent('''432 for (long i=0; i<5; i+=1) {433 do(i);434 }435 for (long i=0; i<5; i+=1) {436 ;437 }438 ''')439 assert code.strip() == expect.strip()440def test_for_with_break_continue():441 # Given442 src = dedent('''443 for i in range(10):444 if i%7 == 0:445 break446 if i%2 == 0:447 continue448 do(i)449 ''')450 # When451 code = py2c(src)452 # Then453 expect = dedent('''454 for (long i=0; i<10; i+=1) {455 if (((i % 7) == 0)) {456 break;457 }458 if (((i % 2) == 0)) {459 continue;460 }461 do(i);462 }463 ''')464 assert code.strip() == expect.strip()465def test_for_not_range_and_else_fails():466 # Given467 src = dedent('''468 for i in something():469 pass470 ''')471 # When/Then472 with pytest.raises(NotImplementedError):473 py2c(src)474 # Given475 src = dedent('''476 for i in range(5):477 pass478 else:479 pass480 ''')481 # When/Then482 with pytest.raises(NotImplementedError):483 py2c(src)484 # Given485 src = dedent('''486 for i in range(0, 5, 2, 3):487 pass488 ''')489 # When/Then490 with pytest.raises(NotImplementedError):491 py2c(src)492def test_while_else_raises_error():493 # Given494 src = dedent('''495 while 1:496 do()497 else:498 do()499 ''')500 # When/Then501 with pytest.raises(NotImplementedError):502 py2c(src)503def test_try_block_raises_error():504 # Given505 src = dedent('''506 try:507 do()508 except ImportError:509 pass510 ''')511 # When/Then512 with pytest.raises(NotImplementedError):513 py2c(src)514def test_attribute_access():515 # Given516 src = dedent('''517 self.x = 1518 ''')519 # When520 code = py2c(src)521 # Then522 expect = dedent('''523 double self;524 self->x = 1;525 ''')526 assert code.strip() == expect.strip()527def test_declare_call_declares_variable():528 # Given529 src = dedent('''530 x = declare('int')531 x += 1532 ''')533 # When534 code = py2c(src)535 # Then536 expect = dedent('''537 int x;538 x += 1;539 ''')540 assert code.strip() == expect.strip()541def test_declare_matrix():542 # Given543 src = dedent('''544 x = declare('matrix((3,))')545 do(x[0])546 ''')547 # When548 code = py2c(src)549 # Then550 expect = dedent('''551 double x[3];552 do(x[0]);553 ''')554 assert code.strip() == expect.strip()555 # Given556 src = dedent('''557 x = declare('matrix((2, 3))')558 do(x[0][1])559 ''')560 # When561 code = py2c(src)562 # Then563 expect = dedent('''564 double x[2][3];565 do(x[0][1]);566 ''')567 assert code.strip() == expect.strip()568def test_class():569 # Given570 src = dedent('''571 class Foo(object):572 def g(self, x=0.0):573 pass574 def f(self, x=0.0):575 y = x + 1576 do(self.a, x)577 self.g(y)578 ''')579 # When580 code = py2c(src)581 # Then582 expect = dedent('''583 void Foo_g(Foo* self, double x)584 {585 ;586 }587 void Foo_f(Foo* self, double x)588 {589 double y;590 y = (x + 1);591 do(self->a, x);592 Foo_g(self, y);593 }594 ''')595 assert code.strip() == expect.strip()596def test_unsupported_method():597 # Given598 src = dedent('''599 np.identity(25)600 ''')601 # When602 with pytest.raises(NotImplementedError):603 py2c(src)604def test_c_struct_helper():605 # Given606 class Fruit(object):607 pass608 f = Fruit()609 f.apple = 1610 f.banana = 2.0611 f.pear = 1.5612 h = CStructHelper(f)613 # When614 result = h.get_code()615 # Then616 expect = dedent('''617 typedef struct Fruit {618 int apple;619 double banana;620 double pear;621 } Fruit;622 ''')623 assert result.strip() == expect.strip()624 # When/Then625 array = h.get_array()626 use_double = get_config().use_double627 fdtype = np.float64 if use_double else np.float32628 expect = np.dtype([('apple', np.int32),629 ('banana', fdtype), ('pear', fdtype)])630 assert array.dtype == expect631 assert array['apple'] == 1632 assert array['banana'] == 2.0633 assert array['pear'] == 1.5634def test_c_struct_helper_empty_object():635 # Given636 class Fruit(object):637 pass638 f = Fruit()639 h = CStructHelper(f)640 # When641 result = h.get_code()642 # Then643 expect = dedent('''644 typedef struct Fruit {645 } Fruit;646 ''')647 assert result.strip() == expect.strip()648 # When/Then649 assert h.get_array() is None650def test_wrapping_class():651 # Given652 class Dummy(object):653 '''Class Docstring'''654 def __init__(self, x=0, f=0.0, s=''):655 "Constructor docstring"656 self.x = x657 self.f = f658 self.s = s659 self._private = 1660 def method(self):661 '''Method docstring.662 '''663 pass664 obj = Dummy()665 # When666 c = CConverter()667 result = c.parse_instance(obj)668 # Then669 expect = dedent('''670 typedef struct Dummy {671 double f;672 int x;673 } Dummy;674 void Dummy_method(Dummy* self)675 {676 ;677 }678 ''')679 assert result.strip() == expect.strip()680 # When681 h = CStructHelper(obj)682 use_double = get_config().use_double683 fdtype = np.float64 if use_double else np.float32684 dtype = np.dtype([('f', fdtype), ('x', np.int32)])685 expect = np.zeros(1, dtype)686 assert h.get_array() == expect687def test_wrapping_class_with_ignore_methods():688 # Given689 class Dummy1(object):690 '''Class Docstring'''691 def f(self):692 pass693 def not_me(self):694 pass695 obj = Dummy1()696 # When697 c = CConverter()698 result = c.parse_instance(obj, ignore_methods=['not_me'])699 # Then700 expect = dedent('''701 typedef struct Dummy1 {702 } Dummy1;703 void Dummy1_f(Dummy1* self)704 {705 ;706 }707 ''')708 assert result.strip() == expect.strip()709def test_opencl_conversion():710 src = dedent('''711 def f(s_idx, s_p, d_idx, d_p, J=0, t=0.0, l=[0,0], xx=(0, 0)):712 pass713 ''')714 # When715 known_types = {'d_p': KnownType('__global int*')}716 converter = OpenCLConverter(known_types=known_types)717 code = converter.convert(src)718 # Then719 expect = dedent('''720void f(long s_idx, __global double* s_p, long d_idx, __global int* d_p, long721 J, double t, double* l, double* xx)722{723 ;724}725 ''')726 assert code.strip() == expect.strip()727def test_opencl_class():728 src = dedent('''729 class Foo(object):730 def g(self, x=0.0):731 pass732 ''')733 # When734 converter = OpenCLConverter()735 code = converter.convert(src)736 # Then737 expect = dedent('''738 void Foo_g(__global Foo* self, double x)739 {740 ;741 }742 ''')743 assert code.strip() == expect.strip()744def test_handles_parsing_functions():745 # Given746 def f(x=1.0):747 return x + 1748 # When749 t = CConverter()750 code = t.parse_function(f)751 # Then752 expect = dedent('''753 double f(double x)754 {755 return (x + 1);756 }757 ''')758 assert code.strip() == expect.strip()759 # Given760 class A(object):761 def f(self, x=1.0):762 return x + 1.0763 # When764 t = CConverter()765 code = t.parse_function(A)766 # Then767 expect = dedent('''768 double A_f(A* self, double x)769 {770 return (x + 1.0);771 }772 ''')...
printerModel.test.ts
Source:printerModel.test.ts
1import { print } from '../index';2import { dedent, dedentString } from '../../__testsUtils__';3import { Source } from '../../language';4describe(__filename, () => {5 describe('models', () => {6 it('correctly print model with description', () => {7 const source = `8 // лÑл9// kek10AcDocument { }`;11 const printed = print(source);12 expect(printed).toEqual(13 `// лÑл14// kek15AcDocument {}\n`,16 );17 });18 it('correctly print empty model without description', () => {19 const source = `AcDocument {}`;20 const printed = print(source);21 expect(printed).toEqual(`AcDocument {}\n`);22 });23 it('correctly print model fields', () => {24 const source = `AcDocument {name}`;25 const printed = print(source);26 expect(dedentString(printed)).toEqual(dedent`27 AcDocument {28 name,29 }\n`);30 });31 it('correctly print model fields with trailing comma', () => {32 const source = `AcDocument {33 name, surname,34 }`;35 const printed = print(source);36 expect(dedentString(printed)).toEqual(dedent`37 AcDocument {38 name,39 surname,40 }\n`);41 });42 it('correctly print model fields with s', () => {43 const source = `AcDocument {44 name: s,45 surname,46 }47 48 49 50 `;51 const source2 = `AcDocument {52 surname,53 name: s,54 }55 56 57 58 `;59 const printed = print(source);60 const printed2 = print(source2);61 expect(dedentString(printed)).toEqual(dedent`62 AcDocument {63 name: s,64 surname,65 }66 `);67 expect(dedentString(printed2)).toEqual(dedent`68 AcDocument {69 surname,70 name: s,71 }72 `);73 });74 it('correctly print optional model fields', () => {75 const source = `AcDocument {76 name?: s,77 surname,78 }`;79 const printed = print(source);80 expect(dedentString(printed)).toEqual(dedent`81 AcDocument {82 name?: s,83 surname,84 }85 `);86 });87 it('correctly print optional model fields without type', () => {88 const source = `AcDocument {89 name?,90 surname,91 }`;92 const printed = print(source);93 expect(dedentString(printed)).toEqual(dedent`94 AcDocument {95 name?,96 surname,97 }98 `);99 });100 it('correctly print field array type', () => {101 const source = `AcDocument {102 name?: s[],103 surname: b[][],104 }`;105 const printed = print(source);106 expect(dedentString(printed)).toEqual(dedent`107 AcDocument {108 name?: s[],109 surname: b[][],110 }111 `);112 });113 it('correctly print strict mode models', () => {114 const source = `115 AcDocument !{116 name?: s[],117 surname: b[],118 }119 `;120 const printed = print(source);121 expect(dedentString(printed)).toEqual(dedent`122 AcDocument !{123 name?: s[],124 surname: b[],125 }126 `);127 });128 it('correctly print extends model', () => {129 const source = `130 131 AcDocument < Kek {132 name?: s[],133 surname: b[],134 }135 `;136 const printed = print(source);137 expect(dedentString(printed)).toEqual(dedent`138 AcDocument < Kek {139 name?: s[],140 surname: b[],141 }142 `);143 });144 it('correctly print with multiple extends model and strict model', () => {145 const source = `AcDocument < Kek, Lel !{146 name?: s[],147 surname: b[],148 }`;149 const printed = print(source);150 expect(dedentString(printed)).toEqual(dedent`151 AcDocument < Kek, Lel !{152 name?: s[],153 surname: b[],154 }155 `);156 });157 it('correctly print model with inline enum', () => {158 const source = `159 AcDocument < Kek, Lel !{160 -name?: s[],161 type?: ( standard | service ),162 surname: b[],163 }164 `;165 const printed = print(source);166 expect(dedentString(printed)).toEqual(dedent`167 AcDocument < Kek, Lel !{168 -name?: s[],169 type?: ( standard | service ),170 surname: b[],171 }172 `);173 });174 it('correctly print model with inline type definitions', () => {175 const source = `AcDocument < Kek, Lel !{176 -name?: s[],177 type?: ( standard | 178 service ),179 kek: {180 conversationId: i,181 users: {182 id: i,183 nickname,184 avatar?,185 }[],186 },187 surname: b[],188 }`;189 const printed = print(source);190 expect(dedentString(printed)).toEqual(dedent`191 AcDocument < Kek, Lel !{192 -name?: s[],193 type?: ( standard | service ),194 kek: {195 conversationId: i,196 users: {197 id: i,198 nickname,199 avatar?,200 }[],201 },202 surname: b[],203 }204 `);205 });206 it('should print strict nested types correctly', () => {207 const source = `AcDocument < Kek, Lel !{208 pathParameters: !{209 pathParameters: !{},210 },211 }`;212 const printed = print(source);213 expect(dedentString(printed)).toEqual(dedent`214 AcDocument < Kek, Lel !{215 pathParameters: !{216 pathParameters: !{},217 },218 }219 `);220 });221 it('correctly print multiple models', () => {222 const ast = `AcDocument {}223 AcDocument2 { name}`;224 const printed = print(ast);225 expect(dedentString(printed)).toEqual(dedent`226 AcDocument {}227 AcDocument2 {228 name,229 }230 `);231 });232 });233 describe('enums', () => {234 it('correctly print model with short named enum and description', () => {235 const source = new Source({236 body: `237 // лÑл238 // kek239 A ( f | b240 )`,241 });242 const printed = print(source);243 expect(dedentString(printed)).toEqual(dedent`244 // лÑл245 // kek246 A (247 f |248 b249 )250 `);251 });252 it('correctly print model with long named enum', () => {253 const source = new Source({254 body: `CompanyType (255 Branch Office Singapore |256 Private Company 'Limited' by Shares (Pte. Ltd.) |257 + amount |258 b-office-singapore259 )`,260 });261 const printed = print(source);262 expect(dedentString(printed)).toEqual(dedent`263 CompanyType (264 Branch Office Singapore |265 Private Company 'Limited' by Shares (Pte. Ltd.) |266 + amount |267 b-office-singapore268 )269 `);270 });271 it('correctly print model with complicated inline enums', () => {272 const source = new Source({273 body: `AcDocument < Kek, Lel !{274 -name?: s[],275 type?: (276 + amount |277 - amount |278 sum + |279 Private Company 'Limited' by Shares (Pte. Ltd.)280 ),281 kek: {282 conversationId: i,283 users: {284 id: i,285 nickname,286 avatar?,287 }[],288 },289 surname: b[],290 }`,291 });292 const printed = print(source);293 expect(dedentString(printed)).toEqual(dedent`294 AcDocument < Kek, Lel !{295 -name?: s[],296 type?: ( + amount | - amount | sum + | Private Company 'Limited' by Shares (Pte. Ltd.) ),297 kek: {298 conversationId: i,299 users: {300 id: i,301 nickname,302 avatar?,303 }[],304 },305 surname: b[],306 }307 `);308 });309 it('correctly print model that uses named enum', () => {310 const source = new Source({311 body: ` A (312 f | b313 )314 MyModel { color: A, }315 B (316 c | d317 )`,318 });319 const printed = print(source);320 expect(dedentString(printed)).toEqual(dedent`321 A (322 f |323 b324 )325 MyModel {326 color: A,327 }328 B (329 c |330 d331 )332 `);333 });334 });335 describe('handle comments', () => {336 it('success', () => {337 const source = `338 # comment1339 AcDocument < Kek, Lel !{340 -name?: s[],341 # comment2342 type?: ( standard | service ),343 # comment4344 kek: {345 conversationId: i,346 users: {347 id: i,348 nickname,349 avatar?,350 }[],351 },352 surname: b[],353 }354 355 # comment3356 Lel ( kek | lol )357 `;358 const printed = print(source);359 expect(dedentString(printed)).toEqual(dedent`360 # comment1361 AcDocument < Kek, Lel !{362 -name?: s[],363 # comment2364 type?: ( standard | service ),365 # comment4366 kek: {367 conversationId: i,368 users: {369 id: i,370 nickname,371 avatar?,372 }[],373 },374 surname: b[],375 }376 # comment3377 Lel (378 kek |379 lol380 )`);381 });382 });...
index.test.ts
Source:index.test.ts
...5const unknownKeysSpec = (6 pluginOptions?: PluginOptions | undefined7) => {8 test('does not transform non-meta property', () => {9 const input = dedent(`10 console.log(foo.import.meta);11 `);12 const expected = dedent(`13 console.log(foo.import.meta);14 `);15 const result = babelCore.transform(input, {16 plugins: [pluginOptions ? [importMetaPlugin, pluginOptions] : importMetaPlugin]17 })?.code ?? '';18 expect(result.trim()).toEqual(expected.trim());19 });20 test('does not transform import.meta if known property is not specified', () => {21 const input = dedent(`22 console.log(import.meta);23 `);24 const expected = dedent(`25 console.log(import.meta);26 `);27 const result = babelCore.transform(input, {28 plugins: [pluginOptions ? [importMetaPlugin, pluginOptions] : importMetaPlugin]29 })?.code ?? '';30 expect(result.trim()).toEqual(expected.trim());31 });32 test('does not transform unknown meta properties', () => {33 const input = dedent(`34 console.log(import.meta.foo);35 `);36 const expected = dedent(`37 console.log(import.meta.foo);38 `);39 const result = babelCore.transform(input, {40 plugins: [pluginOptions ? [importMetaPlugin, pluginOptions] : importMetaPlugin]41 })?.code ?? '';42 expect(result.trim()).toEqual(expected.trim());43 });44};45describe('babel-plugin-import-meta', () => {46 describe('ES5', () => {47 const pluginOptions: PluginOptions | undefined = undefined;48 test('transforms import.meta.url', () => {49 const input = dedent(`50 console.log(import.meta.url);51 `);52 const expected = dedent(`53 console.log(require('url').pathToFileURL(__filename).toString());54 `);55 const result = babelCore.transform(input, {56 // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions57 plugins: [pluginOptions ? [importMetaPlugin, pluginOptions] : importMetaPlugin]58 })?.code ?? '';59 expect(result.trim()).toEqual(expected.trim());60 });61 unknownKeysSpec(pluginOptions);62 });63 describe('ES6', () => {64 const pluginOptions: PluginOptions | undefined = { module: 'ES6' };65 test('transforms import.meta.url', () => {66 const input = dedent(`67 console.log(import.meta.url);68 `);69 const expected = dedent(`70 import url from 'url';71 console.log(url.pathToFileURL(__filename).toString());72 `);73 const result = babelCore.transform(input, {74 // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions75 plugins: [pluginOptions ? [importMetaPlugin, pluginOptions] : importMetaPlugin]76 })?.code ?? '';77 expect(result.trim()).toEqual(expected.trim());78 });79 test('injects import at the top of the file', () => {80 const input = dedent(`81 import path from 'path';82 console.log('foo');83 console.log(import.meta.url);84 `);85 const expected = dedent(`86 import url from 'url';87 import path from 'path';88 console.log('foo');89 console.log(url.pathToFileURL(__filename).toString());90 `);91 const result = babelCore.transform(input, {92 // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions93 plugins: [pluginOptions ? [importMetaPlugin, pluginOptions] : importMetaPlugin]94 })?.code ?? '';95 expect(result.trim()).toEqual(expected.trim());96 });97 unknownKeysSpec(pluginOptions);98 });99});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!