How to use get_errors method in autotest

Best Python code snippet using autotest_python

test_sync.py

Source:test_sync.py Github

copy

Full Screen

1import ast2import textwrap3from flake_rba.plugin import ReferencedBeforeAssignmentASTPlugin4def get_errors(s: str):5 tree = ast.parse(s)6 plugin = ReferencedBeforeAssignmentASTPlugin(tree)7 return {f'{line}:{col} {msg.partition(" ")[0]}' for line, col, msg, _ in plugin.run()}8def test_reference_not_imported():9 code = textwrap.dedent("""10 from ast import walk11 print(a)12 """)13 actual = get_errors(code)14 expected = {'3:6 F823'}15 assert actual == expected16def test_access_not_imported():17 code = textwrap.dedent("""18 import ast19 print(walk)20 """)21 actual = get_errors(code)22 expected = {'3:6 F823'}23 assert actual == expected24def test_import_is_valid():25 code = textwrap.dedent("""26 import ast27 print(ast)28 """)29 actual = get_errors(code)30 expected = set()31 assert actual == expected32def test_import_from_is_valid():33 code = textwrap.dedent("""34 from ast import walk35 print(walk)36 """)37 actual = get_errors(code)38 expected = set()39 assert actual == expected40def test_multiple_import_from_are_valid():41 code = textwrap.dedent("""42 from ast import walk, iter_fields43 print(walk, iter_fields)44 """)45 actual = get_errors(code)46 expected = set()47 assert actual == expected48def test_access_renamed_import_from_fail():49 code = textwrap.dedent("""50 from ast import walk, iter_fields as itf51 print(walk, iter_fields)52 """)53 actual = get_errors(code)54 expected = {'3:12 F823'}55 assert actual == expected56def test_access_renamed_import_from_normal():57 code = textwrap.dedent("""58 from ast import iter_fields as itf59 print(itf)60 """)61 actual = get_errors(code)62 expected = set()63 assert actual == expected64def test_check_normal_fn_definition():65 code = textwrap.dedent("""66 def foo():67 return "bar"68 """)69 actual = get_errors(code)70 expected = set()71 assert actual == expected72def test_check_fn_definition_with_values():73 code = textwrap.dedent("""74 def foo():75 value = 176 return value77 """)78 actual = get_errors(code)79 expected = set()80 assert actual == expected81def test_access_local_variable():82 code = textwrap.dedent("""83 def foo():84 value = 185 return value86 print(value)87 """)88 actual = get_errors(code)89 expected = {'5:6 F823'}90 assert actual == expected91def test_use_value_after_for_loop():92 code = textwrap.dedent("""93 values = [1, 2, 3]94 for value in values:95 print(value)96 print(value)97 value += 198 """)99 actual = get_errors(code)100 expected = {'5:6 F823', '6:0 F823'}101 assert actual == expected102def test_use_value_after_for_loop_in_function():103 code = textwrap.dedent("""104 def fn(values):105 for value in values:106 print(value)107 print(value)108 value += 1109 """)110 actual = get_errors(code)111 expected = {'5:10 F823', '6:4 F823'}112 assert actual == expected113def test_assign_value():114 code = textwrap.dedent("""115 val = 1116 val_ += 2117 """)118 actual = get_errors(code)119 expected = {'3:0 F823'}120 assert actual == expected121def test_return_value_defined_in_for():122 code = textwrap.dedent("""123 x = 1124 def f(values):125 for value in values:126 print(value)127 return value128 """)129 actual = get_errors(code)130 expected = {'6:11 F823'}131 assert actual == expected132def test_function_variable_mentioned_in_header():133 code = textwrap.dedent("""134 def run_fn(value):135 values = [1, 2, 3]136 for value in values:137 print(value)138 return value139 """)140 actual = get_errors(code)141 expected = set()142 assert actual == expected143def test_method_definition_normal():144 code = textwrap.dedent("""145 class Foo:146 def run(self, value):147 values = [1, 2, 3]148 for value in values:149 print(value)150 return value151 """)152 actual = get_errors(code)153 expected = set()154 assert actual == expected155def test_method_definition_for_loop_no_firm_reference():156 code = textwrap.dedent("""157 class Foo:158 def run(self):159 values = [1, 2, 3]160 for value in values:161 print(value)162 return value163 """)164 actual = get_errors(code)165 expected = {'7:15 F823'}166 assert actual == expected167def test_class_with_two_methods_normal():168 code = textwrap.dedent("""169 class Foo:170 class_att = 1171 def bar(self, inp):172 if inp:173 return 1174 self.foo(inp)175 def foo(self, inp):176 if not inp:177 return 0178 self.bar(inp)179 """)180 actual = get_errors(code)181 expected = set()182 assert actual == expected183def test_case_if_else_uncertain():184 code = textwrap.dedent("""185 def foo(cond):186 if cond:187 value = 1188 else:189 print("spam")190 return value191 """)192 actual = get_errors(code)193 expected = {"7:11 F823"}194 assert actual == expected195def test_case_if_elif_uncertain():196 code = textwrap.dedent("""197 def foo(cond):198 if cond == 1:199 value = 1200 elif cond == 2:201 value = 2202 return value203 """)204 actual = get_errors(code)205 expected = {"7:11 F823"}206 assert actual == expected207def test_case_if_multiple_elif_uncertain():208 code = textwrap.dedent("""209 def foo(cond):210 if cond == 1:211 value = 1212 elif cond == 2:213 value = 2214 elif cond == 3:215 value = 3216 return value217 """)218 actual = get_errors(code)219 expected = {"9:11 F823"}220 assert actual == expected221def test_case_if_multiple_elif_set_ok():222 code = textwrap.dedent("""223 def foo(cond):224 if cond == 1:225 value = 1226 elif cond == 2:227 value = 2228 elif cond == 3:229 value = 3230 else:231 value = 4232 return value233 """)234 actual = get_errors(code)235 expected = set()236 assert actual == expected237def test_simple_if_else_set_ok():238 code = textwrap.dedent("""239 def foo(cond):240 if cond == 1:241 value = 1242 else:243 value = 2244 return value245 """)246 actual = get_errors(code)247 expected = set()248 assert actual == expected249def test_if_else_embedded_if_else_ok():250 code = textwrap.dedent("""251 def bar(cond1, cond2):252 if cond1:253 if cond2:254 value = 1255 else:256 value = 2257 else:258 value = 3259 return value260 """)261 actual = get_errors(code)262 expected = set()263 assert actual == expected264def test_if_else_embedded_if_else_uncertain():265 code = textwrap.dedent("""266 def bar(cond1, cond2):267 if cond1:268 if cond2 > 0:269 value = 1270 elif cond2 < 0:271 value = 2272 else:273 value = 3274 return value275 """)276 actual = get_errors(code)277 expected = {"10:11 F823"}278 assert actual == expected279def test_if_else_multiple_embedded_if_else_uncertain():280 code = textwrap.dedent("""281 def bar(cond1, cond2):282 if cond1:283 if cond2 > 0:284 value = 1285 elif cond2 < 0:286 value = 2287 else:288 if cond2 > 0:289 value = 1290 elif cond2 < 0:291 value = 2292 return value293 """)294 actual = get_errors(code)295 expected = {"13:11 F823"}296 assert actual == expected297def test_if_else_only_else_set():298 code = textwrap.dedent("""299 def bar(cond1):300 if cond1:301 print("hello")302 else:303 value = 1304 return value305 """)306 actual = get_errors(code)307 expected = {"7:11 F823"}308 assert actual == expected309def test_fn_with_kwargs():310 code = textwrap.dedent("""311 def bar(cond1, cond2=3):312 if cond1:313 cond2 += 1314 value = cond2315 else:316 value = 1317 return value318 """)319 actual = get_errors(code)320 expected = set()321 assert actual == expected322def test_fn_with_args_list():323 code = textwrap.dedent("""324 def bar(cond1, *args):325 if cond1:326 args[0] += 1327 value = args[0]328 else:329 value = 1330 return value331 """)332 actual = get_errors(code)333 expected = set()334 assert actual == expected335def test_fn_with_kwargs_dict():336 code = textwrap.dedent("""337 def bar(cond1, **kwargs):338 if cond1:339 kwargs['bar'] += 1340 value = kwargs['bar']341 else:342 value = 1343 return value344 """)345 actual = get_errors(code)346 expected = set()347 assert actual == expected348def test_fn_with_args_kwargs_dict():349 code = textwrap.dedent("""350 def bar(cond1, *args, **kwargs):351 if cond1:352 kwargs['bar'] += args[0]353 value = kwargs['bar']354 else:355 value = 1356 return value357 """)358 actual = get_errors(code)359 expected = set()360 assert actual == expected361def test_try_except_ok():362 code = textwrap.dedent("""363 try:364 value = 1365 except Exception:366 value = 1367 value += 1368 """)369 actual = get_errors(code)370 expected = set()371 assert actual == expected372def test_try_except_uncertain():373 code = textwrap.dedent("""374 try:375 value = 1376 except Exception:377 print("fail")378 print("caught an exception")379 value += 1380 """)381 actual = get_errors(code)382 expected = {"7:0 F823"}383 assert actual == expected384def test_try_except_check_e():385 code = textwrap.dedent("""386 try:387 value = 1388 except Exception as e:389 print(e)390 """)391 actual = get_errors(code)392 expected = set()393 assert actual == expected394def test_try_except_e_is_missing():395 code = textwrap.dedent("""396 try:397 value = 1398 except Exception as e:399 print(e)400 print(e)401 """)402 actual = get_errors(code)403 expected = {"6:6 F823"}404 assert actual == expected405def test_embedded_try_except():406 code = textwrap.dedent("""407 values = {}408 try:409 value = 1410 try:411 print(values['a'])412 except KeyError:413 value = 2414 except RuntimeError:415 value = 0416 except Exception as e:417 print(e)418 value += 1419 """)420 # import astpretty421 # astpretty.pprint(ast.parse(code))422 actual = get_errors(code)423 expected = {"13:0 F823"}424 assert actual == expected425def test_try_except_finally_ok():426 code = textwrap.dedent("""427 try:428 value = 1429 print(value)430 except Exception as e:431 print(e)432 finally:433 print("free resources")434 print(value)435 """)436 actual = get_errors(code)437 expected = {'9:6 F823'}438 assert actual == expected439def test_try_except_else_ok():440 code = textwrap.dedent("""441 try:442 value = 1443 print(value)444 except Exception as e:445 print(e)446 value = 2447 finally:448 print('free resources')449 print(value)450 """)451 actual = get_errors(code)452 expected = set()453 assert actual == expected454def test_try_except_else_uncertain():455 code = textwrap.dedent("""456 try:457 value = 1458 print(value)459 except Exception as e:460 print(e)461 else:462 value = 3463 print(value)464 """)465 actual = get_errors(code)466 expected = {"9:6 F823"}467 assert actual == expected468def test_tuple_assign():469 code = textwrap.dedent("""470 k, v = 0, 1471 k += v472 v *= 2473 """)474 actual = get_errors(code)475 expected = set()476 assert actual == expected477def test_for_unzip_tuples_ok():478 code = textwrap.dedent("""479 values = [(0, 1), (1, 2)]480 for k, v in values:481 k += v482 v *= 2483 """)484 actual = get_errors(code)485 expected = set()486 assert actual == expected487def test_embedded_tuple_ok():488 code = textwrap.dedent("""489 first = [0, 1, 2]490 second = [3, 4, 5]491 for idx, (k, v) in enumerate(zip(first, second)):492 k += v * idx493 v *= 2494 """)495 actual = get_errors(code)496 expected = set()497 assert actual == expected498def test_simple_set_comprehension_ok():499 code = textwrap.dedent("""500 values = [0, 1, 2]501 {i for i in values}502 """)503 actual = get_errors(code)504 expected = set()505 assert actual == expected506def test_simple_set_comprehension_wrong():507 code = textwrap.dedent("""508 values = [0, 1, 2]509 {k for i in values}510 """)511 actual = get_errors(code)512 expected = {'3:1 F823'}513 assert actual == expected514def test_simple_list_comprehension_ok():515 code = textwrap.dedent("""516 values = [0, 1, 2]517 [i for i in values]518 """)519 actual = get_errors(code)520 expected = set()521 assert actual == expected522def test_unpack_tuple_list_comprehension_ok():523 code = textwrap.dedent("""524 values = [(0, 1), (2, 3)]525 [(i, j) for i, j in values]526 """)527 actual = get_errors(code)528 expected = set()529 assert actual == expected530def test_unpack_tuple_list_comprehension_wrong():531 code = textwrap.dedent("""532 values = [(0, 1), (2, 3)]533 [(i, k) for i, j in values]534 """)535 actual = get_errors(code)536 expected = {"3:5 F823"}537 assert actual == expected538def test_simple_gen_comprehension_ok():539 code = textwrap.dedent("""540 values = [0, 1, 2]541 (i for i in values)542 """)543 actual = get_errors(code)544 expected = set()545 assert actual == expected546def test_unpack_tuple_gen_comprehension_ok():547 code = textwrap.dedent("""548 values = [(0, 1), (2, 3)]549 ((i, j) for i, j in values)550 """)551 actual = get_errors(code)552 expected = set()553 assert actual == expected554def test_unpack_tuple_gen_comprehension_wrong():555 code = textwrap.dedent("""556 values = [(0, 1), (2, 3)]557 ((i, k) for i, j in values)558 """)559 actual = get_errors(code)560 expected = {"3:5 F823"}561 assert actual == expected562def test_dict_comprehension_ok():563 code = textwrap.dedent("""564 values = {0: 1, 2: 3}565 {j: i for i, j in values.items()}566 """)567 actual = get_errors(code)568 expected = set()569 assert actual == expected570def test_dict_comprehension_wrong():571 code = textwrap.dedent("""572 values = {0: 1, 2: 3}573 {j: k for i, j in values.items()}574 """)575 actual = get_errors(code)576 expected = {"3:4 F823"}577 assert actual == expected578def test_with_clause_ok():579 code = textwrap.dedent("""580 fname = 'file.txt'581 with open(fname) as f:582 f.read()583 """)584 actual = get_errors(code)585 expected = set()586 assert actual == expected587def test_with_clause_undefined():588 code = textwrap.dedent("""589 filename = 'file.txt'590 with open(filename) as f:591 g.read()592 """)593 actual = get_errors(code)594 expected = {"4:4 F823"}595 assert actual == expected596def test_with_clause_variables_accessible_after():597 code = textwrap.dedent("""598 fname = 'file.txt'599 with open(fname) as f:600 f.read()601 k = 1602 print(k)603 """)604 actual = get_errors(code)605 expected = set()606 assert actual == expected607def test_static_class_reference_wrong():608 code = textwrap.dedent("""609 class Foo:610 @staticmethod611 def bar():612 Baz.baz()613 @staticmethod614 def baz():615 print("spam")616 """)617 actual = get_errors(code)618 expected = {"5:8 F823"}619 assert actual == expected620def test_static_class_reference_ok():621 code = textwrap.dedent("""622 class Foo:623 @staticmethod624 def bar():625 Foo.baz()626 @staticmethod627 def baz():628 print("spam")629 """)630 actual = get_errors(code)631 expected = set()632 assert actual == expected633def test_static_class_cross_reference_ok():634 code = textwrap.dedent("""635 class Foo:636 @staticmethod637 def bar():638 Bar.foo()639 class Bar:640 @staticmethod641 def foo():642 Foo.bar()643 """)644 # Endless recursion is not the case here645 actual = get_errors(code)646 expected = set()647 assert actual == expected648def test_text_annotation_ok():649 code = textwrap.dedent("""650 from typing import List651 values: List[int] = [1, 2, 3]652 """)653 # Endless recursion is not the case here654 actual = get_errors(code)655 expected = set()656 assert actual == expected657def test_text_annotation_bad_typing_import():658 code = textwrap.dedent("""659 from typing import Dict660 values: List[int] = [1, 2, 3]661 """)662 # Endless recursion is not the case here663 actual = get_errors(code)664 expected = set()665 assert actual == expected666def test_assign_to_list():667 # Unfortunately, this is syntactically correct and we have to check this.668 code = textwrap.dedent("""669 [k, v] = 0, 1670 k += v671 v *= 2672 """)673 actual = get_errors(code)674 expected = set()675 assert actual == expected676def test_if_else_return_ok():677 code = textwrap.dedent("""678 def fn(value):679 if value > 0:680 a = 1681 elif value < 0:682 a = 2683 else:684 return -1685 return a686 """)687 actual = get_errors(code)688 expected = set()689 assert actual == expected690def test_if_else_raise_ok():691 code = textwrap.dedent("""692 def fn(value):693 if value > 0:694 a = 1695 elif value < 0:696 a = 2697 else:698 raise ValueError699 return a700 """)701 actual = get_errors(code)702 expected = set()703 assert actual == expected704def test_if_else_return_failed():705 code = textwrap.dedent("""706 def fn(value):707 if value > 0:708 a = 1709 elif value < 0:710 a = 2711 return - 1712 else:713 b = 2714 return a715 """)716 actual = get_errors(code)717 expected = {'10:11 F823'}718 assert actual == expected719def test_try_except_return():720 code = textwrap.dedent("""721 def fn(value):722 try:723 a = 1724 except Exception as e:725 return -1726 return a727 """)728 actual = get_errors(code)729 expected = set()730 assert actual == expected731def test_try_except_re_raise():732 code = textwrap.dedent("""733 def fn(value):734 try:735 a = 1736 except Exception as e:737 raise e738 return a739 """)740 actual = get_errors(code)741 expected = set()742 assert actual == expected743def test_lambda():744 code = textwrap.dedent("""745 (lambda x: print(x))()746 """)747 actual = get_errors(code)748 expected = set()749 assert actual == expected750def test_lambda_failed():751 code = textwrap.dedent("""752 (lambda y: print(x))()753 """)754 actual = get_errors(code)755 expected = {'2:17 F823'}756 assert actual == expected757def test_lambda_pair_args():758 code = textwrap.dedent("""759 (lambda x, y: print(x, y))()760 """)761 actual = get_errors(code)762 expected = set()763 assert actual == expected764def test_fn_type_annotated_parameters():765 code = textwrap.dedent("""766 def fn(y: int, x: str = 1):767 print(x, y)768 """)769 actual = get_errors(code)770 expected = set()771 assert actual == expected772def test_fn_type_annotated_parameters_star_syntax():773 code = textwrap.dedent("""774 def fn(y: int, *, x: str = 1):775 print(x, y)776 """)777 actual = get_errors(code)778 expected = set()779 assert actual == expected780def test_fn_type_annotated_parameters_args_syntax():781 code = textwrap.dedent("""782 def fn(y: int, *args, x: str = 1):783 print(x, y)784 """)785 actual = get_errors(code)786 expected = set()787 assert actual == expected788def test_fn_cross_reference():789 code = textwrap.dedent("""790 a = 1791 def foo():792 print("foo")793 bar()794 def bar():795 print("bar")796 foo()797 """)798 actual = get_errors(code)799 expected = set()800 assert actual == expected801def test_if_embedded_ok():802 code = textwrap.dedent("""803 def fn(a, b):804 if a:805 x = 'foo'806 else:807 if b:808 print('spam')809 x = 'bar'810 return x811 """)812 actual = get_errors(code)813 expected = set()814 assert actual == expected815def test_if_elif_fail():816 code = textwrap.dedent("""817 def fn(a, b):818 if a:819 x = 'foo'820 elif b:821 print('spam')822 x = 'bar'823 return x824 """)825 actual = get_errors(code)826 expected = {'8:11 F823'}827 assert actual == expected828def test_if_elif_else_ok():829 code = textwrap.dedent("""830 def fn(a, b):831 if a:832 x = 'foo'833 elif b:834 x = 'bar'835 else:836 x = 'spam'837 return x838 """)839 actual = get_errors(code)840 expected = set()841 assert actual == expected842def test_if_else_embedded_return_undefined():843 code = textwrap.dedent("""844 def fn(a, b):845 if a == 1:846 x = 'foo'847 elif a == 2:848 if b:849 x = 'bar'850 else:851 return x852 else:853 x = 'spam'854 return x855 """)856 actual = get_errors(code)857 expected = {'9:19 F823'}858 assert actual == expected859def test_if_else_continue_undefined():860 code = textwrap.dedent("""861 def fn(a, b):862 if a == 1:863 x = 'foo'864 elif a == 2:865 if b:866 x = 'bar'867 else:868 return x869 else:870 x = 'spam'871 return x872 """)873 actual = get_errors(code)874 expected = {'9:19 F823'}875 assert actual == expected876def test_if_else_continue_ok():877 code = textwrap.dedent("""878 for value in [1, 2, 3]:879 if value == 1:880 x = '1'881 elif value == 2:882 break883 else:884 x = '3'885 print(x)886 print(x)887 """)888 actual = get_errors(code)889 expected = {'10:6 F823'}890 assert actual == expected891def test_if_else_break_ok():892 code = textwrap.dedent("""893 for value in [1, 2, 3]:894 if value == 1:895 x = '1'896 elif value == 2:897 continue898 else:899 x = '3'900 print(x)901 print(x)902 """)903 actual = get_errors(code)904 expected = {'10:6 F823'}905 assert actual == expected906def test_if_else_try_except_continue_ok():907 code = textwrap.dedent("""908 for value in [1, 2, 3]:909 if value == 1:910 try:911 x = 1912 except ValueError:913 continue914 elif value == 2:915 continue916 else:917 x = '3'918 print(x)919 print(x)920 """)921 actual = get_errors(code)922 expected = {'13:6 F823'}923 assert actual == expected924def test_if_else_try_except_break_ok():925 code = textwrap.dedent("""926 for value in [1, 2, 3]:927 if value == 1:928 try:929 x = 1930 except ValueError:931 break932 elif value == 2:933 continue934 else:935 x = '3'936 print(x)937 print(x)938 """)939 actual = get_errors(code)940 expected = {'13:6 F823'}941 assert actual == expected942def test_if_else_try_except_complicated_ok():943 code = textwrap.dedent("""944 for value in [1, 2, 3]:945 if value == 1:946 try:947 print('spam')948 x = 1949 except ValueError:950 if value:951 raise952 else:953 continue954 print(x)955 print(x)956 """)957 actual = get_errors(code)958 expected = {'13:6 F823'}959 assert actual == expected960def test_if_else_embedded_complicated_ok():961 code = textwrap.dedent("""962 for value in [1, 2, 3]:963 if value == 1:964 x = 2965 else:966 if value:967 raise968 else:969 continue970 print(x)971 print(x)972 """)973 actual = get_errors(code)974 expected = {'11:6 F823'}975 assert actual == expected976def test_multiple_assignment():977 code = textwrap.dedent("""978 x = y = 1979 print(x)980 print(y)981 """)982 actual = get_errors(code)983 expected = set()984 assert actual == expected985def test_try_reassign_not_assigned():986 code = textwrap.dedent("""987 for v in [1, 2, 3]:988 x = v989 y = x990 """)991 actual = get_errors(code)992 expected = {'4:4 F823'}993 assert actual == expected994def test_try_use_not_assigned_as_argument_with_attr():995 code = textwrap.dedent("""996 for v in [1, 2, 3]:997 x = v998 print(x.__class__)999 """)1000 actual = get_errors(code)1001 expected = {'4:6 F823'}1002 assert actual == expected1003def test_try_use_not_assigned_as_argument_with_attr_and_assign():1004 code = textwrap.dedent("""1005 def fn(x):1006 return x1007 for v in [1, 2, 3]:1008 x = v1009 x_s = fn(x.__class__)1010 """)1011 actual = get_errors(code)1012 expected = {'7:9 F823'}1013 assert actual == expected1014def test_try_use_not_assigned_as_argument_multiple_values():1015 code = textwrap.dedent("""1016 for v in [1, 2, 3]:1017 x = v1018 a, b = 0, x1019 """)1020 actual = get_errors(code)1021 expected = {'4:10 F823'}1022 assert actual == expected1023def test_assign_builtin_file():1024 code = textwrap.dedent("""1025 x = __file__1026 """)1027 actual = get_errors(code)1028 expected = set()1029 assert actual == expected1030def test_straightforward():1031 # For some reason, PyCharm syntax checker considers this code sample ok, but it1032 # fails and should be marked as referenced-before-assignment. Looks like there's1033 # something wrong with 'with' clause and PyCharm - I found a few more examples.1034 code = textwrap.dedent("""1035 import contextlib1036 reward = None1037 distance_op = 'wrong_value'1038 node = 'SPAM'1039 leaves = 'foo'1040 distance = 01041 with contextlib.suppress():1042 if reward is not None:1043 if distance_op == 'mul':1044 metric = distance * reward[leaves]1045 elif distance_op == 'add':1046 metric = (distance + reward[leaves]) * (distance > 0)1047 else:1048 raise ValueError('unsupported distance_op {}'.format(distance_op))1049 if sum(metric) == 0:1050 print(node)1051 """)1052 actual = get_errors(code)1053 expected = {'16:11 F823'} # metric variable1054 assert actual == expected1055def test_in_with_values_pycharm_wrong():1056 # PyCharm can't detect that x is referenced before assignment within with context.1057 code = textwrap.dedent("""1058 import contextlib1059 a, b = 1, 01060 c = True1061 with contextlib.suppress():1062 if a < b:1063 x = 11064 if c:1065 print(x)1066 """)1067 actual = get_errors(code)1068 expected = {'9:14 F823'} # metric variable1069 assert actual == expected1070def test_if_out_of_with_pycharm_wrong():1071 # This is the same as above, but without with. PyCharm is able to detect this.1072 code = textwrap.dedent("""1073 a, b = 1, 01074 c = True1075 if a < b:1076 x = 11077 if c:1078 print(x)1079 # """)1080 actual = get_errors(code)1081 expected = {'7:10 F823'} # metric variable1082 assert actual == expected1083def test_delete_unassigned_values():1084 code = textwrap.dedent("""1085 for v in [1, 2, 3]:1086 x = v1087 del x, v1088 """)1089 actual = get_errors(code)1090 expected = {'4:4 F823', '4:7 F823'}1091 assert actual == expected1092def test_delete_assigned_values():1093 code = textwrap.dedent("""1094 x, v = 0, 11095 for v in [1, 2, 3]:1096 x = v1097 del x, v1098 """)1099 actual = get_errors(code)1100 expected = set()1101 assert actual == expected1102def test_variable_in_other_variable():1103 code = textwrap.dedent("""1104 d = {}1105 for v in [1, 2, 3]:1106 if v in d:1107 print('check')1108 """)1109 actual = get_errors(code)1110 expected = set()...

