def subpath(tree, search_name, *subpaths): """Find a node in the tree and return a subpath thereof. Given a tree corresponding to: - /foos - bar - baz - quux tree = <setup the above> subpath(tree, 'quux', 'fizz', buzz') # => "/foo/baz/quux/fizz/buzz" subpath(tree, 'nonsense!', 'fizz', buzz') # => None #; if the search fails, don't subpath. """ # get the path values themselves out of the tpath, not the full nodes root_tpath = treant.find_path_ex(tree, lambda n: treant.value(n) == search_name) if not root_tpath: return None return os.path.join(*[_path(root_tpath)] + [p for p in subpaths])
def _path(tree_path): """Given a tree path returns its directory path. - Treepath = [<root_node>, <home_node>, <john_node>] - Directory path => "/home/john" """ # convert nodes e.g. [<root_node>, <home_node>, <john_node>] # to their values, e.g. ["/", "home", "john"] tpath_values = [treant.value(node) for node in tree_path] return os.path.join(*tpath_values)
def test_find_all_miss(): nodes = ('/', [ ('opt', [ ('framed', [ ('bin')]), ('mcv', [ ('bin')])])]) t = tree(nodes) root, opt, framed, framed_bin, mcv, mcv_bin = preorder(t) ns = [n for n in find_all(t, lambda n: value(n) == 'nonsense!')] eq_(ns, [])
def test_find_all_paths_hit_nonleaf(): nodes = ('/', [ ('opt', [ ('framed', [ ('bin')]), ('mcv', [ ('bin')])])]) t = tree(nodes) root, opt, framed, framed_bin, mcv, mcv_bin = preorder(t) ps = [p for p in find_all_paths(t, lambda n: value(n) == 'framed')] eq_(ps, [[root, opt, framed]])
def test_find_ex_hit_nonleaf(): nodes = ('/', [ ('opt', [ ('framed', [ ('bin')]), ('mcv', [ ('bin'), ('tests')])])]) t = tree(nodes) root, opt, framed, framed_bin, mcv, mcv_bin, mcv_tests = preorder(t) n = find_ex(t, lambda n: value(n) == 'mcv') eq_(n, mcv)
def test_find_path_ex_miss_nonunique(): nodes = ('/', [ ('opt', [ ('framed', [ ('bin')]), ('mcv', [ ('bin'), ('tests')])])]) t = tree(nodes) root, opt, framed, framed_bin, mcv, mcv_bin, mcv_tests = preorder(t) n = find_path_ex(t, lambda n: value(n) == 'bin') eq_(n, None)
def root_path(tree): """Returns the root path of a tree, assumed to just be its value.""" return treant.value(tree)
def test_preorder(): nodes = ['/', ['opt', 'framed', 'mcv']] traversal = [value(n) for n in preorder(tree(nodes))] assert traversal == ['/', 'opt', 'framed', 'mcv']
def test_assoc_new_node_keeps_others(): n0 = mknode('foo', ['bar', 'baz']) n1 = assoc(n0, 'children', ['quux', 'wee']) assert value(n1) == value(n0)
def test_get_present(): nodes = ['/', ['opt', 'framed', 'mcv']] t = tree(nodes) n = get(t, ['/', 'opt', 'framed']) assert value(n) == 'framed'