def generic_cancel_test( title, server, client ): console.banner(title) executor = rclpy.executors.MultiThreadedExecutor(num_threads=4) executor.add_node(server.node) executor.add_node(client.node) # Send goal and await future client.setup() goal_future = client.send_goal() start_time = time.monotonic() while (time.monotonic() - start_time) < timeout(): executor.spin_once(timeout_sec=0.1) if goal_future.result() is not None: break assert_banner() assert_details("goal_future.result()", "!None", goal_future.result()) assert(goal_future.result() is not None) print("goal_future.result().accepted.....True [{}]".format( goal_future.result().accepted) ) assert(goal_future.result().accepted) goal_handle = goal_future.result() # cancel _timer = client.node.create_timer(0.05, client.send_cancel_request) # Await preempted goal result future # Note: it's going to spam cancel requests, but that's ok # even desirable to make sure it doesn't flake out result_future = goal_handle.get_result_async() start_time = time.monotonic() while (time.monotonic() - start_time) < timeout(): executor.spin_once(timeout_sec=0.1) if result_future.done(): _timer.cancel() client.node.destroy_timer(_timer) break assert_banner() assert_details("result_future.done()", "True", result_future.done()) assert(result_future.done()) assert_details( "result_future.result().status", "STATUS_CANCELED", client.status_strings[result_future.result().status] ) assert(result_future.result().status == action_msgs.GoalStatus.STATUS_CANCELED) # noqa executor.shutdown() server.shutdown() client.shutdown()
def test_imposter_has_add_child_method(): console.banner("Test Imposter has add_child_method") tuples = [] tuples.append((create_impostered_behaviour(), False)) tuples.append((create_impostered_composite(), True)) for b, asserted_result in tuples: print("%s has add_child: %s [%s]" % (b.name, hasattr(b, 'add_child'), asserted_result)) assert (hasattr(b, 'add_child') == asserted_result)
def test_remove_nonexistant_child(): console.banner("Remove non-existant child") root = py_trees.composites.Sequence(name="Sequence") child = py_trees.behaviours.Success(name="Success") root.add_child(child) non_existant_child = py_trees.behaviours.Success(name="Ooops") with nose.tools.assert_raises(IndexError): print("Expecting an Index Error") root.remove_child_by_id(non_existant_child.id)
def test_symbols(): console.banner("Symbols") # This test has no assertions, except from the human eye. When it fails, # ticks and crosses fail and must be inspected by the human eye print("[{0}][{1}][{2}][{3}]".format( display._behaviour_status_to_ascii[py_trees.common.Status.SUCCESS], display._behaviour_status_to_ascii[py_trees.common.Status.FAILURE], display._behaviour_status_to_ascii[py_trees.common.Status.INVALID], display._behaviour_status_to_ascii[py_trees.common.Status.RUNNING]))
def test_lists(): console.banner("Lists") for create in [create_blackboards, create_namespaced_blackboards]: with create() as (foo, bar, unused_namespace): foo.dude = ["Bob", "Bill"] name = bar.dude[0] print("Read first element of the list: {} [{}]".format( name, "Bob")) assert (name == "Bob")
def test_tree_setup(): console.banner("Tree Setup") duration = 0.05 first = SleepInSetup(name="First", duration=duration) second = SleepInSetup(name="Second", duration=duration) third = SleepInSetup(name="Third", duration=duration) root = py_trees.composites.Sequence() root.add_children([first, second, third]) tree = py_trees.trees.BehaviourTree(root=root) print("\n--------- Assertions ---------\n") print(console.cyan + "Short Timeout: " + console.yellow + "No Visitor" + console.reset) with nose.tools.assert_raises(RuntimeError) as context: tree.setup(timeout=2 * duration) print("RuntimeError has message with substring 'timed out'") assert("timed out" in str(context.exception)) active_threads = threading.active_count() assert(active_threads == 1, "Only one thread should be active but there are {} active".format(active_threads)) print("\n--------- Assertions ---------\n") print(console.cyan + "Short timeout: " + console.yellow + "No Visitor" + console.reset) try: tree.setup(timeout=4 * duration) except RuntimeError: assert False, "should not have timed out" active_threads = threading.active_count() assert(active_threads == 1, "Only one thread should be active but there are {} active".format(active_threads)) print("\n--------- Assertions ---------\n") print(console.cyan + "Long Timeout: " + console.yellow + "With Visitor" + console.reset) visitor = SetupVisitor() with nose.tools.assert_raises(RuntimeError) as context: tree.setup(timeout=2 * duration, visitor=visitor) print("RuntimeError has message with substring 'timed out'") assert("timed out" in str(context.exception)) active_threads = threading.active_count() assert(active_threads == 1, "Only one thread should be active but there are {} active".format(active_threads)) print("\n--------- Assertions ---------\n") print(console.cyan + "Long timeout: " + console.yellow + "With Visitor" + console.reset) visitor = SetupVisitor() try: tree.setup(timeout=4 * duration, visitor=visitor) except RuntimeError: assert False, "should not have timed out" active_threads = threading.active_count() assert(active_threads == 1, "Only one thread should be active but there are {} active".format(active_threads)) print("\n--------- Assertions ---------\n") print(console.cyan + "No timeout: " + console.yellow + "No Visitor" + console.reset) visitor = SetupVisitor() try: tree.setup() except RuntimeError: assert False, "should not have timed out" active_threads = threading.active_count() assert(active_threads == 1, "Only one thread should be active but there are {} active".format(active_threads))
def test_high_priority_interrupt(): console.banner("High Priority Interrupt") task_one = py_trees.behaviours.Count(name="Task 1", fail_until=0, running_until=2, success_until=10) task_two = py_trees.behaviours.Count(name="Task 2", fail_until=0, running_until=2, success_until=10) high_priority_interrupt = py_trees.decorators.RunningIsFailure( name="High Priority", child=py_trees.behaviours.Periodic(name="Periodic", n=3)) piwylo = py_trees.idioms.pick_up_where_you_left_off( name="Pick Up\nWhere You\nLeft Off", tasks=[task_one, task_two]) root = py_trees.composites.Selector(name="Root") root.add_children([high_priority_interrupt, piwylo]) py_trees.display.print_ascii_tree(root) visitor = py_trees.visitors.DebugVisitor() py_trees.tests.tick_tree(root, 1, 3, visitors=[visitor]) print() print("\n--------- Assertions ---------\n") print("high_priority_interrupt.status == py_trees.common.Status.FAILURE") assert (high_priority_interrupt.status == py_trees.common.Status.FAILURE) print("piwylo.status == py_trees.common.Status.RUNNING") assert (piwylo.status == py_trees.common.Status.RUNNING) print("task_one.status == py_trees.common.Status.SUCCESS") assert (task_one.status == py_trees.common.Status.SUCCESS) print("task_two.status == py_trees.common.Status.RUNNING") assert (task_two.status == py_trees.common.Status.RUNNING) py_trees.tests.tick_tree(root, 4, 5, visitors=[visitor]) print("\n--------- Assertions ---------\n") print("high_priority_interrupt.status == py_trees.common.Status.SUCCESS") assert (high_priority_interrupt.status == py_trees.common.Status.SUCCESS) print("piwylo.status == py_trees.common.Status.INVALID") assert (piwylo.status == py_trees.common.Status.INVALID) print("task_one.status == py_trees.common.Status.INVALID") assert (task_one.status == py_trees.common.Status.INVALID) print("task_two.status == py_trees.common.Status.INVALID") assert (task_two.status == py_trees.common.Status.INVALID) py_trees.tests.tick_tree(root, 6, 8, visitors=[visitor]) print("\n--------- Assertions ---------\n") print("high_priority_interrupt.status == py_trees.common.Status.FAILURE") assert (high_priority_interrupt.status == py_trees.common.Status.FAILURE) print("piwylo.status == py_trees.common.Status.RUNNING") assert (piwylo.status == py_trees.common.Status.RUNNING) print("task_one.status == py_trees.common.Status.INVALID") assert (task_one.status == py_trees.common.Status.INVALID) print("task_two.status == py_trees.common.Status.RUNNING") assert (task_two.status == py_trees.common.Status.RUNNING)
def test_parallel_success_on_selected(): console.banner("Parallel Success on Selected") print("") running1 = py_trees.behaviours.Running(name="Running1") success1 = py_trees.behaviours.Count(name="Success1", fail_until=0, running_until=1, success_until=10) success2 = py_trees.behaviours.Count(name="Success2", fail_until=0, running_until=2, success_until=10) running2 = py_trees.behaviours.Running(name="Running2") root = py_trees.composites.Parallel( name="Parallel", policy=py_trees.common.ParallelPolicy.SuccessOnSelected( children=[success1, success2])) root.add_children([running1, success1, success2, running2]) print(py_trees.display.unicode_tree(root)) visitor = py_trees.visitors.DebugVisitor() py_trees.tests.tick_tree(root, 1, 1, visitors=[visitor], print_snapshot=True) print("\n--------- Assertions ---------\n") print("root.status == py_trees.common.Status.RUNNING") assert (root.status == py_trees.common.Status.RUNNING) print("running1.status == py_trees.common.Status.RUNNING") assert (running1.status == py_trees.common.Status.RUNNING) print("success1.status == py_trees.common.Status.RUNNING") assert (success1.status == py_trees.common.Status.RUNNING) print("success2.status == py_trees.common.Status.RUNNING") assert (success2.status == py_trees.common.Status.RUNNING) print("running2.status == py_trees.common.Status.RUNNING") assert (running2.status == py_trees.common.Status.RUNNING) py_trees.tests.tick_tree(root, 2, 3, visitors=[visitor], print_snapshot=True) print("\n--------- Assertions ---------\n") print("root.status == py_trees.common.Status.SUCCESS") assert (root.status == py_trees.common.Status.SUCCESS) print("running1.status == py_trees.common.Status.INVALID") assert (running1.status == py_trees.common.Status.INVALID) print("success1.status == py_trees.common.Status.SUCCESS") assert (success1.status == py_trees.common.Status.SUCCESS) print("success2.status == py_trees.common.Status.SUCCESS") assert (success2.status == py_trees.common.Status.SUCCESS) print("running2.status == py_trees.common.Status.INVALID") assert (running2.status == py_trees.common.Status.INVALID)
def test_protect_against_multiple_parents(): console.banner("Protect Against Multiple Parents") child = py_trees.behaviours.Success() first_parent = py_trees.composites.Selector() second_parent = py_trees.composites.Sequence() with nose.tools.assert_raises(RuntimeError): print("Adding a child to two parents") print("Expecting a RuntimeError") for parent in [first_parent, second_parent]: parent.add_child(child)
def test_set_name(): console.banner("Set Name") child = py_trees.behaviours.Success(name="Woohoo") named_decorator = DummyDecorator(name="Foo", child=child) no_named_decorator = DummyDecorator(child=child) print("\n--------- Assertions ---------\n") print("named_decorator.name == Foo") assert (named_decorator.name == "Foo") print("no_named_decorator.name == DummyDecorator\\n[Woohoo]") assert (no_named_decorator.name == "DummyDecorator\n[Woohoo]")
def test_composite_errors(): console.banner("Timer Errors") root = py_trees.composites.Selector() print( "add_child raises a 'TypeError' due to not being an instance of Behaviour" ) with nose.tools.assert_raises(TypeError) as context: root.add_child(5.0) print("TypeError has message with substring 'behaviours'") assert ("behaviours" in str(context.exception))
def test_tip_simple(): console.banner("Tip Simple") # behaviours will be running the first time they are seen, then success for subsequent ticks seq = py_trees.composites.Sequence(name="Sequence") a = py_trees.behaviours.Count(name="A", fail_until=0, running_until=1, success_until=100) b = py_trees.behaviours.Count(name="B", fail_until=0, running_until=1, success_until=100) seq.add_child(a) seq.add_child(b) tree = py_trees.trees.BehaviourTree(seq) py_trees.display.print_ascii_tree(tree.root) visitor = py_trees.visitors.DebugVisitor() tree.visitors.append(visitor) print("\n--------- Assertions (before initialisation) ---------\n") # an uninitialised tree/behaviour always has a tip of None assert(tree.root.tip() is None) assert(seq.tip() is None) assert(a.tip() is None) assert(b.tip() is None) tree.tick() print("\n--------- Assertions ---------\n") assert(a.status == py_trees.common.Status.RUNNING) assert(b.status == py_trees.common.Status.INVALID) # the root of sequence and tree should be the currently running node assert(tree.root.tip() == a) assert(seq.tip() == a) # when a node is running/has run, its tip is itself assert(a.tip() == a) assert(b.tip() is None) tree.tick() print("\n--------- Assertions ---------\n") assert(a.status == py_trees.common.Status.SUCCESS) assert(b.status == py_trees.common.Status.RUNNING) # the root of sequence and tree should be the currently running node assert(tree.root.tip() == b) assert(seq.tip() == b) # when a node is running/has run, its tip is itself assert(a.tip() == a) assert(b.tip() == b) tree.tick() print("\n--------- Assertions ---------\n") assert(a.status == py_trees.common.Status.SUCCESS) assert(b.status == py_trees.common.Status.SUCCESS) # the root of sequence and tree should be the currently running node assert(tree.root.tip() == b) assert(seq.tip() == b) # when a node is running/has run, its tip is itself assert(a.tip() == a) assert(b.tip() == b)
def test_invalid_setup(): console.banner("Invalid Setup") parent = py_trees.composites.Sequence(name="Parent") child = InvalidSetup(name="Invalid Setup") parent.add_child(child) print("\n--------- Assertions ---------\n") print("TypeError is raised") with assert_raises(TypeError) as context: parent.setup(timeout=15) print("TypeError has message with substring 'NoneType'") assert ("NoneType" in str(context.exception))
def test_tick_add_with_current_child(): console.banner('Tick-Add with Current Child') assert_banner() root = py_trees.composites.Parallel( name="Parallel", policy=py_trees.common.ParallelPolicy.SuccessOnAll(synchronise=False)) root.tick_once() child = py_trees.behaviours.Failure(name="Failure") root.add_child(child) assert_details("Current Child", None, root.current_child) assert (root.current_child is None)
def test_tick_add_with_current_child(): console.banner('Tick-Add with Current Child') assert_banner() root = py_trees.composites.Selector(name="Selector") root.tick_once() child = py_trees.behaviours.Failure(name="Failure") print(py_trees.display.unicode_tree(root, show_status=True)) root.add_child(child) print(py_trees.display.unicode_tree(root, show_status=True)) assert_details("Current Child", None, root.current_child) assert (root.current_child is None)
def test_replacing_children(): console.banner("Replacing Children") parent = py_trees.composites.Sequence(name="Parent") old_child = py_trees.behaviours.Success(name="Old Child") new_child = py_trees.behaviours.Success(name="New Child") parent.add_child(old_child) parent.replace_child(old_child, new_child) print("\n--------- Assertions ---------\n") print("old_child.parent is None") assert (old_child.parent is None) print("new_child.parent is parent") assert (new_child.parent is parent)
def test_blackboard_static_names(): console.banner("Test Absolute Names with Static Methods") print("Set 'foo'") Blackboard.set("foo", "foo") print("Get 'foo' [{}]".format(Blackboard.get("foo"))) assert (Blackboard.get("foo") == "foo") assert (Blackboard.get("/foo") == "foo") print("Set '/bar'") Blackboard.set("/bar", "bar") print("Get 'bar' [{}]".format(Blackboard.get("bar"))) assert (Blackboard.get("bar") == "bar") assert (Blackboard.get("/bar") == "bar")
def test_parallel_no_synchronisation(): console.banner('Parallel No Synchronisation') root = py_trees.composites.Parallel( name="Parallel", policy=py_trees.common.ParallelPolicy.SuccessOnAll( synchronise=False )) success_every_two = py_trees.decorators.FailureIsRunning( name="SuccessEverySecond", child=py_trees.behaviours.SuccessEveryN(name="Flipper2", n=2) ) success_every_three = py_trees.decorators.FailureIsRunning( name="SuccessEveryThird", child=py_trees.behaviours.SuccessEveryN(name="Flipper3", n=3) ) debug_visitor = py_trees.visitors.DebugVisitor() snapshot_visitor = py_trees.visitors.SnapshotVisitor() root.add_children([success_every_two, success_every_three]) for counter in range(1, 6): snapshot_visitor.initialise() py_trees.tests.tick_tree( root, counter, counter, visitors=[debug_visitor, snapshot_visitor], print_snapshot=True ) print(counter) if counter % 2 == 0: print("success_every_two.status == py_trees.common.Status.SUCCESS") assert(success_every_two.status == py_trees.common.Status.SUCCESS) elif counter % 3 == 0: print("success_every_three.status == py_trees.common.Status.SUCCESS") assert(success_every_three.status == py_trees.common.Status.SUCCESS) else: print("success_every_two.status == py_trees.common.Status.RUNNING") assert(success_every_two.status == py_trees.common.Status.RUNNING) print("success_every_three.status == py_trees.common.Status.RUNNING") assert(success_every_three.status == py_trees.common.Status.RUNNING) print("root.status == py_trees.common.Status.RUNNING") assert(root.status == py_trees.common.Status.RUNNING, "{}, {}".format(root.status, counter)) snapshot_visitor.initialise() py_trees.tests.tick_tree( root, 6, 6, print_snapshot=True ) print("success_every_two.status == py_trees.common.Status.SUCCESS") assert(success_every_two.status == py_trees.common.Status.SUCCESS) print("success_every_three.status == py_trees.common.Status.SUCCESS") assert(success_every_three.status == py_trees.common.Status.SUCCESS) print("root.status == py_trees.common.Status.SUCCESS") assert(root.status == py_trees.common.Status.SUCCESS)
def benchmark_read(): console.banner("Read Benchmarks (x1000)") def _impl(with_remaps=False): with create_blackboards() as (root, parameters): width = max(len(root.name), len(parameters.name)) for blackboard in (root, parameters): for i in range(0, 1000): if with_remaps: remaps = {i: "/state/{}/colander_{}".format(blackboard.name.lower(), i) for i in range(0, 1000)} suffix = " with Remaps" blackboard.register_key( key="colander_{}".format(i), access=py_trees.common.Access.READ, remap_to=remaps[i] ) else: suffix = "" blackboard.register_key( key="colander_{}".format(i), access=py_trees.common.Access.READ, ) for i in range(0, 1000): if with_remaps: for blackboard in (root, parameters): py_trees.blackboard.Blackboard.set("/state/{}/colander_{}".format(blackboard.name.lower(), i), i) else: py_trees.blackboard.Blackboard.set("/colander_{}".format(i), i) py_trees.blackboard.Blackboard.set("/parameters/colander_{}".format(i), i) relative_names = {} absolute_names = {"Root": {}, "Namespaced": {}} for i in range(0, 1000): relative_names[i] = "colander_{}".format(i) absolute_names["Root"][i] = "/colander_{}".format(i) absolute_names["Namespaced"][i] = "/parameters/colander_{}".format(i) print("Relative Names" + suffix) for blackboard in (root, parameters): start_time = time.monotonic() foo = 0 for i in range(0, 1000): foo += blackboard.get(relative_names[i]) duration = time.monotonic() - start_time print(" - " + console.cyan + "{0: <{1}}".format(blackboard.name, width) + console.reset + ": " + console.yellow + "{0:.3f}".format(duration) + console.reset) print("Absolute Names" + suffix) for blackboard in (root, parameters): names = absolute_names[blackboard.name] start_time = time.monotonic() foo = 0 for i in range(0, 1000): foo += blackboard.get(names[i]) duration = time.monotonic() - start_time print(" - " + console.cyan + "{0: <{1}}".format(blackboard.name, width) + console.reset + ": " + console.yellow + "{0:.3f}".format(duration) + console.reset) _impl(with_remaps=False)
def test_exchange_setup(self): console.banner("Test Setup") print("----- Asserts -----") try: exchange = py_trees_ros.blackboard.Exchange() node = rclpy.create_node('test_exchange', start_parameter_services=False) exchange.setup(node) node.destroy_node() print("no exceptions [True]") except Exception as e: print("no exceptions [False]") self.fail("exchange.setup() raised an exception [{}]".format(str(e)))
def test_parallel_failure(): console.banner("Parallel Failure") success_on_one = py_trees.common.ParallelPolicy.SuccessOnOne() success_on_all_synchronised = py_trees.common.ParallelPolicy.SuccessOnAll( synchronise=True) success_on_all_not_synchronised = py_trees.common.ParallelPolicy.SuccessOnAll( synchronise=False) for policy in [ success_on_one, success_on_all_synchronised, success_on_all_not_synchronised ]: root = py_trees.composites.Parallel("Parallel", policy=policy) failure = py_trees.behaviours.Failure("Failure") success = py_trees.behaviours.Success("Success") root.add_child(failure) root.add_child(success) print(py_trees.display.unicode_tree(root)) visitor = py_trees.visitors.DebugVisitor() py_trees.tests.tick_tree(root, 1, 1, visitors=[visitor]) print("\n--------- Assertions ---------\n") print("root.status == py_trees.common.Status.FAILURE") assert (root.status == py_trees.common.Status.FAILURE) print("failure.status == py_trees.common.Status.FAILURE") assert (failure.status == py_trees.common.Status.FAILURE) print("success.status == py_trees.common.Status.SUCCESS") assert (success.status == py_trees.common.Status.SUCCESS) failure = py_trees.behaviours.Failure("Failure") success = py_trees.behaviours.Success("Success") for child, synchronise in itertools.product([success, failure], [True, False]): policy = py_trees.common.ParallelPolicy.SuccessOnSelected( children=[child], synchronise=synchronise) root = py_trees.composites.Parallel("Parallel", policy=policy) root.add_child(failure) root.add_child(success) print(py_trees.display.unicode_tree(root)) visitor = py_trees.visitors.DebugVisitor() py_trees.tests.tick_tree(root, 1, 1, visitors=[visitor]) print("\n--------- Assertions ---------\n") print("root.status == py_trees.common.Status.FAILURE") assert (root.status == py_trees.common.Status.FAILURE) print("failure.status == py_trees.common.Status.FAILURE") assert (failure.status == py_trees.common.Status.FAILURE) print("success.status == py_trees.common.Status.SUCCESS") assert (success.status == py_trees.common.Status.SUCCESS) # cleanup so they can be added again root.remove_child(failure) root.remove_child(success)
def test_wait_for_blackboard_variable(): console.banner("Wait for Blackboard Variable") create_blackboard() tuples = [] tuples.append( (py_trees.blackboard.WaitForBlackboardVariable(name="check_foo_exists", variable_name="foo"), Status.SUCCESS)) tuples.append( (py_trees.blackboard.WaitForBlackboardVariable(name="check_bar_exists", variable_name="bar"), Status.RUNNING)) tuples.append((py_trees.blackboard.WaitForBlackboardVariable( name="check_nested_foo_exists", variable_name="foobar.foo"), Status.SUCCESS)) tuples.append((py_trees.blackboard.WaitForBlackboardVariable( name="check_nested_bar_exists", variable_name="foobar.bar"), Status.RUNNING)) tuples.append( (py_trees.blackboard.WaitForBlackboardVariable( name="check_foo_equals_bar", variable_name="foo", expected_value="bar"), Status.SUCCESS)) tuples.append( (py_trees.blackboard.WaitForBlackboardVariable( name="check_foo_equals_foo", variable_name="foo", expected_value="foo"), Status.RUNNING)) tuples.append( (py_trees.blackboard.WaitForBlackboardVariable( name="check_bar_equals_bar", variable_name="bar", expected_value="bar"), Status.RUNNING)) tuples.append( (py_trees.blackboard.WaitForBlackboardVariable( name="check_bar_equals_foo", variable_name="bar", expected_value="foo"), Status.RUNNING)) tuples.append((py_trees.blackboard.WaitForBlackboardVariable( name="check_nested_foo_equals_bar", variable_name="foobar.foo", expected_value="bar"), Status.SUCCESS)) tuples.append((py_trees.blackboard.WaitForBlackboardVariable( name="check_nested_foo_equals_foo", variable_name="foobar.foo", expected_value="foo"), Status.RUNNING)) for b, unused in tuples: b.tick_once() for b, asserted_result in tuples: print("%s: %s [%s]" % (b.name, b.status, asserted_result)) assert (b.status == asserted_result)
def test_write(self): console.banner("Test Write") with create_and_setup_exchange() as exchange: exchange.blackboard.dude = "Bob" exchange.blackboard.dudette = "Sarah" exchange.blackboard.count = 1 print("----- Asserts -----") print("exchange.blackboard.dude: {} [{}]".format(exchange.blackboard.dude, "Bob")) self.assertEqual("Bob", exchange.blackboard.dude) print("exchange.blackboard.dudette: {} [{}]".format(exchange.blackboard.dudette, "Sarah")) self.assertEqual("Sarah", exchange.blackboard.dudette) print("exchange.blackboard.count: {} [{}]".format(exchange.blackboard.count, 1)) self.assertEqual(1, exchange.blackboard.count)
def test_valid_filenames(): console.banner("Valid Filenames") names = { "With\nNewlines": "with_newlines", "With Spaces": "with_spaces", " Leading Space": "leading_space", "Trailing Space ": "trailing_space" } for name, expected_name in names.items(): print(console.cyan + repr(name) + ": " + console.yellow + expected_name + " [" + utilities.get_valid_filename(name) + "]" + console.reset) assert (utilities.get_valid_filename(name) == expected_name)
def test_activity_stream(): console.banner("Activity Stream") Blackboard.enable_activity_stream(100) blackboard = py_trees.blackboard.Client(name="Client") for key in {'foo', 'dude'}: blackboard.register_key(key=key, access=py_trees.common.Access.READ) for key in {"spaghetti", "motley"}: blackboard.register_key(key=key, access=py_trees.common.Access.WRITE) try: unused = blackboard.dude except KeyError: # NO_KEY pass try: unused = blackboard.dudette except AttributeError: # ACCESS_DENIED pass try: blackboard.dudette = "Jane" except AttributeError: # ACCESS_DENIED pass blackboard.spaghetti = {"type": "Carbonara", "quantity": 1} # INITIALISED blackboard.spaghetti = {"type": "Gnocchi", "quantity": 2} # WRITE blackboard.motley = Motley() blackboard.motley.nested = "mutt" unused_result = blackboard.motley.nested try: # NO_OVERWRITE blackboard.set("spaghetti", { "type": "Bolognese", "quantity": 3 }, overwrite=False) except AttributeError: pass blackboard.unset("spaghetti") # UNSET print(py_trees.display.unicode_blackboard_activity_stream()) expected_types = [ py_trees.blackboard.ActivityType.NO_KEY, py_trees.blackboard.ActivityType.ACCESS_DENIED, py_trees.blackboard.ActivityType.ACCESS_DENIED, py_trees.blackboard.ActivityType.INITIALISED, py_trees.blackboard.ActivityType.WRITE, py_trees.blackboard.ActivityType.INITIALISED, py_trees.blackboard.ActivityType.ACCESSED, py_trees.blackboard.ActivityType.ACCESSED, py_trees.blackboard.ActivityType.NO_OVERWRITE, py_trees.blackboard.ActivityType.UNSET, ] for item, expected in zip(Blackboard.activity_stream.data, expected_types): assert (item.activity_type == expected.value) blackboard.unregister(clear=True)
def test_to_blackboard_not_initialised(self): console.banner("ToBlackboard - Uninitialised") self.blackboard.clear() unused_root = py_trees_ros.subscribers.ToBlackboard( name="ToBlackboard", topic_name="/battery/state", topic_type=sensor_msgs.BatteryState, blackboard_variables={'percentage': 'percentage'}, initialise_variables={}, clearing_policy=py_trees.common.ClearingPolicy.NEVER) print("----- Asserts -----") print("blackboard.percentage.............raises AttributeError") with self.assertRaises(AttributeError): print(self.blackboard.percentage)
def test_sequence_composite(): console.banner("Sequence") visitor = py_trees.visitors.DebugVisitor() tree = py_trees.Sequence(name='Sequence') a = py_trees.behaviours.Count(name="A", fail_until=0, running_until=3, success_until=6) b = py_trees.behaviours.Count(name="B", fail_until=0, running_until=3, success_until=6) c = py_trees.behaviours.Count(name="C", fail_until=0, running_until=3, success_until=6) tree.add_child(a) tree.add_child(b) tree.add_child(c) py_trees.tests.tick_tree(tree, visitor, 1, 5) py_trees.tests.print_summary(nodes=[a, b, c]) print("--------- Assertions ---------\n") print("a.status == py_trees.Status.SUCCESS") assert (a.status == py_trees.Status.SUCCESS) print("b.status == py_trees.Status.RUNNING") assert (b.status == py_trees.Status.RUNNING) print("tree.status == py_trees.Status.RUNNING") assert (tree.status == py_trees.Status.RUNNING) py_trees.tests.tick_tree(tree, visitor, 6, 10) py_trees.tests.print_summary(nodes=[a, b, c]) print("--------- Assertions ---------\n") print("a.status == py_trees.Status.SUCCESS") assert (a.status == py_trees.Status.SUCCESS) print("b.status == py_trees.Status.SUCCESS") assert (b.status == py_trees.Status.SUCCESS) print("b.status == py_trees.Status.SUCCESS") assert (c.status == py_trees.Status.SUCCESS) print("tree.status == py_trees.Status.SUCCESS") assert (tree.status == py_trees.Status.SUCCESS) py_trees.tests.tick_tree(tree, visitor, 11, 13) py_trees.tests.print_summary(nodes=[a, b, c]) print("--------- Assertions ---------\n") print("a.status == py_trees.Status.RUNNING") assert (a.status == py_trees.Status.RUNNING) print("b.status == py_trees.Status.INVALID") assert (b.status == py_trees.Status.INVALID) print("c.status == py_trees.Status.INVALID") assert (c.status == py_trees.Status.INVALID) print("tree.status == py_trees.Status.RUNNING") assert (tree.status == py_trees.Status.RUNNING)
def test_running_sequence(): """ Makes sure proper responses are returned from a oneshot sequence with running children. """ console.banner("Running Sequence") run_a_bit = py_trees.behaviours.Count(name="RunABit", fail_until=0, running_until=2, success_until=5) oneshot = py_trees.meta.oneshot(py_trees.composites.Sequence)( name="Oneshot", children=[run_a_bit]) count = tick_tree(root=oneshot, oneshot=oneshot, from_tick=1, to_tick=4) assert (count == 1)
def test_set_blackboard_variable(): console.banner("Set Blackboard Variable") blackboard = create_blackboard() set_foo = py_trees.blackboard.SetBlackboardVariable(name="Set Foo", variable_name="foo", variable_value="bar") print(" - Set 'foo'") set_foo.tick_once() print("\n%s" % blackboard) print(" - Assert blackboard.foo='bar'") assert (hasattr(blackboard, "foo")) assert (blackboard.foo == "bar") print(" - Assert set_foo.status == SUCCESS") assert (set_foo.status == Status.SUCCESS)
def test_to_blackboard_initialised(self): console.banner("ToBlackboard - Initialised") self.blackboard.clear() unused_root = py_trees_ros.subscribers.ToBlackboard( name="ToBlackboard", topic_name="/battery/state", topic_type=sensor_msgs.BatteryState, blackboard_variables={'percentage': 'percentage'}, initialise_variables={'percentage': 0.10}, clearing_policy=py_trees.common.ClearingPolicy.NEVER) print("----- Asserts -----") print("blackboard.percentage.............{} [{}]".format( 0.10, self.blackboard.percentage)) self.assertTrue(self.blackboard.percentage == 0.10)