Full Screen

Full Screen

ganeti_errors.py

Source:ganeti_errors.py Github

copy

Full Screen

...86 store_error(str(msg), obj=vm1, code=msg.code)87 # test get_errors88 get_errors = GanetiError.objects.get_errors89 90 errors = get_errors(msg=str(msg))91 self.assertEqual(len(errors), 5)92 errors = get_errors(msg=str(msg) + "NOTHING")93 self.assertEqual(len(errors), 0)94 errors = get_errors(code=msg.code)95 self.assertEqual(len(errors), 5)96 errors = get_errors(code=msg.code + 123)97 self.assertEqual(len(errors), 0)98 errors = get_errors(obj=cluster0)99 self.assertEqual(len(errors), 2)100 errors = get_errors(obj=cluster1)101 self.assertEqual(len(errors), 2)102 errors = get_errors(obj=cluster2)103 self.assertEqual(len(errors), 1)104 errors = get_errors(obj=vm0)105 self.assertEqual(len(errors), 1)106 errors = get_errors(obj=vm1)107 self.assertEqual(len(errors), 1)108 errors = get_errors(obj=Cluster.objects.all())109 self.assertEqual(len(errors), 5)110 errors = get_errors(obj=VirtualMachine.objects.all())111 self.assertEqual(len(errors), 2)112 # test clear_error(s)113 clear_error = GanetiError.objects.clear_error114 clear_errors = GanetiError.objects.clear_errors115 errors = get_errors()116 self.assertEqual(len(errors), 5)117 errors = get_errors(cleared=False).order_by("id")118 self.assertEqual(len(errors), 5)119 clear_error(errors[0].id)120 errors = get_errors()121 self.assertEqual(len(errors), 5)122 errors = get_errors(cleared=False)123 self.assertEqual(len(errors), 4)124 clear_errors(obj=cluster2)125 errors = get_errors()126 self.assertEqual(len(errors), 5)127 errors = get_errors(cleared=False)128 self.assertEqual(len(errors), 3)129 clear_errors(obj=vm1)130 errors = get_errors()131 self.assertEqual(len(errors), 5)132 errors = get_errors(cleared=False)133 self.assertEqual(len(errors), 2)134 clear_errors(msg=str(msg))135 errors = get_errors()136 self.assertEqual(len(errors), 5)137 errors = get_errors(cleared=False)138 self.assertEqual(len(errors), 0)139 # test remove_errors140 remove_errors = GanetiError.objects.remove_errors141 errors = get_errors()142 self.assertEqual(len(errors), 5)143 remove_errors(obj=cluster2)144 errors = get_errors()145 self.assertEqual(len(errors), 4)146 remove_errors(obj=vm1)147 errors = get_errors()148 self.assertEqual(len(errors), 3)149 remove_errors(msg=str(msg))150 errors = get_errors()151 self.assertEqual(len(errors), 0)152 def test_specified_code_values(self):153 """154 Test if errors with code in (401, 404) are stored in a proper way.155 See tickets #2877, #2883.156 Verifies:157 * Manager store_error works properly for specific code numbers158 """159 cluster0 = self.create_model(Cluster, hostname="test0", slug="OSL_TEST0")160 vm0 = self.create_model(VirtualMachine,cluster=cluster0, hostname="vm0.test.org")161 msg0 = client.GanetiApiError("Simulating 401 error", 401)162 msg1 = client.GanetiApiError("Simulating 404 error", 404)163 RapiProxy.error = msg0164 store_error = GanetiError.objects.store_error165 get_errors = GanetiError.objects.get_errors166 remove_errors = GanetiError.objects.remove_errors167 # 401 - cluster168 store_error(str(msg0), obj=cluster0, code=msg0.code)169 errors = get_errors(obj=cluster0)170 self.assertEqual(len(errors), 1)171 errors = get_errors(obj=vm0)172 self.assertEqual(len(errors), 0)173 remove_errors(obj=cluster0)174 175 # 401 - VM176 store_error(str(msg0), obj=vm0, code=msg0.code)177 errors = get_errors(obj=cluster0)178 self.assertEqual(len(errors), 1)179 errors = get_errors(obj=vm0)180 self.assertEqual(len(errors), 0)181 remove_errors(obj=cluster0)182 remove_errors(obj=vm0)183 # 404 - VM184 store_error(str(msg1), obj=vm0, code=msg1.code)185 errors = get_errors(obj=cluster0)186 self.assertEqual(len(errors), 1)187 errors = get_errors(obj=vm0)188 self.assertEqual(len(errors), 1)189 remove_errors(obj=cluster0)190 remove_errors(obj=vm0)191 # 404 - cluster192 store_error(str(msg1), obj=cluster0, code=msg1.code)193 errors = get_errors(obj=cluster0)194 self.assertEqual(len(errors), 1)195 errors = get_errors(obj=vm0)196 self.assertEqual(len(errors), 0)197 198 # 404 - VM, but error is really with cluster199 store_error(str(msg1), obj=vm0, code=msg1.code)200 errors = get_errors(obj=cluster0)201 self.assertEqual(len(errors), 1)202 errors = get_errors(obj=vm0)203 self.assertEqual(len(errors), 0)204 remove_errors(obj=cluster0)205 def refresh(self, object):206 """207 NOTE: this test is borrowed from TestCachedClusterObject.208 Test forced refresh of cached data209 210 Verifies:211 * Object specific refresh is called212 * Info is parsed213 * Object is saved214 * Cache time is updated215 """216 now = datetime.now()217 object.refresh()218 219 object._refresh.assertCalled(self)220 object.parse_transient_info.assertCalled(self)221 object.parse_persistent_info.assertCalled(self)222 self.assertEqual(1, len(object.parse_persistent_info.calls))223 self.assertTrue(object.id)224 self.assertNotEqual(None, object.cached)225 self.assertTrue(now < object.cached, "Cache time should be newer")226 227 def test_refresh_error(self):228 """229 Test an error during refresh230 231 Verifies:232 * error will be saved as GanetiError object233 * successful refresh after will clear error234 """235 cluster0 = self.create_model(Cluster, hostname="test0", slug="OSL_TEST0")236 cluster1 = self.create_model(Cluster, hostname="test1", slug="OSL_TEST1")237 vm0 = self.create_model(VirtualMachine,cluster=cluster0, hostname="vm0.test.org")238 vm1 = self.create_model(VirtualMachine,cluster=cluster1, hostname="vm1.test.org")239 msg = client.GanetiApiError("Simulating an error", 777)240 RapiProxy.error = msg241 # force an error on all objects to test its capture242 for i in (cluster0, cluster1, vm0, vm1):243 i.refresh()244 self.assertEqual(str(msg), i.error)245 # get errors for object246 # TODO: check log format247 if isinstance(i, VirtualMachine):248 errors = GanetiError.objects.get_errors(obj=i.cluster)249 self.assertEqual(2, len(errors))250 self.assertEqual(errors[0].cleared, False)251 self.assertEqual(errors[1].cleared, False)252 self.assertEqual(errors[0].msg, str(msg))253 self.assertEqual(errors[1].msg, str(msg))254 self.assertEqual(errors[0].code, msg.code)255 self.assertEqual(errors[1].code, msg.code)256 cleared = GanetiError.objects.get_errors(obj=i.cluster, cleared=True)257 self.assertEqual(0, len(cleared))258 else:259 errors = GanetiError.objects.get_errors(obj=i)260 self.assertEqual(1, len(errors))261 self.assertEqual(errors[0].cleared, False)262 self.assertEqual(errors[0].msg, str(msg))263 self.assertEqual(errors[0].code, msg.code)264 cleared = GanetiError.objects.get_errors(obj=i, cleared=True)265 self.assertEqual(0, len(cleared))266 267 # set all errors as cleared and test if it was a success268 for i in (cluster0, cluster1, vm0, vm1):269 if isinstance(i, VirtualMachine):270 GanetiError.objects.clear_errors(obj=i.cluster)271 cleared = GanetiError.objects.get_errors(obj=i.cluster, cleared=True)272 self.assertEqual(2, len(cleared))273 self.assertEqual(cleared[0].cleared, True)274 self.assertEqual(cleared[1].cleared, True)275 self.assertEqual(cleared[0].msg, str(msg))276 self.assertEqual(cleared[1].msg, str(msg))277 self.assertEqual(cleared[0].code, msg.code)278 self.assertEqual(cleared[1].code, msg.code)279 else:280 GanetiError.objects.clear_errors(obj=i)281 cleared = GanetiError.objects.get_errors(obj=i, cleared=True)282 self.assertEqual(2, len(cleared))283 self.assertEqual(cleared[0].cleared, True)284 self.assertEqual(cleared[1].cleared, True)285 self.assertEqual(cleared[0].msg, str(msg))286 self.assertEqual(cleared[1].msg, str(msg))287 self.assertEqual(cleared[0].code, msg.code)288 self.assertEqual(cleared[1].code, msg.code)289 # clear the error and retry290 RapiProxy.error = None291 for i in (cluster0, cluster1, vm0, vm1):292 self.refresh(i)293 self.assertEqual(None, i.error)294class TestErrorViews(TestGanetiErrorBase, TestCase):295 ...

