1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
|
"""Tests the service layer."""
from textwrap import dedent
import pytest
from autoimport.model import common_statements
from autoimport.services import fix_code
def test_fix_code_adds_missing_import() -> None:
"""Understands that os is a package and add it to the top of the file."""
source = "os.getcwd()"
fixed_source = dedent(
"""\
import os
os.getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_doesnt_change_source_if_package_doesnt_exist() -> None:
"""As foo is not found, nothing is changed."""
source = "foo"
result = fix_code(source)
assert result == source
def test_fix_imports_packages_below_docstring() -> None:
"""Imports are located below the module docstrings."""
source = dedent(
'''\
"""Module docstring.
"""
import pytest
os.getcwd()'''
)
fixed_source = dedent(
'''\
"""Module docstring.
"""
import os
os.getcwd()'''
)
result = fix_code(source)
assert result == fixed_source
def test_fix_imports_packages_below_single_line_docstring() -> None:
"""Imports are located below the module docstrings when they only take one line."""
source = dedent(
'''\
"""Module docstring."""
import pytest
os.getcwd()'''
)
fixed_source = dedent(
'''\
"""Module docstring."""
import os
os.getcwd()'''
)
result = fix_code(source)
assert result == fixed_source
def test_fix_imports_type_hints() -> None:
"""Typing objects are initialized with their required header."""
source = dedent(
"""\
def function(dictionary: Dict) -> None:
pass"""
)
fixed_source = dedent(
"""\
from typing import Dict
def function(dictionary: Dict) -> None:
pass"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_unneeded_imports() -> None:
"""If there is an import statement of an unused package it should be removed."""
source = dedent(
"""\
import requests
foo = 1"""
)
fixed_source = "foo = 1"
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_multiple_unneeded_imports() -> None:
"""
Given: A source code with multiple unused import statements.
When: fix_code is run.
Then: The unused import statements are deleted.
"""
source = dedent(
"""\
import requests
from textwrap import dedent
from yaml import YAMLError
foo = 1"""
)
fixed_source = "foo = 1"
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_unneeded_imports_in_from_statements() -> None:
"""Remove `from package import` statement of an unused packages."""
source = dedent(
"""\
from os import path
foo = 1"""
)
fixed_source = "foo = 1"
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_unused_imports_in_multiline_from_statements() -> None:
"""
Given: A source code with multiline import from statements.
When: fix_code is run
Then: Unused import statements are deleted
"""
source = dedent(
"""\
from os import (
getcwd,
path,
)
getcwd()"""
)
fixed_source = dedent(
"""\
from os import (
getcwd,
)
getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_unneeded_imports_in_beginning_of_from_statements() -> None:
"""Remove unused `object_name` in `from package import object_name, other_object`
statements.
"""
source = dedent(
"""\
from os import path, getcwd
getcwd()"""
)
fixed_source = dedent(
"""\
from os import getcwd
getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_unneeded_imports_in_middle_of_from_statements() -> None:
"""Remove unused `object_name` in
`from package import other_object, object_name, other_used_object` statements.
"""
source = dedent(
"""\
from os import getcwd, path, mkdir
getcwd()
mkdir()"""
)
fixed_source = dedent(
"""\
from os import getcwd, mkdir
getcwd()
mkdir()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_unneeded_imports_in_end_of_from_statements() -> None:
"""Remove unused `object_name` in `from package import other_object, object_name`
statements.
"""
source = dedent(
"""\
from os import getcwd, path
getcwd()"""
)
fixed_source = dedent(
"""\
from os import getcwd
getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_respects_multiple_from_import_lines() -> None:
"""
Given: Multiple from X import Y lines.
When: Fix code is run
Then: The import statements aren't broken
"""
source = dedent(
"""\
from os import getcwd
from re import match
getcwd()
match(r'a', 'a')"""
)
result = fix_code(source)
assert result == source
def test_fix_respects_multiple_from_import_lines_in_multiple_lines() -> None:
"""
Given: Multiple from X import Y lines, some with multiline format.
When: Fix code is run
Then: The import statements aren't broken
"""
source = dedent(
"""\
from os import (
getcwd,
)
from re import match
getcwd()
match(r'a', 'a')"""
)
result = fix_code(source)
assert result == source
def test_fix_respects_import_lines_in_multiple_line_strings() -> None:
"""
Given: Import lines in several multiline strings.
When: Fix code is run.
Then: The import statements inside the string are not moved to the top.
"""
source = dedent(
"""\
from textwrap import dedent
source = dedent(
\"\"\"\\
from re import match
match(r'a', 'a')\"\"\"
)
source = dedent(
\"\"\"\\
from os import (
getcwd,
)
getcwd()\"\"\"
)"""
)
fixed_source = dedent(
"""\
from textwrap import dedent
source = dedent(
\"\"\"\\
from re import match
match(r'a', 'a')\"\"\"
)
source = dedent(
\"\"\"\\
from os import (
getcwd,
)
getcwd()\"\"\"
)"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_moves_import_statements_to_the_top() -> None:
"""Move import statements present in the source code to the top of the file"""
source = dedent(
"""\
a = 3
import os
os.getcwd()"""
)
fixed_source = dedent(
"""\
import os
a = 3
os.getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_moves_import_statements_in_indented_code_to_the_top() -> None:
"""Move import statements present indented in the source code
to the top of the file
"""
source = dedent(
"""\
import requests
requests.get('hi')
def test():
import os
os.getcwd()"""
)
fixed_source = dedent(
"""\
import requests
import os
requests.get('hi')
def test():
os.getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_skips_moves_to_the_top_when_disabled_is_true() -> None:
"""Skip moving import statements when disable_move_to_top config is true."""
source = dedent(
"""\
import requests
requests.get('hi')
def test():
import os
os.getcwd()"""
)
config = {"disable_move_to_top": True}
result = fix_code(source, config)
assert result == source
def test_fix_skips_moves_to_the_top_when_disabled_is_false() -> None:
"""Moving import statements should still occur when disable_move_to_top
config is false.
"""
source = dedent(
"""\
import requests
requests.get('hi')
def test():
import os
os.getcwd()"""
)
fixed_source = dedent(
"""\
import requests
import os
requests.get('hi')
def test():
os.getcwd()"""
)
config = {"disable_move_to_top": False}
result = fix_code(source, config)
assert result == fixed_source
def test_fix_moves_from_import_statements_to_the_top() -> None:
"""Move from import statements present in the source code to the top of the file"""
source = dedent(
"""\
a = 3
from os import getcwd
getcwd()"""
)
fixed_source = dedent(
"""\
from os import getcwd
a = 3
getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_moves_multiline_import_statements_to_the_top() -> None:
"""
Given: Multiple from X import Y lines.
When: Fix code is run.
Then: The import statements are moved to the top.
"""
source = dedent(
"""\
from os import getcwd
getcwd()
from re import (
match,
)
match(r'a', 'a')"""
)
fixed_source = dedent(
"""\
from os import getcwd
from re import (
match,
)
getcwd()
match(r'a', 'a')"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_doesnt_break_objects_with_import_in_their_names() -> None:
"""Objects that have the import name in their name should not be changed."""
source = dedent(
"""\
def import_code():
pass
def code_import():
pass
def import():
pass
import_string = 'a'"""
)
result = fix_code(source)
assert result == source
def test_fix_doesnt_move_import_statements_with_noqa_to_the_top() -> None:
"""Ignore lines that have # noqa: autoimport."""
source = dedent(
"""\
a = 3
from os import getcwd # noqa: autoimport
getcwd()"""
)
result = fix_code(source)
assert result == source
def test_fix_doesnt_fail_on_noqa_lines_on_unused_import() -> None:
"""Ignore lines that have # noqa: autoimport."""
source = dedent(
"""\
from os import getcwd # noqa: autoimport"""
)
result = fix_code(source)
assert result == source
def test_fix_respects_fmt_skip_lines() -> None:
"""Ignore lines that have # fmt: skip."""
source = dedent(
"""
def why():
import pdb;pdb.set_trace() # fmt: skip
return 'dunno'
"""
).replace("\n", "", 1)
result = fix_code(source)
assert result == source
def test_fix_respects_noqa_in_from_import_lines_in_multiple_lines() -> None:
"""
Given: Multiple from X import Y lines, some with multiline format with noqa
statement.
When: Fix code is run.
Then: The import statements aren't broken.
"""
source = dedent(
"""\
from os import getcwd
getcwd()
from re import ( # noqa: autoimport
match,
)
match(r'a', 'a')"""
)
result = fix_code(source)
assert result == source
def test_fix_respects_strings_with_import_statements() -> None:
"""
Given: Code with a string that has import statements structure.
When: Fix code is run.
Then: The string is respected
"""
source = dedent(
"""\
import_string = 'import requests'
from_import_string = "from re import match"
multiline string = dedent(
\"\"\"\\
import requests
from re import match
\"\"\"
)
multiline single_quote_string = dedent(
\'\'\'\\
import requests
from re import match
\'\'\'
)
import os"""
)
fixed_source = dedent(
"""\
import os
import_string = 'import requests'
from_import_string = "from re import match"
multiline string = dedent(
\"\"\"\\
import requests
from re import match
\"\"\"
)
multiline single_quote_string = dedent(
\'\'\'\\
import requests
from re import match
\'\'\'
)"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_doesnt_mistake_docstrings_with_multiline_string() -> None:
"""
Given: A function with a docstring.
When: Fix code is run.
Then: The rest of the file is not mistaken for a long multiline string
"""
source = dedent(
"""\
def function_1():
\"\"\"Function docstring\"\"\"
import os
os.getcwd()"""
)
fixed_source = dedent(
"""\
import os
def function_1():
\"\"\"Function docstring\"\"\"
os.getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
@pytest.mark.parametrize(
("import_key", "import_statement"),
((key, value) for key, value in common_statements.items()),
ids=list(common_statements.keys()),
)
def test_fix_autoimports_common_imports(import_key: str, import_statement: str) -> None:
"""
Given: Code with missing import statements that match the common list.
When: Fix code is run.
Then: The imports are done
"""
source = dedent(
f"""\
import os
os.getcwd
variable = {import_key}"""
)
fixed_source = dedent(
f"""\
import os
{import_statement}
os.getcwd
variable = {import_key}"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_autoimports_objects_defined_in_the_root_of_the_package() -> None:
"""
Given:
The fix code is run from a directory that belongs to a python project package.
And a source code with an object that needs an import statement.
And that object belongs to the root of the python package.
When: Fix code is run.
Then: The import is done
"""
source = dedent(
"""\
fix_code()"""
)
fixed_source = dedent(
"""\
from autoimport import fix_code
fix_code()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_autoimports_objects_defined_in___all__special_variable() -> None:
"""
Given: Some missing packages in the __all__ variable
When: Fix code is run.
Then: The import is done
"""
source = dedent(
"""\
__all__ = ['fix_code']"""
)
fixed_source = dedent(
"""\
from autoimport import fix_code
__all__ = ['fix_code']"""
)
result = fix_code(source)
assert result == fixed_source
@pytest.mark.parametrize(
"source",
[
dedent(
"""\
import os
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .model import Book
os.getcwd()
def read_book(book: Book):
pass"""
),
dedent(
"""\
from typing import TYPE_CHECKING
if TYPE_CHECKING:
foo = "bar"
"""
),
],
)
def test_fix_respects_type_checking_import_statements(source: str) -> None:
"""
Given: Code with if TYPE_CHECKING imports
When: Fix code is run.
Then: The imports are not moved above the if statement.
Related to https://github.com/lyz-code/autoimport/issues/231
"""
result = fix_code(source)
assert result == source
def test_fix_respects_multiparagraph_type_checking_import_statements() -> None:
"""
Given: Code with two paragraphs of imports inside an if TYPE_CHECKING block
When: Fix code is run.
Then: The imports are not moved above the if statement.
"""
source = dedent(
"""\
import os
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .model import Book
from other import Other
os.getcwd()
def read_book(book: Book, other: Other):
pass"""
)
result = fix_code(source)
assert result == source
def test_fix_creates_the_typing_import() -> None:
"""
Given: Code with no TYPE_CHECKING import statement
When: Fix code is run.
Then: The import is created.
Related to https://github.com/lyz-code/autoimport/issues/231
"""
source = dedent(
"""\
if TYPE_CHECKING:
foo = 'bar'"""
)
fixed_source = dedent(
"""\
from typing import TYPE_CHECKING
if TYPE_CHECKING:
foo = 'bar'"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_respects_try_except_in_import_statements() -> None:
"""
Given: Code with try except statements in the imports.
When: Fix code is run
Then: The try except statements are respected
"""
source = dedent(
"""\
import os
try:
from typing import TypedDict # noqa
except ImportError:
from mypy_extensions import TypedDict # <=3.7
os.getcwd()
Movie = TypedDict('Movie', {'name': str, 'year': int})"""
)
result = fix_code(source)
assert result == source
def test_fix_respects_leading_comments() -> None:
"""
Given: Code with initial comments like shebang and editor configuration.
When: Fix code is run
Then: The comment statements are respected
"""
source = dedent(
'''\
#!/usr/bin/env python3
# -*- coding: latin-1 -*-
"""docstring"""
print(os.path.exists("."))'''
)
desired_source = dedent(
'''\
#!/usr/bin/env python3
# -*- coding: latin-1 -*-
"""docstring"""
import os
print(os.path.exists("."))'''
)
result = fix_code(source)
assert result == desired_source
def test_fix_respects_leading_comments_with_new_lines() -> None:
"""
Given: Code with initial comments with new lines and a trailing newline.
When: Fix code is run.
Then: The comment statements and trailing newline are respected.
"""
source = dedent(
'''\
#!/usr/bin/env python3
# -*- coding: latin-1 -*-
# pylint: disable=foobar
"""
This is the docstring.
"""
import sys
print(os.path.exists(sys.argv[1]))
'''
)
desired_source = dedent(
'''\
#!/usr/bin/env python3
# -*- coding: latin-1 -*-
# pylint: disable=foobar
"""
This is the docstring.
"""
import sys
import os
print(os.path.exists(sys.argv[1]))
'''
)
result = fix_code(source)
assert result == desired_source
def test_fix_imports_dependency_only_once() -> None:
"""
Given: Code with a line that uses a package three times.
When: Fix code is run.
Then: The dependency is imported only once
"""
source = dedent(
"""\
def f(x):
return os.getcwd() + os.getcwd() + os.getcwd()
"""
)
desired_source = dedent(
"""\
import os
def f(x):
return os.getcwd() + os.getcwd() + os.getcwd()
"""
)
result = fix_code(source)
assert result == desired_source
def test_fix_doesnt_fail_on_empty_file() -> None:
"""
Given: An empty file
When: Fix code is run.
Then: The output doesn't change
"""
source = ""
result = fix_code(source)
assert result == source
def test_fix_not_remove_unused_imports() -> None:
"""
Given: Code with imports, few being used, others not being used.
When: Fix code is run.
Then: Missing imports added, unused imports not removed.
"""
source = dedent(
"""\
import gzip
import hashlib
csv_writer = csv.DictWriter(filename, fieldnames=["name", "age"])
gzip.open(filename, 'wb')
"""
)
desired_source = dedent(
"""\
import gzip
import hashlib
import csv
csv_writer = csv.DictWriter(filename, fieldnames=["name", "age"])
gzip.open(filename, 'wb')
"""
)
result = fix_code(source, keep_unused_imports=True)
assert result == desired_source
def test_file_that_only_has_unused_imports() -> None:
"""
Given: A file that only has unused imports.
When: Fix code is run.
Then: The output should be a single empty line.
"""
source = dedent(
"""\
import os
import sys
"""
)
result = fix_code(source)
assert result == "\n"
def test_file_with_common_statement() -> None:
"""
Given: Code with a commonly-used object.
When: Fix code is run.
Then: The appropriate import statement from the common_statements dict is added.
"""
source = dedent(
"""\
BeautifulSoup
"""
)
desired_source = dedent(
"""\
from bs4 import BeautifulSoup
BeautifulSoup
"""
)
result = fix_code(source)
assert result == desired_source
def test_file_with_custom_common_statement() -> None:
"""
Given: Code that uses an undefined object called `FooBar`.
When:
Fix code is run and a `config` dict is passed specifying `FooBar` as a common
statement.
Then:
The appropriate import statement from the common_statements dict is added.
"""
source = dedent(
"""\
FooBar
"""
)
custom_config = {"common_statements": {"FooBar": "from baz_qux import FooBar"}}
desired_source = dedent(
"""\
from baz_qux import FooBar
FooBar
"""
)
result = fix_code(source, config=custom_config)
assert result == desired_source
def test_file_with_comment_in_import() -> None:
"""
Given: Code with a comment on two import statements
When: Fix code is run.
Then: The unused import line is removed with it's comment
"""
source = dedent(
"""\
import os # comment 1
import sys # comment 2
os.getcwd()
"""
)
desired_source = dedent(
"""\
import os # comment 1
os.getcwd()
"""
)
result = fix_code(source)
assert result == desired_source
def test_file_with_comment_in_from_import() -> None:
"""
Given: Code with a comment on two import statements
When: Fix code is run.
Then: The unused import line is removed with it's comment
"""
source = dedent(
"""\
import os # comment 1
from textwrap import dedent # comment 2
os.getcwd()
"""
)
desired_source = dedent(
"""\
import os # comment 1
os.getcwd()
"""
)
result = fix_code(source)
assert result == desired_source
def test_file_with_comment_in_from_import_partial_remove() -> None:
"""
Given: Code with a comment on an from import statement
When: Fix code is run.
Then: The unused dependency is removed but the comment is respected
"""
source = dedent(
"""\
from os import getcwd, chmod # noqa: E0611
getcwd()
"""
)
desired_source = dedent(
"""\
from os import getcwd # noqa: E0611
getcwd()
"""
)
result = fix_code(source)
assert result == desired_source
def test_file_with_comment_in_from_import_that_will_dissapear() -> None:
"""
Given: Code with a comment on an from import statement that is to be deleted
When: Fix code is run.
Then: Everything is deleted
"""
source = dedent(
"""\
from os import getcwd, chmod # noqa: E0611
a = 1
"""
)
desired_source = dedent(
"""\
a = 1
"""
)
result = fix_code(source)
assert result == desired_source
def test_file_with_import_as() -> None:
"""
Given: Code with an from x import y as z import statement
When: Fix code is run.
Then: The unused import line is removed
"""
source = dedent(
"""\
from subprocess import run as run
"""
)
result = fix_code(source)
assert result == "\n"
def test_file_with_non_used_multiline_import() -> None:
"""
Given: Code with a multiline from import where no one is used.
When: Fix code is run.
Then: The unused import line is removed
"""
source = dedent(
"""\
from foo import (
bar,
baz,
)
"""
)
result = fix_code(source)
assert result == "\n"
def test_file_with_import_and_seperator() -> None:
"""Ensure import lines with seperators are fixed correctly."""
source = dedent(
"""
a = 1
import pdb;pdb.set_trace()
b = 2
"""
)
expected = dedent(
"""
import pdb
a = 1
pdb.set_trace()
b = 2
"""
).replace("\n", "", 1)
result = fix_code(source)
assert result == expected
def test_file_with_import_and_seperator_indentation() -> None:
"""Ensure import lines with seperators are fixed correctly when indented."""
source = dedent(
"""
Class Person:
import pdb; pdb.set_trace()
def say_hi(self):
print('hi')
"""
)
expected = dedent(
"""
import pdb
Class Person:
pdb.set_trace()
def say_hi(self):
print('hi')
"""
).replace("\n", "", 1)
result = fix_code(source)
assert result == expected
def test_import_module_with_dot() -> None:
"""
Given: An import file with an import with a dot
When: running autoimport on the file
Then: ValueError exception is not raised
Tests https://github.com/lyz-code/autoimport/issues/225
"""
source = dedent(
"""
import my_module.m
"""
)
result = fix_code(source)
assert result == "\n"
def test_respect_new_lines_between_imports_and_code() -> None:
r"""
Given: A file with two \n between imports and the code
When: running autoimport on the file
Then: the file is untouched
For more info check https://github.com/lyz-code/autoimport/issues/219
"""
source = dedent(
"""\
import random
def foo():
print(random.random())
"""
)
result = fix_code(source)
assert result == source
|