test_util.py 20.7 KB
Newer Older
1
""" Test suite for the code in fixer_util """
2 3 4 5 6

# Testing imports
from . import support

# Local imports
7 8 9 10
from lib2to3.pytree import Node, Leaf
from lib2to3 import fixer_util
from lib2to3.fixer_util import Attr, Name, Call, Comma
from lib2to3.pgen2 import token
11 12 13 14 15 16 17 18 19 20 21 22 23

def parse(code, strip_levels=0):
    # The topmost node is file_input, which we don't care about.
    # The next-topmost node is a *_stmt node, which we also don't care about
    tree = support.parse_string(code)
    for i in range(strip_levels):
        tree = tree.children[0]
    tree.parent = None
    return tree

class MacroTestCase(support.TestCase):
    def assertStr(self, node, string):
        if isinstance(node, (tuple, list)):
24
            node = Node(fixer_util.syms.simple_stmt, node)
25 26 27 28 29
        self.assertEqual(str(node), string)


class Test_is_tuple(support.TestCase):
    def is_tuple(self, string):
30
        return fixer_util.is_tuple(parse(string, strip_levels=2))
31 32

    def test_valid(self):
33 34 35 36 37
        self.assertTrue(self.is_tuple("(a, b)"))
        self.assertTrue(self.is_tuple("(a, (b, c))"))
        self.assertTrue(self.is_tuple("((a, (b, c)),)"))
        self.assertTrue(self.is_tuple("(a,)"))
        self.assertTrue(self.is_tuple("()"))
38 39

    def test_invalid(self):
40 41
        self.assertFalse(self.is_tuple("(a)"))
        self.assertFalse(self.is_tuple("('foo') % (b, c)"))
42 43 44 45


class Test_is_list(support.TestCase):
    def is_list(self, string):
46
        return fixer_util.is_list(parse(string, strip_levels=2))
47 48

    def test_valid(self):
49 50 51 52 53
        self.assertTrue(self.is_list("[]"))
        self.assertTrue(self.is_list("[a]"))
        self.assertTrue(self.is_list("[a, b]"))
        self.assertTrue(self.is_list("[a, [b, c]]"))
        self.assertTrue(self.is_list("[[a, [b, c]],]"))
54 55

    def test_invalid(self):
56
        self.assertFalse(self.is_list("[]+[]"))
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77


class Test_Attr(MacroTestCase):
    def test(self):
        call = parse("foo()", strip_levels=2)

        self.assertStr(Attr(Name("a"), Name("b")), "a.b")
        self.assertStr(Attr(call, Name("b")), "foo().b")

    def test_returns(self):
        attr = Attr(Name("a"), Name("b"))
        self.assertEqual(type(attr), list)


class Test_Name(MacroTestCase):
    def test(self):
        self.assertStr(Name("a"), "a")
        self.assertStr(Name("foo.foo().bar"), "foo.foo().bar")
        self.assertStr(Name("a", prefix="b"), "ba")


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
class Test_Call(MacroTestCase):
    def _Call(self, name, args=None, prefix=None):
        """Help the next test"""
        children = []
        if isinstance(args, list):
            for arg in args:
                children.append(arg)
                children.append(Comma())
            children.pop()
        return Call(Name(name), children, prefix)

    def test(self):
        kids = [None,
                [Leaf(token.NUMBER, 1), Leaf(token.NUMBER, 2),
                 Leaf(token.NUMBER, 3)],
                [Leaf(token.NUMBER, 1), Leaf(token.NUMBER, 3),
                 Leaf(token.NUMBER, 2), Leaf(token.NUMBER, 4)],
                [Leaf(token.STRING, "b"), Leaf(token.STRING, "j", prefix=" ")]
                ]
        self.assertStr(self._Call("A"), "A()")
        self.assertStr(self._Call("b", kids[1]), "b(1,2,3)")
        self.assertStr(self._Call("a.b().c", kids[2]), "a.b().c(1,3,2,4)")
        self.assertStr(self._Call("d", kids[3], prefix=" "), " d(b, j)")


103 104 105 106
class Test_does_tree_import(support.TestCase):
    def _find_bind_rec(self, name, node):
        # Search a tree for a binding -- used to find the starting
        # point for these tests.
107
        c = fixer_util.find_binding(name, node)
108 109 110 111 112 113 114 115 116
        if c: return c
        for child in node.children:
            c = self._find_bind_rec(name, child)
            if c: return c

    def does_tree_import(self, package, name, string):
        node = parse(string)
        # Find the binding of start -- that's what we'll go from
        node = self._find_bind_rec('start', node)
117
        return fixer_util.does_tree_import(package, name, node)
118 119 120 121 122 123 124 125 126

    def try_with(self, string):
        failing_tests = (("a", "a", "from a import b"),
                         ("a.d", "a", "from a.d import b"),
                         ("d.a", "a", "from d.a import b"),
                         (None, "a", "import b"),
                         (None, "a", "import b, c, d"))
        for package, name, import_ in failing_tests:
            n = self.does_tree_import(package, name, import_ + "\n" + string)
127
            self.assertFalse(n)
128
            n = self.does_tree_import(package, name, string + "\n" + import_)
129
            self.assertFalse(n)
130 131 132 133 134 135 136 137 138 139

        passing_tests = (("a", "a", "from a import a"),
                         ("x", "a", "from x import a"),
                         ("x", "a", "from x import b, c, a, d"),
                         ("x.b", "a", "from x.b import a"),
                         ("x.b", "a", "from x.b import b, c, a, d"),
                         (None, "a", "import a"),
                         (None, "a", "import b, c, a, d"))
        for package, name, import_ in passing_tests:
            n = self.does_tree_import(package, name, import_ + "\n" + string)
140
            self.assertTrue(n)
141
            n = self.does_tree_import(package, name, string + "\n" + import_)
142
            self.assertTrue(n)
143 144 145 146 147 148

    def test_in_function(self):
        self.try_with("def foo():\n\tbar.baz()\n\tstart=3")

class Test_find_binding(support.TestCase):
    def find_binding(self, name, string, package=None):
149
        return fixer_util.find_binding(name, parse(string), package)
150 151

    def test_simple_assignment(self):
152 153 154 155 156 157
        self.assertTrue(self.find_binding("a", "a = b"))
        self.assertTrue(self.find_binding("a", "a = [b, c, d]"))
        self.assertTrue(self.find_binding("a", "a = foo()"))
        self.assertTrue(self.find_binding("a", "a = foo().foo.foo[6][foo]"))
        self.assertFalse(self.find_binding("a", "foo = a"))
        self.assertFalse(self.find_binding("a", "foo = (a, b, c)"))
158 159

    def test_tuple_assignment(self):
160 161 162 163 164 165
        self.assertTrue(self.find_binding("a", "(a,) = b"))
        self.assertTrue(self.find_binding("a", "(a, b, c) = [b, c, d]"))
        self.assertTrue(self.find_binding("a", "(c, (d, a), b) = foo()"))
        self.assertTrue(self.find_binding("a", "(a, b) = foo().foo[6][foo]"))
        self.assertFalse(self.find_binding("a", "(foo, b) = (b, a)"))
        self.assertFalse(self.find_binding("a", "(foo, (b, c)) = (a, b, c)"))
166 167

    def test_list_assignment(self):
168 169 170 171 172 173
        self.assertTrue(self.find_binding("a", "[a] = b"))
        self.assertTrue(self.find_binding("a", "[a, b, c] = [b, c, d]"))
        self.assertTrue(self.find_binding("a", "[c, [d, a], b] = foo()"))
        self.assertTrue(self.find_binding("a", "[a, b] = foo().foo[a][foo]"))
        self.assertFalse(self.find_binding("a", "[foo, b] = (b, a)"))
        self.assertFalse(self.find_binding("a", "[foo, [b, c]] = (a, b, c)"))
174 175

    def test_invalid_assignments(self):
176 177 178 179
        self.assertFalse(self.find_binding("a", "foo.a = 5"))
        self.assertFalse(self.find_binding("a", "foo[a] = 5"))
        self.assertFalse(self.find_binding("a", "foo(a) = 5"))
        self.assertFalse(self.find_binding("a", "foo(a, b) = 5"))
180 181

    def test_simple_import(self):
182 183 184 185
        self.assertTrue(self.find_binding("a", "import a"))
        self.assertTrue(self.find_binding("a", "import b, c, a, d"))
        self.assertFalse(self.find_binding("a", "import b"))
        self.assertFalse(self.find_binding("a", "import b, c, d"))
186 187

    def test_from_import(self):
188 189 190 191 192 193 194 195
        self.assertTrue(self.find_binding("a", "from x import a"))
        self.assertTrue(self.find_binding("a", "from a import a"))
        self.assertTrue(self.find_binding("a", "from x import b, c, a, d"))
        self.assertTrue(self.find_binding("a", "from x.b import a"))
        self.assertTrue(self.find_binding("a", "from x.b import b, c, a, d"))
        self.assertFalse(self.find_binding("a", "from a import b"))
        self.assertFalse(self.find_binding("a", "from a.d import b"))
        self.assertFalse(self.find_binding("a", "from d.a import b"))