Full Screen

Full Screen

tests.py

Source:tests.py Github

copy

Full Screen

...36 """37 # Empty email38 inauth = Auth(email='', password='Password1')39 self.assertEqual(inauth.is_valid(), False)40 self.assertIn('email', inauth.get_errors()[0].keys())41 self.assertEqual(inauth.get_errors()[0]['email'], Auth.errors_dict[NO_EMAIL_ERR][1])42 # Empty password43 inauth = Auth(email='test@site.com', password='')44 self.assertEqual(inauth.is_valid(), False)45 self.assertIn('password', inauth.get_errors()[0].keys())46 self.assertEqual(inauth.get_errors()[0]['password'], Auth.errors_dict[NO_PASSWORD_ERR][1])47 # Invalid password48 inauth = Auth(email='test@site.com', password='123')49 self.assertEqual(inauth.is_valid(), False)50 self.assertIn('password', inauth.get_errors()[0].keys())51 self.assertEqual(inauth.get_errors()[0]['password'], 'Your password must contain at least 6 characters.')52 # Commonly used password error53 inauth = Auth(email='test@site.com', password='123456')54 self.assertEqual(inauth.is_valid(), False)55 self.assertIn('password', inauth.get_errors()[0].keys())56 self.assertEqual(inauth.get_errors()[0]['password'], 'Your password can\'t be a commonly used password.')57 # Inactive user58 inauth = Auth(email=USER_EMAIL, password=USER_PASSWORD)59 self.assertEqual(inauth.is_valid(), False)60 self.assertIn('email', inauth.get_errors()[0].keys())61 self.assertEqual(inauth.get_errors()[0]['email'], Auth.errors_dict[DISABLED_USER_ERR][1])62 # Valid data63 inauth = Auth(email='some@test.com', password='1234df')64 self.assertEqual(inauth.is_valid(), True)65 def test_reset_password_class(self):66 """67 Checks workable `project.inauth.auth.ResetPassword` class.68 """69 # Missing email.70 reset_password = ResetPassword(email="")71 self.assertEqual(reset_password.is_valid(), False)72 self.assertIn('email', reset_password.get_errors()[0].keys())73 self.assertEqual(reset_password.get_errors()[0]['email'], Auth.errors_dict[NO_EMAIL_ERR][1])74 # Invalid email format75 reset_password = ResetPassword(email="wrong@email")76 self.assertEqual(reset_password.is_valid(), False)77 self.assertIn('email', reset_password.get_errors()[0].keys())78 self.assertEqual(reset_password.get_errors()[0]['email'], 'Enter a valid email address.')79 # User not found.80 reset_password = ResetPassword(email="wrong@email.com")81 self.assertEqual(reset_password.is_valid(), False)82 self.assertIn('email', reset_password.get_errors()[0].keys())83 self.assertEqual(reset_password.get_errors()[0]['email'], Auth.errors_dict[EMAIL_NOT_FOUND][1])84 # Inactive user85 reset_password = ResetPassword(email="valid_user@test.com")...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful