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 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
|
#!/usr/bin/env python3
import contextlib
import io
import os
import shutil
import sixer
import subprocess
import sys
import tempfile
import textwrap
import types
import unittest
SIXER = os.path.join(os.path.dirname(__file__), "sixer.py")
@contextlib.contextmanager
def replace_stream(attr):
old_stream = getattr(sys, attr)
try:
stream = io.StringIO()
setattr(sys, attr, stream)
yield stream
finally:
setattr(sys, attr, old_stream)
def run_sixer(operation, *args):
args = (sys.executable, SIXER, '--write', operation) + args
proc = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
with proc:
stdout, stderr = proc.communicate()
exitcode = proc.wait()
return (exitcode, os.fsdecode(stdout), os.fsdecode(stderr))
def mock_options(kw):
options = types.SimpleNamespace()
options.max_range = kw.pop('max_range', sixer.MAX_RANGE)
options.to_stdout = False
options.quiet = False
options.app = kw.pop('app', None)
options.third_party = kw.pop('third_party', None)
options.write = True
return options
class AddImportTests(unittest.TestCase):
def check(self, line, before, after, **kw):
# Keywords: app=None
before = textwrap.dedent(before).strip() + "\n"
after = textwrap.dedent(after).strip() + "\n"
options = mock_options(kw)
patcher = sixer.Patcher(('print',), options)
output = patcher.add_import(before, line)
self.assertEqual(output, after)
def check_unchanged(self, line, code):
self.check(line, code, code)
def test_exiting(self):
self.check_unchanged('import six', """
import six # comment
code
""")
self.check_unchanged('import six', """
import six
code
""")
self.check_unchanged('from __future__ import print_function', """
from __future__ import print_function
code
""")
def test_add_import_six(self):
# no import before
self.check('import six', """
code
""", """
import six
code
""")
# add to existing group, before existing import
self.check('import numpy', """
import six
code
""", """
import numpy
import six
code
""")
# add to existing group, after existing import
self.check('import six', """
import numpy
code
""", """
import numpy
import six
code
""")
# add new future group before
self.check('import six', """
import app
code
""", """
import six
import app
code
""", app='app')
def test_add_future(self):
# no import before
self.check('from __future__ import print_function', """
code
""", """
from __future__ import print_function
code
""")
# add to existing group, before existing import
self.check('from __future__ import absolute_import', """
from __future__ import print_function
code
""", """
from __future__ import absolute_import
from __future__ import print_function
code
""")
# add to existing group, after existing import
self.check('from __future__ import print_function', """
from __future__ import absolute_import
code
""", """
from __future__ import absolute_import
from __future__ import print_function
code
""")
# add new future group before
self.check('from __future__ import print_function', """
import sys
code
""", """
from __future__ import print_function
import sys
code
""")
class TestUtils(unittest.TestCase):
def test_parse_import_groups(self):
self.assertEqual(sixer.parse_import_groups('import sys\n\nimport six\n'),
[(0, 12, {'sys'}), (12, 23, {'six'})])
self.assertEqual(sixer.parse_import_groups('import sys\n\nimport six\n\nimport nova\n'),
[(0, 12, {'sys'}), (12, 24, {'six'}), (24, 36, {'nova'})])
self.assertEqual(sixer.parse_import_groups('import a\nimport b\nimport c\n'),
[(0, 27, {'a', 'b', 'c'})])
class TestOperations(unittest.TestCase):
def _check(self, operation, before, after, **kw):
warnings = kw.pop('warnings', None)
ignore_warnings = kw.pop('ignore_warnings', False)
options = mock_options(kw)
patcher = sixer.Patcher((operation,), options)
for attr, value in kw.items():
raise ValueError("%r:%r" % (attr, value))
setattr(patcher.options, attr, value)
with tempfile.NamedTemporaryFile("w+") as temp:
temp.write(before)
temp.flush()
with replace_stream('stdout'), replace_stream('stderr'):
patcher.patch(temp.name)
temp.seek(0)
code = temp.read()
self.assertEqual(code, after)
if not ignore_warnings:
if warnings:
self.assertEqual(len(patcher.warnings), len(warnings))
for index, expected in enumerate(warnings):
msg = patcher.warnings[index].split(": ", 1)[1]
self.assertEqual(msg, expected)
else:
self.assertEqual(patcher.warnings, [])
def check_program(self, operation, before, after, *args):
with tempfile.NamedTemporaryFile("w+") as tmp:
tmp.write(before)
tmp.flush()
args = args + (tmp.name,)
exitcode, stdout, stderr = run_sixer(operation, *args)
self.assertEqual(exitcode, 0)
#self.assertEqual(stderr, '')
tmp.seek(0)
code = tmp.read()
self.assertEqual(code, after)
def check(self, operation, before, after, **kw):
before = textwrap.dedent(before).strip() + "\n"
after = textwrap.dedent(after).strip() + "\n"
check_program = kw.pop('check_program', True)
# Ensure that the code is patched as expected
self._check(operation, before, after, **kw)
# Ensure that after is not modified by fixer
self._check(operation, after, after, ignore_warnings=True)
# Test command line
if check_program:
args = []
for key, arg_format in (
('app', '--app=%s'),
('third_party', '--third-party=%s'),
('max_range', '--max-range=%s'),
):
arg = kw.get(key)
if arg:
args.append(arg_format % arg)
self.check_program(operation, before, after, *args)
def check_unchanged(self, operation, code, **kw):
self.check(operation, code, code, **kw)
def test_add_import(self):
# import ...
self.check("urllib",
"""
import StringIO
import urllib2
import cue.tests.functional.fixtures.base as base
urllib2.urlopen(url)
""",
"""
import StringIO
from six.moves import urllib
import cue.tests.functional.fixtures.base as base
urllib.request.urlopen(url)
""",
app="cue")
# from ... import ...
self.check("urllib",
"""
import StringIO
from urllib2 import urlopen
import cue.tests.functional.fixtures.base as base
""",
"""
import StringIO
from six.moves.urllib.request import urlopen
import cue.tests.functional.fixtures.base as base
""",
app="cue")
# unable to find the best place
self.check("unicode",
"""
import numpypy
unicode
""",
"""
import numpypy
import six
six.text_type
""",
warnings=["Failed to find the best place to add 'import six': "
"put it at the end. Use --app and --third-party "
"options."])
# test third-party option
self.check("unicode",
"""
import numpypy
unicode
""",
"""
import numpypy
import six
six.text_type
""",
third_party="xyz,numpypy")
def test_raise2(self):
self.check("raise",
"raise Exception, 'message'",
"raise Exception('message')")
# no space after comma
self.check("raise",
"raise Exception,'message'",
"raise Exception('message')")
def test_raise3(self):
self.check("raise",
"raise a, b, c",
"""
import six
six.reraise(a, b, c)
""")
# no space after comma
self.check("raise",
"raise a,b,c",
"""
import six
six.reraise(a, b, c)
""")
def test_reraise(self):
self.check("raise",
"raise exc[0], exc[1], exc[2]",
"""
import six
six.reraise(*exc)
""")
def test_xrange(self):
self.check("xrange",
"for i in xrange(10): pass",
"for i in range(10): pass")
self.check("xrange",
"for i in xrange(n): pass",
"""
from six.moves import range
for i in range(n): pass
""")
self.check("xrange",
"for i in xrange(10): pass",
"""
from six.moves import range
for i in range(10): pass
""",
max_range=5)
self.check_unchanged("xrange",
"from six.moves import xrange")
self.check_unchanged("xrange",
"""
from six import moves
x = list(moves.xrange(n))
x = list(moves.xrange(5))
x = list(moves.xrange(1, 9))
x = list(moves.xrange(0, 10, 2))
""")
def test_unicode(self):
self.check("unicode",
"value = unicode(data)",
"""
import six
value = six.text_type(data)
""")
self.check("unicode",
"""
isinstance('hello', (str,unicode))
isinstance('hello', (str, unicode))
""",
"""
import six
isinstance('hello', six.string_types)
isinstance('hello', six.string_types)
""")
def test_add_six_import(self):
# only stdlib
self.check("unicode",
"""
import copy
t = unicode
""",
"""
import copy
import six
t = six.text_type
""")
# only third party
self.check("unicode",
"""
import oslo_utils
t = unicode
""",
"""
import oslo_utils
import six
t = six.text_type
""")
# stdlib+third party
self.check("unicode",
"""
import copy
import oslo_utils
t = unicode
""",
"""
import copy
import oslo_utils
import six
t = six.text_type
""")
# only application
self.check("unicode",
"""
import nova
t = unicode
""",
"""
import six
import nova
t = six.text_type
""")
def test_unicode_unchanged(self):
self.check_unchanged("unicode",
"""
import unicodedata
# unicode in comments
def test_unicode():
pass
""")
def test_iteritems(self):
self.check("iteritems",
"for key, value in data.iteritems(): pass",
"""
import six
for key, value in six.iteritems(data): pass
""")
def test_iteritems_expr(self):
self.check("iteritems",
"""
items = obj.data[0].attr.iteritems()
""",
"""
import six
items = six.iteritems(obj.data[0].attr)
""")
def test_itervalues(self):
self.check("itervalues",
"for value in data.itervalues(): pass",
"""
import six
for value in six.itervalues(data): pass
""")
def test_iterkeys(self):
self.check("iterkeys",
"for value in data.iterkeys(): pass",
"for value in data: pass")
self.check("iterkeys",
"keys = data.iterkeys()",
"""
import six
keys = six.iterkeys(data)
""")
def test_has_key(self):
self.check("has_key",
"dict.has_key(key)",
"key in dict")
def test_next(self):
self.check("next",
"item = gen.next()",
"item = next(gen)")
self.check("next",
"item = (x+1 for x in data).next()",
"item = next(x+1 for x in data)")
self.check("next",
"item = ((x * 2) for x in data).next()",
"item = next((x * 2) for x in data)")
self.check_unchanged("next",
"""
import six
a = six.next(iter("abc"))
""")
def test_long(self):
self.check("long",
"values = (0L, 1L, 12L, 123L, 1234L, 12345L)",
"values = (0, 1, 12, 123, 1234, 12345)")
# lower case
self.check("long",
"x = 1l",
"x = 1")
# hexadecimal
self.check("long",
"values = (0x1L, 0x1l, 0xfL, 0x0L)",
"values = (0x1, 0x1, 0xf, 0x0)")
# octal
self.check("long",
"values = (00L, 000L, 01L, 012L, 0123L, 01234L, 012345L)",
"values = (0o0, 0o00, 0o1, 0o12, 0o123, 0o1234, 0o12345)")
# (int, long)
self.check("long",
"isinstance(s, (int, long))",
"""
import six
isinstance(s, six.integer_types)
""")
# long(2)
self.check("long",
"x = long(1)",
"x = 1")
def test_basestring(self):
self.check("basestring",
"isinstance(foo, basestring)",
"""
import six
isinstance(foo, six.string_types)
""")
def test_six_moves_import(self):
self.check("six_moves",
"""
import __builtin__
__builtin__.open()
""",
"""
from six.moves import builtins
builtins.open()
""")
self.check("six_moves",
"""
import cPickle as pickle
pickle
""",
"""
from six.moves import cPickle as pickle
pickle
""")
def test_six_moves_from_import(self):
self.check("six_moves",
"""
from __builtin__ import len, open
len([])
""",
"""
from six.moves.builtins import len, open
len([])
""")
def test_six_moves_builtin(self):
# patch reload
self.check("six_moves",
"""
import sys
reload(sys)
""",
"""
import sys
from six.moves import reload_module
reload_module(sys)
""")
# patch reduce
self.check("six_moves",
"""
reduce(lambda x, y: x*10+y, [1, 2, 3])
""",
"""
from six.moves import reduce
reduce(lambda x, y: x*10+y, [1, 2, 3])
""")
# patch reload, don't patch reduce
self.check("six_moves",
"""
import sys
from six.moves import reduce
print(reduce(lambda x, y: x*10+y, [1, 2, 3]))
reload(sys)
""",
"""
import sys
from six.moves import reduce
from six.moves import reload_module
print(reduce(lambda x, y: x*10+y, [1, 2, 3]))
reload_module(sys)
""")
# don't touch moves.reduce()
self.check_unchanged("six_moves",
"""
from six import moves
print(moves.reduce(lambda x, y: x*10+y, [1, 2, 3]))
""")
def test_six_moves_mock_patch(self):
# mock.patch()
self.check("six_moves",
"with mock.patch('__builtin__.open'): pass",
"with mock.patch('six.moves.builtins.open'): pass")
# patch()
self.check("six_moves",
"with patch('__builtin__.open'): pass",
"with patch('six.moves.builtins.open'): pass")
def test_six_moves_functions(self):
# unichr()
self.check("six_moves",
"print(unichr(0x20ac))",
"""
import six
print(six.unichr(0x20ac))
""")
def test_six_moves_configparser(self):
# must not be replaced with configparser.configparser,
# but configparser.ConfigParser
self.check("six_moves",
"""
import ConfigParser
cfg = ConfigParser.ConfigParser()
""",
"""
from six.moves import configparser
cfg = configparser.ConfigParser()
""")
def test_stringio(self):
# import StringIO
self.check("stringio",
"""
import StringIO
s = StringIO.StringIO()
""",
"""
import six
s = six.StringIO()
""")
# from StringIO import StringIO
self.check("stringio",
"""
from StringIO import StringIO
s = StringIO()
""",
"""
from six import StringIO
s = StringIO()
""")
# import cStringIO
self.check("stringio",
"""
import cStringIO
s = cStringIO.StringIO()
""",
"""
from six import moves
s = moves.cStringIO()
""")
# import cStringIO as StringIO
self.check("stringio",
"""
import cStringIO as StringIO
s = StringIO.StringIO()
""",
"""
from six import moves
s = moves.cStringIO()
""")
# from cStringIO import StringIO
self.check("stringio",
"""
from cStringIO import StringIO
s = StringIO()
""",
"""
from six.moves import cStringIO as StringIO
s = StringIO()
""")
def test_urllib_import(self):
# urllib.urlopen
self.check("urllib",
"""
import urllib
urllib.urlopen(url)
""",
"""
from six.moves import urllib
urllib.request.urlopen(url)
""")
# urllib2.urlopen, urllib2.URLError
self.check("urllib",
"""
import urllib2
try:
urllib2.urlopen(url)
except urllib2.URLError as exc:
pass
""",
"""
from six.moves import urllib
try:
urllib.request.urlopen(url)
except urllib.error.URLError as exc:
pass
""")
# urllib2.urlparse.urlparse
self.check("urllib",
"""
import urllib2
urllib2.urlparse.urlparse('')
""",
"""
from six.moves import urllib
urllib.parse.urlparse('')
""")
# urlparse
self.check("urllib",
"""
import urlparse
urlparse.urlparse(uri)
""",
"""
from six.moves import urllib
urllib.parse.urlparse(uri)
""")
# don't touch parse_http_list
self.check_unchanged("urllib",
"""
urllib2.parse_http_list()
""",
warnings=['urllib2.parse_http_list()'])
def test_urllib_from_import(self):
self.check("urllib",
"""
from urllib import quote, urlopen
from urllib2 import urlopen, URLError
quote("abc")
""",
"""
from six.moves.urllib.error import URLError
from six.moves.urllib.parse import quote
from six.moves.urllib.request import urlopen
quote("abc")
""")
self.check("urllib",
"""
import sys
from urllib import quote
quote("abc")
""",
"""
import sys
from six.moves.urllib.parse import quote
quote("abc")
""")
def test_urllib_unknown_symbol(self):
self.check("urllib",
"""
import urllib2
# urllib2.open
urllib2.urlopen(url)
""",
"""
from six.moves import urllib
# urllib2.open
urllib.request.urlopen(url)
""",
warnings=['Unknown urllib symbol: urllib2.open'])
def test_all(self):
self.check("all",
"""
values = (0L, 1L, 12L, 123L, 1234L, 12345L)
for i in xrange(10): pass
""",
"""
values = (0, 1, 12, 123, 1234, 12345)
for i in range(10): pass
""")
def test_itertools_from_import(self):
self.check("itertools",
"""
from itertools import imap
for x in imap(str.upper, "abc"):
print(x)
""",
"""
import six
for x in six.moves.map(str.upper, "abc"):
print(x)
""")
self.check("itertools",
"""
from itertools import izip
for x, y in izip(range(3), "abc"):
print(x, y)
""",
"""
import six
for x, y in six.moves.zip(range(3), "abc"):
print(x, y)
""")
def test_itertools_import(self):
self.check("itertools",
"""
import itertools
for x in itertools.ifilter(str.upper, "abc"):
print(x)
""",
"""
import six
for x in six.moves.filter(str.upper, "abc"):
print(x)
""")
self.check("itertools",
"""
import itertools
for x in itertools.imap(str.upper, "abc"):
print(x)
x = itertools.chain
""",
"""
import itertools
import six
for x in six.moves.map(str.upper, "abc"):
print(x)
x = itertools.chain
""")
def test_dict0(self):
self.check("dict0",
"""
x = {1: 2}
first_key = x.keys()[0]
first_value = x.values()[0]
first_item = x.items()[0]
""",
"""
x = {1: 2}
first_key = list(x.keys())[0]
first_value = list(x.values())[0]
first_item = list(x.items())[0]
""")
self.check("dict0",
"""
x1 = x.values()[1]
x123 = x.values()[123]
""",
"""
x1 = list(x.values())[1]
x123 = list(x.values())[123]
""")
def test_dict_add(self):
self.check("dict_add",
"""
x = {1: 2}
keys = x.keys() + [3]
values = x.values() + [4]
items = x.items() + [5]
""",
"""
x = {1: 2}
keys = list(x.keys()) + [3]
values = list(x.values()) + [4]
items = list(x.items()) + [5]
""")
def test_except(self):
# except ValueError
self.check("except",
"""
try: func()
except ValueError, exc: pass
# no space
try: func()
except TypeError,exc:pass
""",
"""
try: func()
except ValueError as exc: pass
# no space
try: func()
except TypeError as exc:pass
""")
# except (ValueError, TypeError)
self.check("except",
"""
try: func()
except (ValueError, TypeError), exc: pass
# no space
try: func()
except (ValueError,TypeError),exc:pass
""",
"""
try: func()
except (ValueError, TypeError) as exc: pass
# no space
try: func()
except (ValueError,TypeError) as exc:pass
""")
# except (ValueError, TypeError, KeyError)
self.check("except",
"""
try: func()
except (ValueError, TypeError, KeyError), exc: pass
# no space
try: func()
except (ValueError,TypeError,KeyError),exc:pass
""",
"""
try: func()
except (ValueError, TypeError, KeyError) as exc: pass
# no space
try: func()
except (ValueError,TypeError,KeyError) as exc:pass
""")
# except select.error
self.check("except",
"""
try: func()
except select.error, exc: pass
""",
"""
try: func()
except select.error as exc: pass
""")
def test_print(self):
# print
self.check("print",
"""
print
print#comment
print # comment
""",
"""
from __future__ import print_function
print()
print()#comment
print() # comment
""")
# print msg
self.check("print",
"""
print "hello"
print 'hello'
print msg
print msg
print msg
""",
"""
print("hello")
print('hello')
print(msg)
print (msg)
print (msg)
""")
# test STRING_REGEX
self.check("print",
r"""
print "tab\tnewline\n>\"<"
print 'tab\tnewline\n>\'<'
""",
r"""
print("tab\tnewline\n>\"<")
print('tab\tnewline\n>\'<')
""")
# print msg,
self.check("print",
"""
import sys
print "hello",
print "hello",
print "hello",
""",
"""
from __future__ import print_function
import sys
print("hello", end=' ')
print ("hello", end=' ')
print ("hello", end=' ')
""")
# print arg1,arg2
self.check_unchanged("print",
'print "note",note',
warnings=['print "note",note'])
def check_print_into(self, before, after):
self.check("print", '''
import sys
%s
''' % before, '''
from __future__ import print_function
import sys
%s
''' % after)
def test_print_into(self):
self.check_print_into('print >>sys.stderr, "hello"',
'print("hello", file=sys.stderr)')
# no space
self.check_print_into('print>>sys.stderr,"hello"',
'print("hello", file=sys.stderr)')
# 2 spaces before >>
self.check_print_into('print >>sys.stderr, "hello"',
'print ("hello", file=sys.stderr)')
# 3 spaces before >>
self.check_print_into('print >>sys.stderr, "hello"',
'print ("hello", file=sys.stderr)')
def test_string(self):
# upper/lower case
self.check("string",
"""
import string
x = string.lower("ABC")
x = string.upper("abc")
x = string.swapcase("ABCdef")
""",
"""
x = "ABC".lower()
x = "abc".upper()
x = "ABCdef".swapcase()
""")
# strip, split
self.check("string",
"""
import string
x = string.strip(" abc ")
x = string.lstrip(" abc ")
x = string.rstrip(" abc ")
x = string.strip(" def ", ' ')
x = string.lstrip(" def ", ' ')
x = string.rstrip(" def ", ' ')
""",
"""
x = " abc ".strip()
x = " abc ".lstrip()
x = " abc ".rstrip()
x = " def ".strip(' ')
x = " def ".lstrip(' ')
x = " def ".rstrip(' ')
""")
# string.atoX()
self.check("string",
"""
import string
x = string.atof("1.0")
x = string.atoi("123")
x = string.atol("123")
""",
"""
x = float("1.0")
x = int("123")
x = int("123")
""")
# string.letter must emit a warning
self.check_unchanged("string",
"""
import string
x = string.letters
""",
warnings=['x = string.letters'])
# string.ascii_letter is fine (no warning)
self.check_unchanged("string",
"""
import string
x = string.ascii_letters
""")
class TestProgram(unittest.TestCase):
def run_sixer(self, scanned, *paths):
exitcode, stdout, stderr = run_sixer("all", *paths)
self.assertEqual(exitcode, 0)
msg = 'Scanned %s files\n' % scanned
self.assertIn(msg, stdout)
self.assertEqual(stderr, '')
return stdout
def test_patch_file(self):
with tempfile.NamedTemporaryFile("w+", encoding="ASCII") as tmp:
tmp.write("x = 1L\n")
tmp.flush()
stdout = self.run_sixer(1, tmp.name)
tmp.seek(0)
code = tmp.read()
self.assertEqual(code, "x = 1\n")
def test_patch_dir(self):
files = []
path = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, path)
filename = os.path.join(path, "file1.py")
with open(filename, "w", encoding="ASCII") as f:
f.write("x = 1L\n")
files.append((filename, "x = 1\n"))
filename = os.path.join(path, "file2.py")
with open(filename, "w", encoding="ASCII") as f:
f.write("unicode\n")
files.append((filename, "import six\n\n\nsix.text_type\n"))
stdout = self.run_sixer(2, path)
for filename, after in files:
with open(filename, encoding="ASCII") as f:
code = f.read()
self.assertEqual(code, after, "file=%r" % filename)
def test_empty_dir(self):
path = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, path)
exitcode, stdout, stderr = run_sixer("all", path)
self.assertEqual(exitcode, 1)
self.assertIn('Scanned 0 files\n', stdout)
msg = "WARNING: Directory %s doesn't contain any .py file\n" % path
self.assertIn(msg, stderr)
def test_nonexistent_path(self):
path = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, path)
filename = os.path.join(path, 'nonexistent')
exitcode, stdout, stderr = run_sixer("all", filename)
self.assertEqual(exitcode, 1)
self.assertIn('Scanned 0 files\n', stdout)
msg = ("WARNING: Path %s doesn't exist\n"
% filename)
self.assertIn(msg, stderr)
def test_nonexistent_operation(self):
with tempfile.NamedTemporaryFile("w+", encoding="ASCII") as tmp:
tmp.write("x = 1L\n")
tmp.flush()
exitcode, stdout, stderr = run_sixer("nonexistent", tmp.name)
self.assertEqual(exitcode, 1)
self.assertEqual(stderr, '')
expected = ("invalid operation: 'nonexistent'\n"
"\n"
"Usage: sixer.py [options]")
self.assertTrue(stdout.startswith(expected), stdout)
if __name__ == "__main__":
unittest.main()
|