196 197

    def test_import_as(self):
198 199 200 201
        self.assertTrue(self.find_binding("a", "import b as a"))
        self.assertTrue(self.find_binding("a", "import b as a, c, a as f, d"))
        self.assertFalse(self.find_binding("a", "import a as f"))
        self.assertFalse(self.find_binding("a", "import b, c as f, d as e"))
202 203

    def test_from_import_as(self):
204 205 206 207 208 209 210
        self.assertTrue(self.find_binding("a", "from x import b as a"))
        self.assertTrue(self.find_binding("a", "from x import g as a, d as b"))
        self.assertTrue(self.find_binding("a", "from x.b import t as a"))
        self.assertTrue(self.find_binding("a", "from x.b import g as a, d"))
        self.assertFalse(self.find_binding("a", "from a import b as t"))
        self.assertFalse(self.find_binding("a", "from a.d import b as t"))
        self.assertFalse(self.find_binding("a", "from d.a import b as t"))
211 212

    def test_simple_import_with_package(self):
213 214 215 216
        self.assertTrue(self.find_binding("b", "import b"))
        self.assertTrue(self.find_binding("b", "import b, c, d"))
        self.assertFalse(self.find_binding("b", "import b", "b"))
        self.assertFalse(self.find_binding("b", "import b, c, d", "c"))
217 218

    def test_from_import_with_package(self):
219 220 221 222 223 224 225 226 227 228 229
        self.assertTrue(self.find_binding("a", "from x import a", "x"))
        self.assertTrue(self.find_binding("a", "from a import a", "a"))
        self.assertTrue(self.find_binding("a", "from x import *", "x"))
        self.assertTrue(self.find_binding("a", "from x import b, c, a, d", "x"))
        self.assertTrue(self.find_binding("a", "from x.b import a", "x.b"))
        self.assertTrue(self.find_binding("a", "from x.b import *", "x.b"))
        self.assertTrue(self.find_binding("a", "from x.b import b, c, a, d", "x.b"))
        self.assertFalse(self.find_binding("a", "from a import b", "a"))
        self.assertFalse(self.find_binding("a", "from a.d import b", "a.d"))
        self.assertFalse(self.find_binding("a", "from d.a import b", "a.d"))
        self.assertFalse(self.find_binding("a", "from x.y import *", "a.b"))
230 231

    def test_import_as_with_package(self):
232 233 234
        self.assertFalse(self.find_binding("a", "import b.c as a", "b.c"))
        self.assertFalse(self.find_binding("a", "import a as f", "f"))
        self.assertFalse(self.find_binding("a", "import a as f", "a"))
235 236 237 238 239

    def test_from_import_as_with_package(self):
        # Because it would take a lot of special-case code in the fixers
        # to deal with from foo import bar as baz, we'll simply always
        # fail if there is an "from ... import ... as ..."
240 241 242 243 244 245 246
        self.assertFalse(self.find_binding("a", "from x import b as a", "x"))
        self.assertFalse(self.find_binding("a", "from x import g as a, d as b", "x"))
        self.assertFalse(self.find_binding("a", "from x.b import t as a", "x.b"))
        self.assertFalse(self.find_binding("a", "from x.b import g as a, d", "x.b"))
        self.assertFalse(self.find_binding("a", "from a import b as t", "a"))
        self.assertFalse(self.find_binding("a", "from a import b as t", "b"))
        self.assertFalse(self.find_binding("a", "from a import b as t", "t"))
247 248

    def test_function_def(self):
249 250 251 252 253 254 255
        self.assertTrue(self.find_binding("a", "def a(): pass"))
        self.assertTrue(self.find_binding("a", "def a(b, c, d): pass"))
        self.assertTrue(self.find_binding("a", "def a(): b = 7"))
        self.assertFalse(self.find_binding("a", "def d(b, (c, a), e): pass"))
        self.assertFalse(self.find_binding("a", "def d(a=7): pass"))
        self.assertFalse(self.find_binding("a", "def d(a): pass"))
        self.assertFalse(self.find_binding("a", "def d(): a = 7"))
256 257 258 259 260

        s = """
            def d():
                def a():
                    pass"""
261
        self.assertFalse(self.find_binding("a", s))
262 263

    def test_class_def(self):
