summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCeridwen <ceridwenv@gmail.com>2016-02-15 22:28:43 -0500
committerCeridwen <ceridwenv@gmail.com>2016-02-15 22:28:43 -0500
commit329fc88e739e403c4bc0e7bb93f757efd5b49556 (patch)
treec1f97cbd14eb2db23d13e8daa0cc1c8237b3ca13
parent78e5ab8c0b685aed87cab23f5e8dcb769e172a7f (diff)
downloadastroid-git-329fc88e739e403c4bc0e7bb93f757efd5b49556.tar.gz
First version of Hypothesis tests for the zipper; unfinished, but works well enough to find some bugs
-rw-r--r--astroid/tests/unittest_zipper.py76
-rw-r--r--astroid/tree/zipper.py49
-rw-r--r--tox.ini1
3 files changed, 105 insertions, 21 deletions
diff --git a/astroid/tests/unittest_zipper.py b/astroid/tests/unittest_zipper.py
new file mode 100644
index 00000000..7ba57378
--- /dev/null
+++ b/astroid/tests/unittest_zipper.py
@@ -0,0 +1,76 @@
+import cProfile
+import itertools
+import os
+
+import hypothesis
+from hypothesis import strategies
+
+import astroid
+from astroid.tree import zipper
+
+
+# __init__.py screens out the empty init files, testdata because of
+# the deliberately-broken files, and unittests because of #310.
+astroid_file = strategies.sampled_from(os.path.join(p, n) for p, _, ns in os.walk('astroid/') for n in ns if n.endswith('.py') and '__init__.py' not in n)
+
+def parse_ast(name):
+ with open(name, 'r') as source_file:
+ print(name)
+ ast = zipper.Zipper(astroid.parse(source_file.read()))
+ return (ast.down,)
+
+base_case = strategies.builds(parse_ast, astroid_file)
+
+def possible_moves(path):
+ # position = path[-1]()
+ # previous_position = path[-1].__self__
+ # if not len(previous_position):
+ # return ()
+ # length = 0
+ # # If the zipper produces a position that is not the child of the
+ # # previous position, this is a bug and thus should crash.
+ # for child in previous_position:
+ # length += 1
+ # if child == position:
+ # index = length
+ # break
+ # else:
+ # print(position)
+ # print([repr(c) for c in previous_position])
+ # raise astroid.exceptions.AstroidError(
+ # 'Invalid AST: {child!r} is not a child of {parent!r}',
+ # child=position, parent=previous_position)
+ # moves = []
+ # if position._self_path:
+ # moves.append(position.up)
+ # if length > 0:
+ # moves.append(position.down)
+ # if index < length:
+ # moves.append(position.right)
+ # if index > 0:
+ # moves.append(position.left)
+ position = path[-1]()
+ return tuple(m for m in (position.down, position.up, position.left, position.right) if m() is not None)
+
+extend = lambda path_strategy: path_strategy.flatmap(lambda path: strategies.sampled_from(possible_moves(path)).map(lambda move: path + (move,)))
+
+walk_ast = strategies.recursive(base_case, extend)
+
+# print(walk_ast.example())
+
+# cProfile.run('print(walk_ast.example())')
+
+@hypothesis.given(walk_ast)
+def test(moves):
+ print(moves)
+ moves = tuple(reversed(moves))
+ visited_positions = {id(moves[0].__self__): moves[0].__self__}
+ for move in moves:
+ position = move()
+ if id(position) in visited_positions:
+ assert(position == visited_positions[id(position)])
+ visited_positions[id(position)] = position
+
+if __name__ == '__main__':
+ test()
+ # pass
diff --git a/astroid/tree/zipper.py b/astroid/tree/zipper.py
index 51f93b0e..cf306e08 100644
--- a/astroid/tree/zipper.py
+++ b/astroid/tree/zipper.py
@@ -4,9 +4,9 @@ import collections
# has to be optimized as much as possible. Using wrapt here instead
# of lazy_object_proxy avoids several additional function calls every
# time an AST node method has to be accessed through a new zipper.
-# Importing ObjectProxy into the local name space avoids an extra
-# indirection during initialization.
-from wrapt import ObjectProxy as _ObjectProxy
+import wrapt
+
+from astroid.tree import base
# The following are helper functions for working with singly-linked
@@ -16,10 +16,10 @@ def linked_list(*values, **kws):
'''Builds a new linked list of tuples out of its arguments, appending
to the front of an existing list if that's given.
- :param values: The values to add to the front of list.
-
- :param tail: The existing list to append to. Must be provided as
- a keyword argument and not required.
+ Args:
+ values: The values to add to the front of list.
+ tail: The existing list to append to. Must be provided as
+ a keyword argument and is optional.
'''
if values:
@@ -90,24 +90,31 @@ def initial(linked_list):
return tail
-Path = collections.namedtuple('Path', 'left right parent_nodes parent_path changed')
-
-class NodeSequence(list):
- lineno = None
- col_offset = None
- def children(self):
- return tuple(self)
- def make_node(self, linked_list):
- return type(self)(*iterate(linked_list))
+# class NodeSequence(list):
+# lineno = None
+# col_offset = None
+# def children(self):
+# return tuple(self)
+# def make_node(self, linked_list):
+# return type(self)(*iterate(linked_list))
+Path = collections.namedtuple('Path', 'left right parent_nodes parent_path changed')
-class Zipper(_ObjectProxy):
+class Zipper(wrapt.ObjectProxy):
__slots__ = ('path')
- def __init__(self, focus, path=None):
- # Call ObjectProxy.__init__ directly to avoid the super call.
- _ObjectProxy.__init__(self, focus)
+ # Setting wrapt.ObjectProxy.__init__ as a default value turns it into a
+ # local variable, avoiding a super() call, two globals lookups,
+ # and two dict lookups (on wrapt's and ObjectProxy's dicts).
+ def __init__(self, focus, path=None, init=wrapt.ObjectProxy.__init__):
+ try:
+ assert(isinstance(focus, (base.NodeNG, collections.Sequence)))
+ except AssertionError:
+ print(focus)
+ print(path)
+ raise
+ init(self, focus)
self._self_path = path
def left(self):
@@ -135,7 +142,7 @@ class Zipper(_ObjectProxy):
def down(self):
try:
- children = self.__wrapped__.get_children()
+ children = iter(self.__wrapped__)
first = next(children)
except StopIteration:
return
diff --git a/tox.ini b/tox.ini
index 1a7cb7a2..9b328e9b 100644
--- a/tox.ini
+++ b/tox.ini
@@ -19,6 +19,7 @@ deps =
# Temporary hack, ignore this.
dictproxyhack
py27,py33,pypy,jython: enum34
+ hypothesis
lazy-object-proxy
nose
py27,py33,py34,py35: numpy