File: test_futurize.py

package info (click to toggle)
python-future 0.18.2-6
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,264 kB
  • sloc: python: 43,246; makefile: 136; sh: 29
file content (1432 lines) | stat: -rw-r--r-- 43,335 bytes parent folder | download | duplicates (2)
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
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

import pprint
import tempfile
from subprocess import Popen, PIPE
import os

from libfuturize.fixer_util import is_shebang_comment, is_encoding_comment
from lib2to3.fixer_util import FromImport
from lib2to3.pytree import Leaf, Node
from lib2to3.pygram import token

from future.tests.base import (CodeHandler, unittest, skip26, reformat_code,
                               order_future_lines, expectedFailurePY26)
from future.utils import PY2


class TestLibFuturize(unittest.TestCase):

    def setUp(self):
        # For tests that need a text file:
        _, self.textfilename = tempfile.mkstemp(text=True)
        super(TestLibFuturize, self).setUp()

    def tearDown(self):
        os.unlink(self.textfilename)

    def test_correct_exit_status(self):
        """
        Issue #119: futurize and pasteurize were not exiting with the correct
        status code. This is because the status code returned from
        libfuturize.main.main() etc. was a ``newint``, which sys.exit() always
        translates into 1!
        """
        from libfuturize.main import main
        retcode = main([self.textfilename])
        self.assertTrue(isinstance(retcode, int))   # i.e. Py2 builtin int

    def test_is_shebang_comment(self):
        """
        Tests whether the fixer_util.is_encoding_comment() function is working.
        """
        shebang_comments = [u'#!/usr/bin/env python\n'
                             u"#!/usr/bin/python2\n",
                             u"#! /usr/bin/python3\n",
                            ]
        not_shebang_comments = [u"# I saw a giant python\n",
                                 u"# I have never seen a python2\n",
                               ]
        for comment in shebang_comments:
            node = FromImport(u'math', [Leaf(token.NAME, u'cos', prefix=" ")])
            node.prefix = comment
            self.assertTrue(is_shebang_comment(node))

        for comment in not_shebang_comments:
            node = FromImport(u'math', [Leaf(token.NAME, u'cos', prefix=" ")])
            node.prefix = comment
            self.assertFalse(is_shebang_comment(node))


    def test_is_encoding_comment(self):
        """
        Tests whether the fixer_util.is_encoding_comment() function is working.
        """
        encoding_comments = [u"# coding: utf-8",
                             u"# encoding: utf-8",
                             u"# -*- coding: latin-1 -*-",
                             u"# vim: set fileencoding=iso-8859-15 :",
                            ]
        not_encoding_comments = [u"# We use the file encoding utf-8",
                                 u"coding = 'utf-8'",
                                 u"encoding = 'utf-8'",
                                ]
        for comment in encoding_comments:
            node = FromImport(u'math', [Leaf(token.NAME, u'cos', prefix=" ")])
            node.prefix = comment
            self.assertTrue(is_encoding_comment(node))

        for comment in not_encoding_comments:
            node = FromImport(u'math', [Leaf(token.NAME, u'cos', prefix=" ")])
            node.prefix = comment
            self.assertFalse(is_encoding_comment(node))