264 265 266 267 268 269 270 271 272 273
        self.assertTrue(self.find_binding("a", "class a: pass"))
        self.assertTrue(self.find_binding("a", "class a(): pass"))
        self.assertTrue(self.find_binding("a", "class a(b): pass"))
        self.assertTrue(self.find_binding("a", "class a(b, c=8): pass"))
        self.assertFalse(self.find_binding("a", "class d: pass"))
        self.assertFalse(self.find_binding("a", "class d(a): pass"))
        self.assertFalse(self.find_binding("a", "class d(b, a=7): pass"))
        self.assertFalse(self.find_binding("a", "class d(b, *a): pass"))
        self.assertFalse(self.find_binding("a", "class d(b, **a): pass"))
        self.assertFalse(self.find_binding("a", "class d: a = 7"))
274 275 276 277 278

        s = """
            class d():
                class a():
                    pass"""
279
        self.assertFalse(self.find_binding("a", s))
280 281

    def test_for(self):
282 283 284 285 286 287 288
        self.assertTrue(self.find_binding("a", "for a in r: pass"))
        self.assertTrue(self.find_binding("a", "for a, b in r: pass"))
        self.assertTrue(self.find_binding("a", "for (a, b) in r: pass"))
        self.assertTrue(self.find_binding("a", "for c, (a,) in r: pass"))
        self.assertTrue(self.find_binding("a", "for c, (a, b) in r: pass"))
        self.assertTrue(self.find_binding("a", "for c in r: a = c"))
        self.assertFalse(self.find_binding("a", "for c in a: pass"))
289 290 291 292 293 294

    def test_for_nested(self):
        s = """
            for b in r:
                for a in b:
                    pass"""
295
        self.assertTrue(self.find_binding("a", s))
296 297 298 299 300

        s = """
            for b in r:
                for a, c in b:
                    pass"""
301
        self.assertTrue(self.find_binding("a", s))
302 303 304 305 306

        s = """
            for b in r:
                for (a, c) in b:
                    pass"""
307
        self.assertTrue(self.find_binding("a", s))
308 309 310 311 312

        s = """
            for b in r:
                for (a,) in b:
                    pass"""
313
        self.assertTrue(self.find_binding("a", s))
314 315 316 317 318

        s = """
            for b in r:
                for c, (a, d) in b:
                    pass"""
319
        self.assertTrue(self.find_binding("a", s))
320 321 322 323 324

        s = """
            for b in r:
                for c in b:
                    a = 7"""
325
        self.assertTrue(self.find_binding("a", s))
326 327 328 329 330

        s = """
            for b in r:
                for c in b:
                    d = a"""
331
        self.assertFalse(self.find_binding("a", s))
332 333 334 335 336

        s = """
            for b in r:
                for c in a:
                    d = 7"""
337
        self.assertFalse(self.find_binding("a", s))
338 339

    def test_if(self):
340 341
        self.assertTrue(self.find_binding("a", "if b in r: a = c"))
        self.assertFalse(self.find_binding("a", "if a in r: d = e"))
342 343 344 345 346 347

    def test_if_nested(self):
        s = """
            if b in r:
                if c in d:
                    a = c"""
348
        self.assertTrue(self.find_binding("a", s))
349 350 351 352 353

        s = """
            if b in r:
                if c in d:
                    c = a"""
354
        self.assertFalse(self.find_binding("a", s))
355 356

    def test_while(self):
357 358
        self.assertTrue(self.find_binding("a", "while b in r: a = c"))
        self.assertFalse(self.find_binding("a", "while a in r: d = e"))
359 360 361 362 363 364

    def test_while_nested(self):
        s = """
            while b in r:
                while c in d:
                    a = c"""
365
        self.assertTrue(self.find_binding("a", s))
366 367 368 369 370

        s = """
            while b in r:
                while c in d:
                    c = a"""
371
        self.assertFalse(self.find_binding("a", s))
372 373 374 375 376 377 378

    def test_try_except(self):
        s = """
            try:
                a = 6
            except:
                b = 8"""
379
        self.assertTrue(self.find_binding("a", s))
380 381 382 383 384 385

        s = """
            try:
                b = 8
            except:
                a = 6"""
386
        self.assertTrue(self.find_binding("a", s))
387 388 389 390 391 392 393 394

        s = """
            try:
                b = 8
            except KeyError:
                pass
            except:
                a = 6"""
395
        self.assertTrue(self.find_binding("a", s))
396 397 398 399 400 401

        s = """
            try:
                b = 8
            except:
                b = 6"""
402
        self.assertFalse(self.find_binding("a", s))
403 404 405 406 407 408 409 410 411 412

    def test_try_except_nested(self):
        s = """
            try:
                try:
                    a = 6
                except:
                    pass
            except:
                b = 8"""
413
        self.assertTrue(self.find_binding("a", s))