class TestFuturizeSimple(CodeHandler):
    """
    This class contains snippets of Python 2 code (invalid Python 3) and
    tests for whether they can be passed to ``futurize`` and immediately
    run under both Python 2 again and Python 3.
    """

    def test_encoding_comments_kept_at_top(self):
        """
        Issues #10 and #97: If there is a source encoding comment line
        (PEP 263), is it kept at the top of a module by ``futurize``?
        """
        before = """
        # coding=utf-8

        print 'Hello'
        """
        after = """
        # coding=utf-8

        from __future__ import print_function
        print('Hello')
        """
        self.convert_check(before, after)

        before = """
        #!/usr/bin/env python
        # -*- coding: latin-1 -*-"

        print 'Hello'
        """
        after = """
        #!/usr/bin/env python
        # -*- coding: latin-1 -*-"

        from __future__ import print_function
        print('Hello')
        """
        self.convert_check(before, after)

    def test_multiline_future_import(self):
        """
        Issue #113: don't crash if a future import has multiple lines
        """
        text = """
        from __future__ import (
            division
        )
        """
        self.convert(text)

    def test_shebang_blank_with_future_division_import(self):
        """
        Issue #43: Is shebang line preserved as the first
        line by futurize when followed by a blank line?
        """
        before = """
        #!/usr/bin/env python

        import math
        1 / 5
        """
        after = """
        #!/usr/bin/env python

        from __future__ import division
        from past.utils import old_div
        import math
        old_div(1, 5)
        """
        self.convert_check(before, after)

    def test_shebang_blank_with_print_import(self):
        before = """
        #!/usr/bin/env python

        import math
        print 'Hello'
        """
        after = """
        #!/usr/bin/env python
        from __future__ import print_function

        import math
        print('Hello')
        """
        self.convert_check(before, after)

    def test_shebang_comment(self):
        """
        Issue #43: Is shebang line preserved as the first
        line by futurize when followed by a comment?
        """
        before = """
        #!/usr/bin/env python
        # some comments
        # and more comments

        import math
        print 'Hello!'
        """
        after = """
        #!/usr/bin/env python
        # some comments
        # and more comments
        from __future__ import print_function

        import math
        print('Hello!')
        """
        self.convert_check(before, after)

    def test_shebang_docstring(self):
        """
        Issue #43: Is shebang line preserved as the first
        line by futurize when followed by a docstring?
        """
        before = '''
        #!/usr/bin/env python
        """
        a doc string
        """
        import math
        print 'Hello!'
        '''
        after = '''
        #!/usr/bin/env python
        """
        a doc string
        """
        from __future__ import print_function
        import math
        print('Hello!')
        '''
        self.convert_check(before, after)

    def test_oldstyle_classes(self):
        """
        Stage 2 should convert old-style to new-style classes. This makes
        the new-style class explicit and reduces the gap between the
        behaviour (e.g.  method resolution order) on Py2 and Py3. It also
        allows us to provide ``newobject`` (see
        test_oldstyle_classes_iterator).
        """
        before = """
        class Blah:
            pass
        """
        after = """
        from builtins import object
        class Blah(object):
            pass
        """
        self.convert_check(before, after, ignore_imports=False)

    def test_oldstyle_classes_iterator(self):
        """
        An old-style class used as an iterator should be converted
        properly. This requires ``futurize`` to do both steps (adding
        inheritance from object and adding the newobject import) in the
        right order. Any next() method should also be renamed to __next__.
        """
        before = """
        class Upper:
            def __init__(self, iterable):
                self._iter = iter(iterable)
            def next(self):
                return next(self._iter).upper()
            def __iter__(self):
                return self

        assert list(Upper('hello')) == list('HELLO')
        """
        after = """
        from builtins import next
        from builtins import object
        class Upper(object):
            def __init__(self, iterable):
                self._iter = iter(iterable)
            def __next__(self):
                return next(self._iter).upper()
            def __iter__(self):
                return self

        assert list(Upper('hello')) == list('HELLO')
        """
        self.convert_check(before, after, ignore_imports=False)

        # Try it again with this convention: class Upper():
        before2 = """
        class Upper():
            def __init__(self, iterable):
                self._iter = iter(iterable)
            def next(self):
                return next(self._iter).upper()
            def __iter__(self):
                return self

        assert list(Upper('hello')) == list('HELLO')
        """
        self.convert_check(before2, after)

    @unittest.expectedFailure
    def test_problematic_string(self):
        """ This string generates a SyntaxError on Python 3 unless it has
        an r prefix.
        """
        before = r"""
        s = 'The folder is "C:\Users"'.
        """
        after = r"""
        s = r'The folder is "C:\Users"'.
        """
        self.convert_check(before, after)

    @unittest.skip('--tobytes feature removed for now ...')
    def test_tobytes(self):
        """
        The --tobytes option converts all UNADORNED string literals 'abcd' to b'abcd'.
        It does apply to multi-line strings but doesn't apply if it's a raw
        string, because ur'abcd' is a SyntaxError on Python 2 and br'abcd' is a
        SyntaxError on Python 3.
        """
        before = r"""
        s0 = '1234'
        s1 = '''5678
        '''
        s2 = "9abc"
        # Unchanged:
        s3 = r'1234'
        s4 = R"defg"
        s5 = u'hijk'
        s6 = u"lmno"
        s7 = b'lmno'
        s8 = b"pqrs"
        """
        after = r"""
        s0 = b'1234'
        s1 = b'''5678
        '''
        s2 = b"9abc"
        # Unchanged:
        s3 = r'1234'
        s4 = R"defg"
        s5 = u'hijk'
        s6 = u"lmno"
        s7 = b'lmno'
        s8 = b"pqrs"
        """
        self.convert_check(before, after, tobytes=True)

    def test_cmp(self):
        before = """
        assert cmp(1, 2) == -1
        assert cmp(2, 1) == 1
        """
        after = """
        from past.builtins import cmp
        assert cmp(1, 2) == -1
        assert cmp(2, 1) == 1
        """
        self.convert_check(before, after, stages=(1, 2), ignore_imports=False)

    def test_execfile(self):
        before = """
        with open('mytempfile.py', 'w') as f:
            f.write('x = 1')
        execfile('mytempfile.py')
        x += 1
        assert x == 2
        """
        after = """
        from past.builtins import execfile
        with open('mytempfile.py', 'w') as f:
            f.write('x = 1')
        execfile('mytempfile.py')
        x += 1
        assert x == 2
        """
        self.convert_check(before, after, stages=(1, 2), ignore_imports=False)

    @unittest.expectedFailure
    def test_izip(self):
        before = """
        from itertools import izip
        for (a, b) in izip([1, 3, 5], [2, 4, 6]):
            pass
        """
        after = """
        from builtins import zip
        for (a, b) in zip([1, 3, 5], [2, 4, 6]):
            pass
        """
        self.convert_check(before, after, stages=(1, 2), ignore_imports=False)

    def test_UserList(self):
        before = """
        from UserList import UserList
        a = UserList([1, 3, 5])
        assert len(a) == 3
        """
        after = """
        from collections import UserList
        a = UserList([1, 3, 5])
        assert len(a) == 3
        """
        self.convert_check(before, after, stages=(1, 2), ignore_imports=True)

    @unittest.expectedFailure
    def test_no_unneeded_list_calls(self):
        """
        TODO: get this working
        """
        code = """
        for (a, b) in zip(range(3), range(3, 6)):
            pass
        """
        self.unchanged(code)

    @expectedFailurePY26
    def test_import_builtins(self):
        before = """
        a = raw_input()
        b = open(a, b, c)
        c = filter(a, b)
        d = map(a, b)
        e = isinstance(a, str)
        f = bytes(a, encoding='utf-8')
        for g in xrange(10**10):
            pass
        h = reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
        super(MyClass, self)
        """
        after = """
        from builtins import bytes
        from builtins import filter
        from builtins import input
        from builtins import map
        from builtins import range
        from functools import reduce
        a = input()
        b = open(a, b, c)
        c = list(filter(a, b))
        d = list(map(a, b))
        e = isinstance(a, str)
        f = bytes(a, encoding='utf-8')
        for g in range(10**10):
            pass
        h = reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
        super(MyClass, self)
        """
        self.convert_check(before, after, ignore_imports=False, run=False)

    def test_input_without_import(self):
        before = """
        a = input()
        """
        after = """
        from builtins import input
        a = eval(input())
        """
        self.convert_check(before, after, ignore_imports=False, run=False)

    def test_input_with_import(self):
        before = """
        from builtins import input
        a = input()
        """
        after = """
        from builtins import input
        a = input()
        """
        self.convert_check(before, after, ignore_imports=False, run=False)

    def test_xrange(self):
        """
        The ``from builtins import range`` line was being added to the
        bottom of the file as of v0.11.4, but only using Py2.7's lib2to3.
        (Py3.3's lib2to3 seems to work.)
        """
        before = """
        for i in xrange(10):
            pass
        """
        after = """
        from builtins import range
        for i in range(10):
            pass
        """
        self.convert_check(before, after, ignore_imports=False)

    def test_source_coding_utf8(self):
        """
        Tests to ensure that the source coding line is not corrupted or
        removed. It must be left as the first line in the file (including
        before any __future__ imports). Also tests whether the unicode
        characters in this encoding are parsed correctly and left alone.
        """
        code = """
        # -*- coding: utf-8 -*-
        icons = [u"◐", u"◓", u"◑", u"◒"]
        """

    def test_exception_syntax(self):
        """
        Test of whether futurize handles the old-style exception syntax
        """
        before = """
        try:
            pass
        except IOError, e:
            val = e.errno
        """
        after = """
        try:
            pass
        except IOError as e:
            val = e.errno
        """
        self.convert_check(before, after)

    def test_super(self):
        """
        This tests whether futurize keeps the old two-argument super() calls the
        same as before. It should, because this still works in Py3.
        """
        code = '''
        class VerboseList(list):
            def append(self, item):
                print('Adding an item')
                super(VerboseList, self).append(item)
        '''
        self.unchanged(code)

    @unittest.expectedFailure
    def test_file(self):
        """
        file() as a synonym for open() is obsolete and invalid on Python 3.
        """
        before = '''
        f = file(self.textfilename)
        data = f.read()
        f.close()
        '''
        after = '''
        f = open(__file__)
        data = f.read()
        f.close()
        '''
        self.convert_check(before, after)

    def test_apply(self):
        before = '''
        def addup(*x):
            return sum(x)

        assert apply(addup, (10,20)) == 30
        '''
        after = """
        def addup(*x):
            return sum(x)

        assert addup(*(10,20)) == 30
        """
        self.convert_check(before, after)

    @unittest.skip('not implemented yet')
    def test_download_pypi_package_and_test(self):
        URL = 'http://pypi.python.org/pypi/{0}/json'

        import requests
        package = 'future'
        r = requests.get(URL.format(package))
        pprint.pprint(r.json())

        download_url = r.json()['urls'][0]['url']
        filename = r.json()['urls'][0]['filename']
        # r2 = requests.get(download_url)
        # with open('/tmp/' + filename, 'w') as tarball:
        #     tarball.write(r2.content)

    @expectedFailurePY26
    def test_raw_input(self):
        """
        Passes in a string to the waiting input() after futurize
        conversion.

        The code is the first snippet from these docs:
            http://docs.python.org/2/library/2to3.html
        """
        before = """
        from io import BytesIO
        def greet(name):
            print "Hello, {0}!".format(name)
        print "What's your name?"
        import sys
        oldstdin = sys.stdin

        sys.stdin = BytesIO(b'Ed\\n')
        name = raw_input()
        greet(name.decode())

        sys.stdin = oldstdin
        assert name == b'Ed'
        """
        desired = """
        from io import BytesIO
        def greet(name):
            print("Hello, {0}!".format(name))
        print("What's your name?")
        import sys
        oldstdin = sys.stdin

        sys.stdin = BytesIO(b'Ed\\n')
        name = input()
        greet(name.decode())

        sys.stdin = oldstdin
        assert name == b'Ed'
        """
        self.convert_check(before, desired, run=False)

        for interpreter in self.interpreters:
            p1 = Popen([interpreter, self.tempdir + 'mytestscript.py'],
                       stdout=PIPE, stdin=PIPE, stderr=PIPE)
            (stdout, stderr) = p1.communicate(b'Ed')
            self.assertEqual(stderr, b'')
            self.assertEqual(stdout, b"What's your name?\nHello, Ed!\n")

    def test_literal_prefixes_are_not_stripped(self):
        """
        Tests to ensure that the u'' and b'' prefixes on unicode strings and
        byte strings are not removed by the futurize script.  Removing the
        prefixes on Py3.3+ is unnecessary and loses some information -- namely,
        that the strings have explicitly been marked as unicode or bytes,
        rather than just e.g. a guess by some automated tool about what they
        are.
        """
        code = '''
        s = u'unicode string'
        b = b'byte string'
        '''
        self.unchanged(code)

    def test_division(self):
        before = """
        x = 1 / 2
        """
        after = """
        from past.utils import old_div
        x = old_div(1, 2)
        """
        self.convert_check(before, after, stages=[1, 2])

    def test_already_future_division(self):
        code = """
        from __future__ import division
        x = 1 / 2
        assert x == 0.5
        y = 3. / 2.
        assert y == 1.5
        """
        self.unchanged(code)


class TestFuturizeRenamedStdlib(CodeHandler):
    @unittest.skip('Infinite loop?')
    def test_renamed_modules(self):
        before = """
        import ConfigParser
        import copy_reg
        import cPickle
        import cStringIO
        """
        after = """
        import configparser
        import copyreg
        import pickle
        import io
        """
        # We can't run the converted code because configparser may
        # not be there.
        self.convert_check(before, after, run=False)

    @unittest.skip('Not working yet ...')
    def test_urllib_refactor(self):
        # Code like this using urllib is refactored by futurize --stage2 to use
        # the new Py3 module names, but ``future`` doesn't support urllib yet.
        before = """
        import urllib

        URL = 'http://pypi.python.org/pypi/future/json'
        package = 'future'
        r = urllib.urlopen(URL.format(package))
        data = r.read()
        """
        after = """
        from future import standard_library
        standard_library.install_aliases()
        import urllib.request

        URL = 'http://pypi.python.org/pypi/future/json'
        package = 'future'
        r = urllib.request.urlopen(URL.format(package))
        data = r.read()
        """
        self.convert_check(before, after)

    @unittest.skip('Infinite loop?')
    def test_renamed_copy_reg_and_cPickle_modules(self):
        """
        Example from docs.python.org/2/library/copy_reg.html
        """
        before = """
        import copy_reg
        import copy
        import cPickle
        class C(object):
            def __init__(self, a):
                self.a = a

        def pickle_c(c):
            print('pickling a C instance...')
            return C, (c.a,)

        copy_reg.pickle(C, pickle_c)
        c = C(1)
        d = copy.copy(c)
        p = cPickle.dumps(c)
        """
        after = """
        import copyreg
        import copy
        import pickle
        class C(object):
            def __init__(self, a):
                self.a = a

        def pickle_c(c):
            print('pickling a C instance...')
            return C, (c.a,)

        copyreg.pickle(C, pickle_c)
        c = C(1)
        d = copy.copy(c)
        p = pickle.dumps(c)
        """
        self.convert_check(before, after)

    @unittest.expectedFailure
    def test_Py2_StringIO_module(self):
        """
        This requires that the argument to io.StringIO be made a
        unicode string explicitly if we're not using unicode_literals:

        Ideally, there would be a fixer for this. For now:

        TODO: add the Py3 equivalent for this to the docs. Also add back
        a test for the unicode_literals case.
        """
        before = """
        import cStringIO
        import StringIO
        s1 = cStringIO.StringIO('my string')
        s2 = StringIO.StringIO('my other string')
        assert isinstance(s1, cStringIO.InputType)
        """

        # There is no io.InputType in Python 3. futurize should change this to
        # something like this. But note that the input to io.StringIO
        # must be a unicode string on both Py2 and Py3.
        after = """
        import io
        import io
        s1 = io.StringIO(u'my string')
        s2 = io.StringIO(u'my other string')
        assert isinstance(s1, io.StringIO)
        """
        self.convert_check(before, after)