414 415 416 417 418 419 420 421 422

        s = """
            try:
                b = 8
            except:
                try:
                    a = 6
                except:
                    pass"""
423
        self.assertTrue(self.find_binding("a", s))
424 425 426 427 428 429 430 431 432

        s = """
            try:
                b = 8
            except:
                try:
                    pass
                except:
                    a = 6"""
433
        self.assertTrue(self.find_binding("a", s))
434 435 436 437 438 439 440 441 442 443 444

        s = """
            try:
                try:
                    b = 8
                except KeyError:
                    pass
                except:
                    a = 6
            except:
                pass"""
445
        self.assertTrue(self.find_binding("a", s))
446 447 448 449 450 451 452 453 454 455 456

        s = """
            try:
                pass
            except:
                try:
                    b = 8
                except KeyError:
                    pass
                except:
                    a = 6"""
457
        self.assertTrue(self.find_binding("a", s))
458 459 460 461 462 463

        s = """
            try:
                b = 8
            except:
                b = 6"""
464
        self.assertFalse(self.find_binding("a", s))
465 466 467 468 469 470 471 472 473 474 475 476 477 478

        s = """
            try:
                try:
                    b = 8
                except:
                    c = d
            except:
                try:
                    b = 6
                except:
                    t = 8
                except:
                    o = y"""
479
        self.assertFalse(self.find_binding("a", s))
480 481 482 483 484 485 486 487 488

    def test_try_except_finally(self):
        s = """
            try:
                c = 6
            except:
                b = 8
            finally:
                a = 9"""
489
        self.assertTrue(self.find_binding("a", s))
490 491 492 493 494 495

        s = """
            try:
                b = 8
            finally:
                a = 6"""
496
        self.assertTrue(self.find_binding("a", s))
497 498 499 500 501 502

        s = """
            try:
                b = 8
            finally:
                b = 6"""
503
        self.assertFalse(self.find_binding("a", s))
504 505 506 507 508 509 510 511

        s = """
            try:
                b = 8
            except:
                b = 9
            finally:
                b = 6"""
512
        self.assertFalse(self.find_binding("a", s))
513 514 515 516 517 518 519 520 521 522 523 524 525 526

    def test_try_except_finally_nested(self):
        s = """
            try:
                c = 6
            except:
                b = 8
            finally:
                try:
                    a = 9
                except:
                    b = 9
                finally:
                    c = 9"""
527
        self.assertTrue(self.find_binding("a", s))
528 529 530 531 532 533 534 535 536

        s = """
            try:
                b = 8
            finally:
                try:
                    pass
                finally:
                    a = 6"""
537
        self.assertTrue(self.find_binding("a", s))
538 539 540 541 542 543 544 545 546

        s = """
            try:
                b = 8
            finally:
                try:
                    b = 6
                finally:
                    b = 7"""
547
        self.assertFalse(self.find_binding("a", s))
548

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
class Test_touch_import(support.TestCase):

    def test_after_docstring(self):
        node = parse('"""foo"""\nbar()')
        fixer_util.touch_import(None, "foo", node)
        self.assertEqual(str(node), '"""foo"""\nimport foo\nbar()\n\n')

    def test_after_imports(self):
        node = parse('"""foo"""\nimport bar\nbar()')
        fixer_util.touch_import(None, "foo", node)
        self.assertEqual(str(node), '"""foo"""\nimport bar\nimport foo\nbar()\n\n')

    def test_beginning(self):
        node = parse('bar()')
        fixer_util.touch_import(None, "foo", node)
        self.assertEqual(str(node), 'import foo\nbar()\n\n')

    def test_from_import(self):
        node = parse('bar()')
568 569
        fixer_util.touch_import("html", "escape", node)
        self.assertEqual(str(node), 'from html import escape\nbar()\n\n')
570 571 572 573 574

    def test_name_import(self):
        node = parse('bar()')
        fixer_util.touch_import(None, "cgi", node)
        self.assertEqual(str(node), 'import cgi\nbar()\n\n')
Benjamin Peterson's avatar
Benjamin Peterson committed
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591

class Test_find_indentation(support.TestCase):

    def test_nothing(self):
        fi = fixer_util.find_indentation
        node = parse("node()")
        self.assertEqual(fi(node), "")
        node = parse("")
        self.assertEqual(fi(node), "")

    def test_simple(self):
        fi = fixer_util.find_indentation
        node = parse("def f():\n    x()")
        self.assertEqual(fi(node), "")
        self.assertEqual(fi(node.children[0].children[4].children[2]), "    ")
        node = parse("def f():\n    x()\n    y()")
        self.assertEqual(fi(node.children[0].children[4].children[4]), "    ")