class TestFuturizeStage1(CodeHandler):
    """
    Tests "stage 1": safe optimizations: modernizing Python 2 code so that it
    uses print functions, new-style exception syntax, etc.

    The behaviour should not change and this should introduce no dependency on
    the ``future`` package. It produces more modern Python 2-only code. The
    goal is to reduce the size of the real porting patch-set by performing
    the uncontroversial patches first.
    """

    def test_apply(self):
        """
        apply() should be changed by futurize --stage1
        """
        before = '''
        def f(a, b):
            return a + b

        args = (1, 2)
        assert apply(f, args) == 3
        assert apply(f, ('a', 'b')) == 'ab'
        '''
        after = '''
        def f(a, b):
            return a + b

        args = (1, 2)
        assert f(*args) == 3
        assert f(*('a', 'b')) == 'ab'
        '''
        self.convert_check(before, after, stages=[1])

    def test_next_1(self):
        """
        Custom next methods should not be converted to __next__ in stage1, but
        any obj.next() calls should be converted to next(obj).
        """
        before = """
        class Upper:
            def __init__(self, iterable):
                self._iter = iter(iterable)
            def next(self):                 # note the Py2 interface
                return next(self._iter).upper()
            def __iter__(self):
                return self

        itr = Upper('hello')
        assert itr.next() == 'H'
        assert next(itr) == 'E'
        assert list(itr) == list('LLO')
        """

        after = """
        class Upper:
            def __init__(self, iterable):
                self._iter = iter(iterable)
            def next(self):                 # note the Py2 interface
                return next(self._iter).upper()
            def __iter__(self):
                return self

        itr = Upper('hello')
        assert next(itr) == 'H'
        assert next(itr) == 'E'
        assert list(itr) == list('LLO')
        """
        self.convert_check(before, after, stages=[1], run=PY2)

    @unittest.expectedFailure
    def test_next_2(self):
        """
        This version of the above doesn't currently work: the self._iter.next() call in
        line 5 isn't converted to next(self._iter).
        """
        before = """
        class Upper:
            def __init__(self, iterable):
                self._iter = iter(iterable)
            def next(self):                 # note the Py2 interface
                return self._iter.next().upper()
            def __iter__(self):
                return self

        itr = Upper('hello')
        assert itr.next() == 'H'
        assert next(itr) == 'E'
        assert list(itr) == list('LLO')
        """

        after = """
        class Upper(object):
            def __init__(self, iterable):
                self._iter = iter(iterable)
            def next(self):                 # note the Py2 interface
                return next(self._iter).upper()
            def __iter__(self):
                return self

        itr = Upper('hello')
        assert next(itr) == 'H'
        assert next(itr) == 'E'
        assert list(itr) == list('LLO')
        """
        self.convert_check(before, after, stages=[1], run=PY2)

    def test_xrange(self):
        """
        xrange should not be changed by futurize --stage1
        """
        code = '''
        for i in xrange(10):
            pass
        '''
        self.unchanged(code, stages=[1], run=PY2)

    @unittest.expectedFailure
    def test_absolute_import_changes(self):
        """
        Implicit relative imports should be converted to absolute or explicit
        relative imports correctly.

        Issue #16 (with porting bokeh/bbmodel.py)
        """
        with open(self.tempdir + 'specialmodels.py', 'w') as f:
            f.write('pass')

        before = """
        import specialmodels.pandasmodel
        specialmodels.pandasmodel.blah()
        """
        after = """
        from __future__ import absolute_import
        from .specialmodels import pandasmodel
        pandasmodel.blah()
        """
        self.convert_check(before, after, stages=[1])

    def test_safe_futurize_imports(self):
        """
        The standard library module names should not be changed until stage 2
        """
        before = """
        import ConfigParser
        import HTMLParser
        from itertools import ifilterfalse

        ConfigParser.ConfigParser
        HTMLParser.HTMLParser
        assert list(ifilterfalse(lambda x: x % 2, [2, 4])) == [2, 4]
        """
        self.unchanged(before, stages=[1], run=PY2)

    def test_print(self):
        before = """
        print 'Hello'
        """
        after = """
        print('Hello')
        """
        self.convert_check(before, after, stages=[1])

        before = """
        import sys
        print >> sys.stderr, 'Hello', 'world'
        """
        after = """
        import sys
        print('Hello', 'world', file=sys.stderr)
        """
        self.convert_check(before, after, stages=[1])

    def test_print_already_function(self):
        """
        Running futurize --stage1 should not add a second set of parentheses
        """
        before = """
        print('Hello')
        """
        self.unchanged(before, stages=[1])

    @unittest.expectedFailure
    def test_print_already_function_complex(self):
        """
        Running futurize --stage1 does add a second second set of parentheses
        in this case. This is because the underlying lib2to3 has two distinct
        grammars -- with a print statement and with a print function -- and,
        when going forwards (2 to both), futurize assumes print is a statement,
        which raises a ParseError.
        """
        before = """
        import sys
        print('Hello', 'world', file=sys.stderr)
        """
        self.unchanged(before, stages=[1])

    def test_exceptions(self):
        before = """
        try:
            raise AttributeError('blah')
        except AttributeError, e:
            pass
        """
        after = """
        try:
            raise AttributeError('blah')
        except AttributeError as e:
            pass
        """
        self.convert_check(before, after, stages=[1])

    @unittest.expectedFailure
    def test_string_exceptions(self):
        """
        2to3 does not convert string exceptions: see
        http://python3porting.com/differences.html.
        """
        before = """
        try:
            raise "old string exception"
        except Exception, e:
            pass
        """
        after = """
        try:
            raise Exception("old string exception")
        except Exception as e:
            pass
        """
        self.convert_check(before, after, stages=[1])

    def test_oldstyle_classes(self):
        """
        We don't convert old-style classes to new-style automatically in
        stage 1 (but we should in stage 2). So Blah should not inherit
        explicitly from object yet.
        """
        before = """
        class Blah:
            pass
        """
        self.unchanged(before, stages=[1])

    def test_stdlib_modules_not_changed(self):
        """
        Standard library module names should not be changed in stage 1
        """
        before = """
        import ConfigParser
        import HTMLParser
        import collections

        print 'Hello'
        try:
            raise AttributeError('blah')
        except AttributeError, e:
            pass
        """
        after = """
        import ConfigParser
        import HTMLParser
        import collections

        print('Hello')
        try:
            raise AttributeError('blah')
        except AttributeError as e:
            pass
        """
        self.convert_check(before, after, stages=[1], run=PY2)

    def test_octal_literals(self):
        before = """
        mode = 0644
        """
        after = """
        mode = 0o644
        """
        self.convert_check(before, after)

    def test_long_int_literals(self):
        before = """
        bignumber = 12345678901234567890L
        """
        after = """
        bignumber = 12345678901234567890
        """
        self.convert_check(before, after)

    def test___future___import_position(self):
        """
        Issue #4: __future__ imports inserted too low in file: SyntaxError
        """
        code = """
        # Comments here
        # and here
        __version__=''' $Id$ '''
        __doc__="A Sequencer class counts things. It aids numbering and formatting lists."
        __all__='Sequencer getSequencer setSequencer'.split()
        #
        # another comment
        #

        CONSTANTS = [ 0, 01, 011, 0111, 012, 02, 021, 0211, 02111, 013 ]
        _RN_LETTERS = "IVXLCDM"

        def my_func(value):
            pass

        ''' Docstring-like comment here '''
        """
        self.convert(code)

    def test_issue_45(self):
        """
        Tests whether running futurize -f libfuturize.fixes.fix_future_standard_library_urllib
        on the code below causes a ValueError (issue #45).
        """
        code = r"""
            from __future__ import print_function
            from urllib import urlopen, urlencode
            oeis_url = 'http://oeis.org/'
            def _fetch(url):
                try:
                    f = urlopen(url)
                    result = f.read()
                    f.close()
                    return result
                except IOError as msg:
                    raise IOError("%s\nError fetching %s." % (msg, url))
        """
        self.convert(code)

    def test_order_future_lines(self):
        """
        Tests the internal order_future_lines() function.
        """
        before = '''
               # comment here
               from __future__ import print_function
               from __future__ import absolute_import
                                 # blank line or comment here
               from future.utils import with_metaclass
               from builtins import zzz
               from builtins import aaa
               from builtins import blah
               # another comment

               import something_else
               code_here
               more_code_here
               '''
        after = '''
               # comment here
               from __future__ import absolute_import
               from __future__ import print_function
                                 # blank line or comment here
               from future.utils import with_metaclass
               from builtins import aaa
               from builtins import blah
               from builtins import zzz
               # another comment

               import something_else
               code_here
               more_code_here
               '''
        self.assertEqual(order_future_lines(reformat_code(before)),
                         reformat_code(after))

    @unittest.expectedFailure
    def test_issue_12(self):
        """
        Issue #12: This code shouldn't be upset by additional imports.
        __future__ imports must appear at the top of modules since about Python
        2.5.
        """
        code = """
        from __future__ import with_statement
        f = open('setup.py')
        for i in xrange(100):
            pass
        """
        self.unchanged(code)

    @expectedFailurePY26
    def test_range_necessary_list_calls(self):
        """
        On Py2.6 (only), the xrange_with_import fixer somehow seems to cause
            l = range(10)
        to be converted to:
            l = list(list(range(10)))
        with an extra list(...) call.
        """
        before = """
        l = range(10)
        assert isinstance(l, list)
        for i in range(3):
            print i
        for i in xrange(3):
            print i
        """
        after = """
        from __future__ import print_function
        from builtins import range
        l = list(range(10))
        assert isinstance(l, list)
        for i in range(3):
            print(i)
        for i in range(3):
            print(i)
        """
        self.convert_check(before, after)

    def test_basestring(self):
        """
        The 2to3 basestring fixer breaks working Py2 code that uses basestring.
        This tests whether something sensible is done instead.
        """
        before = """
        assert isinstance('hello', basestring)
        assert isinstance(u'hello', basestring)
        assert isinstance(b'hello', basestring)
        """
        after = """
        from past.builtins import basestring
        assert isinstance('hello', basestring)
        assert isinstance(u'hello', basestring)
        assert isinstance(b'hello', basestring)
        """
        self.convert_check(before, after)

    def test_safe_division(self):
        """
        Tests whether Py2 scripts using old-style division still work
        after futurization.
        """
        before = """
        import random
        class fraction(object):
            numer = 0
            denom = 0
            def __init__(self, numer, denom):
                self.numer = numer
                self.denom = denom

            def total_count(self):
                return self.numer * 50

        x = 3 / 2
        y = 3. / 2
        foo = list(range(100))
        assert x == 1 and isinstance(x, int)
        assert y == 1.5 and isinstance(y, float)
        a = 1 + foo[len(foo) / 2]
        b = 1 + foo[len(foo) * 3 / 4]
        assert a == 51
        assert b == 76
        r = random.randint(0, 1000) * 1.0 / 1000
        output = { "SUCCESS": 5, "TOTAL": 10 }
        output["SUCCESS"] * 100 / output["TOTAL"]
        obj = fraction(1, 50)
        val = float(obj.numer) / obj.denom * 1e-9
        obj.numer * obj.denom / val
        obj.total_count() * val / 100
        obj.numer / obj.denom * 1e-9
        obj.numer / (obj.denom * 1e-9)
        obj.numer / obj.denom / 1e-9
        obj.numer / (obj.denom / 1e-9)
        original_numer = 1
        original_denom = 50
        100 * abs(obj.numer - original_numer) / float(max(obj.denom, original_denom))
        100 * abs(obj.numer - original_numer) / max(obj.denom, original_denom)
        float(original_numer) * float(original_denom) / float(obj.numer)
        """
        after = """
        from __future__ import division
        from past.utils import old_div
        import random
        class fraction(object):
            numer = 0
            denom = 0
            def __init__(self, numer, denom):
                self.numer = numer
                self.denom = denom

            def total_count(self):
                return self.numer * 50

        x = old_div(3, 2)
        y = 3. / 2
        foo = list(range(100))
        assert x == 1 and isinstance(x, int)
        assert y == 1.5 and isinstance(y, float)
        a = 1 + foo[old_div(len(foo), 2)]
        b = 1 + foo[old_div(len(foo) * 3, 4)]
        assert a == 51
        assert b == 76
        r = random.randint(0, 1000) * 1.0 / 1000
        output = { "SUCCESS": 5, "TOTAL": 10 }
        old_div(output["SUCCESS"] * 100, output["TOTAL"])
        obj = fraction(1, 50)
        val = float(obj.numer) / obj.denom * 1e-9
        old_div(obj.numer * obj.denom, val)
        old_div(obj.total_count() * val, 100)
        old_div(obj.numer, obj.denom) * 1e-9
        old_div(obj.numer, (obj.denom * 1e-9))
        old_div(old_div(obj.numer, obj.denom), 1e-9)
        old_div(obj.numer, (old_div(obj.denom, 1e-9)))
        original_numer = 1
        original_denom = 50
        100 * abs(obj.numer - original_numer) / float(max(obj.denom, original_denom))
        old_div(100 * abs(obj.numer - original_numer), max(obj.denom, original_denom))
        float(original_numer) * float(original_denom) / float(obj.numer)
        """
        self.convert_check(before, after)

    def test_safe_division_overloaded(self):
        """
        If division is overloaded, futurize may produce spurious old_div
        calls.  This test is for whether the code still works on Py2
        despite these calls.
        """
        before = """
        class Path(str):
            def __div__(self, other):
                return self.__truediv__(other)
            def __truediv__(self, other):
                return Path(str(self) + '/' + str(other))
        path1 = Path('home')
        path2 = Path('user')
        z = path1 / path2
        assert isinstance(z, Path)
        assert str(z) == 'home/user'
        """
        after = """
        from __future__ import division
        from past.utils import old_div
        class Path(str):
            def __div__(self, other):
                return self.__truediv__(other)
            def __truediv__(self, other):
                return Path(str(self) + '/' + str(other))
        path1 = Path('home')
        path2 = Path('user')
        z = old_div(path1, path2)
        assert isinstance(z, Path)
        assert str(z) == 'home/user'
        """
        self.convert_check(before, after)

    def test_basestring_issue_156(self):
        before = """
        x = str(3)
        allowed_types = basestring, int
        assert isinstance('', allowed_types)
        assert isinstance(u'', allowed_types)
        assert isinstance(u'foo', basestring)
        """
        after = """
        from builtins import str
        from past.builtins import basestring
        x = str(3)
        allowed_types = basestring, int
        assert isinstance('', allowed_types)
        assert isinstance(u'', allowed_types)
        assert isinstance(u'foo', basestring)
        """
        self.convert_check(before, after)


class TestConservativeFuturize(CodeHandler):
    @unittest.expectedFailure
    def test_basestring(self):
        """
        In conservative mode, futurize would not modify "basestring"
        but merely import it from ``past``, and the following code would still
        run on both Py2 and Py3.
        """
        before = """
        assert isinstance('hello', basestring)
        assert isinstance(u'hello', basestring)
        assert isinstance(b'hello', basestring)
        """
        after = """
        from past.builtins import basestring
        assert isinstance('hello', basestring)
        assert isinstance(u'hello', basestring)
        assert isinstance(b'hello', basestring)
        """
        self.convert_check(before, after, conservative=True)

    @unittest.expectedFailure
    def test_open(self):
        """
        In conservative mode, futurize would not import io.open because
        this changes the default return type from bytes to text.
        """
        before = """
        filename = 'temp_file_open.test'
        contents = 'Temporary file contents. Delete me.'
        with open(filename, 'w') as f:
            f.write(contents)

        with open(filename, 'r') as f:
            data = f.read()
        assert isinstance(data, str)
        assert data == contents
        """
        after = """
        from past.builtins import open, str as oldbytes, unicode
        filename = oldbytes(b'temp_file_open.test')
        contents = oldbytes(b'Temporary file contents. Delete me.')
        with open(filename, oldbytes(b'w')) as f:
            f.write(contents)

        with open(filename, oldbytes(b'r')) as f:
            data = f.read()
        assert isinstance(data, oldbytes)
        assert data == contents
        assert isinstance(oldbytes(b'hello'), basestring)
        assert isinstance(unicode(u'hello'), basestring)
        assert isinstance(oldbytes(b'hello'), basestring)
        """
        self.convert_check(before, after, conservative=True)


class TestFuturizeAllImports(CodeHandler):
    """
    Tests "futurize --all-imports".
    """
    @expectedFailurePY26
    def test_all_imports(self):
        before = """
        import math
        import os
        l = range(10)
        assert isinstance(l, list)
        print 'Hello'
        for i in xrange(100):
            pass
        print('Hello')
        """
        after = """
        from __future__ import absolute_import
        from __future__ import division
        from __future__ import print_function
        from __future__ import unicode_literals
        from future import standard_library
        standard_library.install_aliases()
        from builtins import *
        from builtins import range
        import math
        import os
        l = list(range(10))
        assert isinstance(l, list)
        print('Hello')
        for i in range(100):
            pass
        print('Hello')
        """
        self.convert_check(before, after, all_imports=True, ignore_imports=False)


if __name__ == '__main__':
    unittest.main()